import type { AppLocale } from "../../../../shared/locale"

export const zhCN = {
  "app.loading": "加载中",
  "app.save": "保存",
  "app.saving": "正在保存...",
  "app.saveChanges": "保存更改",
  "app.cancel": "取消",
  "app.close": "关闭",
  "app.dismiss": "关闭",
  "app.enabled": "已启用",
  "app.disabled": "已禁用",
  "app.editing": "正在编辑",
  "app.new": "新建",
  "app.connected": "已连接",
  "app.notConnected": "未连接",
  "app.configured": "已配置",
  "app.available": "可用",
  "app.needsKey": "需要密钥",
  "app.keyReady": "密钥就绪",
  "app.primary": "主模型",
  "app.small": "小模型",
  "app.search": "搜索",
  "app.reset": "重置",
  "app.resetting": "正在重置...",
  "app.delete": "删除",
  "app.restore": "恢复",
  "app.copy": "复制",
  "app.loadingData": "正在读取数据",
  "app.empty": "暂无内容",
  "app.error": "错误",
  "shell.workspace": "工作区",
  "shell.skills": "技能",
  "shell.prompts": "提示词",
  "shell.mcp": "MCP",
  "shell.plugins": "插件",
  "shell.tools": "工具",
  "shell.settings": "设置",
  "shell.openSettings": "打开设置",
  "shell.closeWindow": "关闭窗口",
  "shell.minimizeWindow": "最小化窗口",
  "shell.toggleMaximize": "最大化/还原窗口",
  "settings.title": "设置",
  "settings.close": "关闭设置",
  "settings.dismissMessage": "关闭设置消息",
  "settings.options": "选项",
  "settings.nav.general": "通用",
  "settings.nav.about": "关于",
  "settings.nav.provider": "Provider",
  "settings.nav.models": "模型",
  "settings.nav.appearance": "外观",
  "settings.nav.developer": "开发者模式",
  "settings.nav.archive": "归档会话",
  "settings.about.version": "版本",
  "settings.about.checkUpdates": "检查更新",
  "settings.about.checkingUpdates": "正在检查...",
  "settings.about.automaticUpdates": "自动更新",
  "settings.about.updatesEnabled": "自动下载并在退出时安装应用更新。",
  "settings.about.updatesDisabled": "保留当前版本，直到你手动检查更新。",
  "settings.general.languageLabel": "语言",
  "settings.general.languageTitle": "显示语言",
  "settings.general.languageCopy": "切换整个桌面应用的界面语言。",
  "settings.general.localeGroup": "显示语言",
  "settings.general.localeSaveFailed": "无法保存语言设置。界面会继续使用当前选择。",
  "settings.provider.refreshCatalog": "刷新 Provider 目录",
  "settings.provider.searchProviders": "搜索 Provider",
  "settings.provider.providerList": "Provider 列表",
  "settings.provider.connectionMethod": "连接方式",
  "settings.provider.advancedSettings": "高级设置",
  "settings.provider.providerModels": "Provider 模型",
  "settings.provider.testConnection": "测试连接",
  "settings.provider.saveSettings": "保存设置",
  "settings.provider.saved": "Provider 设置已保存。",
  "settings.models.primaryModel": "主模型",
  "settings.models.smallModel": "小模型",
  "settings.models.connectedModels": "已连接模型",
  "settings.models.saved": "模型设置已保存。",
  "settings.models.noModels": "暂无已连接 Provider 暴露模型",
  "settings.models.noModelsCopy": "打开 Provider 页面，配置一个 Provider，然后回到这里查看可用模型。",
  "settings.appearance.brand": "品牌",
  "settings.appearance.accentTheme": "强调主题",
  "settings.appearance.accentThemeCopy": "在新的暖色 Terra 调色板和原有冷色 Sage 外壳之间切换。",
  "settings.appearance.theme": "主题",
  "settings.appearance.colorMode": "颜色模式",
  "settings.appearance.colorModeCopy": "选择亮色、暗色或跟随系统的配色方案。",
  "settings.appearance.languageLabel": "语言",
  "settings.appearance.languageTitle": "显示语言",
  "settings.appearance.languageCopy": "切换整个桌面应用的界面语言。",
  "settings.appearance.localeZh": "中文",
  "settings.appearance.localeEn": "English",
  "settings.appearance.localeZhDescription": "简体中文界面",
  "settings.appearance.localeEnDescription": "English interface",
  "settings.appearance.localeGroup": "显示语言",
  "settings.appearance.localeSaveFailed": "无法保存语言设置。界面会继续使用当前选择。",
  "settings.appearance.system": "跟随系统",
  "settings.appearance.light": "亮色",
  "settings.appearance.dark": "暗色",
  "settings.appearance.resetPalette": "重置调色板",
  "settings.appearance.config": "配置",
  "settings.appearance.current": "当前",
  "settings.appearance.state": "外观状态",
  "settings.appearance.activityRail": "活动栏",
  "settings.appearance.shown": "显示",
  "settings.appearance.hidden": "隐藏",
  "settings.developer.state": "开发者状态",
  "settings.developer.debugRegions": "调试区域颜色",
  "settings.developer.traceMetadata": "Trace 调试元数据",
  "settings.archive.title": "归档会话",
  "settings.archive.loading": "正在读取归档会话",
  "settings.archive.loadingCopy": "正在读取归档会话快照，以便恢复或永久删除。",
  "settings.archive.emptyTitle": "暂无归档会话",
  "settings.archive.emptyCopy": "从工作区侧栏归档会话后，可以在这里管理。",
  "settings.archive.projectMissing": "项目缺失",
  "tools.title": "工具",
  "tools.topMenu": "工具顶部菜单",
  "tools.builtIn": "内置工具",
  "tools.categories": "工具分类",
  "tools.availability": "可用性",
  "tools.globalAvailability": "全局工具可用性",
  "tools.resetDefault": "恢复默认",
  "tools.noTools": "暂无内置工具",
  "tools.noToolsCopy": "Agent 注册表没有返回任何内置工具。",
  "tools.fetching": "正在读取内置工具",
  "tools.fetchingCopy": "正在读取内置注册表和已保存的全局可用性限制。",
  "tools.shell": "Shell",
  "tools.write": "写入",
  "tools.search": "搜索",
  "tools.read": "读取",
  "tools.workflow": "工作流",
  "tools.interaction": "交互",
  "tools.delegation": "委派",
  "tools.other": "其他",
  "tools.shellAccess": "Shell 访问",
  "tools.delegationStatus": "委派状态",
  "tools.delegatesWork": "委派工作",
  "tools.workflowControl": "工作流控制",
  "tools.userInteraction": "用户交互",
  "tools.highRisk": "高风险",
  "tools.readOnly": "只读",
  "tools.moderate": "中等",
  "composer.taskDraft": "任务草稿",
  "composer.placeholder": "描述任务，或添加文件、图片和上下文...",
  "composer.send": "发送",
  "composer.stop": "停止",
  "composer.attach": "添加附件",
  "composer.reasoning": "推理",
  "composer.model": "模型",
  "composer.skills": "技能",
  "composer.mcp": "MCP",
  "composer.permissionDefault": "工具权限：默认权限",
  "composer.permissionFullAccess": "完全访问权限",
  "composer.permissionReadOnly": "只读权限",
  "sidebar.projects": "项目",
  "sidebar.sessions": "会话",
  "sidebar.newSession": "新建会话",
  "sidebar.createSession": "创建会话",
  "sidebar.archiveSession": "归档会话",
  "sidebar.deleteSession": "删除会话",
  "sidebar.noSessions": "暂无会话",
  "rightSidebar.inspector": "检查器侧栏",
  "rightSidebar.preview": "预览",
  "rightSidebar.files": "文件",
  "rightSidebar.changes": "变更",
  "rightSidebar.git": "Git",
  "rightSidebar.runtime": "运行时",
  "preview.openExternal": "在外部打开",
  "preview.reload": "重新加载",
  "preview.addComment": "添加评论",
  "thread.imagePreview.close": "Close image preview",
  "thread.imagePreview.fitWidth": "Fit width",
  "thread.imagePreview.fitContain": "Fit contain",
  "thread.imagePreview.zoomOut": "Zoom out",
  "thread.imagePreview.zoomReset": "Reset zoom",
  "thread.imagePreview.zoomIn": "Zoom in",
  "changes.title": "变更",
  "changes.noChanges": "暂无变更",
  "files.title": "文件",
  "files.searchFiles": "搜索文件",
  "terminal.title": "终端",
  "terminal.newTerminal": "新建终端",
  "terminal.closeTerminal": "关闭终端",
  "prompts.title": "提示词",
  "prompts.newPreset": "新建预设",
  "prompts.savePreset": "保存预设",
  "prompts.resetPreset": "重置预设",
  "prompts.installFromUrl": "从 URL 安装",
  "plugins.title": "插件",
  "plugins.search": "搜索",
  "plugins.install": "安装",
  "plugins.update": "更新",
  "plugins.remove": "移除",
  "mcp.importJson": "导入 JSON",
  "mcp.title": "MCP 服务器",
  "mcp.serverConfiguration": "服务器配置",
  "mcp.noServers": "暂无服务器",
  "mcp.noServersTitle": "还没有配置全局 MCP 服务器",
  "mcp.noServersCopy": "在这里创建可复用的本地或远程服务器，然后在项目中按需启用。",
} as const

