from django.apps import AppConfig


class ServicesConfig(AppConfig):
    default_auto_field = "django.db.models.BigAutoField"
    name = "services"

    def ready(self) -> None:
        """
        Load the country snapshot into memory at Django startup.

        This runs once per process:
          - gunicorn pre-fork:  master process loads, workers inherit via fork.
          - gunicorn post-fork: each worker calls ready() independently.
          - Kubernetes replicas: each pod loads independently from the same DB.

        Failure policy
        --------------
        We distinguish two categories of startup failure:

        1. MIGRATION STATE (table does not exist yet):
           django.db.OperationalError / ProgrammingError are caught and
           silently ignored.  The snapshot will NOT be loaded, and any
           attempt to call resolve_istat_country_code() before the table
           exists will raise SnapshotNotLoadedError — which is the correct
           behavior during `manage.py migrate`.

        2. ALL OTHER FAILURES (DB reachable, table exists, data invalid):
           RuntimeError from _validate_snapshot() is NOT caught here.
           The process will fail to start with a clear error message.
           This is intentional — a partially-initialized country reference
           is a fatal misconfiguration, not a recoverable runtime error.

        Multi-worker safety
        -------------------
        The snapshot is loaded per process.  No shared memory is assumed
        across nodes or Kubernetes replicas.  Each worker/pod loads
        independently from the same DB at startup.
        """
        # Import DB exception classes explicitly — never catch by name string.
        from django.db import OperationalError, ProgrammingError

        try:
            from services.country_snapshot import load_country_snapshot
            load_country_snapshot()
        except (OperationalError, ProgrammingError):
            # Table does not exist yet — expected during `manage.py migrate`.
            # Snapshot will be absent; SnapshotNotLoadedError will fire on
            # first use if resolve_istat_country_code() is called before the
            # table exists.
            return
        # RuntimeError from _validate_snapshot(), ImportError, or any other
        # unexpected failure propagates immediately — fail-fast is intentional.
