"""Lightweight i18n helpers for ORION-AI UI and messages."""

from __future__ import annotations

from copy import deepcopy
from typing import Any

DEFAULT_LANGUAGE = "es"
SUPPORTED_LANGUAGES = ("es", "en")

translations: dict[str, dict[str, Any]] = {
    "es": {
        "config": {
            "title": "Configuración",
            "subtitle": "Todas las configuraciones son independientes. Guarda solo lo que necesites.",
            "toolbar": {
                "back": "Volver",
            },
            "sections": {
                "language": {
                    "title": "Idioma Predeterminado del Asistente",
                    "helper": "Si un mensaje es ambiguo, el asistente usará este idioma como respaldo.",
                    "save": "Guardar Idioma",
                },
                "ai": {
                    "title_remote": "Proveedor de IA (API Remota)",
                    "title_local": "Proveedor de IA (Modelo Local)",
                    "helper_remote": "Modo cloud. Ingresa tu clave de Gemini para habilitar respuestas y análisis remotos.",
                    "helper_local": "Modo local. ORION-AI usará tu instancia de Ollama en http://localhost:11434.",
                    "radio_ollama": "Modelo local (Ollama)",
                    "radio_gemini": "API remota (Gemini)",
                    "gemini_key": "Clave API de Gemini",
                    "gemini_key_fallback": "Clave API de Gemini de respaldo (opcional)",
                    "gemini_model": "Modelo de Gemini",
                    "ollama_model": "Nombre del modelo de Ollama",
                    "save": "Guardar Proveedor IA",
                    "allow_fallback": "Permitir respaldo a Gemini si el modelo local no está disponible",
                    "test_api": "Probar API",
                    "test_fallback_api": "Probar API de respaldo",
                    "test_local": "Probar modelo local",
                    "status_not_configured": "Estado: No configurado",
                    "status_not_detected": "Estado: No detectado",
                    "status_api_key_configured": "Estado: Clave API configurada",
                    "status_model_set": "Estado: Modelo configurado ({model})",
                    "status_detail": "Estado: {detail}",
                    "badge_not_configured": "No configurado",
                    "badge_local": "Local (Ollama)",
                    "badge_remote": "Remoto (Gemini)",
                },
                "defaults": {
                    "title": "Proveedores Predeterminados",
                    "badge": "Independiente",
                    "task_provider": "Proveedor predeterminado de tareas",
                    "notes_provider": "Proveedor predeterminado de notas",
                    "save": "Guardar Predeterminados",
                },
                "todoist": {
                    "title": "Todoist",
                    "helper": "Proveedor por token. Déjalo vacío y desconecta para deshabilitarlo.",
                    "save": "Guardar Todoist",
                },
                "vault": {
                    "title": "Rutas de Contexto Vault",
                    "helper": "Puedes guardar carpetas inexistentes; se mostrará una advertencia.",
                    "save": "Guardar Rutas Vault",
                    "add_path": "Agregar Ruta",
                    "empty_paths": "Aún no hay rutas de vault configuradas.",
                },
                "integrations": {
                    "title": "Integraciones",
                    "badge": "Tareas + Notas",
                    "oauth": "OAuth",
                    "token_based": "Token",
                    "token_based_pat": "Token (PAT)",
                    "save": "Guardar",
                    "test": "Probar",
                    "test_connection": "Probar conexión",
                    "disconnect": "Desconectar",
                    "connect_oauth": "Conectar OAuth",
                },
            },
            "providers": {
                "gemini": "Gemini",
                "ollama": "Ollama",
                "todoist": "Todoist",
                "vault_local": "Vault (Local)",
                "google_tasks": "Google Tasks",
                "microsoft_todo": "Microsoft To Do",
                "trello": "Trello",
                "github_issues": "GitHub Issues",
                "notion": "Notion",
            },
            "common": {
                "enabled": "Habilitado",
                "remove": "Eliminar",
                "configured": "Configurado",
                "connected": "Conectado",
                "not_configured": "No configurado",
                "disabled": "Deshabilitado",
                "default": "Predeterminado",
                "paths_configured": "{count} rutas configuradas",
                "status_enabled": "Habilitado",
                "status_disabled": "Deshabilitado",
                "status_error": "Error",
                "status_not_configured": "No configurado",
                "status_connected": "Conectado",
            },
            "global": {
                "save_all_enter": "Guardar Todo y Entrar",
                "enter_without_config": "Entrar Sin Configurar",
            },
            "fields": {
                "language_es": "Español",
                "language_en": "English",
                "todoist_token_placeholder": "Token API de Todoist",
                "vault_path_placeholder": "~/Documents/Notas",
                "google_task_list_id": "ID de lista (opcional)",
                "google_task_list_placeholder": "@default o id de lista",
                "microsoft_list_id": "ID de lista (opcional)",
                "microsoft_list_placeholder": "ID de lista de Graph",
                "trello_api_key": "Clave API",
                "trello_api_key_placeholder": "Clave API de Trello",
                "trello_token": "Token",
                "trello_token_placeholder": "Token de Trello",
                "trello_board_id": "ID de tablero (opcional)",
                "trello_board_id_placeholder": "ID de tablero",
                "trello_list_id": "ID de lista",
                "trello_list_id_placeholder": "ID de lista",
                "trello_done_list_id": "ID de lista done (opcional)",
                "trello_done_list_id_placeholder": "ID de lista done",
                "github_token": "Token personal de acceso",
                "github_token_placeholder": "Token de GitHub",
                "github_repo": "Repositorio (owner/repo)",
                "github_repo_placeholder": "owner/repo",
                "notion_token": "Token de integración interna",
                "notion_token_placeholder": "Token de Notion",
                "notion_page_id": "ID de página (opcional)",
                "notion_page_id_placeholder": "ID de página",
                "notion_database_id": "ID de base de datos (opcional)",
                "notion_database_id_placeholder": "ID de base de datos",
                "ollama_model_placeholder": "llama3.2:3b",
                "gemini_api_key_placeholder": "Clave API de Gemini",
                "gemini_api_key_fallback_placeholder": "Clave API de Gemini (respaldo)",
                "gemini_model_placeholder": "gemini-2.5-flash",
            },
            "messages": {
                "saving": "Guardando...",
                "saving_defaults": "Guardando predeterminados...",
                "language_saved": "Idioma guardado.",
                "ai_saved": "Configuración de IA guardada.",
                "config_saved": "Configuración guardada.",
                "defaults_saved": "Proveedores predeterminados guardados.",
                "path_already_added": "La ruta ya fue agregada.",
                "opening_assistant": "Abriendo asistente...",
                "saving_provider": "Guardando {provider}...",
                "provider_saved": "{provider} guardado.",
                "provider_enabled": "{provider} habilitado.",
                "provider_disabled": "{provider} deshabilitado.",
                "disconnecting_provider": "Desconectando {provider}...",
                "provider_disconnected": "{provider} desconectado.",
                "testing_provider": "Probando {provider}...",
                "connection_ok": "Conexión correcta con {provider}.",
                "connection_failed": "No se pudo conectar con {provider}.",
                "testing_ai": "Probando {provider}...",
                "oauth_opening": "Abriendo OAuth para {provider}...",
                "oauth_started": "OAuth iniciado para {provider}. Completa la autorización en tu navegador.",
                "oauth_url_fallback": "Se abrió la URL de OAuth. Si no apareció ventana, abre: {url}",
                "status_line": "Idioma: {language}. IA: {ai}. Tareas predeterminadas: {task_provider}. Notas predeterminadas: {notes_provider}.",
                "warning_vault_path_not_found": "Ruta de vault no encontrada: {path}",
                "warning_todoist_short": "El token de Todoist parece corto. Se guardó, pero verifícalo si falla.",
                "warning_todoist_whitespace": "El token de Todoist incluye espacios. Se guardó tal como se ingresó.",
                "warning_gemini_key_missing": "Gemini está seleccionado sin clave API. Las respuestas de IA pueden no estar disponibles.",
                "model_pending": "modelo pendiente",
                "request_failed": "Solicitud falló ({status})",
                "test_failed": "Prueba falló: {detail}",
                "risk_notice": (
                    "Las credenciales OAuth/token se almacenan localmente en esta máquina. "
                    "Protege el acceso local y rota los tokens si se ven comprometidos."
                ),
                "assistant_query_failed": "El asistente no pudo procesar la solicitud: {error}",
                "assistant_chat_failed": "El chat del asistente no pudo procesar la solicitud: {error}",
            },
        },
        "assistant": {
            "settings_button": "Configuración",
            "settings_aria": "Abrir configuración",
            "settings_disabled": "Disponible cuando el asistente esté en reposo",
            "input_placeholder": "Escribe un mensaje para Orion",
            "send_button": "Enviar",
            "stop_button": "Detener",
            "stop_aria": "Detener respuesta",
            "mic_button": "Hablar",
            "mic_retry": "Reintentar micrófono",
            "mic_unavailable": "No microphone detected / input unavailable",
            "status_state": "Estado",
            "status_backend": "STT",
            "status_device": "Micrófono",
            "state_idle": "reposo",
            "state_listening": "escuchando",
            "state_transcribing": "transcribiendo",
            "state_thinking": "pensando",
            "state_speaking": "hablando",
            "state_cooldown": "enfriamiento",
            "state_paused": "pausado",
            "state_unknown": "desconocido",
            "prompt_failed": "No se pudo enviar el mensaje.",
            "voice_connection_unavailable": "Conexión de voz no disponible.",
            "runtime_worker_active": "Runtime de voz activo",
            "runtime_worker_inactive": "Runtime de voz inactivo",
            "runtime_not_running": "Runtime de voz no iniciado.",
        },
    },
    "en": {
        "config": {
            "title": "Configuration",
            "subtitle": "All settings are independent. Save only the sections you need.",
            "toolbar": {
                "back": "Back",
            },
            "sections": {
                "language": {
                    "title": "Assistant Default Language",
                    "helper": "If a message is ambiguous, the assistant uses this language as fallback.",
                    "save": "Save Language",
                },
                "ai": {
                    "title_remote": "AI Provider (Remote API)",
                    "title_local": "AI Provider (Local Model)",
                    "helper_remote": "Cloud mode. Enter your Gemini key to enable remote responses and analysis.",
                    "helper_local": "Local mode. ORION-AI will call your Ollama instance at http://localhost:11434.",
                    "radio_ollama": "Local model (Ollama)",
                    "radio_gemini": "Remote API (Gemini)",
                    "gemini_key": "Gemini API key",
                    "gemini_key_fallback": "Fallback Gemini API key (optional)",
                    "gemini_model": "Gemini model",
                    "ollama_model": "Ollama model name",
                    "save": "Save AI Provider",
                    "allow_fallback": "Allow fallback to Gemini if the local model is unavailable",
                    "test_api": "Test API",
                    "test_fallback_api": "Test fallback API",
                    "test_local": "Test local model",
                    "status_not_configured": "Status: Not configured",
                    "status_not_detected": "Status: Not detected",
                    "status_api_key_configured": "Status: API key configured",
                    "status_model_set": "Status: Model set ({model})",
                    "status_detail": "Status: {detail}",
                    "badge_not_configured": "Not configured",
                    "badge_local": "Local (Ollama)",
                    "badge_remote": "Remote (Gemini)",
                },
                "defaults": {
                    "title": "Default Providers",
                    "badge": "Independent",
                    "task_provider": "Default task provider",
                    "notes_provider": "Default notes provider",
                    "save": "Save Defaults",
                },
                "todoist": {
                    "title": "Todoist",
                    "helper": "Token-based provider. Leave empty and disconnect to disable.",
                    "save": "Save Todoist",
                },
                "vault": {
                    "title": "Vault Context Paths",
                    "helper": "Missing folders are allowed and saved with a warning.",
                    "save": "Save Vault Paths",
                    "add_path": "Add Path",
                    "empty_paths": "No vault paths configured yet.",
                },
                "integrations": {
                    "title": "Integrations",
                    "badge": "Tasks + Notes",
                    "oauth": "OAuth",
                    "token_based": "Token-based",
                    "token_based_pat": "Token-based (PAT)",
                    "save": "Save",
                    "test": "Test",
                    "test_connection": "Test connection",
                    "disconnect": "Disconnect",
                    "connect_oauth": "Connect OAuth",
                },
            },
            "providers": {
                "gemini": "Gemini",
                "ollama": "Ollama",
                "todoist": "Todoist",
                "vault_local": "Vault (Local)",
                "google_tasks": "Google Tasks",
                "microsoft_todo": "Microsoft To Do",
                "trello": "Trello",
                "github_issues": "GitHub Issues",
                "notion": "Notion",
            },
            "common": {
                "enabled": "Enabled",
                "remove": "Remove",
                "configured": "Configured",
                "connected": "Connected",
                "not_configured": "Not configured",
                "disabled": "Disabled",
                "default": "Default",
                "paths_configured": "{count} paths configured",
                "status_enabled": "Enabled",
                "status_disabled": "Disabled",
                "status_error": "Error",
                "status_not_configured": "Not configured",
                "status_connected": "Connected",
            },
            "global": {
                "save_all_enter": "Save All & Enter",
                "enter_without_config": "Enter Without Configuring",
            },
            "fields": {
                "language_es": "Español",
                "language_en": "English",
                "todoist_token_placeholder": "Todoist API token",
                "vault_path_placeholder": "~/Documents/Notes",
                "google_task_list_id": "Task list id (optional)",
                "google_task_list_placeholder": "@default or list id",
                "microsoft_list_id": "List id (optional)",
                "microsoft_list_placeholder": "Graph list id",
                "trello_api_key": "API key",
                "trello_api_key_placeholder": "Trello API key",
                "trello_token": "Token",
                "trello_token_placeholder": "Trello token",
                "trello_board_id": "Board id (optional)",
                "trello_board_id_placeholder": "Board id",
                "trello_list_id": "List id",
                "trello_list_id_placeholder": "List id",
                "trello_done_list_id": "Done list id (optional)",
                "trello_done_list_id_placeholder": "Done list id",
                "github_token": "Personal access token",
                "github_token_placeholder": "GitHub token",
                "github_repo": "Repository (owner/repo)",
                "github_repo_placeholder": "owner/repo",
                "notion_token": "Internal integration token",
                "notion_token_placeholder": "Notion token",
                "notion_page_id": "Page id (optional)",
                "notion_page_id_placeholder": "Page id",
                "notion_database_id": "Database id (optional)",
                "notion_database_id_placeholder": "Database id",
                "ollama_model_placeholder": "llama3.2:3b",
                "gemini_api_key_placeholder": "Gemini API key",
                "gemini_api_key_fallback_placeholder": "Gemini API key (fallback)",
                "gemini_model_placeholder": "gemini-2.5-flash",
            },
            "messages": {
                "saving": "Saving...",
                "saving_defaults": "Saving defaults...",
                "language_saved": "Language saved.",
                "ai_saved": "AI provider settings saved.",
                "config_saved": "Configuration saved.",
                "defaults_saved": "Default providers saved.",
                "path_already_added": "Path already added.",
                "opening_assistant": "Opening assistant...",
                "saving_provider": "Saving {provider}...",
                "provider_saved": "{provider} saved.",
                "provider_enabled": "{provider} enabled.",
                "provider_disabled": "{provider} disabled.",
                "disconnecting_provider": "Disconnecting {provider}...",
                "provider_disconnected": "{provider} disconnected.",
                "testing_provider": "Testing {provider}...",
                "connection_ok": "{provider} connection successful.",
                "connection_failed": "Could not connect to {provider}.",
                "testing_ai": "Testing {provider}...",
                "oauth_opening": "Opening OAuth for {provider}...",
                "oauth_started": "OAuth started for {provider}. Complete authorization in your browser.",
                "oauth_url_fallback": "OAuth URL opened. If no window appeared, open: {url}",
                "status_line": "Language: {language}. AI: {ai}. Default tasks: {task_provider}. Default notes: {notes_provider}.",
                "warning_vault_path_not_found": "Vault path not found: {path}",
                "warning_todoist_short": "Todoist token seems short. It was saved, but verify it if requests fail.",
                "warning_todoist_whitespace": "Todoist token includes whitespace. It was saved exactly as provided.",
                "warning_gemini_key_missing": "Gemini provider selected without API key. AI responses may be unavailable.",
                "model_pending": "model pending",
                "request_failed": "Request failed ({status})",
                "test_failed": "Test failed: {detail}",
                "risk_notice": (
                    "OAuth/token credentials are stored locally on this machine. "
                    "Protect local access and rotate tokens if compromised."
                ),
                "assistant_query_failed": "Assistant could not process the request: {error}",
                "assistant_chat_failed": "Assistant chat could not process the request: {error}",
            },
        },
        "assistant": {
            "settings_button": "Settings",
            "settings_aria": "Open settings",
            "settings_disabled": "Available once the assistant is idle",
            "input_placeholder": "Type a message for Orion",
            "send_button": "Send",
            "stop_button": "Stop",
            "stop_aria": "Stop response",
            "mic_button": "Talk",
            "mic_retry": "Retry Mic",
            "mic_unavailable": "No microphone detected / input unavailable",
            "status_state": "State",
            "status_backend": "STT",
            "status_device": "Microphone",
            "state_idle": "idle",
            "state_listening": "listening",
            "state_transcribing": "transcribing",
            "state_thinking": "thinking",
            "state_speaking": "speaking",
            "state_cooldown": "cooldown",
            "state_paused": "paused",
            "state_unknown": "unknown",
            "prompt_failed": "Could not send the message.",
            "voice_connection_unavailable": "Voice connection unavailable.",
            "runtime_worker_active": "Voice runtime active",
            "runtime_worker_inactive": "Voice runtime inactive",
            "runtime_not_running": "Voice runtime not running.",
        },
    },
}


