"""
Modelgen - Generic Model Generation Tool

Generates typed models from various sources to various formats.

Input sources:
- Configuration files (soleprint.config.json style)
- JSON Schema (planned)
- Existing codebases: Django, SQLAlchemy, Prisma (planned - for databrowse)

Output formats:
- pydantic: Pydantic BaseModel classes
- django: Django ORM models (planned)
- prisma: Prisma schema (planned)
- sqlalchemy: SQLAlchemy models (planned)

Usage:
    python -m station.tools.modelgen --help
    python -m station.tools.modelgen from-config -c config.json -o models/ -f pydantic
    python -m station.tools.modelgen from-schema -s schema.json -o models/ -f pydantic
    python -m station.tools.modelgen extract -s /path/to/django/app -o models/ -f pydantic

This is a GENERIC tool. For soleprint-specific builds, use:
    python build.py dev|deploy
"""

import argparse
import sys
from pathlib import Path


def cmd_from_config(args):
    """Generate models from a configuration file (soleprint.config.json style)."""
    from .config_loader import load_config
    from .model_generator import ModelGenerator

    config_path = Path(args.config)
    if not config_path.exists():
        print(f"Error: Config file not found: {config_path}", file=sys.stderr)
        sys.exit(1)

    output_path = Path(args.output)

    print(f"Loading config: {config_path}")
    config = load_config(config_path)

    print(f"Generating {args.format} models to: {output_path}")
    generator = ModelGenerator(
        config=config,
        output_path=output_path,
        output_format=args.format,
    )
    result_path = generator.generate()

    print(f"✓ Models generated: {result_path}")


def cmd_from_schema(args):
    """Generate models from JSON Schema."""
    print("Error: from-schema not yet implemented", file=sys.stderr)
    print("Use from-config with a soleprint.config.json file for now", file=sys.stderr)
    sys.exit(1)


def cmd_extract(args):
    """Extract models from existing codebase (for databrowse graphs)."""
    print("Error: extract not yet implemented", file=sys.stderr)
    print(
        "This will extract models from Django/SQLAlchemy/Prisma codebases.",
        file=sys.stderr,
    )
    print("Use cases:", file=sys.stderr)
    print("  - Generate browsable graphs for databrowse tool", file=sys.stderr)
    print("  - Convert between ORM formats", file=sys.stderr)
    sys.exit(1)


def cmd_list_formats(args):
    """List available output formats."""
    from .model_generator import ModelGenerator

    print("Available output formats:")
    for fmt in ModelGenerator.available_formats():
        print(f"  - {fmt}")


def main():
    parser = argparse.ArgumentParser(
        description="Modelgen - Generic Model Generation Tool",
        formatter_class=argparse.RawDescriptionHelpFormatter,
        epilog=__doc__,
    )

    subparsers = parser.add_subparsers(dest="command", required=True)

    # from-config command
    config_parser = subparsers.add_parser(
        "from-config",
        help="Generate models from configuration file",
    )
    config_parser.add_argument(
        "--config",
        "-c",
        type=str,
        required=True,
        help="Path to configuration file (e.g., soleprint.config.json)",
    )
    config_parser.add_argument(
        "--output",
        "-o",
        type=str,
        required=True,
        help="Output path (file or directory)",
    )
    config_parser.add_argument(
        "--format",
        "-f",
        type=str,
        default="pydantic",
        choices=["pydantic", "django", "prisma", "sqlalchemy"],
        help="Output format (default: pydantic)",
    )
    config_parser.set_defaults(func=cmd_from_config)

    # from-schema command (placeholder)
    schema_parser = subparsers.add_parser(
        "from-schema",
        help="Generate models from JSON Schema (not yet implemented)",
    )
    schema_parser.add_argument(
        "--schema",
        "-s",
        type=str,
        required=True,
        help="Path to JSON Schema file",
    )
    schema_parser.add_argument(
        "--output",
        "-o",
        type=str,
        required=True,
        help="Output path (file or directory)",
    )
    schema_parser.add_argument(
        "--format",
        "-f",
        type=str,
        default="pydantic",
        choices=["pydantic", "django", "prisma", "sqlalchemy"],
        help="Output format (default: pydantic)",
    )
    schema_parser.set_defaults(func=cmd_from_schema)

    # extract command (placeholder for databrowse)
    extract_parser = subparsers.add_parser(
        "extract",
        help="Extract models from existing codebase (not yet implemented)",
    )
    extract_parser.add_argument(
        "--source",
        "-s",
        type=str,
        required=True,
        help="Path to source codebase",
    )
    extract_parser.add_argument(
        "--framework",
        type=str,
        choices=["django", "sqlalchemy", "prisma", "auto"],
        default="auto",
        help="Source framework to extract from (default: auto-detect)",
    )
    extract_parser.add_argument(
        "--output",
        "-o",
        type=str,
        required=True,
        help="Output path (file or directory)",
    )
    extract_parser.add_argument(
        "--format",
        "-f",
        type=str,
        default="pydantic",
        choices=["pydantic", "django", "prisma", "sqlalchemy"],
        help="Output format (default: pydantic)",
    )
    extract_parser.set_defaults(func=cmd_extract)

    # list-formats command
    formats_parser = subparsers.add_parser(
        "list-formats",
        help="List available output formats",
    )
    formats_parser.set_defaults(func=cmd_list_formats)

    args = parser.parse_args()
    args.func(args)


if __name__ == "__main__":
    main()
