"""json_to_types.py - Convert JSON files to TypeScript interfaces or Python dataclasses."""

import argparse
import json
import os
import sys
from typing import Any, Dict, List, Optional, Set, Union

def generate_types(json_data: Union[Dict, List], name: str, is_ts: bool = True) -> str:
    """Generate TypeScript interfaces or Python dataclasses from JSON data."""
    def _generate_type(obj: Any, depth: int = 0) -> str:
        if isinstance(obj, dict):
            if not obj:
                return "Record<string, any>"
            fields = []
            for key, value in obj.items():
                field_type = _generate_type(value, depth + 1)
                field_name = key
                if not field_name.isidentifier():
                    field_name = f'"{key}"'
                if is_ts:
                    fields.append(f"  {field_name}: {field_type};")
                else:
                    fields.append(f"  {field_name}: {field_type}")
            return f"{{\n{chr(10).join(fields)}\n}}"
        elif isinstance(obj, list):
            if not obj:
                return "any[]"
            item_type = _generate_type(obj[0], depth + 1)
            return f"{item_type}[]"
        else:
            return "any"

    if is_ts:
        interface_name = name.capitalize()
        result = f"interface {interface_name} {{\n"
        result += _generate_type(json_data)
        result += "\n}"
        return result
    else:
        dataclass_name = name.capitalize()
        result = f"@dataclass\nclass {dataclass_name}:\n"
        result += _generate_type(json_data, depth=1)
        return result

def parse_json(file_path: str) -> Dict:
    """Parse JSON file and return its content as a dictionary."""
    try:
        with open(file_path, 'r', encoding='utf-8') as f:
            return json.load(f)
    except json.JSONDecodeError as e:
        raise ValueError(f"Invalid JSON in {file_path}: {e}") from e
    except Exception as e:
        raise ValueError(f"Error reading {file_path}: {e}") from e

def main():
    """Main function for the JSON to Types script."""
    parser = argparse.ArgumentParser(description="Convert JSON files to TypeScript interfaces or Python dataclasses.")
    parser.add_argument("input_file", help="Path to the JSON input file")
    parser.add_argument("--output", "-o", help="Output file path (default: stdout)")
    parser.add_argument("--types", "-t", action="store_true", help="Generate TypeScript interfaces (default: Python dataclasses)")
    parser.add_argument("--name", "-n", default="Root", help="Name of the generated type (default: Root)")
    parser.add_argument("--no-header", action="store_true", help="Do not include header comments")
    args = parser.parse_args()

    try:
        if not os.path.isfile(args.input_file):
            raise ValueError(f"Input file not found: {args.input_file}")

        json_data = parse_json(args.input_file)
        output = generate_types(json_data, args.name, is_ts=args.types)

        if args.output:
            with open(args.output, 'w', encoding='utf-8') as f:
                f.write(output)
            print(f"Generated {'TypeScript' if args.types else 'Python'} types to {args.output}")
        else:
            print(output)

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

if __name__ == "__main__":
    main()