export type TranslationKey = keyof typeof zhCN

export const enUS = {
  "app.loading": "Loading",
  "app.save": "Save",
  "app.saving": "Saving...",
  "app.saveChanges": "Save changes",
  "app.cancel": "Cancel",
  "app.close": "Close",
  "app.dismiss": "Dismiss",
  "app.enabled": "Enabled",
  "app.disabled": "Disabled",
  "app.editing": "Editing",
  "app.new": "New",
  "app.connected": "Connected",
  "app.notConnected": "Not connected",
  "app.configured": "Configured",
  "app.available": "Available",
  "app.needsKey": "Needs key",
  "app.keyReady": "Key ready",
  "app.primary": "Primary",
  "app.small": "Small",
  "app.search": "Search",
  "app.reset": "Reset",
  "app.resetting": "Resetting...",
  "app.delete": "Delete",
  "app.restore": "Restore",
  "app.copy": "Copy",
  "app.loadingData": "Loading data",
  "app.empty": "Empty",
  "app.error": "Error",
  "shell.workspace": "Workspace",
  "shell.skills": "Skills",
  "shell.prompts": "Prompts",
  "shell.mcp": "MCP",
  "shell.plugins": "Plugins",
  "shell.tools": "Tools",
  "shell.settings": "Settings",
  "shell.openSettings": "Open settings",
  "shell.closeWindow": "Close window",
  "shell.minimizeWindow": "Minimize window",
  "shell.toggleMaximize": "Toggle maximize window",
  "settings.title": "Settings",
  "settings.close": "Close settings",
  "settings.dismissMessage": "Dismiss settings message",
  "settings.options": "Options",
  "settings.nav.general": "General",
  "settings.nav.about": "About",
  "settings.nav.provider": "Provider",
  "settings.nav.models": "Models",
  "settings.nav.appearance": "Appearance",
  "settings.nav.developer": "Developer Mode",
  "settings.nav.archive": "Archived Sessions",
  "settings.about.version": "Version",
  "settings.about.checkUpdates": "Check for updates",
  "settings.about.checkingUpdates": "Checking...",
  "settings.about.automaticUpdates": "Automatic updates",
  "settings.about.updatesEnabled": "Download app updates automatically and install them when the app quits.",
  "settings.about.updatesDisabled": "Keep the current version until you manually check for updates.",
  "settings.general.languageLabel": "Language",
  "settings.general.languageTitle": "Display Language",
  "settings.general.languageCopy": "Switch the interface language for the whole desktop app.",
  "settings.general.localeGroup": "Display language",
  "settings.general.localeSaveFailed": "Unable to save language settings. The interface will keep using the current selection.",
  "settings.provider.refreshCatalog": "Refresh provider catalog",
  "settings.provider.searchProviders": "Search providers",
  "settings.provider.providerList": "Provider list",
  "settings.provider.connectionMethod": "Connection method",
  "settings.provider.advancedSettings": "Advanced settings",
  "settings.provider.providerModels": "Provider Models",
  "settings.provider.testConnection": "Test connection",
  "settings.provider.saveSettings": "Save settings",
  "settings.provider.saved": "Provider settings saved.",
  "settings.models.primaryModel": "Primary model",
  "settings.models.smallModel": "Small model",
  "settings.models.connectedModels": "Connected Models",
  "settings.models.saved": "Model settings saved.",
  "settings.models.noModels": "No connected provider is exposing models yet",
  "settings.models.noModelsCopy": "Open the Provider page, configure a provider, then come back here to review the unlocked models.",
  "settings.appearance.brand": "Brand",
  "settings.appearance.accentTheme": "Accent Theme",
  "settings.appearance.accentThemeCopy": "Switch between the new warm terra palette and the original cool sage shell.",
  "settings.appearance.theme": "Theme",
  "settings.appearance.colorMode": "Color Mode",
  "settings.appearance.colorModeCopy": "Choose between light, dark, or system-matched color scheme.",
  "settings.appearance.languageLabel": "Language",
  "settings.appearance.languageTitle": "Display Language",
  "settings.appearance.languageCopy": "Switch the interface language for the whole desktop app.",
  "settings.appearance.localeZh": "中文",
  "settings.appearance.localeEn": "English",
  "settings.appearance.localeZhDescription": "Simplified Chinese interface",
  "settings.appearance.localeEnDescription": "English interface",
  "settings.appearance.localeGroup": "Display language",
  "settings.appearance.localeSaveFailed": "Unable to save language settings. The interface will keep using the current selection.",
  "settings.appearance.system": "System",
  "settings.appearance.light": "Light",
  "settings.appearance.dark": "Dark",
  "settings.appearance.resetPalette": "Reset palette",
  "settings.appearance.config": "Config",
  "settings.appearance.current": "Current",
  "settings.appearance.state": "Appearance State",
  "settings.appearance.activityRail": "Activity Rail",
  "settings.appearance.shown": "Shown",
  "settings.appearance.hidden": "Hidden",
  "settings.developer.state": "Developer State",
  "settings.developer.debugRegions": "Debug region colors",
  "settings.developer.traceMetadata": "Trace debug metadata",
  "settings.archive.title": "Archived Sessions",
  "settings.archive.loading": "Fetching archived sessions",
  "settings.archive.loadingCopy": "Reading archived session snapshots so you can restore or permanently delete them.",
  "settings.archive.emptyTitle": "No archived sessions",
  "settings.archive.emptyCopy": "Archive a session from the workspace sidebar to manage it here.",
  "settings.archive.projectMissing": "Project missing",
  "tools.title": "Tools",
  "tools.topMenu": "Tools top menu",
  "tools.builtIn": "Built-in tools",
  "tools.categories": "Tool categories",
  "tools.availability": "Availability",
  "tools.globalAvailability": "Global tool availability",
  "tools.resetDefault": "Reset to default",
  "tools.noTools": "No built-in tools",
  "tools.noToolsCopy": "The agent registry did not return any built-in tools.",
  "tools.fetching": "Fetching built-in tools",
  "tools.fetchingCopy": "Reading the built-in registry and saved global availability limits.",
  "tools.shell": "Shell",
  "tools.write": "Write",
  "tools.search": "Search",
  "tools.read": "Read",
  "tools.workflow": "Workflow",
  "tools.interaction": "Interaction",
  "tools.delegation": "Delegation",
  "tools.other": "Other",
  "tools.shellAccess": "Shell access",
  "tools.delegationStatus": "Delegation status",
  "tools.delegatesWork": "Delegates work",
  "tools.workflowControl": "Workflow control",
  "tools.userInteraction": "User interaction",
  "tools.highRisk": "High risk",
  "tools.readOnly": "Read-only",
  "tools.moderate": "Moderate",
  "composer.taskDraft": "Task draft",
  "composer.placeholder": "Describe the task, or add files, images, and context...",
  "composer.send": "Send",
  "composer.stop": "Stop",
  "composer.attach": "Attach",
  "composer.reasoning": "Reasoning",
  "composer.model": "Model",
  "composer.skills": "Skills",
  "composer.mcp": "MCP",
  "composer.permissionDefault": "Tool permission: default",
  "composer.permissionFullAccess": "Full access",
  "composer.permissionReadOnly": "Read only",
  "sidebar.projects": "Projects",
  "sidebar.sessions": "Sessions",
  "sidebar.newSession": "New session",
  "sidebar.createSession": "Create session",
  "sidebar.archiveSession": "Archive session",
  "sidebar.deleteSession": "Delete session",
  "sidebar.noSessions": "No sessions",
  "rightSidebar.inspector": "Inspector sidebar",
  "rightSidebar.preview": "Preview",
  "rightSidebar.files": "Files",
  "rightSidebar.changes": "Changes",
  "rightSidebar.git": "Git",
  "rightSidebar.runtime": "Runtime",
  "preview.openExternal": "Open External",
  "preview.reload": "Reload",
  "preview.addComment": "Add comment",
  "thread.imagePreview.close": "Close image preview",
  "thread.imagePreview.fitWidth": "Fit width",
  "thread.imagePreview.fitContain": "Fit contain",
  "thread.imagePreview.zoomOut": "Zoom out",
  "thread.imagePreview.zoomReset": "Reset zoom",
  "thread.imagePreview.zoomIn": "Zoom in",
  "changes.title": "Changes",
  "changes.noChanges": "No changes",
  "files.title": "Files",
  "files.searchFiles": "Search files",
  "terminal.title": "Terminal",
  "terminal.newTerminal": "New terminal",
  "terminal.closeTerminal": "Close terminal",
  "prompts.title": "Prompts",
  "prompts.newPreset": "New preset",
  "prompts.savePreset": "Save preset",
  "prompts.resetPreset": "Reset preset",
  "prompts.installFromUrl": "Install from URL",
  "plugins.title": "Plugins",
  "plugins.search": "Search",
  "plugins.install": "Install",
  "plugins.update": "Update",
  "plugins.remove": "Remove",
  "mcp.importJson": "Import Json",
  "mcp.title": "MCP servers",
  "mcp.serverConfiguration": "Server Configuration",
  "mcp.noServers": "No Servers",
  "mcp.noServersTitle": "No global MCP servers configured yet",
  "mcp.noServersCopy": "Create a reusable local or remote server here, then enable it from a project when needed.",
} as const satisfies Record<TranslationKey, string>

