"""
UI translation strings.

Usage:
    from .i18n import get_translations, get_calc_item_names, SUPPORTED_LANGS

    t = get_translations("de")   # → dict[str, str]
    t["nav_planner"]             # → "Finanzplaner"
"""
import json
from pathlib import Path

SUPPORTED_LANGS = {"en", "de"}
LANG_BLUEPRINTS = {"public", "planner", "directory", "content", "leads", "suppliers"}

# 2-letter ISO country code → English name.
# Used by the directory, article templates, and get_country_name().
COUNTRY_LABELS: dict[str, str] = {
    "DE": "Germany",
    "ES": "Spain",
    "IT": "Italy",
    "FR": "France",
    "PT": "Portugal",
    "GB": "United Kingdom",
    "NL": "Netherlands",
    "BE": "Belgium",
    "SE": "Sweden",
    "DK": "Denmark",
    "FI": "Finland",
    "NO": "Norway",
    "AT": "Austria",
    "SI": "Slovenia",
    "IS": "Iceland",
    "CH": "Switzerland",
    "EE": "Estonia",
    "US": "United States",
    "CA": "Canada",
    "MX": "Mexico",
    "BR": "Brazil",
    "AR": "Argentina",
    "AE": "UAE",
    "SA": "Saudi Arabia",
    "TR": "Turkey",
    "CN": "China",
    "IN": "India",
    "SG": "Singapore",
    "ID": "Indonesia",
    "TH": "Thailand",
    "AU": "Australia",
    "ZA": "South Africa",
    "EG": "Egypt",
}

_LOCALES_DIR = Path(__file__).parent / "locales"


def _load_locale(filename: str) -> dict[str, str]:
    path = _LOCALES_DIR / filename
    assert path.is_file(), f"Missing locale file: {path}"
    data = json.loads(path.read_text(encoding="utf-8"))
    assert isinstance(data, dict), f"Locale file must be a flat JSON object: {path}"
    return data


_TRANSLATIONS: dict[str, dict[str, str]] = {
    lang: _load_locale(f"{lang}.json") for lang in SUPPORTED_LANGS
}
assert _TRANSLATIONS["en"].keys() == _TRANSLATIONS["de"].keys(), (
    "EN/DE key mismatch — "
    f"EN-only: {sorted(_TRANSLATIONS['en'].keys() - _TRANSLATIONS['de'].keys())}, "
    f"DE-only: {sorted(_TRANSLATIONS['de'].keys() - _TRANSLATIONS['en'].keys())}"
)


def get_translations(lang: str) -> dict[str, str]:
    """Return UI translation strings for the given language.

    Falls back to English for unsupported languages (should never happen
    in practice since we 404 unsupported langs in before_request).
    """
    assert lang in _TRANSLATIONS, f"Unknown lang: {lang!r}"
    return _TRANSLATIONS[lang]


# ── Calculator item names ─────────────────────────────────────────────────────
# Used in calculator.py calc(s, lang) to localise CAPEX/OPEX line item names.
# Kept inline (36 keys per lang) — different namespace from UI strings,
# used only by calculator.py, no benefit from externalising.

