#!/usr/bin/env python3
"""
[Script Name] - [Brief Description]

Part of the [skill-name] skill.

Usage:
    python script_name.py [required_arg] [--optional-flag]

Arguments:
    required_arg    Description of required argument
    --optional-flag Description of optional flag

Examples:
    python script_name.py input.txt
    python script_name.py input.txt --verbose

Output:
    [Description of what the script outputs]
"""

import argparse
import json
import sys
from pathlib import Path
from typing import Optional


def parse_args() -> argparse.Namespace:
    """Parse command line arguments."""
    parser = argparse.ArgumentParser(
        description=__doc__,
        formatter_class=argparse.RawDescriptionHelpFormatter
    )

    # Required arguments
    parser.add_argument(
        "input",
        type=str,
        help="Input file or value"
    )

    # Optional arguments
    parser.add_argument(
        "--output", "-o",
        type=str,
        default=None,
        help="Output file (default: stdout)"
    )

    parser.add_argument(
        "--verbose", "-v",
        action="store_true",
        help="Enable verbose output"
    )

    parser.add_argument(
        "--json",
        action="store_true",
        help="Output as JSON"
    )

    return parser.parse_args()


def process(input_path: str, verbose: bool = False) -> dict:
    """
    Main processing logic.

    Args:
        input_path: Path to input file or input value
        verbose: Whether to print verbose output

    Returns:
        Dictionary with processing results
    """
    result = {
        "status": "success",
        "input": input_path,
        "output": None,
        "metadata": {}
    }

    # Check if input is a file
    input_file = Path(input_path)
    if input_file.exists():
        if verbose:
            print(f"Reading file: {input_file}", file=sys.stderr)

        content = input_file.read_text()
        result["metadata"]["file_size"] = len(content)
        result["metadata"]["line_count"] = len(content.splitlines())

        # Process content here
        result["output"] = f"Processed {len(content)} characters"
    else:
        # Treat as direct input
        if verbose:
            print(f"Processing input: {input_path[:50]}...", file=sys.stderr)

        result["output"] = f"Processed input value"

    return result


def output_result(result: dict, output_path: Optional[str], as_json: bool):
    """Output the result to file or stdout."""
    if as_json:
        output_text = json.dumps(result, indent=2)
    else:
        output_text = result.get("output", str(result))

    if output_path:
        Path(output_path).write_text(output_text)
        print(f"Output written to: {output_path}", file=sys.stderr)
    else:
        print(output_text)


def main():
    """Main entry point."""
    args = parse_args()

    try:
        result = process(
            input_path=args.input,
            verbose=args.verbose
        )

        output_result(
            result=result,
            output_path=args.output,
            as_json=args.json
        )

        sys.exit(0)

    except FileNotFoundError as e:
        print(f"Error: File not found - {e}", file=sys.stderr)
        sys.exit(1)

    except Exception as e:
        print(f"Error: {e}", file=sys.stderr)
        sys.exit(1)


if __name__ == "__main__":
    main()
