"""Residence classification for future ISTAT XML payloads."""

from __future__ import annotations

from typing import TypedDict

from istat.xml_export.exceptions import XmlPayloadValidationError
from istat.xml_export.services.validators import (
    validate_country_mapping,
    validate_province_mapping,
)


class XmlResidence(TypedDict):
    """Resolved residence values required by the ISTAT XML export."""

    is_italian: bool
    country_code: str | None
    province_code: str | None
    region_code: str | None


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


def resolve_xml_residence(country: str | None, province: str | None = None) -> XmlResidence:
    """Resolve residence classification and ISTAT XML mapping codes.

    Italian residents are resolved through province mappings, which also carry
    the final XML region code. Foreign residents are resolved through country
    mappings only; any province value is intentionally ignored.
    """
    country_code = _normalize_code(country)

    if country_code == "IT":
        province_sigla = _normalize_code(province)
        if not province_sigla:
            raise XmlPayloadValidationError("Province is required for Italian residents")

        province_mapping = validate_province_mapping(province_sigla)
        return {
            "is_italian": True,
            "country_code": None,
            "province_code": province_mapping["province_code"],
            "region_code": province_mapping["region_code"],
        }

    country_mapping = validate_country_mapping(country_code)
    return {
        "is_italian": False,
        "country_code": country_mapping["istat_code"],
        "province_code": None,
        "region_code": None,
    }

