"""
Lightweight localization for the Mac menu-bar strings.

The menu is the one place the desktop wrapper shows user-facing text, so it gets a tiny
self-contained i18n table (no gettext / string catalog — this is a handful of labels). The
language is resolved once from the macOS user's preferred languages and mapped to one of the
app's 9 shipping locales, English fallback. Only the *visible menu item labels* + inline
status words are translated; modal alert dialogs and relative timestamps stay English for now.

Usage:
    from . import menu_i18n as i18n
    i18n.t("restart_bridge")                     # → localized label
    i18n.t("connected_devices", n=2)             # → "2 connected devices" (localized)
"""
from __future__ import annotations

# The app's 9 shipping locales (menu mirrors them). English is the fallback.
_LOCALES = ["en", "ru", "es", "de", "fr", "pt-BR", "zh-Hans", "ja", "ko"]

# Native display names for the language picker.
_LANG_NAMES = {
    "en": "English", "ru": "Русский", "es": "Español", "de": "Deutsch", "fr": "Français",
    "pt-BR": "Português (BR)", "zh-Hans": "简体中文", "ja": "日本語", "ko": "한국어",
}

# Persisted menu-language override (NSUserDefaults). "system" (or absent) = auto-detect.
_OVERRIDE_KEY = "terminull_menu_language"
SYSTEM = "system"


def _defaults():
    try:
        from Foundation import NSUserDefaults
        return NSUserDefaults.standardUserDefaults()
    except Exception:
        return None


def get_override() -> str:
    """The user's saved menu-language choice, or SYSTEM when unset/auto."""
    d = _defaults()
    if d is not None:
        val = d.stringForKey_(_OVERRIDE_KEY)
        if val and str(val) in _LOCALES:
            return str(val)
    return SYSTEM


def set_override(code: str) -> None:
    """Persist the menu-language choice. `code` in _LOCALES pins a language; SYSTEM clears it."""
    d = _defaults()
    if d is None:
        return
    if code == SYSTEM or code not in _LOCALES:
        d.removeObjectForKey_(_OVERRIDE_KEY)
    else:
        d.setObject_forKey_(code, _OVERRIDE_KEY)


def _map_pref(pref: str) -> str | None:
    """Map a system language tag (e.g. 'pt-BR', 'zh-Hans-CN') → one of _LOCALES, or None."""
    pref = (pref or "").replace("_", "-").lower()
    if not pref:
        return None
    if pref.startswith("pt"):
        return "pt-BR"
    if pref.startswith("zh"):
        return "zh-Hans"
    for code in ("ru", "es", "de", "fr", "ja", "ko", "en"):
        if pref.startswith(code):
            return code
    return None


def _system_locale() -> str:
    """macOS preferred language → one of _LOCALES (English fallback)."""
    try:
        from Foundation import NSLocale
        for lang in (NSLocale.preferredLanguages() or []):
            code = _map_pref(str(lang))
            if code:
                return code
    except Exception:
        pass
    import os
    return _map_pref(os.environ.get("LANG", "") or os.environ.get("LC_ALL", "")) or "en"


def current_locale() -> str:
    """Resolved menu locale: the saved override if any, else the system language, English fallback."""
    ov = get_override()
    if ov != SYSTEM:
        return ov
    return _system_locale()


def language_display_name(code: str) -> str:
    return _LANG_NAMES.get(code, code)


def available_languages() -> list[str]:
    """Codes to offer in the picker: the user's macOS languages that we support (in order),
    always including English as the universal secondary choice."""
    out: list[str] = []
    try:
        from Foundation import NSLocale
        for lang in (NSLocale.preferredLanguages() or []):
            code = _map_pref(str(lang))
            if code and code not in out:
                out.append(code)
    except Exception:
        pass
    if "en" not in out:
        out.append("en")            # English always selectable (universal fallback)
    if not out:
        out = ["en"]
    return out


