import os
import json
from qgis.PyQt.QtCore import QSettings

_translations = {}
_current_language = "en"

def _detect_qgis_language():
    """Read QGIS locale and return a 2-letter language code."""
    settings = QSettings()
    locale = settings.value("locale/userLocale", "en", type=str)
    return locale[:2].lower()  # e.g. "pl_PL" -> "pl"

def load_language(lang_code=None):
    """
    Load a translation file. Call this once at plugin startup.
    lang_code: "pl", "en", etc. Pass None to auto-detect from QGIS locale.
    """
    global _translations, _current_language

    if lang_code is None or lang_code == "auto":
        lang_code = _detect_qgis_language()

    _current_language = lang_code

    if lang_code == "en":
        _translations = {}
        return

    package_dir = os.path.dirname(__file__)
    translations_dir = os.path.join(package_dir, "translations")
    candidates = [
        os.path.join(translations_dir, f"{lang_code}.json"),
        os.path.join(os.path.dirname(package_dir), f"{lang_code}.json"),
    ]

    json_path = next((path for path in candidates if os.path.isfile(path)), None)
    if json_path is None:
        _translations = {}  # fallback to English silently
        return

    with open(json_path, "r", encoding="utf-8") as f:
        _translations = json.load(f)

def get_language():
    """Return the currently active language code."""
    return _current_language

def get_available_languages():
    """
    Return list of available language codes based on JSON files in translations/.
    Always includes 'en'. Example return: ['en', 'pl']
    """
    package_dir = os.path.dirname(__file__)
    translations_dir = os.path.join(package_dir, "translations")
    langs = ["en"]
    if os.path.isdir(translations_dir):
        for f in os.listdir(translations_dir):
            if f.endswith(".json"):
                code = f[:-5]
                if code != "en":
                    langs.append(code)
    root_dir = os.path.dirname(package_dir)
    if os.path.isdir(root_dir):
        for f in os.listdir(root_dir):
            if f.endswith(".json"):
                code = f[:-5]
                if code not in langs and code != "en":
                    langs.append(code)
    return sorted(langs)

def tr(text):
    """
    Translate a string. Returns the Polish (or other active language) version,
    or the original English text if no translation is found.
    """
    if not text:
        return text
    return _translations.get(text, text)
