"""
Django management command to validate and fix AI model metadata issues.
This command addresses the "No model metadata found for this model" error.
"""

from django.core.management.base import BaseCommand

from endoreg_db.models.metadata.model_meta_logic import validate_and_fix_ai_model_metadata_logic


class Command(BaseCommand):
    help = """
    Validate and fix AI model metadata to prevent processing errors.
    
    This command:
    - Checks all AI models for proper metadata configuration
    - Creates missing metadata with sensible defaults
    - Sets active metadata for models that don't have it
    - Validates that all models can access their latest versions
    
    Use this command to fix "No model metadata found for this model" errors.
    """

    def add_arguments(self, parser):
        parser.add_argument(
            "--dry-run",
            action="store_true",
            help="Show what would be fixed without making changes",
        )
        parser.add_argument(
            "--force",
            action="store_true",
            help="Force recreation of existing metadata",
        )

    def handle(self, *args, **options):
        dry_run = options.get("dry_run", False)
        force = options.get("force", False)

        self.stdout.write(self.style.SUCCESS("🔍 Validating AI model metadata..."))

        if dry_run:
            self.stdout.write(self.style.WARNING("🧪 DRY RUN MODE - No changes will be made"))

        try:
            if dry_run:
                # In dry run, we just check and report issues
                summary = self._check_ai_models_dry_run()
            else:
                # Actually fix the issues
                summary = validate_and_fix_ai_model_metadata_logic()

            # Report results
            self._report_summary(summary)

            if summary["errors"]:
                self.stdout.write(self.style.ERROR("❌ Validation completed with errors"))
                for error in summary["errors"]:
                    self.stdout.write(self.style.ERROR(f"  - {error}"))
                return

            self.stdout.write(self.style.SUCCESS("✅ AI model metadata validation completed successfully"))

        except Exception as e:
            self.stdout.write(self.style.ERROR(f"❌ Validation failed: {e}"))
            raise

    def _check_ai_models_dry_run(self):
        """Check AI models without making changes."""
        from endoreg_db.models import AiModel

        summary = {"models_checked": 0, "models_fixed": 0, "metadata_created": 0, "active_meta_set": 0, "errors": []}

        all_models = AiModel.objects.all()
        summary["models_checked"] = all_models.count()

        for model in all_models:
            self.stdout.write(f"Checking model: {model.name}")

            metadata_count = model.metadata_versions.count()
            self.stdout.write(f"  Metadata versions: {metadata_count}")

            if metadata_count == 0:
                self.stdout.write(f"  🔧 Would create metadata for {model.name}")
                summary["models_fixed"] += 1
                summary["metadata_created"] += 1

            elif not model.active_meta:
                self.stdout.write(f"  🔧 Would set active metadata for {model.name}")
                summary["models_fixed"] += 1
                summary["active_meta_set"] += 1

            else:
                self.stdout.write(f"  ✅ Model {model.name} has valid active metadata")

            # Test metadata access
            try:
                latest = model.get_latest_version()
                self.stdout.write(f"  ✅ Can access latest version: {latest}")
            except Exception as e:
                error_msg = f"Model {model.name} metadata test failed: {e}"
                self.stdout.write(self.style.ERROR(f"  ❌ {error_msg}"))
                summary["errors"].append(error_msg)

        return summary

    def _report_summary(self, summary):
        """Report the validation summary."""
        self.stdout.write("\n📊 Validation Summary:")
        self.stdout.write(f"  Models checked: {summary['models_checked']}")

        if summary["models_fixed"] > 0:
            self.stdout.write(f"  Models fixed: {summary['models_fixed']}")

        if summary["metadata_created"] > 0:
            self.stdout.write(f"  Metadata created: {summary['metadata_created']}")

        if summary["active_meta_set"] > 0:
            self.stdout.write(f"  Active metadata set: {summary['active_meta_set']}")

        if summary["errors"]:
            self.stdout.write(f"  Errors encountered: {len(summary['errors'])}")
        else:
            self.stdout.write("  No errors found")
