"""Simple dictionary-based i18n for the GUI. Supports EN, ES, PT."""

from __future__ import annotations

_STRINGS = {
    "en": {
        # App / Navigation
        "app_title": "AI Interview Assistant",
        "dashboard": "Dashboard",
        "hotkeys": "Hotkeys",
        "settings": "Settings",
        "stopped": "Stopped",
        "running": "Running",

        # Dashboard — Start Form
        "interview_context": "INTERVIEW CONTEXT",
        "ai_provider": "AI PROVIDER",
        "transcription": "TRANSCRIPTION",
        "challenge_type": "Challenge Type",
        "code_challenge": "Code Challenge",
        "system_design": "System Design",
        "general_behavioural": "General / Behavioural",
        "programming_language": "Programming Language",
        "interview_brief": "Interview Brief (optional)",
        "hint_code_challenge": "Paste job description, key topics, language requirements, time limit...",
        "hint_system_design": "Paste job description, system requirements, scale expectations, constraints...",
        "hint_general": "Paste job description, role expectations, topics to prepare, company context...",
        "codebase_path": "Codebase Path",
        "hint_codebase": "/path/to/repo (optional)",
        "provider": "Provider",
        "model": "Model",
        "transcriber": "Transcriber",
        "language": "Language",
        "ollama_free": "Ollama (free)",
        "gemini_free": "Gemini (free)",
        "whisper_free": "Whisper (free)",
        "start_interview": "Start Interview",
        "starting": "Starting...",
        "failed_to_start": "Failed to start — check logs",
        "model_not_available": "Model {model} not available. Download it in Settings.",
        "download_first": "Download the model first",
        "no_models": "(no models — download in Settings)",
        "include_cv": "Include CV: {name}",
        "no_cv": "No CV attached (set in Settings)",

        # Dashboard — Running
        "interview_in_progress": "Interview in progress",
        "no_interview": "No interview running",
        "stop": "Stop",
        "restart": "Restart",
        "stopping": "Stopping...",
        "restarting": "Restarting...",
        "provider_label": "Provider",
        "model_label": "Model",
        "transcriber_label": "Transcriber",
        "language_label": "Language",
        "transcription_label": "Transcription",
        "uptime_label": "Uptime",
        "codebase_label": "Codebase",

        # Settings
        "api_keys": "API KEYS",
        "anthropic_api_key": "Anthropic API Key",
        "google_api_key": "Google Gemini API Key",
        "deepgram_api_key": "Deepgram API Key",
        "hint_anthropic": "sk-ant-...",
        "hint_google": "AIza... (free at aistudio.google.com/apikey)",
        "hint_deepgram": "Optional — falls back to local Whisper",
        "how_to_get_key": "How to get a key",
        "help_claude": "1. Go to console.anthropic.com\n2. Sign up or log in\n3. Go to API Keys\n4. Create a new key (starts with sk-ant-...)\n5. Free tier: $5 credit",
        "help_gemini": "1. Go to aistudio.google.com/apikey\n2. Sign in with Google\n3. Click 'Create API Key'\n4. Copy the key (starts with AIza...)\n5. Free tier: generous limits",
        "help_deepgram": "1. Go to console.deepgram.com\n2. Sign up (free tier: $200 credit)\n3. Go to API Keys\n4. Create a new key\n5. Optional — Whisper (free) works without this",
        "default_provider": "Default Provider",
        "claude_model": "Claude Model",
        "gemini_model": "Gemini Model",
        "local_model": "Local Model (Ollama)",
        "ollama_host": "Ollama Server",
        "hint_ollama_host": "http://localhost:11434 or http://<remote-ip>:11434",
        "download": "Download",
        "downloading": "Downloading {model}…",
        "model_ready": "{model} — ready",
        "model_not_downloaded": "{model} — not downloaded",
        "download_timed_out": "Download timed out",
        "ollama_not_installed": "Ollama not installed. Run: ai-interview version",
        "default_transcriber": "Default Transcriber",
        "whisper_host": "Whisper Server",
        "hint_whisper_host": "Empty = local, or http://<remote-ip>:8000",
        "speed_fastest": "fastest",
        "speed_fast": "fast",
        "speed_balanced": "balanced",
        "speed_slow": "slow",
        "vision_tag": "vision",
        "no_screenshot_support": "This model does not support screenshots",
        "connected": "Connected",
        "not_reachable": "Not reachable",
        "checking_connection": "Checking…",
        "transcription_language": "Transcription Language",
        "cv_resume": "CV / RESUME",
        "cv_pdf": "CV / Resume (PDF)",
        "hint_cv": "Path to your CV — used to tailor experience-based answers",
        "browse": "Browse",
        "clear": "Clear",
        "general": "GENERAL",
        "theme": "Theme",
        "viewer_port": "Viewer Port",
        "show_menubar": "Show menu bar icon",
        "menubar_icon": "Menu bar icon",
        "autostart_login": "Auto-start menu bar on login",
        "interface_language": "Interface Language",
        "saved": "Saved",
        "restart_to_apply": "Restart GUI to apply language",

        # Hotkeys
        "hotkeys_readonly": "Hotkeys are read-only during an active session",
        "press_keys": "Press any key or combination...",
        "reset_default": "Reset to default",
        "beep_feedback": "Beep feedback",
        "conflict": "⚠ Conflict: {names}",

        # Hotkey groups
        "group_ai_actions": "AI Actions",
        "group_screenshots": "Screenshots & Context",
        "group_navigation": "Viewer Navigation",
        "group_ui": "UI",

        # Hotkey actions
        "hk_trigger_query": "Send to AI",
        "hk_trigger_query_desc": "Send transcript + screenshots to AI and get a response",
        "hk_copy_and_query": "Copy & Send",
        "hk_copy_and_query_desc": "Copy selected text from editor, then send everything to AI",
        "hk_manual_recording": "Voice Record",
        "hk_manual_recording_desc": "Hold to record your voice, release to transcribe and send",
        "hk_toggle_code_mode": "Code Mode",
        "hk_toggle_code_mode_desc": "Toggle between auto mode (bullets) and code mode (always code)",
        "hk_capture_screenshot": "Screenshot",
        "hk_capture_screenshot_desc": "Capture the active window and add to next AI query",
        "hk_scroll_up": "Scroll Up",
        "hk_scroll_up_desc": "Scroll the phone/viewer up",
        "hk_scroll_down": "Scroll Down",
        "hk_scroll_down_desc": "Scroll the phone/viewer down",
        "hk_nav_prev": "Previous",
        "hk_nav_prev_desc": "Show the previous AI response",
        "hk_nav_next": "Next",
        "hk_nav_next_desc": "Show the next AI response",
        "hk_font_size_up": "Larger Text",
        "hk_font_size_up_desc": "Increase viewer font size",
        "hk_font_size_down": "Smaller Text",
        "hk_font_size_down_desc": "Decrease viewer font size",
        "hk_toggle_overlay": "Toggle Overlay",
        "hk_toggle_overlay_desc": "Show or hide the desktop overlay window",

        # Hotkey types
        "type_combined": "Hold + Press",
        "type_double_tap": "Double Tap",
        "type_press_hold": "Tap + Hold",

        # Menubar
        "menu_open_dashboard": "Open Dashboard",
        "menu_start_interview": "Start Interview",
        "menu_stop_interview": "Stop Interview",
        "menu_restart": "Restart",
        "menu_quit": "Quit",
    },

    "es": {
        "app_title": "Asistente de Entrevistas IA",
        "dashboard": "Panel",
        "hotkeys": "Atajos",
        "settings": "Configuración",
        "stopped": "Detenido",
        "running": "En ejecución",

        "interview_context": "CONTEXTO DE ENTREVISTA",
        "ai_provider": "PROVEEDOR IA",
        "transcription": "TRANSCRIPCIÓN",
        "challenge_type": "Tipo de Desafío",
        "code_challenge": "Desafío de Código",
        "system_design": "Diseño de Sistemas",
        "general_behavioural": "General / Comportamental",
        "programming_language": "Lenguaje de Programación",
        "interview_brief": "Resumen de Entrevista (opcional)",
        "hint_code_challenge": "Pega la descripción del puesto, temas clave, requisitos de lenguaje...",
        "hint_system_design": "Pega la descripción del puesto, requisitos del sistema, expectativas de escala...",
        "hint_general": "Pega la descripción del puesto, expectativas del rol, temas a preparar...",
        "codebase_path": "Ruta del Código",
        "hint_codebase": "/ruta/al/repo (opcional)",
        "provider": "Proveedor",
        "model": "Modelo",
        "transcriber": "Transcriptor",
        "language": "Idioma",
        "ollama_free": "Ollama (gratis)",
        "gemini_free": "Gemini (gratis)",
        "whisper_free": "Whisper (gratis)",
        "start_interview": "Iniciar Entrevista",
        "starting": "Iniciando...",
        "failed_to_start": "Error al iniciar — revisa los logs",
        "model_not_available": "Modelo {model} no disponible. Descárgalo en Configuración.",
        "download_first": "Descarga el modelo primero",
        "no_models": "(sin modelos — descarga en Configuración)",
        "include_cv": "Incluir CV: {name}",
        "no_cv": "Sin CV adjunto (configura en Ajustes)",

        "interview_in_progress": "Entrevista en progreso",
        "no_interview": "Sin entrevista activa",
        "stop": "Detener",
        "restart": "Reiniciar",
        "stopping": "Deteniendo...",
        "restarting": "Reiniciando...",
        "provider_label": "Proveedor",
        "model_label": "Modelo",
        "transcriber_label": "Transcriptor",
        "language_label": "Lenguaje",
        "transcription_label": "Transcripción",
        "uptime_label": "Tiempo activo",
        "codebase_label": "Código",

        "api_keys": "CLAVES API",
        "anthropic_api_key": "Clave API Anthropic",
        "google_api_key": "Clave API Google Gemini",
        "deepgram_api_key": "Clave API Deepgram",
        "hint_anthropic": "sk-ant-...",
        "hint_google": "AIza... (gratis en aistudio.google.com/apikey)",
        "hint_deepgram": "Opcional — usa Whisper local si está vacío",
        "how_to_get_key": "Cómo obtener una clave",
        "help_claude": "1. Ve a console.anthropic.com\n2. Regístrate o inicia sesión\n3. Ve a Claves de API\n4. Crea una nueva clave (empieza con sk-ant-...)\n5. Nivel gratis: $5 de crédito",
        "help_gemini": "1. Ve a aistudio.google.com/apikey\n2. Inicia sesión con Google\n3. Haz clic en 'Crear clave de API'\n4. Copia la clave (empieza con AIza...)\n5. Nivel gratis: límites generosos",
        "help_deepgram": "1. Ve a console.deepgram.com\n2. Regístrate (gratis: $200 de crédito)\n3. Ve a Claves de API\n4. Crea una nueva clave\n5. Opcional — Whisper (gratis) funciona sin esto",
        "default_provider": "Proveedor Predeterminado",
        "claude_model": "Modelo Claude",
        "gemini_model": "Modelo Gemini",
        "local_model": "Modelo Local (Ollama)",
        "ollama_host": "Servidor Ollama",
        "hint_ollama_host": "http://localhost:11434 o http://<ip-remota>:11434",
        "download": "Descargar",
        "downloading": "Descargando {model}…",
        "model_ready": "{model} — listo",
        "model_not_downloaded": "{model} — no descargado",
        "download_timed_out": "Descarga agotada",
        "ollama_not_installed": "Ollama no instalado. Ejecuta: ai-interview version",
        "default_transcriber": "Transcriptor Predeterminado",
        "whisper_host": "Servidor Whisper",
        "hint_whisper_host": "Vacío = local, o http://<ip-remota>:8000",
        "speed_fastest": "más rápido",
        "speed_fast": "rápido",
        "speed_balanced": "equilibrado",
        "speed_slow": "lento",
        "vision_tag": "visión",
        "no_screenshot_support": "Este modelo no soporta capturas de pantalla",
        "connected": "Conectado",
        "not_reachable": "No alcanzable",
        "checking_connection": "Verificando…",
        "transcription_language": "Idioma de Transcripción",
        "cv_resume": "CV / CURRÍCULUM",
        "cv_pdf": "CV / Currículum (PDF)",
        "hint_cv": "Ruta a tu CV — se usa para personalizar respuestas basadas en experiencia",
        "browse": "Examinar",
        "clear": "Limpiar",
        "general": "GENERAL",
        "theme": "Tema",
        "viewer_port": "Puerto del Visor",
        "show_menubar": "Mostrar icono en barra de menú",
        "menubar_icon": "Icono de barra de menú",
        "autostart_login": "Iniciar barra de menú al iniciar sesión",
        "interface_language": "Idioma de Interfaz",
        "saved": "Guardado",
        "restart_to_apply": "Reinicia la GUI para aplicar el idioma",

        "hotkeys_readonly": "Los atajos son de solo lectura durante una sesión activa",
        "press_keys": "Presiona cualquier tecla o combinación...",
        "reset_default": "Restablecer valor predeterminado",
        "beep_feedback": "Sonido de confirmación",
        "conflict": "⚠ Conflicto: {names}",

        "group_ai_actions": "Acciones IA",
        "group_screenshots": "Capturas y Contexto",
        "group_navigation": "Navegación del Visor",
        "group_ui": "Interfaz",

        "hk_trigger_query": "Enviar a IA",
        "hk_trigger_query_desc": "Envía transcripción + capturas a la IA y obtén una respuesta",
        "hk_copy_and_query": "Copiar y Enviar",
        "hk_copy_and_query_desc": "Copia el texto seleccionado del editor, luego envía todo a la IA",
        "hk_manual_recording": "Grabar Voz",
        "hk_manual_recording_desc": "Mantén pulsado para grabar tu voz, suelta para transcribir y enviar",
        "hk_toggle_code_mode": "Modo Código",
        "hk_toggle_code_mode_desc": "Alterna entre modo auto (puntos) y modo código (siempre código)",
        "hk_capture_screenshot": "Captura",
        "hk_capture_screenshot_desc": "Captura la ventana activa y la agrega a la siguiente consulta",
        "hk_scroll_up": "Desplazar Arriba",
        "hk_scroll_up_desc": "Desplaza el visor hacia arriba",
        "hk_scroll_down": "Desplazar Abajo",
        "hk_scroll_down_desc": "Desplaza el visor hacia abajo",
        "hk_nav_prev": "Anterior",
        "hk_nav_prev_desc": "Muestra la respuesta anterior de la IA",
        "hk_nav_next": "Siguiente",
        "hk_nav_next_desc": "Muestra la siguiente respuesta de la IA",
        "hk_font_size_up": "Texto Mayor",
        "hk_font_size_up_desc": "Aumenta el tamaño de fuente del visor",
        "hk_font_size_down": "Texto Menor",
        "hk_font_size_down_desc": "Disminuye el tamaño de fuente del visor",
        "hk_toggle_overlay": "Alternar Overlay",
        "hk_toggle_overlay_desc": "Muestra u oculta la ventana overlay del escritorio",

        "type_combined": "Mantener + Pulsar",
        "type_double_tap": "Doble Toque",
        "type_press_hold": "Tocar + Mantener",

        "menu_open_dashboard": "Abrir Panel",
        "menu_start_interview": "Iniciar Entrevista",
        "menu_stop_interview": "Detener Entrevista",
        "menu_restart": "Reiniciar",
        "menu_quit": "Salir",
    },

    "pt": {
        "app_title": "Assistente de Entrevistas IA",
        "dashboard": "Painel",
        "hotkeys": "Atalhos",
        "settings": "Configurações",
        "stopped": "Parado",
        "running": "Em execução",

        "interview_context": "CONTEXTO DA ENTREVISTA",
        "ai_provider": "PROVEDOR IA",
        "transcription": "TRANSCRIÇÃO",
        "challenge_type": "Tipo de Desafio",
        "code_challenge": "Desafio de Código",
        "system_design": "Design de Sistemas",
        "general_behavioural": "Geral / Comportamental",
        "programming_language": "Linguagem de Programação",
        "interview_brief": "Resumo da Entrevista (opcional)",
        "hint_code_challenge": "Cole a descrição da vaga, tópicos chave, requisitos de linguagem...",
        "hint_system_design": "Cole a descrição da vaga, requisitos do sistema, expectativas de escala...",
        "hint_general": "Cole a descrição da vaga, expectativas do cargo, tópicos para preparar...",
        "codebase_path": "Caminho do Código",
        "hint_codebase": "/caminho/do/repo (opcional)",
        "provider": "Provedor",
        "model": "Modelo",
        "transcriber": "Transcritor",
        "language": "Idioma",
        "ollama_free": "Ollama (grátis)",
        "gemini_free": "Gemini (grátis)",
        "whisper_free": "Whisper (grátis)",
        "start_interview": "Iniciar Entrevista",
        "starting": "Iniciando...",
        "failed_to_start": "Falha ao iniciar — verifique os logs",
        "model_not_available": "Modelo {model} indisponível. Baixe em Configurações.",
        "download_first": "Baixe o modelo primeiro",
        "no_models": "(sem modelos — baixe em Configurações)",
        "include_cv": "Incluir CV: {name}",
        "no_cv": "Sem CV anexado (configure em Ajustes)",

        "interview_in_progress": "Entrevista em andamento",
        "no_interview": "Nenhuma entrevista ativa",
        "stop": "Parar",
        "restart": "Reiniciar",
        "stopping": "Parando...",
        "restarting": "Reiniciando...",
        "provider_label": "Provedor",
        "model_label": "Modelo",
        "transcriber_label": "Transcritor",
        "language_label": "Linguagem",
        "transcription_label": "Transcrição",
        "uptime_label": "Tempo ativo",
        "codebase_label": "Código",

        "api_keys": "CHAVES API",
        "anthropic_api_key": "Chave API Anthropic",
        "google_api_key": "Chave API Google Gemini",
        "deepgram_api_key": "Chave API Deepgram",
        "hint_anthropic": "sk-ant-...",
        "hint_google": "AIza... (grátis em aistudio.google.com/apikey)",
        "hint_deepgram": "Opcional — usa Whisper local se vazio",
        "how_to_get_key": "Como obter uma chave",
        "help_claude": "1. Acesse console.anthropic.com\n2. Cadastre-se ou faça login\n3. Vá em Chaves de API\n4. Crie uma nova chave (começa com sk-ant-...)\n5. Nível grátis: $5 de crédito",
        "help_gemini": "1. Acesse aistudio.google.com/apikey\n2. Faça login com Google\n3. Clique em 'Criar chave de API'\n4. Copie a chave (começa com AIza...)\n5. Nível grátis: limites generosos",
        "help_deepgram": "1. Acesse console.deepgram.com\n2. Cadastre-se (grátis: $200 de crédito)\n3. Vá em Chaves de API\n4. Crie uma nova chave\n5. Opcional — Whisper (grátis) funciona sem isso",
        "default_provider": "Provedor Padrão",
        "claude_model": "Modelo Claude",
        "gemini_model": "Modelo Gemini",
        "local_model": "Modelo Local (Ollama)",
        "ollama_host": "Servidor Ollama",
        "hint_ollama_host": "http://localhost:11434 ou http://<ip-remoto>:11434",
        "download": "Baixar",
        "downloading": "Baixando {model}…",
        "model_ready": "{model} — pronto",
        "model_not_downloaded": "{model} — não baixado",
        "download_timed_out": "Download expirou",
        "ollama_not_installed": "Ollama não instalado. Execute: ai-interview version",
        "default_transcriber": "Transcritor Padrão",
        "whisper_host": "Servidor Whisper",
        "hint_whisper_host": "Vazio = local, ou http://<ip-remoto>:8000",
        "speed_fastest": "mais rápido",
        "speed_fast": "rápido",
        "speed_balanced": "equilibrado",
        "speed_slow": "lento",
        "vision_tag": "visão",
        "no_screenshot_support": "Este modelo não suporta capturas de tela",
        "connected": "Conectado",
        "not_reachable": "Não alcançável",
        "checking_connection": "Verificando…",
        "transcription_language": "Idioma de Transcrição",
        "cv_resume": "CV / CURRÍCULO",
        "cv_pdf": "CV / Currículo (PDF)",
        "hint_cv": "Caminho do seu CV — usado para personalizar respostas baseadas em experiência",
        "browse": "Procurar",
        "clear": "Limpar",
        "general": "GERAL",
        "theme": "Tema",
        "viewer_port": "Porta do Visualizador",
        "show_menubar": "Mostrar ícone na barra de menu",
        "menubar_icon": "Ícone da barra de menu",
        "autostart_login": "Iniciar barra de menu ao fazer login",
        "interface_language": "Idioma da Interface",
        "saved": "Salvo",
        "restart_to_apply": "Reinicie a GUI para aplicar o idioma",

        "hotkeys_readonly": "Atalhos são somente leitura durante uma sessão ativa",
        "press_keys": "Pressione qualquer tecla ou combinação...",
        "reset_default": "Restaurar padrão",
        "beep_feedback": "Som de confirmação",
        "conflict": "⚠ Conflito: {names}",

        "group_ai_actions": "Ações IA",
        "group_screenshots": "Capturas e Contexto",
        "group_navigation": "Navegação do Visualizador",
        "group_ui": "Interface",

        "hk_trigger_query": "Enviar para IA",
        "hk_trigger_query_desc": "Envia transcrição + capturas para a IA e obtém uma resposta",
        "hk_copy_and_query": "Copiar e Enviar",
        "hk_copy_and_query_desc": "Copia o texto selecionado do editor, depois envia tudo para a IA",
        "hk_manual_recording": "Gravar Voz",
        "hk_manual_recording_desc": "Segure para gravar sua voz, solte para transcrever e enviar",
        "hk_toggle_code_mode": "Modo Código",
        "hk_toggle_code_mode_desc": "Alterna entre modo auto (tópicos) e modo código (sempre código)",
        "hk_capture_screenshot": "Captura",
        "hk_capture_screenshot_desc": "Captura a janela ativa e adiciona à próxima consulta",
        "hk_scroll_up": "Rolar Acima",
        "hk_scroll_up_desc": "Rola o visualizador para cima",
        "hk_scroll_down": "Rolar Abaixo",
        "hk_scroll_down_desc": "Rola o visualizador para baixo",
        "hk_nav_prev": "Anterior",
        "hk_nav_prev_desc": "Mostra a resposta anterior da IA",
        "hk_nav_next": "Próximo",
        "hk_nav_next_desc": "Mostra a próxima resposta da IA",
        "hk_font_size_up": "Texto Maior",
        "hk_font_size_up_desc": "Aumenta o tamanho da fonte do visualizador",
        "hk_font_size_down": "Texto Menor",
        "hk_font_size_down_desc": "Diminui o tamanho da fonte do visualizador",
        "hk_toggle_overlay": "Alternar Overlay",
        "hk_toggle_overlay_desc": "Mostra ou esconde a janela overlay da área de trabalho",

        "type_combined": "Segurar + Pressionar",
        "type_double_tap": "Toque Duplo",
        "type_press_hold": "Tocar + Segurar",

        "menu_open_dashboard": "Abrir Painel",
        "menu_start_interview": "Iniciar Entrevista",
        "menu_stop_interview": "Parar Entrevista",
        "menu_restart": "Reiniciar",
        "menu_quit": "Sair",
    },
}

_current_lang = "en"


def set_language(lang: str) -> None:
    """Set the active GUI language."""
    global _current_lang
    _current_lang = lang if lang in _STRINGS else "en"


def get_language() -> str:
    return _current_lang


def t(key: str, **kwargs) -> str:
    """Translate a string key. Falls back to English. Supports {var} placeholders."""
    text = _STRINGS.get(_current_lang, _STRINGS["en"]).get(key, _STRINGS["en"].get(key, key))
    if kwargs:
        try:
            text = text.format(**kwargs)
        except (KeyError, IndexError):
            pass
    return text
