"""Management command to validate state machine configurations for moderation models."""

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

from apps.core.state_machine import MetadataValidator
from apps.moderation.models import (
    BulkOperation,
    EditSubmission,
    ModerationQueue,
    ModerationReport,
    PhotoSubmission,
)


class Command(BaseCommand):
    """Validate state machine configurations for all moderation models."""

    help = (
        "Validates state machine configurations for all moderation models. "
        "Checks metadata, transitions, and FSM field setup."
    )

    def add_arguments(self, parser):
        """Add command arguments."""
        parser.add_argument(
            "--model",
            type=str,
            help=(
                "Validate only specific model "
                "(editsubmission, moderationreport, moderationqueue, "
                "bulkoperation, photosubmission)"
            ),
        )
        parser.add_argument(
            "--verbose",
            action="store_true",
            help="Show detailed validation information",
        )

    def handle(self, *args, **options):
        """Execute the command."""
        model_name = options.get("model")
        verbose = options.get("verbose", False)

        # Define models to validate
        models_to_validate = {
            "editsubmission": (
                EditSubmission,
                "edit_submission_statuses",
                "moderation",
            ),
            "moderationreport": (
                ModerationReport,
                "moderation_report_statuses",
                "moderation",
            ),
            "moderationqueue": (
                ModerationQueue,
                "moderation_queue_statuses",
                "moderation",
            ),
            "bulkoperation": (
                BulkOperation,
                "bulk_operation_statuses",
                "moderation",
            ),
            "photosubmission": (
                PhotoSubmission,
                "photo_submission_statuses",
                "moderation",
            ),
        }

        # Filter by model name if specified
        if model_name:
            model_key = model_name.lower()
            if model_key not in models_to_validate:
                raise CommandError(
                    f"Unknown model: {model_name}. " f"Valid options: {', '.join(models_to_validate.keys())}"
                )
            models_to_validate = {model_key: models_to_validate[model_key]}

        self.stdout.write(self.style.SUCCESS("\nValidating State Machine Configurations\n"))
        self.stdout.write("=" * 60 + "\n")

        all_valid = True
        for _model_key, (
            model_class,
            choice_group,
            domain,
        ) in models_to_validate.items():
            self.stdout.write(f"\nValidating {model_class.__name__}...")
            self.stdout.write(f"  Choice Group: {choice_group}")
            self.stdout.write(f"  Domain: {domain}\n")

            # Validate metadata
            validator = MetadataValidator(choice_group, domain)
            result = validator.validate_choice_group()

            if result.is_valid:
                self.stdout.write(self.style.SUCCESS(f"  ✓ {model_class.__name__} validation passed"))

                if verbose:
                    self._show_transition_graph(choice_group, domain)
            else:
                all_valid = False
                self.stdout.write(self.style.ERROR(f"  ✗ {model_class.__name__} validation failed"))

                for error in result.errors:
                    self.stdout.write(self.style.ERROR(f"    - {error.message}"))

            # Check FSM field
            if not self._check_fsm_field(model_class):
                all_valid = False
                self.stdout.write(self.style.ERROR(f"    - FSM field 'status' not found on " f"{model_class.__name__}"))

            # Check mixin
            if not self._check_state_machine_mixin(model_class):
                all_valid = False
                self.stdout.write(
                    self.style.WARNING(f"    - StateMachineMixin not found on " f"{model_class.__name__}")
                )

        self.stdout.write("\n" + "=" * 60)
        if all_valid:
            self.stdout.write(self.style.SUCCESS("\n✓ All validations passed successfully!\n"))
        else:
            self.stdout.write(self.style.ERROR("\n✗ Some validations failed. " "Please review the errors above.\n"))
            raise CommandError("State machine validation failed")

    def _check_fsm_field(self, model_class):
        """Check if model has FSM field."""
        from apps.core.state_machine import RichFSMField

        status_field = model_class._meta.get_field("status")
        return isinstance(status_field, RichFSMField)

    def _check_state_machine_mixin(self, model_class):
        """Check if model uses StateMachineMixin."""
        from apps.core.state_machine import StateMachineMixin

        return issubclass(model_class, StateMachineMixin)

    def _show_transition_graph(self, choice_group, domain):
        """Show transition graph for choice group."""
        from apps.core.state_machine import registry_instance

        self.stdout.write("\n    Transition Graph:")

        graph = registry_instance.export_transition_graph(choice_group, domain)

        for source, targets in sorted(graph.items()):
            if targets:
                for target in sorted(targets):
                    self.stdout.write(f"      {source} -> {target}")
            else:
                self.stdout.write(f"      {source} (no transitions)")

        self.stdout.write("")
