"""
Switch Downgrader — Internationalization (i18n) module.
Simple JSON-based translation system.
"""
import json
import os
import locale

_translations = {}
_current_lang = "en"
_fallback_lang = "en"


def get_locales_path():
    """Get the path to the locales directory."""
    import sys
    if getattr(sys, 'frozen', False):
        # PyInstaller bundles data into _MEIPASS (_internal/)
        base = getattr(sys, '_MEIPASS', os.path.dirname(sys.executable))
    else:
        base = os.path.dirname(os.path.dirname(os.path.abspath(__file__)))
    return os.path.join(base, "locales")


def get_available_languages():
    """Return a dict of {code: display_name} for available languages."""
    locales_dir = get_locales_path()
    langs = {}
    if not os.path.isdir(locales_dir):
        return {"en": "English"}
    for f in os.listdir(locales_dir):
        if f.endswith(".json"):
            code = f[:-5]
            try:
                with open(os.path.join(locales_dir, f), "r", encoding="utf-8") as fh:
                    data = json.load(fh)
                    langs[code] = data.get("_language_name", code.upper())
            except Exception:
                langs[code] = code.upper()
    return langs if langs else {"en": "English"}


def load_language(lang_code):
    """Load a language file. Falls back to English if not found."""
    global _translations, _current_lang
    locales_dir = get_locales_path()
    filepath = os.path.join(locales_dir, f"{lang_code}.json")

    if not os.path.exists(filepath):
        filepath = os.path.join(locales_dir, f"{_fallback_lang}.json")
        lang_code = _fallback_lang

    try:
        with open(filepath, "r", encoding="utf-8") as f:
            _translations = json.load(f)
        _current_lang = lang_code
    except Exception:
        _translations = {}
        _current_lang = "en"


def get_current_language():
    """Return the current language code."""
    return _current_lang


def detect_system_language():
    """Detect the system language and return a supported language code."""
    try:
        sys_lang = locale.getdefaultlocale()[0] or ""
        if sys_lang.startswith("es"):
            return "es"
    except Exception:
        pass
    return "en"


def t(key, **kwargs):
    """
    Get a translated string by key. Supports nested keys with dots.
    Example: t("ui.title") → looks up _translations["ui"]["title"]
    Supports {variable} substitution via kwargs.
    Falls back to the key itself if not found.
    """
    parts = key.split(".")
    value = _translations
    for part in parts:
        if isinstance(value, dict):
            value = value.get(part)
        else:
            return key
    if value is None:
        return key
    if isinstance(value, str) and kwargs:
        try:
            return value.format(**kwargs)
        except (KeyError, ValueError):
            return value
    return value if isinstance(value, str) else key
