"""Data region resolution from Paddle billing address country code.

Maps ISO 3166-1 alpha-2 country codes to ComplyForm data regions
(``us``, ``eu``, ``me``), respecting the tier's ``available_regions``.
"""

from __future__ import annotations

_EU_EEA_COUNTRIES: frozenset[str] = frozenset(
    [
        "AT",
        "BE",
        "BG",
        "HR",
        "CY",
        "CZ",
        "DK",
        "EE",
        "FI",
        "FR",
        "DE",
        "GR",
        "HU",
        "IE",
        "IT",
        "LV",
        "LT",
        "LU",
        "MT",
        "NL",
        "PL",
        "PT",
        "RO",
        "SK",
        "SI",
        "ES",
        "SE",
        # EEA (non-EU)
        "IS",
        "LI",
        "NO",
    ]
)

_ME_COUNTRIES: frozenset[str] = frozenset(
    [
        "SA",
        "AE",
        "QA",
        "KW",
        "OM",
        "BH",
    ]
)


def resolve_data_region(
    country_code: str | None,
    available_regions: list[str],
) -> str:
    """Resolve customer data region from Paddle billing address country code.

    Args:
        country_code: ISO 3166-1 alpha-2 (from Paddle transaction address.country_code)
        available_regions: Regions available for this tier (from TIER_CONFIG)

    Returns:
        ``"us"``, ``"eu"``, or ``"me"`` — always returns a valid region
        from *available_regions*.
    """
    if country_code is None:
        return "us"

    upper = country_code.upper()

    if upper in _EU_EEA_COUNTRIES:
        return "eu" if "eu" in available_regions else "us"

    if upper in _ME_COUNTRIES:
        return "me" if "me" in available_regions else "us"

    return "us"
