import os
from core.config import CONFIG

MESSAGES = {
    "zh": {
        # cbridge.py
        "cli_desc": "ContextBridge: 智能体本地记忆桥梁",
        "init_desc": "交互式初始化 ContextBridge 配置",
        "init_welcome": "[bold cyan]✨ 欢迎使用 ContextBridge 初始化向导！[/bold cyan]",
        "init_config_exists": "[yellow]⚠️  检测到已存在配置文件: {path}[/yellow]",
        "init_config_delete_confirm": "是否删除现有配置并重新初始化？",
        "init_config_deleted": "[green]✓[/green] 已删除现有配置",
        "init_workspace_delete_confirm": "是否同时删除工作区目录 {dir}？（包含所有索引数据）",
        "init_workspace_deleted": "[green]✓[/green] 已删除工作区目录",
        "init_cancelled": "[yellow]初始化已取消[/yellow]",
        "init_stopped_watcher": "[green]✓[/green] 已停止监控服务 (PID {pid})",
        "init_stopped_serve": "[green]✓[/green] 已停止 API 服务 (PID {pid})",
        "init_services_stopped": "[dim]所有运行中的服务已停止[/dim]",
        "init_stop_permission_error": "[red]❌ 权限不足，无法停止服务[/red]",
        "init_config_prompt": "\n[bold]开始配置 ContextBridge:[/bold]",
        "init_starting_daemon": "\n[bold cyan]🚀 正在启动后台服务...[/bold cyan]",
        "init_complete": "[bold green]✅ 初始化完成！ContextBridge 已在后台运行。[/bold green]",
        "init_daemon_failed": "[red]❌ 启动后台服务失败: {error}[/red]",
        "choose_lang": "请选择语言 / Choose language (zh/en)",
        "workspace_dir": "工作区目录",
        "config_saved": "[bold green]✅ 配置已保存至 {path}[/bold green]",
        "watch_desc": "管理监控目录",
        "watch_list_desc": "列出所有正在监控的目录",
        "watch_list_title": "[bold cyan]👀 当前正在监控的目录:[/bold cyan]",
        "watch_add_desc": "添加新的监控目录",
        "watch_add_success": "[bold green]✅ 已将 '{path}' 加入监控列表。[/bold green]",
        "watch_add_exists": "[yellow]⚠️ '{path}' 已经在监控列表中了。[/yellow]",
        "watch_add_not_exist": "[bold red]❌ 路径不存在: {path}[/bold red]",
        "watch_add_scanning": "[cyan]📂 正在扫描文件夹...[/cyan]",
        "watch_add_no_supported_files": "[yellow]⚠️  未发现支持的文件格式[/yellow]",
        "watch_add_supported_formats": "[dim]支持的格式: {formats}[/dim]",
        "watch_add_files_found": "[green]✅ 发现 {count} 个文件需要索引[/green]",
        "watch_add_many_files_hint": "[yellow]💡 检测到文件数量较多，建议后台执行以避免阻塞[/yellow]",
        "watch_add_background_confirm": "是否需要后台执行索引？(后台执行可立即返回，使用 'cbridge logs' 查看进度)",
        "watch_add_starting_background": "[cyan]🚀 启动后台索引进程...[/cyan]",
        "watch_add_background_started": "[green]✅ 文件夹已添加到监控列表，后台索引已启动[/green]",
        "watch_add_background_hint1": "[dim]💡 提示: 使用 'cbridge logs' 查看索引进度[/dim]",
        "watch_add_background_hint2": "[dim]💡 提示: 使用 'cbridge status' 查看系统状态[/dim]",
        "watch_add_background_failed": "[red]❌ 启动后台索引失败: {error}[/red]",
        "watch_add_fallback_foreground": "[yellow]⚠️  将改为前台执行索引...[/yellow]",
        "watch_add_starting_foreground": "[cyan]🔄 开始前台索引...[/cyan]",
        "watch_add_foreground_complete": "[green]✅ 文件夹已添加到监控列表并完成索引[/green]",
        "watch_add_foreground_hint1": "[dim]💡 提示: 使用 'cbridge start' 启动后台监控[/dim]",
        "watch_add_foreground_hint2": "[dim]💡 提示: 使用 'cbridge logs' 查看实时日志[/dim]",
        "watch_add_no_index_success": "[green]✅ 文件夹已添加到监控列表[/green]",
        "watch_add_no_index_hint1": "[dim]💡 提示: 使用 'cbridge start' 启动后台监控并自动索引[/dim]",
        "watch_add_no_index_hint2": "[dim]💡 提示: 使用 'cbridge index' 手动索引所有文件[/dim]",
        "watch_remove_desc": "移除指定的监控目录",
        "watch_remove_success": "[bold green]✅ 已将 '{path}' 从监控列表中移除。[/bold green]",
        "watch_remove_not_found": "[yellow]⚠️ '{path}' 不在监控列表中。[/yellow]",
        "index_desc": "对所有监控目录进行一次性全量索引",
        "index_start": "[bold cyan]🚀 开始全量构建索引...[/bold cyan]",
        "start_desc": "启动 ContextBridge 实时监控服务",
        "start_init": "[bold cyan]🔧 正在初始化 ContextBridge 工作区...[/bold cyan]",
        "start_engine": "[bold green]🚀 正在启动 ContextBridge 核心引擎...[/bold green]",
        "serve_desc": "启动 ContextBridge API 服务供 AI Agent 调用",
        "serve_stopped_existing": "[green]✓[/green] 已停止现有服务 (PID {pid})",
        "serve_cleaned_stale_pid": "[dim]已清理过期的 PID 文件[/dim]",
        "serve_stop_permission_error": "[red]❌ 权限不足，无法停止现有服务[/red]",
        "serve_start": "[bold cyan]🚀 正在启动 ContextBridge API 服务 (http://{host}:{port})...[/bold cyan]",
        "serve_foreground_start": "[bold cyan]🚀 正在前台启动 ContextBridge API 服务 (http://{host}:{port})...[/bold cyan]",
        "serve_daemon_start": "[bold green]✓[/bold green] ContextBridge 已在后台启动 (PID: {pid})",
        "serve_daemon_url": "[cyan]访问地址: http://{host}:{port}[/cyan]",
        "serve_daemon_hint": "[dim]日志保存至: ~/.cbridge/logs/cbridge-serve.log[/dim]",
        "search_desc": "在知识库中进行语义检索",
        "search_empty": "[yellow]📭 未找到相关结果。[/yellow]",
        "search_filtered": "[dim]已过滤 {count} 个低相似度结果 (阈值: {threshold:.2f})[/dim]",
        "search_reranked": "[dim]✨ 已根据关键词匹配重新排序[/dim]",
        "search_empty_after_filter": "[yellow]📭 过滤后未找到符合条件的结果。[/yellow]",
        "search_results_title": "\n[bold cyan]🔍 检索结果: '{query}'[/bold cyan]\n" + "="*40,
        "search_result_item": "\n[bold green]📄 来源:[/bold green] {source} [dim](相似度: {score:.4f})[/dim]\n{line}\n{content}\n",
        "search_result_item_numbered": "\n[bold green]#{idx} 📄 来源:[/bold green] {source} [dim](相似度: {score:.4f})[/dim]\n{line}\n{content}\n",
        
        # Explainable search results
        "explain_result_header": "\n[bold green]#{idx} 📄 来源:[/bold green] {source}",
        "explain_match_score": "   [bold cyan]✅ 匹配度:[/bold cyan] {score:.1f}%",
        "explain_keywords": "   [bold yellow]🔑 关键词:[/bold yellow] 命中 {matched}/{total} - {keywords}",
        "explain_details_header": "   [bold magenta]📊 匹配详情:[/bold magenta]",
        "explain_semantic_score": "      • 语义相似度: {score:.1f}%",
        "explain_keyword_score": "      • 关键词匹配: {score:.1f}%",
        "explain_final_score": "      • 综合得分: {score:.1f}% (语义70% + 关键词30%)",
        "explain_content_preview": "   [bold blue]📝 内容预览:[/bold blue]",
        "explain_no_keywords": "无",
        "explain_abstract_label": "[bold cyan]📖 摘要:[/bold cyan]",
        "search_abstract_label": "[bold]摘要:[/bold]",
        "search_excerpts_label": "[bold]相关片段:[/bold]",
        "search_no_content": "无内容",
        
        "status_desc": "查看当前配置和运行状态",
        "status_title": "[bold cyan]📊 ContextBridge 运行状态:[/bold cyan]",
        "status_lang": "  [bold]当前语言:[/bold] {lang}",
        "status_workspace": "  [bold]工作区:[/bold] {workspace}",
        "status_ov_mount": "  [bold]OpenViking 挂载点:[/bold] {mount}",
        "status_qmd_coll": "  [bold]QMD 集合:[/bold] {coll}",
        "status_mcp_port": "  [bold]MCP 端口:[/bold] {port}",
        "config_desc": "查看当前配置文件路径及内容",
        "config_title": "[bold cyan]⚙️ 配置文件:[/bold cyan] {path}",
        "config_content": "\n[bold]内容:[/bold]\n" + "-"*40,
        "config_not_found": "[yellow]⚠️ 未找到 config.yaml，当前使用默认内嵌配置。[/yellow]",
        "mcp_desc": "启动 MCP Server 供 Claude 接入",
        "mcp_start": "[bold cyan]🔌 正在启动 ContextBridge MCP 服务...[/bold cyan]",
        "lang_desc": "切换显示语言 / Switch display language",
        "lang_success": "[bold green]✅ 语言已切换为: {lang}[/bold green]",
        "workspace_init": "[dim]工作区已初始化于 {dir}[/dim]",
        "logs_desc": "查看实时日志",
        "logs_lines_help": "显示最后 N 行日志",
        "logs_follow_help": "实时跟踪日志（类似 tail -f）",
        "logs_not_found": "[yellow]⚠️  日志文件不存在: {file}[/yellow]",
        "logs_hint": "[dim]💡 提示: 使用 'cbridge start' 启动后台服务后会生成日志[/dim]",
        "logs_follow_mode": "[cyan]📝 实时跟踪日志:[/cyan] {file}",
        "logs_exit_hint": "[dim]按 Ctrl+C 退出[/dim]",
        "logs_file": "[cyan]📝 日志文件:[/cyan] {file}",
        "logs_showing": "[dim]显示最后 {lines} 行[/dim]",
        "logs_follow_hint": "\n[dim]💡 提示: 使用 'cbridge logs -f' 实时跟踪日志[/dim]",
        "logs_stopped": "\n[yellow]已停止跟踪日志[/yellow]",
        "logs_error": "[red]❌ 读取日志失败: {error}[/red]",
        
        # model_downloader.py
        "mdl_first_run": "\n[bold cyan]✨ 首次运行: 正在为您准备本地 AI 向量模型 ({model_name})[/bold cyan]",
        "mdl_desc": "[dim]该模型用于将您的文档转换为 AI 可理解的数学向量，仅需下载一次。[/dim]",
        "mdl_downloading": "下载模型中...",
        "mdl_extracting": "[bold green]✅ 下载完成！正在解压模型...[/bold green]",
        "mdl_ready": "[bold green]🎉 模型准备就绪！[/bold green]\n",
        "mdl_failed": "\n[bold red]❌ 模型下载失败: {error}[/bold red]",
        "mdl_hint": "[yellow]💡 提示: 这通常是因为网络连接 AWS S3 较慢。[/yellow]",
        "mdl_manual": "[yellow]请尝试开启代理，或者手动下载以下链接并解压到 {cache_dir} 目录下：[/yellow]",
        
        # openviking_manager.py
        "ov_init_embed": "[dim]⚙️ 初始化内嵌 OpenViking 管理器, 挂载路径: {mount_path}[/dim]",
        "ov_write_embed": "[cyan]📝 [OpenViking] 正在处理上下文:[/cyan] {uri}",
        "ov_del_embed": "[yellow]🗑️ [OpenViking] 正在删除上下文:[/yellow] {uri}",
        "ov_ret_embed": "[magenta]🧠 [OpenViking] 执行目录递归检索策略:[/magenta] '{query}'",
        
        # qmd_runtime.py
        "qmd_init_embed": "[dim]⚙️ 初始化内嵌 QMD 引擎 (基于 ChromaDB)...[/dim]",

        
        # parser.py
        "parse_start": "[dim]📄 正在解析文档:[/dim] {file_path}",
        "parse_failed": "[bold red]❌ 解析失败 {file_path}:[/bold red] {error}",
        
        # watcher.py
        "watch_del": "[yellow]🗑️ 文件已删除:[/yellow] {name}",
        "watch_event": "[green]📄 文件已{event}:[/green] {name}",
        "watch_ev_create": "创建",
        "watch_ev_modify": "修改",
        "watch_ev_delete": "删除",
        "watch_vectorizing": "[cyan]🔄 正在向量化:[/cyan] {name}",
        "watch_vectorize_success": "[green]✅ 向量化成功:[/green] {name}",
        "watch_vectorize_failed": "[red]❌ 向量化失败:[/red] {name}",
        "watch_vectorize_reason": "   [dim]原因:[/dim] {error}",
        "watch_performance_mode": "[cyan]📊 性能模式：{mode}[/cyan]",
        "watch_poll_interval": "   - 轮询间隔：{interval}秒",
        "watch_debounce_time": "   - 防抖时间：{seconds}秒",
        "watch_max_file_size": "   - 最大文件大小：{size}MB",
        "watch_queue_size": "   - 任务队列大小：{size}",
        "watch_worker_threads": "   - Worker 线程数：{count}",
        "watch_workers_started": "[green]✅ 已启动 {count} 个 worker 线程[/green]",
        "watch_skip_large_file": "[yellow]⚠️  跳过大文件：{name} ({size:.1f}MB > {max_size}MB)[/yellow]",
        "watch_queue_full": "[yellow]⚠️  任务队列已满，丢弃事件：{name}[/yellow]",
        "watch_resource_stats": "[cyan]📊 资源监控统计:[/cyan]",
        "watch_queue_drops": "   - 队列丢弃事件：{count}",
        "watch_large_file_skips": "   - 跳过大文件：{count}",
        "watch_stopped": "[green]✅ ContextBridge watcher stopped.[/green]",
        "watch_error_processing": "[red]❌ 处理文件出错:[/red] {file_path} - {error}",
        "watch_worker_fatal": "[red]❌ Worker 线程致命错误:[/red] {error}",
        "watch_init_failed": "[red]❌ 初始化系统失败:[/red] {error}",
        "watch_schedule_error": "[red]❌ 调度监控目录出错:[/red] {error}",
        "watch_loop_error": "[red]❌ 监控循环出错:[/red] {error}",
        "watch_started_success": "[green]✅ ContextBridge 监控服务启动成功[/green]",
        "idx_success_log": "成功索引: {name}",
        "idx_failed_log": "索引失败 {name}: {error}",
        "idx_no_files": "[yellow]📭 未找到需要索引的文件。[/yellow]",
        "idx_scanning_dir": "[cyan]📂 扫描文件夹:[/cyan] {directory}",
        "idx_files_found": "[green]✅ 发现 {count} 个文件[/green]",
        "idx_starting_vectorize": "[cyan]🔄 开始向量化...[/cyan]",
        "idx_vectorize_complete": "[green]✅ 向量化完成！[/green]",
        "idx_summary": "[dim]成功: {success} | 失败: {failed}[/dim]",
        "idx_found": "[bold cyan]📦 找到 {count} 个文件，开始构建索引...[/bold cyan]",
        "idx_ghost_clean": "[yellow]🧹 发现 {count} 个已删除的幽灵文件，正在清理...[/yellow]",
        "idx_progress": "正在解析并向量化...",
        "idx_file_count": "{completed}/{total} 文件",
        "idx_complete": "[bold green]✅ 索引构建完成！[/bold green]",
        "watch_dir": "[bold cyan]👀 正在监控目录变更:[/bold cyan] {dir}",
        
        # Additional cbridge.py messages
        "failed_files_header": "[yellow]失败的文件:[/yellow]",
        "and_more": "[dim]... 还有 {count} 个[/dim]",
        "watcher_started_bg": "[green]✅ ContextBridge 监控服务已在后台启动 (PID {pid})[/green]",
        "logs_location": "[dim]📝 日志: {path}[/dim]",
        "logs_view_hint": "[dim]💡 使用 'cbridge logs -f' 查看实时日志[/dim]",
        "stop_hint": "[dim]💡 使用 'cbridge stop' 停止监控服务[/dim]",
        "watcher_already_running": "[red]❌ 监控服务已在运行 (PID: {pid})[/red]",
        "stop_first_hint": "[dim]请先使用 'cbridge stop' 停止它[/dim]",
        "api_server_detected": "[yellow]⚠️  检测到 API 服务器正在运行（PID: {pid}）[/yellow]",
        "api_has_watcher": "[yellow]API 服务器已包含文件监控功能，无需单独启动 watcher[/yellow]",
        "suggestion_header": "[cyan]建议：[/cyan]",
        "suggestion_serve_fg": "  - 如需同时运行，请使用：[green]cbridge serve --foreground[/green]",
        "suggestion_stop_api": "  - 或先停止 API 服务器：[green]cbridge stop[/green]",
        "continue_watcher_confirm": "是否继续启动 watcher？",
        "cancelled_watcher": "[dim]已取消启动 watcher[/dim]",
        "continuing_watcher": "[dim]继续启动 watcher...[/dim]",
        "watcher_running_fg": "[green]✅ ContextBridge 监控服务正在前台运行...[/green]",
        "press_ctrl_c": "[dim]按 Ctrl+C 停止[/dim]",
        "watcher_running": "[green]✅ ContextBridge 监控服务正在运行...[/green]",
        "api_already_running": "[red]❌ API 服务器已在运行 (PID: {pid})[/red]",
        "no_permission_stop_watcher": "[red]❌ 无权限停止 watcher 进程（PID: {pid}）[/red]",
        "port_in_use": "[yellow]⚠️ 端口 {original} 已被占用，改用端口 {new}[/yellow]",
        "watcher_stopped": "[green]✅ 监控服务 (PID {pid}) 已停止[/green]",
        "watcher_not_found": "[yellow]⚠️  监控进程未找到，正在清理 PID 文件[/yellow]",
        "no_permission_stop": "[red]❌ 无权限停止监控进程[/red]",
        "daemon_stopped": "[green]✅ 后台服务 (PID {pid}) 已停止[/green]",
        "process_not_found": "[yellow]⚠️  进程 {pid} 未找到，正在清理 PID 文件[/yellow]",
        "no_permission_stop_process": "[red]❌ 无权限停止进程 {pid}[/red]",
        "no_daemon_found": "[yellow]⚠️  未找到后台服务 PID 文件。是否有服务在运行？[/yellow]",
        "watcher_status_running": "[green]✅ 监控服务: 运行中 (PID {pid})[/green]",
        "watcher_status_stale": "[yellow]⚠️  监控服务: 未运行 (过期 PID {pid})[/yellow]",
        "watcher_status_not_running": "[yellow]⚠️  监控服务: 未运行[/yellow]",
        "api_status_running": "[green]✅ API 服务器: 运行中 (PID {pid})[/green]",
        "api_status_stale": "[yellow]⚠️  API 服务器: 未运行 (过期 PID {pid})[/yellow]",
        "api_status_not_running": "[yellow]⚠️  API 服务器: 未运行[/yellow]",
        "cleanup_skip_warning": "[yellow]⚠️  已跳过向量数据清理[/yellow]",
        "cleanup_skip_hint": "[dim]💡 提示: 向量数据仍保留在数据库中[/dim]",
        "cleanup_scanning": "[cyan]🔄 正在扫描文件夹...[/cyan]",
        "cleanup_no_files": "[yellow]⚠️  未找到需要清理的文件[/yellow]",
        "cleanup_files_found": "[green]✅ 发现 {count} 个文件需要清理[/green]",
        "cleanup_background": "[cyan]🚀 清理任务已转入后台执行[/cyan]",
        "cleanup_progress_hint": "[dim]💡 使用 'cbridge logs -f' 查看实时清理进度[/dim]",
        "cleanup_log_file": "[dim]📝 日志文件: {path}[/dim]",
        "cleanup_deleted": "[green]✅ [{idx}/{total}][/green] {filename}",
        "cleanup_not_found": "[yellow]⚠️  [{idx}/{total}][/yellow] {filename} (未找到)",
        "cleanup_failed": "[red]❌ [{idx}/{total}][/red] {filename} - {error}",
        "cleanup_summary_header": "[bold cyan]📊 清理汇总[/bold cyan]",
        "cleanup_total": "[dim]总文件数:[/dim] {count}",
        "cleanup_success": "[green]成功:[/green] {count}",
        "cleanup_failed_count": "[yellow]失败/未找到:[/yellow] {count}",
        "cleanup_complete": "[green]✅ 向量数据清理完成[/green]",
        "cleanup_error": "[red]❌ 清理过程出错: {error}[/red]",
        "cleanup_start_failed": "[red]❌ 启动清理任务失败: {error}[/red]",
        "cleanup_in_progress": "[dim]正在清理，请稍候...[/dim]",
        "watcher_auto_stopped": "[cyan]检测到 watcher 进程运行中，已自动停止[/cyan]",
        
        # repo_manager.py
        "repo_auto_sync_started": "[dim]⏱️ 自动拉取 GitHub 仓库的后台任务已启动[/dim]",
        
        # update command
        "update_desc": "升级 ContextBridge 到最新版本",
        "update_start": "[bold cyan]🚀 正在联网升级 ContextBridge...[/bold cyan]",
        "update_success": "[bold green]✅ 升级成功！请重启相关服务以应用更新。[/bold green]",
        "update_failed": "[bold red]❌ 升级失败:[/bold red] {error}",
    },
    "en": {
        # cbridge.py
        "cli_desc": "ContextBridge: An intelligent context management bridge",
        "init_desc": "Interactively initialize ContextBridge configuration",
        "init_welcome": "[bold cyan]✨ Welcome to ContextBridge Initialization Wizard![/bold cyan]",
        "init_config_exists": "[yellow]⚠️  Existing configuration detected: {path}[/yellow]",
        "init_config_delete_confirm": "Delete existing configuration and reinitialize?",
        "init_config_deleted": "[green]✓[/green] Existing configuration deleted",
        "init_workspace_delete_confirm": "Also delete workspace directory {dir}? (includes all indexed data)",
        "init_workspace_deleted": "[green]✓[/green] Workspace directory deleted",
        "init_cancelled": "[yellow]Initialization cancelled[/yellow]",
        "init_stopped_watcher": "[green]✓[/green] Stopped watcher service (PID {pid})",
        "init_stopped_serve": "[green]✓[/green] Stopped API service (PID {pid})",
        "init_services_stopped": "[dim]All running services stopped[/dim]",
        "init_stop_permission_error": "[red]❌ Permission denied to stop services[/red]",
        "init_config_prompt": "\n[bold]Configure ContextBridge:[/bold]",
        "init_starting_daemon": "\n[bold cyan]🚀 Starting background service...[/bold cyan]",
        "init_complete": "[bold green]✅ Initialization complete! ContextBridge is now running in the background.[/bold green]",
        "init_daemon_failed": "[red]❌ Failed to start background service: {error}[/red]",
        "choose_lang": "Choose language / 请选择语言",
        "workspace_dir": "Workspace Directory",
        "config_saved": "[bold green]✅ Configuration saved to {path}[/bold green]",
        "watch_desc": "Manage monitored directories",
        "watch_list_desc": "List all monitored directories",
        "watch_list_title": "[bold cyan]👀 Currently monitored directories:[/bold cyan]",
        "watch_add_desc": "Add a new directory to monitor",
        "watch_add_success": "[bold green]✅ Added '{path}' to monitored list.[/bold green]",
        "watch_add_exists": "[yellow]⚠️ '{path}' is already in the monitored list.[/yellow]",
        "watch_add_not_exist": "[bold red]❌ Path does not exist: {path}[/bold red]",
        "watch_add_scanning": "[cyan]📂 Scanning folder...[/cyan]",
        "watch_add_no_supported_files": "[yellow]⚠️  No supported file formats found[/yellow]",
        "watch_add_supported_formats": "[dim]Supported formats: {formats}[/dim]",
        "watch_add_files_found": "[green]✅ Found {count} files to index[/green]",
        "watch_add_many_files_hint": "[yellow]💡 Many files detected, background execution recommended to avoid blocking[/yellow]",
        "watch_add_background_confirm": "Run indexing in background? (background execution returns immediately, use 'cbridge logs' to view progress)",
        "watch_add_starting_background": "[cyan]🚀 Starting background indexing process...[/cyan]",
        "watch_add_background_started": "[green]✅ Folder added to monitored list, background indexing started[/green]",
        "watch_add_background_hint1": "[dim]💡 Tip: Use 'cbridge logs' to view indexing progress[/dim]",
        "watch_add_background_hint2": "[dim]💡 Tip: Use 'cbridge status' to view system status[/dim]",
        "watch_add_background_failed": "[red]❌ Failed to start background indexing: {error}[/red]",
        "watch_add_fallback_foreground": "[yellow]⚠️  Falling back to foreground execution...[/yellow]",
        "watch_add_starting_foreground": "[cyan]🔄 Starting foreground indexing...[/cyan]",
        "watch_add_foreground_complete": "[green]✅ Folder added to monitored list and indexing complete[/green]",
        "watch_add_foreground_hint1": "[dim]💡 Tip: Use 'cbridge start' to start background monitoring[/dim]",
        "watch_add_foreground_hint2": "[dim]💡 Tip: Use 'cbridge logs' to view real-time logs[/dim]",
        "watch_add_no_index_success": "[green]✅ Folder added to monitored list[/green]",
        "watch_add_no_index_hint1": "[dim]💡 Tip: Use 'cbridge start' to start background monitoring and auto-indexing[/dim]",
        "watch_add_no_index_hint2": "[dim]💡 Tip: Use 'cbridge index' to manually index all files[/dim]",
        "watch_remove_desc": "Remove a monitored directory",
        "watch_remove_success": "[bold green]✅ Removed '{path}' from monitored list.[/bold green]",
        "watch_remove_not_found": "[yellow]⚠️ '{path}' is not in the monitored list.[/yellow]",
        "index_desc": "Run a one-time full index on all monitored directories",
        "index_start": "[bold cyan]🚀 Starting full index build...[/bold cyan]",
        "start_desc": "Start ContextBridge real-time monitoring service",
        "start_init": "[bold cyan]🔧 Initializing ContextBridge workspace...[/bold cyan]",
        "start_engine": "[bold green]🚀 Starting ContextBridge core engine...[/bold green]",
        "serve_desc": "Start ContextBridge API service for AI Agents",
        "serve_stopped_existing": "[green]✓[/green] Stopped existing service (PID {pid})",
        "serve_cleaned_stale_pid": "[dim]Cleaned up stale PID file[/dim]",
        "serve_stop_permission_error": "[red]❌ Permission denied to stop existing service[/red]",
        "serve_start": "[bold cyan]🚀 Starting ContextBridge API service (http://{host}:{port})...[/bold cyan]",
        "serve_foreground_start": "[bold cyan]🚀 Starting ContextBridge API service in foreground (http://{host}:{port})...[/bold cyan]",
        "serve_daemon_start": "[bold green]✓[/bold green] ContextBridge started in background (PID: {pid})",
        "serve_daemon_url": "[cyan]Access at: http://{host}:{port}[/cyan]",
        "serve_daemon_hint": "[dim]Logs are saved to: ~/.cbridge/logs/cbridge-serve.log[/dim]",
        "search_desc": "Perform semantic search in the knowledge base",
        "search_empty": "[yellow]📭 No relevant results found.[/yellow]",
        "search_filtered": "[dim]Filtered {count} low-similarity results (threshold: {threshold:.2f})[/dim]",
        "search_reranked": "[dim]✨ Reranked by keyword matching[/dim]",
        "search_empty_after_filter": "[yellow]📭 No results found after filtering.[/yellow]",
        "search_results_title": "\n[bold cyan]� Search Results: '{query}'[/bold cyan]\n" + "="*40,
        "search_result_item": "\n[bold green]📄 Source:[/bold green] {source} [dim](Score: {score:.4f})[/dim]\n{line}\n{content}\n",
        "search_result_item_numbered": "\n[bold green]#{idx} 📄 Source:[/bold green] {source} [dim](Score: {score:.4f})[/dim]\n{line}\n{content}\n",
        
        # Explainable search results
        "explain_result_header": "\n[bold green]#{idx} 📄 Source:[/bold green] {source}",
        "explain_match_score": "   [bold cyan]✅ Match Score:[/bold cyan] {score:.1f}%",
        "explain_keywords": "   [bold yellow]🔑 Keywords:[/bold yellow] Matched {matched}/{total} - {keywords}",
        "explain_details_header": "   [bold magenta]📊 Match Details:[/bold magenta]",
        "explain_semantic_score": "      • Semantic similarity: {score:.1f}%",
        "explain_keyword_score": "      • Keyword matching: {score:.1f}%",
        "explain_final_score": "      • Final score: {score:.1f}% (70% semantic + 30% keyword)",
        "explain_content_preview": "   [bold blue]📝 Content Preview:[/bold blue]",
        "explain_no_keywords": "None",
        "explain_abstract_label": "[bold cyan]📖 Abstract:[/bold cyan]",
        "search_abstract_label": "[bold]Abstract:[/bold]",
        "search_excerpts_label": "[bold]Relevant Excerpts:[/bold]",
        "search_no_content": "No content available",
        
        "status_desc": "View current configuration and running status",
        "status_title": "[bold cyan]📊 ContextBridge Status:[/bold cyan]",
        "status_lang": "  [bold]Language:[/bold] {lang}",
        "status_workspace": "  [bold]Workspace:[/bold] {workspace}",
        "status_ov_mount": "  [bold]OpenViking Mount:[/bold] {mount}",
        "status_qmd_coll": "  [bold]QMD Collection:[/bold] {coll}",
        "status_mcp_port": "  [bold]MCP Port:[/bold] {port}",
        "config_desc": "View current configuration file path and content",
        "config_title": "[bold cyan]⚙️ Config File:[/bold cyan] {path}",
        "config_content": "\n[bold]Content:[/bold]\n" + "-"*40,
        "config_not_found": "[yellow]⚠️ config.yaml not found, using default embedded configuration.[/yellow]",
        "mcp_desc": "Start MCP Server for Claude integration",
        "mcp_start": "[bold cyan]🔌 Starting ContextBridge MCP Service...[/bold cyan]",
        "lang_desc": "切换显示语言 / Switch display language",
        "lang_success": "[bold green]✅ Language switched to: {lang}[/bold green]",
        "workspace_init": "[dim]Workspace initialized at {dir}[/dim]",
        "logs_desc": "View real-time logs",
        "logs_lines_help": "Display last N lines of logs",
        "logs_follow_help": "Follow logs in real-time (like tail -f)",
        "logs_not_found": "[yellow]⚠️  Log file not found: {file}[/yellow]",
        "logs_hint": "[dim]💡 Hint: Logs are generated after starting the background service with 'cbridge start'[/dim]",
        "logs_follow_mode": "[cyan]📝 Following logs:[/cyan] {file}",
        "logs_exit_hint": "[dim]Press Ctrl+C to exit[/dim]",
        "logs_file": "[cyan]📝 Log file:[/cyan] {file}",
        "logs_showing": "[dim]Showing last {lines} lines[/dim]",
        "logs_follow_hint": "\n[dim]💡 Hint: Use 'cbridge logs -f' to follow logs in real-time[/dim]",
        "logs_stopped": "\n[yellow]Stopped following logs[/yellow]",
        "logs_error": "[red]❌ Failed to read logs: {error}[/red]",
        
        # model_downloader.py
        "mdl_first_run": "\n[bold cyan]✨ First run: Preparing local AI vector model ({model_name})[/bold cyan]",
        "mdl_desc": "[dim]This model converts your documents into AI-understandable mathematical vectors. It only needs to be downloaded once.[/dim]",
        "mdl_downloading": "Downloading model...",
        "mdl_extracting": "[bold green]✅ Download complete! Extracting model...[/bold green]",
        "mdl_ready": "[bold green]🎉 Model is ready![/bold green]\n",
        "mdl_failed": "\n[bold red]❌ Model download failed: {error}[/bold red]",
        "mdl_hint": "[yellow]💡 Hint: This is usually due to slow network connection to AWS S3.[/yellow]",
        "mdl_manual": "[yellow]Please try using a proxy, or manually download the following link and extract it to {cache_dir}:[/yellow]",
        
        # openviking_manager.py
        "ov_init_embed": "[dim]⚙️ Initializing embedded OpenViking manager, mount path: {mount_path}[/dim]",
        "ov_write_embed": "[cyan]📝 [OpenViking] Processing context:[/cyan] {uri}",
        "ov_del_embed": "[yellow]🗑️ [OpenViking] Deleting context:[/yellow] {uri}",
        "ov_ret_embed": "[magenta]🧠 [OpenViking] Executing directory recursive retrieval strategy:[/magenta] '{query}'",
        
        # qmd_runtime.py
        "qmd_init_embed": "[dim]⚙️ Initializing embedded QMD engine (based on ChromaDB)...[/dim]",

        
        # parser.py
        "parse_start": "[dim]📄 Parsing document:[/dim] {file_path}",
        "parse_failed": "[bold red]❌ Parsing failed {file_path}:[/bold red] {error}",
        
        # watcher.py
        "watch_del": "[yellow]🗑️ File deleted:[/yellow] {name}",
        "watch_event": "[green]📄 File {event}:[/green] {name}",
        "watch_ev_create": "created",
        "watch_ev_modify": "modified",
        "watch_ev_delete": "deleted",
        "watch_vectorizing": "[cyan]🔄 Vectorizing:[/cyan] {name}",
        "watch_vectorize_success": "[green]✅ Vectorization successful:[/green] {name}",
        "watch_vectorize_failed": "[red]❌ Vectorization failed:[/red] {name}",
        "watch_vectorize_reason": "   [dim]Reason:[/dim] {error}",
        "watch_performance_mode": "[cyan]📊 Performance mode: {mode}[/cyan]",
        "watch_poll_interval": "   - Poll interval: {interval}s",
        "watch_debounce_time": "   - Debounce time: {seconds}s",
        "watch_max_file_size": "   - Max file size: {size}MB",
        "watch_queue_size": "   - Task queue size: {size}",
        "watch_worker_threads": "   - Worker threads: {count}",
        "watch_workers_started": "[green]✅ Started {count} worker threads[/green]",
        "watch_skip_large_file": "[yellow]⚠️  Skipping large file: {name} ({size:.1f}MB > {max_size}MB)[/yellow]",
        "watch_queue_full": "[yellow]⚠️  Task queue full, dropping event: {name}[/yellow]",
        "watch_resource_stats": "[cyan]📊 Resource monitoring stats:[/cyan]",
        "watch_queue_drops": "   - Queue dropped events: {count}",
        "watch_large_file_skips": "   - Large files skipped: {count}",
        "watch_stopped": "[green]✅ ContextBridge watcher stopped.[/green]",
        "watch_error_processing": "[red]❌ Error processing file:[/red] {file_path} - {error}",
        "watch_worker_fatal": "[red]❌ Worker thread fatal error:[/red] {error}",
        "watch_init_failed": "[red]❌ Failed to initialize system:[/red] {error}",
        "watch_schedule_error": "[red]❌ Error scheduling watch directories:[/red] {error}",
        "watch_loop_error": "[red]❌ Error in watch loop:[/red] {error}",
        "watch_started_success": "[green]✅ ContextBridge watcher started successfully[/green]",
        "idx_success_log": "Successfully indexed: {name}",
        "idx_failed_log": "Failed to index {name}: {error}",
        "idx_no_files": "[yellow]📭 No files found to index.[/yellow]",
        "idx_scanning_dir": "[cyan]📂 Scanning folder:[/cyan] {directory}",
        "idx_files_found": "[green]✅ Found {count} files[/green]",
        "idx_starting_vectorize": "[cyan]🔄 Starting vectorization...[/cyan]",
        "idx_vectorize_complete": "[green]✅ Vectorization complete![/green]",
        "idx_summary": "[dim]Success: {success} | Failed: {failed}[/dim]",
        "idx_found": "[bold cyan]📦 Found {count} files, starting index build...[/bold cyan]",
        "idx_ghost_clean": "[yellow]🧹 Found {count} deleted ghost files, cleaning up...[/yellow]",
        "idx_progress": "Parsing and vectorizing...",
        "idx_file_count": "{completed}/{total} files",
        "idx_complete": "[bold green]✅ Index build complete![/bold green]",
        "watch_dir": "[bold cyan]👀 Monitoring directory changes:[/bold cyan] {dir}",
        
        # Additional cbridge.py messages
        "failed_files_header": "[yellow]Failed files:[/yellow]",
        "and_more": "[dim]... and {count} more[/dim]",
        "watcher_started_bg": "[green]✅ ContextBridge watcher started in background (PID {pid})[/green]",
        "logs_location": "[dim]📝 Logs: {path}[/dim]",
        "logs_view_hint": "[dim]💡 Use 'cbridge logs -f' to view real-time logs[/dim]",
        "stop_hint": "[dim]💡 Use 'cbridge stop' to stop the watcher[/dim]",
        "watcher_already_running": "[red]❌ Watcher already running (PID: {pid})[/red]",
        "stop_first_hint": "[dim]Use 'cbridge stop' to stop it first[/dim]",
        "api_server_detected": "[yellow]⚠️  API server detected running (PID: {pid})[/yellow]",
        "api_has_watcher": "[yellow]API server already includes file monitoring, no need to start watcher separately[/yellow]",
        "suggestion_header": "[cyan]Suggestions:[/cyan]",
        "suggestion_serve_fg": "  - To run both, use: [green]cbridge serve --foreground[/green]",
        "suggestion_stop_api": "  - Or stop API server first: [green]cbridge stop[/green]",
        "continue_watcher_confirm": "Continue starting watcher?",
        "cancelled_watcher": "[dim]Cancelled starting watcher[/dim]",
        "continuing_watcher": "[dim]Continuing to start watcher...[/dim]",
        "watcher_running_fg": "[green]✅ ContextBridge watcher is running in foreground...[/green]",
        "press_ctrl_c": "[dim]Press Ctrl+C to stop[/dim]",
        "watcher_running": "[green]✅ ContextBridge watcher is running...[/green]",
        "api_already_running": "[red]❌ API server already running (PID: {pid})[/red]",
        "no_permission_stop_watcher": "[red]❌ Permission denied to stop watcher process (PID: {pid})[/red]",
        "port_in_use": "[yellow]⚠️ Port {original} is in use. Falling back to port {new}[/yellow]",
        "watcher_stopped": "[green]✅ Watcher (PID {pid}) stopped[/green]",
        "watcher_not_found": "[yellow]⚠️  Watcher process not found, cleaning up PID file[/yellow]",
        "no_permission_stop": "[red]❌ Permission denied to stop watcher process[/red]",
        "daemon_stopped": "[green]✅ Daemon (PID {pid}) stopped[/green]",
        "process_not_found": "[yellow]⚠️  Process {pid} not found, cleaning up PID file[/yellow]",
        "no_permission_stop_process": "[red]❌ Permission denied to stop process {pid}[/red]",
        "no_daemon_found": "[yellow]⚠️  No daemon PID files found. Is any daemon running?[/yellow]",
        "watcher_status_running": "[green]✅ Watcher: Running (PID {pid})[/green]",
        "watcher_status_stale": "[yellow]⚠️  Watcher: Not running (stale PID {pid})[/yellow]",
        "watcher_status_not_running": "[yellow]⚠️  Watcher: Not running[/yellow]",
        "api_status_running": "[green]✅ API Server: Running (PID {pid})[/green]",
        "api_status_stale": "[yellow]⚠️  API Server: Not running (stale PID {pid})[/yellow]",
        "api_status_not_running": "[yellow]⚠️  API Server: Not running[/yellow]",
        "cleanup_skip_warning": "[yellow]⚠️  Skipped vector data cleanup[/yellow]",
        "cleanup_skip_hint": "[dim]💡 Tip: Vector data is still retained in the database[/dim]",
        "cleanup_scanning": "[cyan]🔄 Scanning folder...[/cyan]",
        "cleanup_no_files": "[yellow]⚠️  No files found to clean up[/yellow]",
        "cleanup_files_found": "[green]✅ Found {count} files to clean up[/green]",
        "cleanup_background": "[cyan]🚀 Cleanup task moved to background[/cyan]",
        "cleanup_progress_hint": "[dim]💡 Use 'cbridge logs -f' to view real-time cleanup progress[/dim]",
        "cleanup_log_file": "[dim]📝 Log file: {path}[/dim]",
        "cleanup_deleted": "[green]✅ [{idx}/{total}][/green] {filename}",
        "cleanup_not_found": "[yellow]⚠️  [{idx}/{total}][/yellow] {filename} (not found)",
        "cleanup_failed": "[red]❌ [{idx}/{total}][/red] {filename} - {error}",
        "cleanup_summary_header": "[bold cyan]📊 Cleanup Summary[/bold cyan]",
        "cleanup_total": "[dim]Total files:[/dim] {count}",
        "cleanup_success": "[green]Success:[/green] {count}",
        "cleanup_failed_count": "[yellow]Failed/Not found:[/yellow] {count}",
        "cleanup_complete": "[green]✅ Vector data cleanup complete[/green]",
        "cleanup_error": "[red]❌ Cleanup error: {error}[/red]",
        "cleanup_start_failed": "[red]❌ Failed to start cleanup task: {error}[/red]",
        "cleanup_in_progress": "[dim]Cleaning up, please wait...[/dim]",
        "watcher_auto_stopped": "[cyan]Detected watcher process running, automatically stopped[/cyan]",
        
        # repo_manager.py
        "repo_auto_sync_started": "[dim]⏱️ Background task for auto-syncing GitHub repositories started[/dim]",
        
        # update command
        "update_desc": "Update ContextBridge to the latest version",
        "update_start": "[bold cyan]🚀 Updating ContextBridge from network...[/bold cyan]",
        "update_success": "[bold green]✅ Update successful! Please restart related services to apply the update.[/bold green]",
        "update_failed": "[bold red]❌ Update failed:[/bold red] {error}",
    }
}

def t(key, **kwargs):
    lang = CONFIG.get("language", "en")
    if lang not in MESSAGES:
        lang = "en"
    text = MESSAGES[lang].get(key, MESSAGES["en"].get(key, key))
    if kwargs:
        try:
            return text.format(**kwargs)
        except KeyError:
            return text
    return text