# key → { locale → text }.  `{n}` / `{pct}` / `{v}` / `{model}` are .format() slots.
_STRINGS: dict[str, dict[str, str]] = {
    # ── Section: app / maintenance submenu ──────────────────────────────────
    "app_menu":        {"en": "Terminull {v}", "ru": "Terminull {v}", "es": "Terminull {v}",
                         "de": "Terminull {v}", "fr": "Terminull {v}", "pt-BR": "Terminull {v}",
                         "zh-Hans": "Terminull {v}", "ja": "Terminull {v}", "ko": "Terminull {v}"},
    "view_logs":       {"en": "View Logs", "ru": "Показать логи", "es": "Ver registros",
                         "de": "Protokolle anzeigen", "fr": "Voir les journaux", "pt-BR": "Ver registros",
                         "zh-Hans": "查看日志", "ja": "ログを表示", "ko": "로그 보기"},
    "restart_bridge":  {"en": "Restart Bridge", "ru": "Перезапустить службу", "es": "Reiniciar el puente",
                         "de": "Bridge neu starten", "fr": "Redémarrer le pont", "pt-BR": "Reiniciar a ponte",
                         "zh-Hans": "重启桥接服务", "ja": "ブリッジを再起動", "ko": "브리지 재시작"},
    "check_updates":   {"en": "Check for Updates…", "ru": "Проверить обновления…", "es": "Buscar actualizaciones…",
                         "de": "Nach Updates suchen…", "fr": "Rechercher des mises à jour…", "pt-BR": "Verificar atualizações…",
                         "zh-Hans": "检查更新…", "ja": "アップデートを確認…", "ko": "업데이트 확인…"},
    "checking":        {"en": "Checking…", "ru": "Проверка…", "es": "Comprobando…", "de": "Prüfe…", "fr": "Vérification…",
                        "pt-BR": "Verificando…", "zh-Hans": "检查中…", "ja": "確認中…", "ko": "확인 중…"},
    "update_to":       {"en": "↓  Update to {v}", "ru": "↓  Обновить до {v}", "es": "↓  Actualizar a {v}",
                         "de": "↓  Aktualisieren auf {v}", "fr": "↓  Mettre à jour vers {v}", "pt-BR": "↓  Atualizar para {v}",
                         "zh-Hans": "↓  更新到 {v}", "ja": "↓  {v} に更新", "ko": "↓  {v}(으)로 업데이트"},
    # ── Status header lines ─────────────────────────────────────────────────
    "connected_devices": {"en": "● {n} connected devices", "ru": "● {n} подключённых устройств",
                          "es": "● {n} dispositivos conectados", "de": "● {n} verbundene Geräte",
                          "fr": "● {n} appareils connectés", "pt-BR": "● {n} dispositivos conectados",
                          "zh-Hans": "● 已连接 {n} 台设备", "ja": "● 接続中のデバイス {n} 台", "ko": "● 연결된 기기 {n}대"},
    "connected_device_one": {"en": "● 1 connected device", "ru": "● 1 подключённое устройство",
                          "es": "● 1 dispositivo conectado", "de": "● 1 verbundenes Gerät",
                          "fr": "● 1 appareil connecté", "pt-BR": "● 1 dispositivo conectado",
                          "zh-Hans": "● 已连接 1 台设备", "ja": "● 接続中のデバイス 1 台", "ko": "● 연결된 기기 1대"},
    "no_devices":      {"en": "No devices connected", "ru": "Нет подключённых устройств",
                        "es": "Ningún dispositivo conectado", "de": "Keine Geräte verbunden",
                        "fr": "Aucun appareil connecté", "pt-BR": "Nenhum dispositivo conectado",
                        "zh-Hans": "没有已连接的设备", "ja": "接続中のデバイスなし", "ko": "연결된 기기 없음"},
    "active_sessions": {"en": "   {n} active sessions", "ru": "   {n} активных сессий",
                        "es": "   {n} sesiones activas", "de": "   {n} aktive Sitzungen",
                        "fr": "   {n} sessions actives", "pt-BR": "   {n} sessões ativas",
                        "zh-Hans": "   {n} 个活动会话", "ja": "   アクティブなセッション {n} 件", "ko": "   활성 세션 {n}개"},
    "active_session_one": {"en": "   1 active session", "ru": "   1 активная сессия",
                        "es": "   1 sesión activa", "de": "   1 aktive Sitzung",
                        "fr": "   1 session active", "pt-BR": "   1 sessão ativa",
                        "zh-Hans": "   1 个活动会话", "ja": "   アクティブなセッション 1 件", "ko": "   활성 세션 1개"},
    "no_sessions":     {"en": "   No active sessions", "ru": "   Нет активных сессий",
                        "es": "   Ninguna sesión activa", "de": "   Keine aktiven Sitzungen",
                        "fr": "   Aucune session active", "pt-BR": "   Nenhuma sessão ativa",
                        "zh-Hans": "   没有活动会话", "ja": "   アクティブなセッションなし", "ko": "   활성 세션 없음"},
    "relay_connected": {"en": "Relay: connected", "ru": "Реле: подключено", "es": "Relé: conectado",
                        "de": "Relay: verbunden", "fr": "Relais : connecté", "pt-BR": "Relay: conectado",
                        "zh-Hans": "中继：已连接", "ja": "リレー：接続済み", "ko": "릴레이: 연결됨"},
    "relay_disconnected": {"en": "Relay: disconnected", "ru": "Реле: отключено", "es": "Relé: desconectado",
                        "de": "Relay: getrennt", "fr": "Relais : déconnecté", "pt-BR": "Relay: desconectado",
                        "zh-Hans": "中继：已断开", "ja": "リレー：切断", "ko": "릴레이: 연결 끊김"},
    "relay_off":       {"en": "Relay: off (LAN-only)", "ru": "Реле: выкл (только LAN)", "es": "Relé: apagado (solo LAN)",
                        "de": "Relay: aus (nur LAN)", "fr": "Relais : désactivé (LAN seul)", "pt-BR": "Relay: desligado (só LAN)",
                        "zh-Hans": "中继：关闭（仅局域网）", "ja": "リレー：オフ（LANのみ）", "ko": "릴레이: 꺼짐 (LAN 전용)"},
    "relay_connecting": {"en": "Relay: connecting…", "ru": "Реле: подключение…", "es": "Relé: conectando…",
                        "de": "Relay: verbinde…", "fr": "Relais : connexion…", "pt-BR": "Relay: conectando…",
                        "zh-Hans": "中继：连接中…", "ja": "リレー：接続中…", "ko": "릴레이: 연결 중…"},
    "detecting_agents": {"en": "Detecting agents…", "ru": "Поиск агентов…", "es": "Detectando agentes…",
                        "de": "Suche Agenten…", "fr": "Détection des agents…", "pt-BR": "Detectando agentes…",
                        "zh-Hans": "正在检测代理…", "ja": "エージェントを検出中…", "ko": "에이전트 감지 중…"},
    "no_agents":       {"en": "No agents detected", "ru": "Агенты не найдены", "es": "No se detectaron agentes",
                        "de": "Keine Agenten gefunden", "fr": "Aucun agent détecté", "pt-BR": "Nenhum agente detectado",
                        "zh-Hans": "未检测到代理", "ja": "エージェントが見つかりません", "ko": "에이전트를 찾을 수 없음"},
    # ── Sections + toggles ──────────────────────────────────────────────────
    "agents":          {"en": "Agents", "ru": "Агенты", "es": "Agentes", "de": "Agenten", "fr": "Agents",
                        "pt-BR": "Agentes", "zh-Hans": "代理", "ja": "エージェント", "ko": "에이전트"},
    "add_device_qr":   {"en": "＋ Add device by QR (pairing)", "ru": "＋ Добавить устройство по QR (сопряжение)",
                        "es": "＋ Añadir dispositivo por QR (emparejar)", "de": "＋ Gerät per QR hinzufügen (koppeln)",
                        "fr": "＋ Ajouter un appareil par QR (association)", "pt-BR": "＋ Adicionar dispositivo por QR (pareamento)",
                        "zh-Hans": "＋ 通过二维码添加设备（配对）", "ja": "＋ QRでデバイスを追加（ペアリング）", "ko": "＋ QR로 기기 추가 (페어링)"},
    "paired_devices":  {"en": "Paired Devices", "ru": "Сопряжённые устройства", "es": "Dispositivos emparejados",
                        "de": "Gekoppelte Geräte", "fr": "Appareils associés", "pt-BR": "Dispositivos pareados",
                        "zh-Hans": "已配对设备", "ja": "ペアリング済みデバイス", "ko": "페어링된 기기"},
    "no_paired_devices": {"en": "No paired devices", "ru": "Нет сопряжённых устройств", "es": "Sin dispositivos emparejados",
                        "de": "Keine gekoppelten Geräte", "fr": "Aucun appareil associé", "pt-BR": "Nenhum dispositivo pareado",
                        "zh-Hans": "没有已配对的设备", "ja": "ペアリング済みデバイスなし", "ko": "페어링된 기기 없음"},
    "drop_device":     {"en": "Drop This Device", "ru": "Отключить это устройство", "es": "Eliminar este dispositivo",
                        "de": "Dieses Gerät entfernen", "fr": "Supprimer cet appareil", "pt-BR": "Remover este dispositivo",
                        "zh-Hans": "移除此设备", "ja": "このデバイスを削除", "ko": "이 기기 해제"},
    "last_used":       {"en": "Last used: {when}", "ru": "Последнее использование: {when}", "es": "Último uso: {when}",
                        "de": "Zuletzt verwendet: {when}", "fr": "Dernière utilisation : {when}", "pt-BR": "Último uso: {when}",
                        "zh-Hans": "上次使用：{when}", "ja": "最終使用：{when}", "ko": "마지막 사용: {when}"},
    "voice_ai_models": {"en": "Voice & AI Models", "ru": "Голос и ИИ-модели", "es": "Voz y modelos de IA",
                        "de": "Sprache & KI-Modelle", "fr": "Voix et modèles IA", "pt-BR": "Voz e modelos de IA",
                        "zh-Hans": "语音与 AI 模型", "ja": "音声とAIモデル", "ko": "음성 및 AI 모델"},
    "voice_transcription": {"en": "Voice Transcription (Whisper)", "ru": "Голосовой ввод (Whisper)",
                        "es": "Transcripción de voz (Whisper)", "de": "Sprachtranskription (Whisper)",
                        "fr": "Transcription vocale (Whisper)", "pt-BR": "Transcrição de voz (Whisper)",
                        "zh-Hans": "语音转写（Whisper）", "ja": "音声文字起こし（Whisper）", "ko": "음성 전사 (Whisper)"},
    "ai_summaries":    {"en": "AI Summaries & Titles", "ru": "ИИ-сводки и заголовки", "es": "Resúmenes y títulos con IA",
                        "de": "KI-Zusammenfassungen & Titel", "fr": "Résumés et titres IA", "pt-BR": "Resumos e títulos por IA",
                        "zh-Hans": "AI 摘要与标题", "ja": "AI要約とタイトル", "ko": "AI 요약 및 제목"},
    "model_label":     {"en": "Model: {model}", "ru": "Модель: {model}", "es": "Modelo: {model}",
                        "de": "Modell: {model}", "fr": "Modèle : {model}", "pt-BR": "Modelo: {model}",
                        "zh-Hans": "模型：{model}", "ja": "モデル：{model}", "ko": "모델: {model}"},
    "start_at_login":  {"en": "Start at Login", "ru": "Запуск при входе", "es": "Iniciar al iniciar sesión",
                        "de": "Beim Anmelden starten", "fr": "Lancer à l’ouverture de session", "pt-BR": "Iniciar ao fazer login",
                        "zh-Hans": "登录时启动", "ja": "ログイン時に起動", "ko": "로그인 시 시작"},
    "keep_awake":      {"en": "Keep Mac Awake", "ru": "Не давать Mac засыпать", "es": "Mantener el Mac activo",
                        "de": "Mac wach halten", "fr": "Garder le Mac éveillé", "pt-BR": "Manter o Mac ativo",
                        "zh-Hans": "保持 Mac 唤醒", "ja": "Mac をスリープさせない", "ko": "Mac 절전 방지"},
    "lan_only":        {"en": "LAN-only (no relay)", "ru": "Только LAN (без реле)", "es": "Solo LAN (sin relé)",
                        "de": "Nur LAN (kein Relay)", "fr": "LAN seul (sans relais)", "pt-BR": "Somente LAN (sem relay)",
                        "zh-Hans": "仅局域网（无中继）", "ja": "LANのみ（リレーなし）", "ko": "LAN 전용 (릴레이 없음)"},
    "terminal_access": {"en": "Terminal Access", "ru": "Доступ к терминалу", "es": "Acceso a la terminal",
                        "de": "Terminal-Zugriff", "fr": "Accès au terminal", "pt-BR": "Acesso ao terminal",
                        "zh-Hans": "终端访问", "ja": "ターミナルアクセス", "ko": "터미널 접근"},
    "web_proxy":       {"en": "Web Proxy", "ru": "Веб-прокси", "es": "Proxy web",
                        "de": "Web-Proxy", "fr": "Proxy web", "pt-BR": "Proxy da web",
                        "zh-Hans": "网页代理", "ja": "Web プロキシ", "ko": "웹 프록시"},
    "reauthenticate":  {"en": "⚠ Re-authenticate…", "ru": "⚠ Пройти авторизацию заново…", "es": "⚠ Volver a autenticar…",
                        "de": "⚠ Erneut anmelden…", "fr": "⚠ Se ré-authentifier…", "pt-BR": "⚠ Autenticar novamente…",
                        "zh-Hans": "⚠ 重新认证…", "ja": "⚠ 再認証…", "ko": "⚠ 다시 인증…"},
    "quit":            {"en": "Quit Terminull", "ru": "Выйти из Terminull", "es": "Salir de Terminull",
                        "de": "Terminull beenden", "fr": "Quitter Terminull", "pt-BR": "Sair do Terminull",
                        "zh-Hans": "退出 Terminull", "ja": "Terminull を終了", "ko": "Terminull 종료"},
    "keepawake_off":   {"en": "Off", "ru": "Выкл", "es": "Desactivado", "de": "Aus", "fr": "Désactivé",
                        "pt-BR": "Desligado", "zh-Hans": "关闭", "ja": "オフ", "ko": "끔"},
    "language":        {"en": "Language", "ru": "Язык", "es": "Idioma", "de": "Sprache", "fr": "Langue",
                        "pt-BR": "Idioma", "zh-Hans": "语言", "ja": "言語", "ko": "언어"},
    "language_system": {"en": "System", "ru": "Системный", "es": "Sistema", "de": "System", "fr": "Système",
                        "pt-BR": "Sistema", "zh-Hans": "跟随系统", "ja": "システム", "ko": "시스템"},
    # ── Inline model-status words (suffix after " — ") ──────────────────────
    "st_downloading_pct": {"en": "downloading… {pct}%", "ru": "загрузка… {pct}%", "es": "descargando… {pct}%",
                        "de": "Lädt herunter… {pct}%", "fr": "téléchargement… {pct}%", "pt-BR": "baixando… {pct}%",
                        "zh-Hans": "下载中… {pct}%", "ja": "ダウンロード中… {pct}%", "ko": "다운로드 중… {pct}%"},
    "st_downloading":  {"en": "downloading…", "ru": "загрузка…", "es": "descargando…", "de": "Lädt herunter…",
                        "fr": "téléchargement…", "pt-BR": "baixando…", "zh-Hans": "下载中…", "ja": "ダウンロード中…", "ko": "다운로드 중…"},
    "st_loading":      {"en": "loading…", "ru": "загрузка в память…", "es": "cargando…", "de": "Lädt…",
                        "fr": "chargement…", "pt-BR": "carregando…", "zh-Hans": "加载中…", "ja": "読み込み中…", "ko": "불러오는 중…"},
    "st_loaded":       {"en": "loaded", "ru": "загружено", "es": "cargado", "de": "geladen", "fr": "chargé",
                        "pt-BR": "carregado", "zh-Hans": "已加载", "ja": "読み込み済み", "ko": "로드됨"},
    "st_not_loaded":   {"en": "not loaded", "ru": "не загружено", "es": "no cargado", "de": "nicht geladen",
                        "fr": "non chargé", "pt-BR": "não carregado", "zh-Hans": "未加载", "ja": "未読み込み", "ko": "로드 안 됨"},
    "st_idle":         {"en": "idle", "ru": "простой", "es": "inactivo", "de": "inaktiv", "fr": "inactif",
                        "pt-BR": "ocioso", "zh-Hans": "空闲", "ja": "アイドル", "ko": "대기"},
    "st_off":          {"en": "off", "ru": "выкл", "es": "apagado", "de": "aus", "fr": "désactivé",
                        "pt-BR": "desligado", "zh-Hans": "关闭", "ja": "オフ", "ko": "꺼짐"},
    "st_cloud":        {"en": "cloud", "ru": "облако", "es": "nube", "de": "Cloud", "fr": "cloud",
                        "pt-BR": "nuvem", "zh-Hans": "云端", "ja": "クラウド", "ko": "클라우드"},
    "st_ready":        {"en": "ready", "ru": "готово", "es": "listo", "de": "bereit", "fr": "prêt",
                        "pt-BR": "pronto", "zh-Hans": "就绪", "ja": "準備完了", "ko": "준비됨"},
}


def t(key: str, *, locale: str | None = None, **fmt) -> str:
    """Localized string for `key` (English fallback), with `{...}` slots filled from `fmt`."""
    loc = locale or current_locale()
    row = _STRINGS.get(key, {})
    text = row.get(loc) or row.get("en") or key
    if fmt:
        try:
            return text.format(**fmt)
        except Exception:
            return text
    return text
