"""Localized strings for desktop/web agent activity overlay."""

from __future__ import annotations

import os
from typing import Callable

from iuve_connect_agents.desktop.ui.i18n import detect_language, is_supported_locale, normalize_language

# ua is a common alias; desktop i18n maps it to uk.
AGENT_STATUS_LOCALES: tuple[str, ...] = ("en", "ru", "ro", "de", "fr", "uk", "es")

STATUS_KEYS = ("working", "error", "blocked", "idle")

TRANSLATIONS: dict[str, dict[str, str]] = {
    "en": {
        "working": "Agent working",
        "error": "Agent error",
        "blocked": "Agent waiting",
        "idle": "Agent idle",
    },
    "ru": {
        "working": "Агент работает",
        "error": "Агент: ошибка",
        "blocked": "Агент ожидает",
        "idle": "Агент простаивает",
    },
    "ro": {
        "working": "Agentul lucrează",
        "error": "Agent: eroare",
        "blocked": "Agentul așteaptă",
        "idle": "Agent inactiv",
    },
    "de": {
        "working": "Agent arbeitet",
        "error": "Agent: Fehler",
        "blocked": "Agent wartet",
        "idle": "Agent bereit",
    },
    "fr": {
        "working": "Agent en cours",
        "error": "Agent : erreur",
        "blocked": "Agent en attente",
        "idle": "Agent inactif",
    },
    "uk": {
        "working": "Агент працює",
        "error": "Агент: помилка",
        "blocked": "Агент очікує",
        "idle": "Агент простоює",
    },
    "es": {
        "working": "Agente trabajando",
        "error": "Agente: error",
        "blocked": "Agente en espera",
        "idle": "Agente inactivo",
    },
}


def normalize_agent_status_locale(raw_value: str | None) -> str:
    raw = str(raw_value or "").strip().lower()
    if raw in {"ua", "uk", "uk-ua"}:
        return "uk"
    code = normalize_language(raw)
    if code in AGENT_STATUS_LOCALES:
        return code
    return "en"


def resolve_agent_status_locale(
    *,
    profile_lang: str | None = None,
    cached_lang: str | None = None,
    env_override: str | None = None,
) -> str:
    env_lang = str(env_override or os.getenv("IUVE_AGENT_UI_LANG", "")).strip()
    if env_lang and is_supported_locale(env_lang):
        return normalize_agent_status_locale(env_lang)
    if profile_lang and is_supported_locale(profile_lang):
        return normalize_agent_status_locale(profile_lang)
    if cached_lang and is_supported_locale(cached_lang):
        return normalize_agent_status_locale(cached_lang)
    return normalize_agent_status_locale(detect_language())


def agent_status_label(lang: str, status_key: str) -> str:
    code = normalize_agent_status_locale(lang)
    table = TRANSLATIONS.get(code) or TRANSLATIONS["en"]
    key = str(status_key or "").strip().lower()
    if key not in STATUS_KEYS:
        key = "working"
    return table.get(key) or TRANSLATIONS["en"][key]


def agent_status_labels_for_locale(lang: str) -> dict[str, str]:
    return {key: agent_status_label(lang, key) for key in STATUS_KEYS}