_CALC_ITEM_NAMES: dict[str, dict[str, str]] = {
    "en": {
        # CAPEX
        "padel_courts": "Padel Courts",
        "shipping": "Shipping",
        "hall_construction": "Hall Construction",
        "foundation": "Foundation",
        "land_purchase": "Land Purchase",
        "transaction_costs": "Transaction Costs",
        "hvac_system": "HVAC System",
        "electrical_lighting": "Electrical + Lighting",
        "sanitary_changing": "Sanitary / Changing",
        "parking_exterior": "Parking + Exterior",
        "planning_permits": "Planning + Permits",
        "fire_protection": "Fire Protection",
        "floor_preparation": "Floor Preparation",
        "hvac_upgrade": "HVAC Upgrade",
        "lighting_upgrade": "Lighting Upgrade",
        "fitout_reception": "Fit-Out & Reception",
        "permits_compliance": "Permits & Compliance",
        "concrete_foundation": "Concrete Foundation",
        "site_work": "Site Work",
        "outdoor_lighting": "Lighting",
        "fencing": "Fencing",
        "equipment": "Equipment",
        "working_capital": "Working Capital",
        "miscellaneous": "Miscellaneous",
        "contingency": "Contingency",
        # OPEX
        "rent": "Rent",
        "property_tax": "Property Tax",
        "insurance": "Insurance",
        "electricity": "Electricity",
        "heating": "Heating",
        "water": "Water",
        "maintenance": "Maintenance",
        "cleaning": "Cleaning",
        "marketing_misc": "Marketing / Software / Misc",
        "staff": "Staff",
    },
    "de": {
        # CAPEX
        "padel_courts": "Padelplätze",
        "shipping": "Transport & Lieferung",
        "hall_construction": "Hallenbau",
        "foundation": "Fundament",
        "land_purchase": "Grundstücks-kauf",
        "transaction_costs": "Erwerbsnebenkosten",
        "hvac_system": "Lüftung & Klimaanlage",
        "electrical_lighting": "Elektro + Beleuchtung",
        "sanitary_changing": "Sanitär / Umkleide",
        "parking_exterior": "Parkplatz + Außenanlage",
        "planning_permits": "Planung + Genehmigungen",
        "fire_protection": "Brandschutz",
        "floor_preparation": "Bodenvorbereitung",
        "hvac_upgrade": "Lüftungsausbau",
        "lighting_upgrade": "Beleuchtungsausbau",
        "fitout_reception": "Ausbau & Empfang",
        "permits_compliance": "Genehmigungen & Auflagen",
        "concrete_foundation": "Betonfundament",
        "site_work": "Erschließung",
        "outdoor_lighting": "Beleuchtung",
        "fencing": "Einzäunung",
        "equipment": "Ausstattung",
        "working_capital": "Betriebskapital",
        "miscellaneous": "Sonstiges",
        "contingency": "Reserve",
        # OPEX
        "rent": "Miete",
        "property_tax": "Grundsteuer",
        "insurance": "Versicherung",
        "electricity": "Strom",
        "heating": "Heizung",
        "water": "Wasser",
        "maintenance": "Wartung",
        "cleaning": "Reinigung",
        "marketing_misc": "Marketing / Software / Sonstiges",
        "staff": "Personal",
    },
}


def get_calc_item_names(lang: str) -> dict[str, str]:
    """Return CAPEX/OPEX item name translations for the given language.

    Used by calculator.py: calc(s, lang) looks up item names here.
    """
    assert lang in _CALC_ITEM_NAMES, f"Unknown lang: {lang!r}"
    return _CALC_ITEM_NAMES[lang]


# Reverse map: English country name → 2-letter code (e.g. "Germany" → "DE").
# Built once at load time from COUNTRY_LABELS.
_COUNTRY_CODE_BY_EN_NAME: dict[str, str] = {v: k for k, v in COUNTRY_LABELS.items()}


def get_country_name(country_str: str, lang: str) -> str:
    """Return the localised name for a country stored as a 2-letter code or English name.

    Handles both formats stored in the DB:
    - 2-letter ISO code: "CH" → "Schweiz" (de) / "Switzerland" (en)
    - English name: "Switzerland" → "Schweiz" (de)

    Falls back to the original string if not found in translations.
    Used as a Jinja filter: {{ article.country | country_name(lang) }}
    """
    if not country_str:
        return country_str
    effective_lang = lang if lang in _TRANSLATIONS else "en"
    # Accept both 2-letter code ("CH") and English name ("Switzerland")
    upper = country_str.upper()
    code = upper if upper in COUNTRY_LABELS else _COUNTRY_CODE_BY_EN_NAME.get(country_str, "")
    if not code:
        return country_str
    key = f"dir_country_{code}"
    return _TRANSLATIONS[effective_lang].get(key, country_str)