const translations = {
  "zh-CN": zhCN,
  "en-US": enUS,
} satisfies Record<AppLocale, Record<TranslationKey, string>>

type LiteralPattern = {
  match: RegExp
  format: Record<AppLocale, (match: RegExpMatchArray) => string>
}

const literalPatterns: LiteralPattern[] = [
  {
    match: /^Version (.+)$/i,
    format: {
      "zh-CN": (match) => `版本 ${match[1]}`,
      "en-US": (match) => `Version ${match[1]}`,
    },
  },
  {
    match: /^(\d+) of (\d+) enabled$/i,
    format: {
      "zh-CN": (match) => `已启用 ${match[1]} / ${match[2]}`,
      "en-US": (match) => `${match[1]} of ${match[2]} enabled`,
    },
  },
  {
    match: /^(\d+)\/(\d+) enabled$/i,
    format: {
      "zh-CN": (match) => `已启用 ${match[1]} / ${match[2]}`,
      "en-US": (match) => `${match[1]}/${match[2]} enabled`,
    },
  },
  {
    match: /^(\d+)\/(\d+) total enabled$/i,
    format: {
      "zh-CN": (match) => `总计已启用 ${match[1]} / ${match[2]}`,
      "en-US": (match) => `${match[1]}/${match[2]} total enabled`,
    },
  },
  {
    match: /^(\d+) aliases$/i,
    format: {
      "zh-CN": (match) => `${match[1]} 个别名`,
      "en-US": (match) => `${match[1]} aliases`,
    },
  },
  {
    match: /^(\d+) models$/i,
    format: {
      "zh-CN": (match) => `${match[1]} 个模型`,
      "en-US": (match) => `${match[1]} models`,
    },
  },
  {
    match: /^(\d+) messages$/i,
    format: {
      "zh-CN": (match) => `${match[1]} 条消息`,
      "en-US": (match) => `${match[1]} messages`,
    },
  },
  {
    match: /^(\d+) events$/i,
    format: {
      "zh-CN": (match) => `${match[1]} 个事件`,
      "en-US": (match) => `${match[1]} events`,
    },
  },
  {
    match: /^Archived (.+)$/i,
    format: {
      "zh-CN": (match) => `归档于 ${match[1]}`,
      "en-US": (match) => `Archived ${match[1]}`,
    },
  },
]

