"""Lookup helpers for ISTAT XML export mappings."""

from __future__ import annotations

import logging

from istat.xml_export.mappings.countries import COUNTRY_MAPPINGS, FALLBACK_COUNTRY_MAPPING
from istat.xml_export.mappings.provinces import PROVINCE_MAPPINGS
from istat.xml_export.mappings.regions import REGION_MAPPINGS


logger = logging.getLogger(__name__)


class IstatLookupService:
    """Centralized read access to static ISTAT XML mappings."""

    @staticmethod
    def _normalize(value: str | None) -> str:
        return (value or "").strip().upper()

    @classmethod
    def get_province(cls, sigla: str | None) -> dict[str, str] | None:
        """Return XML province metadata for a province sigla, or None."""
        return PROVINCE_MAPPINGS.get(cls._normalize(sigla))

    @classmethod
    def get_country(cls, iso_code: str | None) -> dict[str, str] | None:
        """Return XML country metadata for an ISO-2 code, or None.

        Resolution order:
        1. Direct lookup in ``COUNTRY_MAPPINGS``.
        2. If not found, check ``FALLBACK_COUNTRY_MAPPING`` for a canonical
           ISO-2 alias, then resolve that alias against ``COUNTRY_MAPPINGS``.
        3. If still not found, return ``None`` so callers can raise a
           controlled error — unknown codes are never silently swallowed.

        When a fallback is used, a WARNING is emitted so the substitution is
        visible in production logs and auditable.
        """
        normalized = cls._normalize(iso_code)

        # 1. Primary lookup — fast path for the vast majority of codes.
        result = COUNTRY_MAPPINGS.get(normalized)
        if result is not None:
            return result

        # 2. Fallback lookup — handles territories / recently-split states.
        canonical = FALLBACK_COUNTRY_MAPPING.get(normalized)
        if canonical is not None:
            result = COUNTRY_MAPPINGS.get(canonical)
            if result is not None:
                logger.warning(
                    "ISTAT country fallback applied: '%s' resolved via '%s' → istat_code='%s'",
                    normalized,
                    canonical,
                    result.get("istat_code"),
                    extra={
                        "original_iso_code": normalized,
                        "fallback_iso_code": canonical,
                        "istat_code": result.get("istat_code"),
                    },
                )
                return result

        # 3. Truly unknown — return None; caller raises XmlPayloadValidationError.
        return None

    @classmethod
    def get_country_code(cls, iso_code: str | None) -> str | None:
        """Return the ISTAT XML country code for an ISO-2 code, or None."""
        country = cls.get_country(iso_code)
        return country["istat_code"] if country else None

    @classmethod
    def get_region(cls, cod_regione: str | None) -> dict[str, str] | None:
        """Return XML region metadata for an internal CODREGIONE, or None."""
        normalized = cls._normalize(cod_regione)
        if normalized.isdigit():
            normalized = normalized.zfill(2)
        return REGION_MAPPINGS.get(normalized)

    @classmethod
    def get_region_by_istat_code(cls, istat_region_code: str | None) -> dict[str, str] | None:
        """Return XML region metadata for a final ISTAT XML region code, or None."""
        normalized = cls._normalize(istat_region_code)
        return next(
            (
                region
                for region in REGION_MAPPINGS.values()
                if region["istat_region_code"] == normalized
            ),
            None,
        )
