"""Simple i18n for backend user-facing messages.

Loads JSON locale files. System prompts to the LLM stay in English —
only user-visible messages (channel responses, errors, notifications) are translated.
"""

from __future__ import annotations

import json
import logging
from pathlib import Path

log = logging.getLogger(__name__)

_LOCALES_DIR = Path(__file__).parent.parent / "locales"
_TRANSLATIONS: dict[str, dict[str, str]] = {}
_CURRENT_LOCALE = "en"


def _load_locale(code: str) -> dict[str, str]:
    """Load a locale JSON file. Returns flat key→value mapping."""
    path = _LOCALES_DIR / f"{code}.json"
    if not path.exists():
        return {}
    try:
        with open(path, encoding="utf-8") as f:
            data = json.load(f)
        # Flatten nested keys: {"pairing": {"code_msg": "..."}} → "pairing.code_msg"
        flat: dict[str, str] = {}
        def _flatten(obj: dict, prefix: str = "") -> None:
            for k, v in obj.items():
                key = f"{prefix}.{k}" if prefix else k
                if isinstance(v, dict):
                    _flatten(v, key)
                else:
                    flat[key] = str(v)
        _flatten(data)
        return flat
    except Exception as e:
        log.warning("Failed to load locale %s: %s", code, e)
        return {}


def init(locale: str = "en") -> None:
    """Initialize i18n with the given locale."""
    global _CURRENT_LOCALE
    _CURRENT_LOCALE = locale
    # Always load English as fallback
    if "en" not in _TRANSLATIONS:
        _TRANSLATIONS["en"] = _load_locale("en")
    if locale != "en" and locale not in _TRANSLATIONS:
        _TRANSLATIONS[locale] = _load_locale(locale)


def set_locale(locale: str) -> None:
    """Change the active locale."""
    global _CURRENT_LOCALE
    _CURRENT_LOCALE = locale
    if locale not in _TRANSLATIONS:
        _TRANSLATIONS[locale] = _load_locale(locale)


def get_locale() -> str:
    """Return the active locale code (e.g. ``"en"``, ``"sv"``)."""
    return _CURRENT_LOCALE


def t(key: str, **kwargs: str) -> str:
    """Translate a key. Falls back to English, then to the key itself.

    Supports simple interpolation: t("pairing.code_msg", code="ABC123")
    """
    # Try current locale
    translations = _TRANSLATIONS.get(_CURRENT_LOCALE, {})
    value = translations.get(key)

    # Fall back to English
    if value is None and _CURRENT_LOCALE != "en":
        value = _TRANSLATIONS.get("en", {}).get(key)

    # Fall back to key
    if value is None:
        return key

    # Interpolate
    if kwargs:
        try:
            return value.format(**kwargs)
        except (KeyError, IndexError):
            return value

    return value