const extraSources: Partial<Record<TranslationKey, readonly string[]>> = {
  "settings.appearance.system": ["System", "跟随系统"],
  "settings.nav.general": ["General", "通用"],
  "settings.appearance.localeGroup": ["Language", "Display language", "显示语言"],
  "settings.provider.saveSettings": ["保存", "Save DeepSeek settings", "Save OpenAI settings"],
  "settings.provider.testConnection": ["测试连接"],
  "composer.permissionDefault": ["工具权限：默认权限"],
  "composer.permissionFullAccess": ["完全访问权限"],
  "app.configured": ["已配置"],
  "app.notConnected": ["未连接"],
}

const sourceToKey = new Map<string, TranslationKey>()

for (const key of Object.keys(zhCN) as TranslationKey[]) {
  sourceToKey.set(zhCN[key], key)
  sourceToKey.set(enUS[key], key)
  for (const source of extraSources[key] ?? []) {
    sourceToKey.set(source, key)
  }
}

function interpolate(template: string, params?: Record<string, string | number>) {
  if (!params) return template
  return template.replace(/\{(?<key>[\w.-]+)\}/g, (match, key: string) =>
    Object.prototype.hasOwnProperty.call(params, key) ? String(params[key]) : match,
  )
}

export function t(locale: AppLocale, key: TranslationKey, params?: Record<string, string | number>) {
  return interpolate(translations[locale][key], params)
}

export function translateLiteral(locale: AppLocale, literal: string) {
  const trimmed = literal.trim()
  if (!trimmed) return literal

  const key = sourceToKey.get(trimmed)
  if (key) {
    return literal.replace(trimmed, translations[locale][key])
  }

  for (const pattern of literalPatterns) {
    const match = trimmed.match(pattern.match)
    if (match) {
      return literal.replace(trimmed, pattern.format[locale](match))
    }
  }

  return literal
}

export function getLiteralVariants(literal: string) {
  const trimmed = literal.trim()
  const key = sourceToKey.get(trimmed)
  if (key) {
    return new Set([trimmed, zhCN[key], enUS[key], ...(extraSources[key] ?? [])])
  }

  return new Set([trimmed])
}

export function getTranslationDictionary(locale: AppLocale) {
  return translations[locale]
}
