import importlib
from django.conf import settings

def load_translations(lang, file):
    """
    Load translation dictionary from lang/{lang}/{file}.py
    """
    try:
        module_path = f"backend.lang.{lang}.{file}"
        module = importlib.import_module(module_path)
        return getattr(module, "translations", {})
    except ModuleNotFoundError:
        return {}

def __(key, **kwargs):
    lang = getattr(settings, "CURRENT_LANG", "en")

    if "." not in key:
        return key

    file, text_key = key.split(".", 1)
    translations = load_translations(lang, file)

    # Resolve nested dicts using dot notation
    def deep_get(dic, keys):
        for k in keys.split("."):
            if isinstance(dic, dict):
                dic = dic.get(k)
            else:
                return None
        return dic

    text = deep_get(translations, text_key)

    if text is None:
        return key

    # Replace placeholders
    for k, v in kwargs.items():
        text = text.replace(f":{k}", str(v))
    return text