from django.core.management.base import BaseCommand

from djino.registry import djinoRegistry
from djino.typegen.generator import TypeGenerator


class Command(BaseCommand):
    help = "Generate TypeScript types from registered djino models"

    def add_arguments(self, parser):
        parser.add_argument(
            "--output",
            "-o",
            default="client/src/generated",
            help="Output directory for generated TypeScript files",
        )
        parser.add_argument(
            "--dry-run",
            action="store_true",
            help="Print generated output without writing files",
        )
        parser.add_argument(
            "--models",
            nargs="*",
            help="Generate types for specific models only (format: app_label.ModelName)",
        )
        parser.add_argument(
            "--check",
            action="store_true",
            help="Exit with error if generated types would change (useful for CI)",
        )

    def handle(self, *args, **options):
        registry = djinoRegistry.get_models()

        if not registry:
            self.stderr.write(
                self.style.WARNING(
                    "No SyncModel subclasses found. "
                    "Make sure djino is in INSTALLED_APPS and your models "
                    "inherit from SyncModel."
                )
            )
            return

        if options["models"]:
            registry = {k: v for k, v in registry.items() if k in options["models"]}

        generator = TypeGenerator(registry, djinoRegistry)
        output = generator.generate()

        if options["dry_run"]:
            for filepath, content in output.items():
                self.stdout.write(f"\n--- {filepath} ---\n")
                self.stdout.write(content)
            return

        if options["check"]:
            has_changes = generator.check_for_changes(options["output"], output)
            if has_changes:
                self.stderr.write(
                    self.style.ERROR(
                        "Generated types are out of date. "
                        "Run `manage.py generate_types` to update."
                    )
                )
                raise SystemExit(1)
            else:
                self.stdout.write(self.style.SUCCESS("Generated types are up to date."))
            return

        written = generator.write(options["output"], output)
        self.stdout.write(
            self.style.SUCCESS(f"Generated {len(written)} files in {options['output']}/")
        )
        for filepath in written:
            self.stdout.write(f"  {filepath}")
