"""
多语言支持模块

提供简单的键值映射，将界面提示在英语与中文之间切换。
"""

from typing import Dict


class I18n:
    """全局多语言翻译器"""
    
    _language: str = "en"
    
    STRINGS: Dict[str, Dict[str, str]] = {
        "en": {
            # 通用
            "common_yes": "Yes",
            "common_no": "No",
            "common_operation_cancelled": "Operation cancelled",
            "common_invalid_option": "Invalid option, please try again",
            "common_press_key": "Press key to select:",
            "common_enter_option": "Please enter option: ",
            "common_generated_command_title": "Generated Command",
            "common_help_title": "Help",
            "common_warning": "Warning",
            
            # 主流程
            "warn_api_key_missing": "Warning: API key not configured, please configure it first",
            "error_agent_init_failed": "Failed to initialize AI Agent: {error}",
            "error_agent_not_initialized": "Error: AI Agent not initialized, please check configuration",
            "info_generating_command": "Generating command...",
            "error_generate_command": "Error: Failed to generate command - {error}",
            "info_command_cancelled": "Command execution cancelled",
            "title_recovery_suggestion": "Recovery Suggestion",
            "label_command": "Command: {command}",
            "label_tip": "Tip: {tip}",
            "warn_generating_recovery": "Command execution failed, generating a new suggestion based on error details...",
            "error_recovery_failed": "Failed to generate recovery suggestion: {error}",
            
            # 历史记录
            "history_none": "No history records",
            "history_total": "Total {count} history records:",
            "history_query": "  Query: {query}",
            "history_command": "  Command: {command}",
            "history_status_success": "✓ Success",
            "history_status_failed": "✗ Failed",
            "history_status": "  Status: {status}",
            "history_output": "  Output: {output}",
            "history_clear_confirm": "Are you sure you want to clear all history records? (y/N): ",
            "history_cleared": "✓ History records cleared",
            
            # 测试与提示
            "info_run_init_first": "Please run 'aibash --init' to configure first",
            "info_run_init_or_check": "Please run 'aibash --init' to configure, or check configuration file",
            "info_testing_connection": "Testing AI connection...",
            "info_connection_success": "✓ Connection successful",
            "info_connection_model": "Model: {model}",
            "info_connection_provider": "Provider: {provider}",
            "error_connection_failed": "✗ Connection failed, please check configuration and network connection",
            "error_initialization_failed": "Error: Initialization failed - {error}",
            "error_file_not_found": "Error: File not found - {error}",
            "error_generic": "Error: {error}",
            
            # 交互式选择
            "interactive_prompt_select": "Please select an action:",
            "interactive_option_execute": "[e] Execute command",
            "interactive_option_copy": "[c] Copy to clipboard",
            "interactive_option_modify": "[m] Modify command",
            "interactive_option_skip": "[s] Skip/Cancel",
            "interactive_option_help": "[h] Show help",
            "interactive_enter_modified": "Enter modified command (press Enter to use original): ",
            "interactive_current_command": "Current command: {command}",
            "interactive_executing": "Executing command: {command}",
            "interactive_launch_new_terminal": "Launching command in new terminal: {command}",
            "interactive_no_terminal_found": "No supported terminal emulator found (tried gnome-terminal, konsole, xterm)",
            "interactive_command_launched": "✓ Command launched in new terminal ({terminal})",
            "interactive_mac_terminal": "✓ Command launched in macOS Terminal",
            "interactive_windows_terminal": "✓ Command launched in new Command Prompt window",
            "interactive_output_not_captured": "Output not captured",
            "interactive_copy_success": "✓ Command copied to clipboard",
            "interactive_copy_failed": "✗ Failed to copy to clipboard (may need to install xclip/xsel/pyperclip)",
            "interactive_execution_success": "✓ Command executed successfully",
            "interactive_execution_failed": "✗ Command execution failed (exit code: {code})",
            "interactive_execution_timeout": "Command execution timeout (exceeded 5 minutes)",
            "interactive_execution_error": "Error executing command: {error}",
            
            # 自动化模式
            "automation_title": "Automation Mode",
            "automation_task": "Task: {task}",
            "automation_mode": "Mode: Step-by-step with confirmation",
            "automation_new_terminal": "New terminal: {state}",
            "automation_task_empty": "Automation task description is empty.",
            "automation_step_plan": "Step {index} Plan",
            "automation_step_action": "Action: {action}",
            "automation_step_reason": "Reason: {reason}",
            "automation_command_suggestion": "Model suggests executing the following command:",
            "automation_no_action": "Failed to obtain a valid action from model, automation stopped.",
            "automation_max_steps": "Reached maximum automation steps; the task may be unfinished.",
            "automation_invalid_action": "Unknown action type: {action}",
            "automation_missing_command": "Model did not provide a command to execute.",
            "automation_command_expectation": "Expected outcome: {expectation}",
            "automation_confirm_run_command": "Execute this command? (y/N): ",
            "automation_command_denied": "Command execution has been denied by user.",
            "automation_command_failed": "Command execution failed, automation will re-plan the next steps based on error details.",
            "automation_no_output_captured": "No output captured",
            "automation_file_request": "Model requested to read file: {path}",
            "automation_missing_path": "Model did not provide a file path.",
            "automation_file_missing": "File does not exist: {path}",
            "automation_file_binary": "File is not UTF-8 text or contains binary data.",
            "automation_file_error": "Failed to read file: {error}",
            "automation_file_denied": "File reading has been denied by user.",
            "automation_file_preview_title": "File Preview",
            "automation_confirm_read_file": "Read and display this file? (y/N): ",
            "automation_web_request": "Model requested to access URL: {url}",
            "automation_web_expectation": "Expected info: {expectation}",
            "automation_web_protocol": "Only http/https protocols are allowed.",
            "automation_web_denied": "Web request has been denied by user.",
            "automation_web_error": "Web request failed: {error}",
            "automation_ssl_error": "Web request failed because certificate verification did not succeed: {error}",
            "automation_ssl_prompt": "Retry without verifying the TLS certificate for {url}? (y/N): ",
            "automation_ssl_denied": "User declined to bypass certificate verification.",
            "automation_ssl_unverified_note": "Request executed without SSL verification; results may be insecure.",
            "automation_missing_url": "Model did not provide a URL to access.",
            "automation_confirm_web_request": "Continue with this web request? (y/N): ",
            "automation_question_title": "Model Question",
            "automation_finish_title": "Automation Finished",
            "automation_finish_message": "Message: {message}",
            "automation_finish_summary": "Summary: {summary}",
            "automation_auto_confirm": "Automation action auto-confirmed.",
            "automation_new_terminal_failed": "Failed to launch new terminal, fallback to current terminal execution",
            "automation_new_terminal_error": "Error launching new terminal: {error}",
            "automation_prompt_invalid_json": "Note: Previous response was not valid JSON. Please return JSON only. Last output:\n{response}",
            "automation_ask_user_prompt": "Please provide additional information (leave empty if unavailable): ",
            
            # 配置初始化
            "config_init_title": "AIBash Configuration Initialization",
            "config_init_language_prompt": "Select interface language (en/zh) [en]: ",
            "config_init_provider_prompt": "Please select AI model provider:",
            "config_init_option_openai": "  1. OpenAI API compatible services (e.g. OpenAI GPT, Qwen, Moonshot)",
            "config_init_option_ollama": "  2. Ollama (Local)",
            "config_init_input_option": "Enter option (1/2): ",
            "config_init_openai_tips": "Tip: Any service compatible with OpenAI API protocol can be used. Popular choices include GPT-4o, GPT-4.1, GPT-4.1-mini, Qwen-max, Moonshot, DeepSeek, etc.",
            "config_init_api_base": "API Base URL [{default}]: ",
            "config_init_api_key": "API Key (required): ",
            "config_init_model": "Model name [{default}]: ",
            "config_init_history_header": "\nHistory configuration:",
            "config_init_history_enabled": "Enable history? (Y/n): ",
            "config_init_history_max": "Max records [50]: ",
            "config_init_history_output": "Include command output? (Y/n): ",
            "config_init_system_header": "\nSystem information configuration:",
            "config_init_system_info": "System info (leave empty for auto-detection): ",
            "config_init_error_no_key": "Error: API Key cannot be empty",
            "config_init_save_success": "\n✓ Configuration saved to: {path}",
            "config_init_save_failed": "\n✗ Failed to save configuration: {error}",
            
            # 参数解析
            "parser_usage": "{prog} [-h] [-l QUERY | -a QUERY | -A QUERY] [-p PATH] [--config PATH] [-new] [--auto-approve-all] [--auto-approve-commands] [--auto-approve-files] [--auto-approve-web] [--auto-max-steps AUTO_MAX_STEPS] [--ui-language {{en,zh}}] [-v] [--init] [--history] [--clear-history] [--test]",
            "parser_description": "AI-powered shell command generator",
            "parser_epilog": "Examples:\n  aibash -l \"list all files in current directory\"\n  aibash -l \"find files containing test\"\n  aibash --config /path/to/config.yaml -l \"perform some operation\"\n\nFor more information, visit: https://github.com/W1412X/aibash",
            "help_lang_option": "Natural language description to generate a single shell command",
            "help_auto_option": "Automation mode: describe the task in natural language to let AI plan and execute step by step",
            "help_analyze_option": "Project analysis mode for large codebases; performs deep project inspection before planning actions",
            "help_plan_file": "Provide automation task description via file path",
            "help_config_option": "Specify config file path (default: ~/.aibash/config.yaml)",
            "help_new_terminal": "Execute generated commands in a new terminal window",
            "help_auto_approve_all": "Automation: automatically approve all actions without confirmation",
            "help_auto_approve_commands": "Automation: automatically execute shell commands without confirmation",
            "help_auto_approve_files": "Automation: automatically approve file reading actions",
            "help_auto_approve_web": "Automation: automatically approve outbound web requests",
            "help_auto_max_steps": "Automation: limit the maximum number of actions (default: 30)",
            "help_ui_language": "Select UI language for this session (default from config)",
            "help_plan_file": "Provide automation task description via file path",
            "help_version": "show program's version number and exit",
            "help_init": "Interactive configuration initialization",
            "help_history": "View command execution history",
            "help_clear_history": "Clear command execution history",
            "help_test": "Test AI connection",
            "error_auto_file_not_found": "Automation file not found: {path}",
            "error_auto_file_read": "Failed to read automation file {path}: {error}",
            "info_auto_file_loaded": "Loaded automation task from file: {path}",
            "error_auto_missing_query": "Automation mode requires a task description. Provide -a QUERY or use -p PATH.",
            "error_summarize_path_missing": "Summarize target does not exist: {path}",
            "error_summarize_not_text": "Skipping non-text or unreadable file: {path}",
            "info_summarize_start": "Generating summaries for {count} file(s) under {path} ...",
            "info_summarize_result": "Summary generated for {path}",
            "info_summarize_done": "Summaries completed.",
            "info_summary_cache_used": "Using cached summary for {path}",
            "info_summary_cache_saved": "Updated summary cache for {count} file(s).",
            "automation_file_preview_note": "File preview generated and passed to AI (content hidden). Metadata: {meta}",
            "warn_language_persist_failed": "Warning: failed to save UI language to config: {error}",
            
            # 其他
            "info_new_language": "UI language switched to {language}",
            "state_on": "ON",
            "state_off": "OFF",
        },
        "zh": {
            # 通用
            "common_yes": "是",
            "common_no": "否",
            "common_operation_cancelled": "操作已取消",
            "common_invalid_option": "无效的选项，请重试",
            "common_press_key": "按键直接选择：",
            "common_enter_option": "请输入选项：",
            "common_generated_command_title": "生成的命令",
            "common_help_title": "帮助",
            "common_warning": "警告",
            
            # 主流程
            "warn_api_key_missing": "警告：未配置 API Key，请先完成配置",
            "error_agent_init_failed": "初始化 AI Agent 失败：{error}",
            "error_agent_not_initialized": "错误：AI Agent 未初始化，请检查配置",
            "info_generating_command": "正在生成命令...",
            "error_generate_command": "错误：生成命令失败 - {error}",
            "info_command_cancelled": "命令执行已取消",
            "title_recovery_suggestion": "命令恢复建议",
            "label_command": "命令: {command}",
            "label_tip": "提示: {tip}",
            "warn_generating_recovery": "命令执行失败，正在根据错误信息生成新的建议...",
            "error_recovery_failed": "生成恢复建议失败：{error}",
            
            # 历史记录
            "history_none": "暂无历史记录",
            "history_total": "共 {count} 条历史记录：",
            "history_query": "  查询: {query}",
            "history_command": "  命令: {command}",
            "history_status_success": "✓ 成功",
            "history_status_failed": "✗ 失败",
            "history_status": "  状态: {status}",
            "history_output": "  输出: {output}",
            "history_clear_confirm": "确认清空所有历史记录？(y/N)：",
            "history_cleared": "✓ 历史记录已清空",
            
            # 测试与提示
            "info_run_init_first": "请先运行 'aibash --init' 完成配置",
            "info_run_init_or_check": "请运行 'aibash --init' 完成配置，或检查配置文件",
            "info_testing_connection": "正在测试 AI 连接...",
            "info_connection_success": "✓ 连接成功",
            "info_connection_model": "模型: {model}",
            "info_connection_provider": "提供商: {provider}",
            "error_connection_failed": "✗ 连接失败，请检查配置和网络",
            "error_initialization_failed": "错误：初始化失败 - {error}",
            "error_file_not_found": "错误：未找到文件 - {error}",
            "error_generic": "错误：{error}",
            
            # 交互式选择
            "interactive_prompt_select": "请选择操作：",
            "interactive_option_execute": "[e] 执行命令",
            "interactive_option_copy": "[c] 复制到剪贴板",
            "interactive_option_modify": "[m] 修改命令",
            "interactive_option_skip": "[s] 跳过/取消",
            "interactive_option_help": "[h] 显示帮助",
            "interactive_enter_modified": "请输入修改后的命令（直接回车使用原命令）：",
            "interactive_current_command": "当前命令: {command}",
            "interactive_executing": "正在执行命令: {command}",
            "interactive_launch_new_terminal": "在新终端中执行命令: {command}",
            "interactive_no_terminal_found": "未找到可用的终端模拟器（已尝试 gnome-terminal、konsole、xterm）",
            "interactive_command_launched": "✓ 已在新终端中执行命令（{terminal}）",
            "interactive_mac_terminal": "✓ 已在 macOS Terminal 中执行命令",
            "interactive_windows_terminal": "✓ 已在新的命令提示符窗口中执行命令",
            "interactive_output_not_captured": "未捕获输出",
            "interactive_copy_success": "✓ 命令已复制到剪贴板",
            "interactive_copy_failed": "✗ 复制到剪贴板失败（可能需要安装 xclip/xsel/pyperclip）",
            "interactive_execution_success": "✓ 命令执行成功",
            "interactive_execution_failed": "✗ 命令执行失败（退出码: {code}）",
            "interactive_execution_timeout": "命令执行超时（超过 5 分钟）",
            "interactive_execution_error": "执行命令出错: {error}",
            
            # 自动化模式
            "automation_title": "自动模式",
            "automation_task": "任务: {task}",
            "automation_mode": "模式: 步进执行并逐条确认",
            "automation_new_terminal": "新终端: {state}",
            "automation_task_empty": "自动化任务描述为空。",
            "automation_step_plan": "步骤 {index} 计划",
            "automation_step_action": "动作: {action}",
            "automation_step_reason": "原因: {reason}",
            "automation_command_suggestion": "模型建议执行以下命令：",
            "automation_no_action": "无法从模型获取有效动作，自动模式已停止。",
            "automation_max_steps": "达到自动模式最大步数限制，任务可能未完成。",
            "automation_invalid_action": "未知的动作类型：{action}",
            "automation_missing_command": "模型未提供要执行的命令。",
            "automation_command_expectation": "预期结果: {expectation}",
            "automation_confirm_run_command": "执行该命令吗？ (y/N)：",
            "automation_command_denied": "用户拒绝执行该命令。",
            "automation_command_failed": "命令执行失败，自动模式将根据错误信息重新规划后续步骤。",
            "automation_no_output_captured": "无输出或未捕获输出",
            "automation_file_request": "模型请求查看文件：{path}",
            "automation_missing_path": "模型未提供要读取的文件路径。",
            "automation_file_missing": "文件不存在：{path}",
            "automation_file_binary": "文件不是 UTF-8 文本或包含二进制数据。",
            "automation_file_error": "读取文件失败：{error}",
            "automation_file_denied": "用户拒绝读取文件。",
            "automation_file_preview_title": "文件预览",
            "automation_confirm_read_file": "读取并展示该文件吗？ (y/N)：",
            "automation_web_request": "模型请求访问网络资源：{url}",
            "automation_web_expectation": "预期用途: {expectation}",
            "automation_web_protocol": "仅允许 http/https 协议。",
            "automation_web_denied": "用户拒绝访问网络资源。",
            "automation_web_error": "网络访问失败：{error}",
            "automation_ssl_error": "网络访问因证书校验失败而终止：{error}",
            "automation_ssl_prompt": "是否忽略证书校验并重试访问 {url}？(y/N)：",
            "automation_ssl_denied": "用户拒绝忽略证书校验。",
            "automation_ssl_unverified_note": "已在未验证 SSL 证书的情况下执行请求，结果可能不安全。",
            "automation_missing_url": "模型未提供要访问的 URL。",
            "automation_confirm_web_request": "继续访问该链接吗？ (y/N)：",
            "automation_question_title": "模型提问",
            "automation_finish_title": "自动模式结束",
            "automation_finish_message": "提示: {message}",
            "automation_finish_summary": "总结: {summary}",
            "automation_auto_confirm": "自动模式已自动确认此操作。",
            "automation_new_terminal_failed": "无法启动新终端，将回退到当前终端执行",
            "automation_new_terminal_error": "启动新终端出错：{error}",
            "automation_prompt_invalid_json": "注意：上一次响应不是有效的 JSON，请严格返回 JSON。上一次输出：\n{response}",
            "automation_ask_user_prompt": "请输入补充信息（留空表示无法提供）：",
            
            # 配置初始化
            "config_init_title": "AIBash 配置初始化",
            "config_init_language_prompt": "请选择界面语言 (en/zh) [en]：",
            "config_init_provider_prompt": "请选择 AI 模型提供商：",
            "config_init_option_openai": "  1. OpenAI API 兼容服务（如 GPT、通义千问、Moonshot 等）",
            "config_init_option_ollama": "  2. Ollama（本地）",
            "config_init_input_option": "请输入选项 (1/2)：",
            "config_init_openai_tips": "提示：任何兼容 OpenAI API 协议的服务都可使用，常见模型包括 GPT-4o、GPT-4.1、Qwen-max、Moonshot、DeepSeek 等。",
            "config_init_api_base": "API 基础地址 [{default}]：",
            "config_init_api_key": "API Key（必填）：",
            "config_init_model": "模型名称 [{default}]：",
            "config_init_history_header": "\n历史记录配置：",
            "config_init_history_enabled": "启用历史记录？(Y/n)：",
            "config_init_history_max": "最大记录数 [50]：",
            "config_init_history_output": "是否保存命令输出？(Y/n)：",
            "config_init_system_header": "\n系统信息配置：",
            "config_init_system_info": "系统信息（留空则自动检测）：",
            "config_init_error_no_key": "错误：API Key 不能为空",
            "config_init_save_success": "\n✓ 配置已保存到：{path}",
            "config_init_save_failed": "\n✗ 保存配置失败：{error}",
            
            # 参数解析
            "parser_usage": "{prog} [-h] [-l QUERY | -a QUERY | -A QUERY] [-p PATH] [--config PATH] [-new] [--auto-approve-all] [--auto-approve-commands] [--auto-approve-files] [--auto-approve-web] [--auto-max-steps AUTO_MAX_STEPS] [--ui-language {{en,zh}}] [-v] [--init] [--history] [--clear-history] [--test]",
            "parser_description": "AI 命令行助手，用于根据自然语言生成 Shell 命令",
            "parser_epilog": "示例：\n  aibash -l \"列出当前目录下的所有文件\"\n  aibash -l \"查找包含 test 的文件\"\n  aibash --config /path/to/config.yaml -l \"执行某个操作\"\n\n更多信息请访问：https://github.com/W1412X/aibash",
            "help_lang_option": "根据自然语言描述生成单条 Shell 命令",
            "help_auto_option": "自动模式：根据自然语言描述规划并逐步执行任务",
            "help_analyze_option": "项目分析模式：适合大型代码库，会先深入分析项目再规划执行步骤",
            "help_plan_file": "通过文件路径提供自动模式任务描述",
            "help_config_option": "指定配置文件路径（默认: ~/.aibash/config.yaml）",
            "help_new_terminal": "在新的终端窗口中执行生成的命令",
            "help_auto_approve_all": "自动模式：自动批准所有动作（无需确认）",
            "help_auto_approve_commands": "自动模式：自动执行 Shell 命令",
            "help_auto_approve_files": "自动模式：自动批准文件读取操作",
            "help_auto_approve_web": "自动模式：自动批准网络请求",
            "help_auto_max_steps": "自动模式：限制最多执行的步骤数量（默认 30）",
            "help_ui_language": "选择当前会话的界面语言（默认读取配置）",
            "help_plan_file": "通过文件路径提供自动模式任务描述",
            "help_version": "显示程序版本并退出",
            "help_init": "交互式初始化配置文件",
            "help_history": "查看命令执行历史",
            "help_clear_history": "清空命令执行历史",
            "help_test": "测试 AI 连接",
            "error_auto_file_not_found": "未找到自动模式任务文件：{path}",
            "error_auto_file_read": "读取自动模式任务文件时出错 {path}：{error}",
            "info_auto_file_loaded": "已从文件加载自动模式任务：{path}",
            "error_auto_missing_query": "自动模式需要任务描述，请使用 -a QUERY 或 -p PATH。",
            "error_summarize_path_missing": "摘要目标不存在：{path}",
            "error_summarize_not_text": "跳过非文本或无法读取的文件：{path}",
            "info_summarize_start": "正在为 {path} 下的 {count} 个文件生成摘要...",
            "info_summarize_result": "已生成 {path} 的摘要",
            "info_summarize_done": "摘要生成完成。",
            "info_summary_cache_used": "复用缓存摘要：{path}",
            "info_summary_cache_saved": "已更新 {count} 个文件的摘要缓存。",
            "automation_file_preview_note": "已生成文件摘要（终端不展示内容），元信息：{meta}",
            "warn_language_persist_failed": "警告：无法将界面语言写入配置文件：{error}",
            
            # 其他
            "info_new_language": "界面语言已切换为 {language}",
            "state_on": "开启",
            "state_off": "关闭",
        },
    }
    
    @classmethod
    def set_language(cls, language: str):
        """设置全局语言"""
        if language in cls.STRINGS:
            cls._language = language
        else:
            cls._language = "en"
    
    @classmethod
    def get_language(cls) -> str:
        return cls._language
    
    @classmethod
    def translate(cls, key: str, **kwargs) -> str:
        lang = cls._language
        template = cls.STRINGS.get(lang, {}).get(key)
        if template is None:
            template = cls.STRINGS["en"].get(key, key)
        try:
            return template.format(**kwargs)
        except Exception:
            return template


def t(key: str, **kwargs) -> str:
    """便捷函数"""
    return I18n.translate(key, **kwargs)

