import logging

from django.apps import AppConfig

logger = logging.getLogger(__name__)


class ModerationConfig(AppConfig):
    default_auto_field = "django.db.models.BigAutoField"
    name = "apps.moderation"
    verbose_name = "Content Moderation"

    def ready(self):
        """Initialize state machines and callbacks for all moderation models."""
        self._apply_state_machines()
        self._register_callbacks()
        self._register_signal_handlers()

    def _apply_state_machines(self):
        """Apply FSM to all moderation models."""
        from apps.core.state_machine import apply_state_machine

        from .models import (
            BulkOperation,
            EditSubmission,
            ModerationQueue,
            ModerationReport,
            PhotoSubmission,
        )

        # Apply FSM to all models with their respective choice groups
        apply_state_machine(
            EditSubmission,
            field_name="status",
            choice_group="edit_submission_statuses",
            domain="moderation",
        )
        apply_state_machine(
            ModerationReport,
            field_name="status",
            choice_group="moderation_report_statuses",
            domain="moderation",
        )
        apply_state_machine(
            ModerationQueue,
            field_name="status",
            choice_group="moderation_queue_statuses",
            domain="moderation",
        )
        apply_state_machine(
            BulkOperation,
            field_name="status",
            choice_group="bulk_operation_statuses",
            domain="moderation",
        )
        apply_state_machine(
            PhotoSubmission,
            field_name="status",
            choice_group="photo_submission_statuses",
            domain="moderation",
        )

    def _register_callbacks(self):
        """Register FSM transition callbacks for moderation models."""
        from apps.core.state_machine.callbacks.cache import (
            ModerationCacheInvalidation,
        )
        from apps.core.state_machine.callbacks.notifications import (
            ModerationNotificationCallback,
            SubmissionApprovedNotification,
            SubmissionEscalatedNotification,
            SubmissionRejectedNotification,
        )
        from apps.core.state_machine.registry import register_callback

        from .models import (
            BulkOperation,
            EditSubmission,
            ModerationQueue,
            ModerationReport,
            PhotoSubmission,
        )

        # EditSubmission callbacks (transitions from CLAIMED state)
        register_callback(EditSubmission, "status", "CLAIMED", "APPROVED", SubmissionApprovedNotification())
        register_callback(EditSubmission, "status", "CLAIMED", "APPROVED", ModerationCacheInvalidation())
        register_callback(EditSubmission, "status", "CLAIMED", "REJECTED", SubmissionRejectedNotification())
        register_callback(EditSubmission, "status", "CLAIMED", "REJECTED", ModerationCacheInvalidation())
        register_callback(EditSubmission, "status", "CLAIMED", "ESCALATED", SubmissionEscalatedNotification())
        register_callback(EditSubmission, "status", "CLAIMED", "ESCALATED", ModerationCacheInvalidation())

        # PhotoSubmission callbacks (transitions from CLAIMED state)
        register_callback(PhotoSubmission, "status", "CLAIMED", "APPROVED", SubmissionApprovedNotification())
        register_callback(PhotoSubmission, "status", "CLAIMED", "APPROVED", ModerationCacheInvalidation())
        register_callback(PhotoSubmission, "status", "CLAIMED", "REJECTED", SubmissionRejectedNotification())
        register_callback(PhotoSubmission, "status", "CLAIMED", "REJECTED", ModerationCacheInvalidation())
        register_callback(PhotoSubmission, "status", "CLAIMED", "ESCALATED", SubmissionEscalatedNotification())

        # ModerationReport callbacks
        register_callback(ModerationReport, "status", "*", "*", ModerationNotificationCallback())
        register_callback(ModerationReport, "status", "*", "*", ModerationCacheInvalidation())

        # ModerationQueue callbacks
        register_callback(ModerationQueue, "status", "*", "*", ModerationNotificationCallback())
        register_callback(ModerationQueue, "status", "*", "*", ModerationCacheInvalidation())

        # BulkOperation callbacks
        register_callback(BulkOperation, "status", "*", "*", ModerationNotificationCallback())
        register_callback(BulkOperation, "status", "*", "*", ModerationCacheInvalidation())

        logger.debug("Registered moderation transition callbacks")

    def _register_signal_handlers(self):
        """Register signal handlers for moderation transitions."""
        from .signals import register_moderation_signal_handlers

        try:
            register_moderation_signal_handlers()
            logger.debug("Registered moderation signal handlers")
        except Exception as e:
            logger.warning(f"Could not register moderation signal handlers: {e}")
