import logging

from django.apps import AppConfig

logger = logging.getLogger(__name__)


class RidesConfig(AppConfig):
    default_auto_field = "django.db.models.BigAutoField"
    name = "apps.rides"

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

        self._apply_state_machines()
        self._register_callbacks()

    def _apply_state_machines(self):
        """Apply FSM to ride models."""
        from apps.core.state_machine import apply_state_machine
        from apps.rides.models import Ride

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

    def _register_callbacks(self):
        """Register FSM transition callbacks for ride models."""
        from apps.core.state_machine.callbacks.cache import (
            APICacheInvalidation,
            RideCacheInvalidation,
        )
        from apps.core.state_machine.callbacks.related_updates import (
            ParkCountUpdateCallback,
            SearchTextUpdateCallback,
        )
        from apps.core.state_machine.registry import register_callback
        from apps.rides.models import Ride

        # Cache invalidation for all ride status changes
        register_callback(Ride, "status", "*", "*", RideCacheInvalidation())

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

        # Park count updates for status changes that affect active rides
        register_callback(Ride, "status", "*", "OPERATING", ParkCountUpdateCallback())
        register_callback(Ride, "status", "OPERATING", "*", ParkCountUpdateCallback())
        register_callback(Ride, "status", "*", "CLOSED_PERM", ParkCountUpdateCallback())
        register_callback(Ride, "status", "*", "DEMOLISHED", ParkCountUpdateCallback())
        register_callback(Ride, "status", "*", "RELOCATED", ParkCountUpdateCallback())

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

        logger.debug("Registered ride transition callbacks")
