"""
i18n.py — Translations for Powernet.

Translations live in  src/assets/lang/{code}.json.
Adding a new language is as simple as dropping a new JSON file there
and adding an entry to LANGUAGES below.

Usage
-----
::

    from helpers.i18n import t, set_language, LANGUAGES

    set_language("de")
    print(t("play"))   # → "SPIELEN"

    # Template strings (use Python .format-style keys)
    print(t("now_playing", track="Candy"))   # → "Läuft:  Candy"
"""

from __future__ import annotations

import json
from pathlib import Path

_LANG_DIR = Path(__file__).parent.parent / "assets" / "lang"

LANGUAGES: dict[str, str] = {
    "en": "English",
    "de": "Deutsch",
    "nl": "Nederlands",
    "fr": "Français",
}

# Cache: language code → loaded dict
_cache: dict[str, dict[str, str]] = {}


def _load(code: str) -> dict[str, str]:
    """Load and cache the JSON file for *code*. Falls back to empty dict."""
    if code in _cache:
        return _cache[code]
    path = _LANG_DIR / f"{code}.json"
    try:
        with open(path, encoding="utf-8") as fh:
            data: dict[str, str] = json.load(fh)
    except Exception:
        data = {}
    _cache[code] = data
    return data


def _reload_all() -> None:
    """Flush the in-memory cache (used after editing language files at runtime)."""
    _cache.clear()


_lang = "en"


def set_language(code: str) -> None:
    global _lang
    if code in LANGUAGES:
        _lang = code


def get_language() -> str:
    return _lang


def t(key: str, **kwargs: str) -> str:
    """Return the translation for *key*, applying **kwargs format substitutions."""
    s = _load(_lang).get(key) or _load("en").get(key, key)
    if kwargs:
        try:
            s = s.format(**kwargs)
        except (KeyError, IndexError):
            pass
    return s
