import logging

from django.apps import AppConfig

logger = logging.getLogger(__name__)


class ParksConfig(AppConfig):
    default_auto_field = "django.db.models.BigAutoField"
    name = "apps.parks"

    def ready(self):
        import apps.parks.choices  # noqa: F401 - Register choices
        import apps.parks.signals  # noqa: F401 - Register signals

        self._apply_state_machines()
        self._register_callbacks()

    def _apply_state_machines(self):
        """Apply FSM to park models."""
        from apps.core.state_machine import apply_state_machine
        from apps.parks.models import Park

        # Register FSM transitions for Park
        apply_state_machine(Park, field_name="status", choice_group="statuses", domain="parks")

    def _register_callbacks(self):
        """Register FSM transition callbacks for park models."""
        from apps.core.state_machine.callbacks.cache import (
            APICacheInvalidation,
            ParkCacheInvalidation,
        )
        from apps.core.state_machine.callbacks.notifications import (
            StatusChangeNotification,
        )
        from apps.core.state_machine.callbacks.related_updates import (
            SearchTextUpdateCallback,
        )
        from apps.core.state_machine.registry import register_callback
        from apps.parks.models import Park

        # Cache invalidation for all park status changes
        register_callback(Park, "status", "*", "*", ParkCacheInvalidation())

        # API cache invalidation
        register_callback(Park, "status", "*", "*", APICacheInvalidation(include_geo_cache=True))

        # Search text update
        register_callback(Park, "status", "*", "*", SearchTextUpdateCallback())

        # Notification for significant status changes
        register_callback(Park, "status", "*", "CLOSED_PERM", StatusChangeNotification(notify_admins=True))
        register_callback(Park, "status", "*", "DEMOLISHED", StatusChangeNotification(notify_admins=True))

        logger.debug("Registered park transition callbacks")
