"""
Management command to validate YAML schema files.

Usage:
    # Validate all schemas
    python manage.py validate_schema

    # Validate specific schema
    python manage.py validate_schema --schema layouts

    # Verbose output
    python manage.py validate_schema -v 2
"""

from django.core.management.base import BaseCommand, CommandError

from lightwave.schema.loaders.base import get_schema_files, get_schema_path, load_schema, validate_schema


class Command(BaseCommand):
    help = "Validate YAML schema definition files"

    def add_arguments(self, parser):
        parser.add_argument(
            "--schema",
            type=str,
            help=f"Specific schema to validate. Available: {', '.join(get_schema_files().keys())}",
        )

    def handle(self, *args, **options):
        schema_name = options.get("schema")
        verbosity = options.get("verbosity", 1)

        # Determine which schemas to validate
        if schema_name:
            if schema_name not in get_schema_files():
                raise CommandError(f"Unknown schema '{schema_name}'. Available: {', '.join(get_schema_files().keys())}")
            schemas = [schema_name]
        else:
            schemas = list(get_schema_files().keys())

        self.stdout.write(f"\nValidating {len(schemas)} schema file(s)...\n")

        all_errors = {}
        all_warnings = {}

        for name in schemas:
            path = get_schema_path(name)

            if not path.exists():
                self.stdout.write(self.style.WARNING(f"⚠️  {name}: File not found at {path}"))
                all_warnings[name] = [f"File not found: {path}"]
                continue

            errors = validate_schema(name)

            if errors:
                self.stdout.write(self.style.ERROR(f"❌ {name}: {len(errors)} error(s)"))
                all_errors[name] = errors
                if verbosity > 1:
                    for error in errors:
                        self.stdout.write(self.style.ERROR(f"     - {error}"))
            else:
                # Load and show basic info
                try:
                    data = load_schema(name)
                    meta = data.get("_meta", {})
                    version = meta.get("version", "unknown")
                    model = meta.get("model", "N/A")

                    self.stdout.write(self.style.SUCCESS(f"✅ {name}: Valid (v{version}, model: {model})"))

                    if verbosity > 1:
                        # Show item count
                        from lightwave.schema.loaders.base import SchemaLoader

                        loader = SchemaLoader()
                        try:
                            items = loader.get_items(name)
                            self.stdout.write(f"     Items: {len(items)}")
                        except Exception:
                            pass

                except Exception as e:
                    self.stdout.write(self.style.WARNING(f"✅ {name}: Valid (couldn't load details: {e})"))

        # Summary
        self.stdout.write("\n" + "=" * 50)

        total_errors = sum(len(e) for e in all_errors.values())
        total_warnings = sum(len(w) for w in all_warnings.values())

        if total_errors == 0 and total_warnings == 0:
            self.stdout.write(self.style.SUCCESS(f"\n✅ All {len(schemas)} schemas valid!"))
        else:
            if total_errors:
                self.stdout.write(self.style.ERROR(f"\n❌ {total_errors} error(s) in {len(all_errors)} schema(s)"))
            if total_warnings:
                self.stdout.write(
                    self.style.WARNING(f"⚠️  {total_warnings} warning(s) in {len(all_warnings)} schema(s)")
                )

            if verbosity > 0 and all_errors:
                self.stdout.write("\nErrors by schema:")
                for name, errors in all_errors.items():
                    self.stdout.write(self.style.ERROR(f"\n  {name}:"))
                    for error in errors:
                        self.stdout.write(f"    - {error}")
