from __future__ import annotations

import json
from pathlib import Path

from .i18n import detect_language, is_supported_locale, normalize_language

UI_LANGUAGE_STATE_KEY = "ui_language"


def default_ui_language_cache_path() -> Path:
    return Path.home() / ".config" / "iuve-connect-agent" / "desktop-state.json"


def load_cached_ui_language(path: str | Path | None = None) -> str | None:
    state_path = Path(path).expanduser() if path else default_ui_language_cache_path()
    if not state_path.is_file():
        return None
    try:
        data = json.loads(state_path.read_text(encoding="utf-8"))
    except Exception:
        return None
    if not isinstance(data, dict):
        return None
    raw = str(data.get(UI_LANGUAGE_STATE_KEY) or "").strip()
    if not raw or not is_supported_locale(raw):
        return None
    return normalize_language(raw)


def save_cached_ui_language(lang: str, path: str | Path | None = None) -> None:
    code = normalize_language(lang)
    if not is_supported_locale(code):
        return
    state_path = Path(path).expanduser() if path else default_ui_language_cache_path()
    state_path.parent.mkdir(parents=True, exist_ok=True)
    data: dict[str, object] = {}
    if state_path.is_file():
        try:
            loaded = json.loads(state_path.read_text(encoding="utf-8"))
            if isinstance(loaded, dict):
                data = loaded
        except Exception:
            data = {}
    data[UI_LANGUAGE_STATE_KEY] = code
    state_path.write_text(json.dumps(data, ensure_ascii=True, indent=2, sort_keys=True), encoding="utf-8")


def extract_profile_interface_language(profile: dict[str, object] | None) -> str | None:
    if not isinstance(profile, dict):
        return None
    raw = str(profile.get("interface_language") or "").strip()
    if not raw or not is_supported_locale(raw):
        return None
    return normalize_language(raw)


def resolve_ui_language(
    *,
    profile_lang: str | None,
    cached_lang: str | None,
    env_override: str | None = None,
) -> str:
    env_lang = normalize_language(str(env_override or "").strip()) if env_override else ""
    if env_lang and is_supported_locale(env_lang):
        return env_lang
    if profile_lang and is_supported_locale(profile_lang):
        return normalize_language(profile_lang)
    if cached_lang and is_supported_locale(cached_lang):
        return normalize_language(cached_lang)
    return detect_language()