def normalize_language(lang: str | None) -> str:
    """Normalize language to a supported value."""
    value = str(lang or "").strip().lower()
    if value == "en":
        return "en"
    return DEFAULT_LANGUAGE


def _lookup_key(tree: dict[str, Any], key: str) -> Any:
    current: Any = tree
    for part in key.split("."):
        if not isinstance(current, dict) or part not in current:
            return None
        current = current[part]
    return current


def translate(key: str, lang: str | None = None, **kwargs: Any) -> str:
    """Translate one key in the requested language."""
    language = normalize_language(lang)
    value = _lookup_key(translations.get(language, {}), key)
    if value is None:
        value = _lookup_key(translations.get(DEFAULT_LANGUAGE, {}), key)
    if not isinstance(value, str):
        return key

    if kwargs:
        try:
            return value.format(**kwargs)
        except Exception:
            return value
    return value


def get_language_pack(lang: str | None = None, *, namespace: str | None = None) -> dict[str, Any]:
    """Return a copy of language map (or one namespace subtree)."""
    language = normalize_language(lang)
    root = translations.get(language) or translations[DEFAULT_LANGUAGE]
    if namespace is None:
        return deepcopy(root)
    selected = _lookup_key(root, namespace)
    if selected is None:
        selected = _lookup_key(translations[DEFAULT_LANGUAGE], namespace) or {}
    if isinstance(selected, dict):
        return deepcopy(selected)
    return {}
