"""Localized UI text loader for the warehouse desktop application."""

from __future__ import annotations

import json
from functools import lru_cache
from pathlib import Path

from version_info import module_version

__version__ = module_version(__name__)

_LOCALE_FILE = Path(__file__).with_name("locale.json")


@lru_cache(maxsize=1)
def load_locale_catalog() -> dict:
    """Load the locale catalog from JSON, returning a safe default on errors."""

    try:
        return json.loads(_LOCALE_FILE.read_text(encoding="utf-8"))
    except Exception:
        return {"default_language": "IT", "IT": {}, "ENG": {}}


def reload_locale_catalog() -> dict:
    """Clear the locale cache and reload the catalog from disk."""

    load_locale_catalog.cache_clear()
    return load_locale_catalog()


def text(key: str, *, language: str | None = None, catalog: dict | None = None, default: str = "") -> str:
    """Return the localized UI text for ``key`` with Italian fallback."""

    data = catalog or load_locale_catalog()
    lang = str(language or data.get("default_language") or "IT").upper()
    texts = data.get(lang, {}) or {}
    if key in texts:
        return str(texts[key])
    fallback = data.get("IT", {}) or {}
    if key in fallback:
        return str(fallback[key])
    return str(default)
