/* eslint-disable no-param-reassign */
/* eslint-disable no-template-curly-in-string */

/**
 * 用于批量翻译 Tauri Schema 文件中的文件
 */

import fs from 'fs';
import path from 'path';
import { fileURLToPath } from 'url';

const __filename = fileURLToPath(import.meta.url);
const __dirname = path.dirname(__filename);

/**
 * 翻译函数
 */
function translateCommandDescription(text: string) {
  if (typeof text !== 'string') {
    return text;
  }

  // 处理 "Enables the X command without any pre-configured scope." 模式
  const enablesPattern = /Enables the ([\w_]+) command without any pre-configured scope\./g;
  text = text.replace(enablesPattern, (match, command) => {
    return `在没有任何预配置范围的情况下启用 ${command} 命令。`;
  });

  // 处理 "Denies the X command without any pre-configured scope." 模式
  const deniesPattern = /Denies the ([\w_]+) command without any pre-configured scope\./g;
  text = text.replace(deniesPattern, (match, command) => {
    return `在没有任何预配置范围的情况下拒绝 ${command} 命令。`;
  });

  return text;
}

/**
 * 翻译函数
 */
function translateSchemaDescription(text: string) {
  if (typeof text !== 'string') {
    return text;
  }

  // 先处理多行描述 - 将换行符规范化
  text = text.replace(/\\n/g, '\n');

  // 处理实际换行符的多行描述
  text = text.replace(
    /This denies read access to the\n`\$APPLOCALDATA` folder on linux as the webview data and configuration values are stored here\.\nAllowing access can lead to sensitive information disclosure and should be well considered\./gs,
    '这拒绝读取 Linux 上的 `$APPLOCALDATA` 文件夹,因为 webview 数据和配置值存储在这里。允许访问可能导致敏感信息泄露,应仔细考虑。'
  );

  text = text.replace(
    /This denies read access to the\n`\$APPLOCALDATA\/EBWebView` folder on windows as the webview data and configuration values are stored here\.\nAllowing access can lead to sensitive information disclosure and should be well considered\./gs,
    '这拒绝读取 Windows 上的 `$APPLOCALDATA/EBWebView` 文件夹,因为 webview 数据和配置值存储在这里。允许访问可能导致敏感信息泄露,应仔细考虑。'
  );

  // 处理带 JSON 示例的长描述
  text = text.replace(
    /An empty permission you can use to modify the global scope\.\n\n## Example\n\n```json\n{\n {2}"identifier": "read-documents",\n {2}"windows": \["main"\],\n {2}"permissions": \[\n {4}"fs:allow-read",\n {3} {\n {6}"identifier": "fs:scope",\n {6}"allow": \[\n {8}"\$APPDATA\/documents\/\*\*\/\*"\n {6}\],\n {6}"deny": \[\n {8}"\$APPDATA\/documents\/secret\.txt"\n {6}\]\n {4}}\n {2}\]\n}\n```\n/gs,
    '一个可用于修改全局范围的空权限。\n\n## 示例\n\n```json\n{\n  "identifier": "read-documents",\n  "windows": ["main"],\n  "permissions": [\n    "fs:allow-read",\n    {\n      "identifier": "fs:scope",\n      "allow": [\n        "$APPDATA/documents/**/*"\n      ],\n      "deny": [\n        "$APPDATA/documents/secret.txt"\n      ]\n    }\n  ]\n}\n```\n'
  );

  // 先应用正则表达式替换(通用模式)
  const regexReplacements = [
    [
      /This allows non-recursive read access to metadata of the `(\$[^`]+)` folder, including file listing and statistics\./g,
      '这允许对 `$1` 文件夹的元数据进行非递归读取访问,包括文件列表和统计信息。',
    ],
    [
      /This allows full recursive read access to metadata of the `(\$[^`]+)` folder, including file listing and statistics\./g,
      '这允许对 `$1` 文件夹的元数据进行完全递归读取访问,包括文件列表和统计信息。',
    ],
    [/This allows non-recursive read access to the `(\$[^`]+)` folder\./g, '这允许对 `$1` 文件夹进行非递归读取访问。'],
    [
      /This allows full recursive read access to the complete `(\$[^`]+)` folder, files and subdirectories\./g,
      '这允许对完整的 `$1` 文件夹、文件和子目录进行完全递归读取访问。',
    ],
    [/This allows non-recursive write access to the `(\$[^`]+)` folder\./g, '这允许对 `$1` 文件夹进行非递归写入访问。'],
    [
      /This allows full recursive write access to the complete `(\$[^`]+)` folder, files and subdirectories\./g,
      '这允许对完整的 `$1` 文件夹、文件和子目录进行完全递归写入访问。',
    ],

    // 新增模式
    [
      /This denies read access to the `\$APPLOCALDATA` folder on linux as the webview data and configuration values are stored here\. Allowing access can lead to sensitive information disclosure and should be well considered\./gs,
      '这拒绝读取 Linux 上的 `$APPLOCALDATA` 文件夹,因为 webview 数据和配置值存储在这里。允许访问可能导致敏感信息泄露,应仔细考虑。',
    ],
    [
      /This denies read access to the `\$APPLOCALDATA\/EBWebView` folder on windows as the webview data and configuration values are stored here\. Allowing access can lead to sensitive information disclosure and should be well considered\./gs,
      '这拒绝读取 Windows 上的 `$APPLOCALDATA/EBWebView` 文件夹,因为 webview 数据和配置值存储在这里。允许访问可能导致敏感信息泄露,应仔细考虑。',
    ],

    [/This enables all read related commands without any pre-configured accessible paths\./g, '这在没有任何预配置可访问路径的情况下启用所有与读取相关的命令。'],
    [
      /This enables directory read and file metadata related commands without any pre-configured accessible paths\./g,
      '这在没有任何预配置可访问路径的情况下启用目录读取和文件元数据相关命令。',
    ],
    [/This enables file read related commands without any pre-configured accessible paths\./g, '这在没有任何预配置可访问路径的情况下启用文件读取相关命令。'],
    [
      /This enables all index or metadata related commands without any pre-configured accessible paths\./g,
      '这在没有任何预配置可访问路径的情况下启用所有索引或元数据相关命令。',
    ],
    [
      /This enables all write related commands without any pre-configured accessible paths\./g,
      '这在没有任何预配置可访问路径的情况下启用所有与写入相关的命令。',
    ],
    [
      /This enables all file write related commands without any pre-configured accessible paths\./g,
      '这在没有任何预配置可访问路径的情况下启用所有文件写入相关命令。',
    ],

    [
      /This scope permits access to all files and list content of top level directories in the application folders\./g,
      '此范围允许访问应用程序文件夹中所有文件和顶级目录的内容列表。',
    ],
    [/This scope permits to list all files and folders in the application directories\./g, '此范围允许列出应用程序目录中的所有文件和文件夹。'],
    [
      /This scope permits recursive access to the complete application folders, including sub directories and files\./g,
      '此范围允许对完整的应用程序文件夹进行递归访问,包括子目录和文件。',
    ],

    [
      /This scope permits access to all files and list content of top level directories in the `(\$[^`]+)` folder\./g,
      '此范围允许访问 `$1` 文件夹中所有文件和顶级目录的内容列表。',
    ],
    [/This scope permits to list all files and folders in the `(\$[^`]+)` folder\./g, '此范围允许列出 `$1` 文件夹中的所有文件和文件夹。'],
    [/This scope permits to list all files and folders in the `(\$[^`]+)`folder\./g, '此范围允许列出 `$1` 文件夹中的所有文件和文件夹。'],
    [
      /This scope permits recursive access to the complete `(\$[^`]+)` folder, including sub directories and files\./g,
      '此范围允许对完整的 `$1` 文件夹进行递归访问,包括子目录和文件。',
    ],

    [/This scope permits to list all files and folders in the `(\$[^`]+)` folder\./g, '此范围允许列出 `$1` 文件夹中的所有文件和文件夹。'],
  ];

  for (const [pattern, replacement] of regexReplacements) {
    text = text.replace(pattern!, replacement as any);
  }

  const translations = {
    'Capability formats accepted in a capability file.': '能力文件中接受的能力格式。',
    'A single capability.': '单个能力。',
    'A list of capabilities.': '能力列表。',
    'The list of capabilities.': '能力列表。',
    'Default core plugins set.': '默认核心插件集。',
    'Default permissions for the plugin.': '插件的默认权限。',
    'Default permissions for the plugin, which enables all commands.': '插件的默认权限,启用所有命令。',

    'This permissions allows to create the application specific directories.': '此权限允许创建应用程序特定的目录。',
    'This denies access to dangerous Tauri relevant files and folders by default.': '这默认拒绝访问危险的 Tauri 相关文件和文件夹。',

    'Identifier of the permission or permission set.': '权限或权限集的标识符。',
    'Data that defines what is allowed by the scope.': '定义范围允许内容的数据。',
    'Data that defines what is denied by the scope. This should be prioritized by validation logic.': '定义范围拒绝内容的数据。这应该由验证逻辑优先处理。',

    'All supported ACL values.': '所有支持的 ACL 值。',
    'Represents a null JSON value.': '表示一个空的 JSON 值。',
    'Represents a list of other [`Value`]s.': '表示其他 [`Value`] 的列表。',
    'Represents a map of [`String`] keys to [`Value`]s.': '表示 [`String`] 键到 [`Value`] 的映射。',

    'Represents a [`bool`].': '表示一个 [`bool`]。',
    'Represents a valid ACL [`Number`].': '表示一个有效的 ACL [`Number`]。',
    'Represents a [`String`].': '表示一个 [`String`]。',
    'Represents an [`i64`].': '表示一个 [`i64`]。',
    'Represents a [`f64`].': '表示一个 [`f64`]。',

    'Permission identifier.': '权限标识符。',
    'Permission identifier': '权限标识符',

    'Platform target.': '平台目标。',
    'Windows.': 'Windows。',
    'Linux.': 'Linux。',
    'Android.': 'Android。',
    'macOS.': 'macOS。',
    'Allows the log command': '允许 log 命令',
    'Allows connecting and sending data to a WebSocket server': '允许连接到 WebSocket 服务器并发送数据',

    'Identifier of the capability.': '能力的标识符。',
    'Description of what the capability is intended to allow on associated windows.': '描述该能力旨在在关联窗口上允许的内容。',
    'It should contain a description of what the grouped permissions should allow.': '它应包含有关分组权限应允许内容的描述。',

    'Configure remote URLs that can use the capability permissions.': '配置可以使用此能力权限的远程 URL。',
    'This setting is optional and defaults to not being set, as our default use case is that the content is served from our local application.':
      '此设置是可选的,默认未设置,因为我们的默认用例是内容从本地应用程序提供。',
    ':::caution Make sure you understand the security implications of providing remote sources with local system access. :::':
      ':::caution 确保你了解为远程源提供本地系统访问的安全影响。 :::',
    'Whether this capability is enabled for local app URLs or not. Defaults to `true`.': '是否为本地应用URL启用此能力。默认为 `true`。',

    'List of windows that are affected by this capability. Can be a glob pattern.': '受此能力影响的窗口列表。可以是 glob 模式。',
    'If a window label matches any of the patterns in this list, the capability will be enabled on all the webviews of that window, regardless of the value of [`Self::webviews`].':
      '如果窗口标签匹配此列表中的任何模式,则该能力将在该窗口的所有 webview 上启用,无论 [`Self::webviews`] 的值如何。',
    'On multiwebview windows, prefer specifying [`Self::webviews`] and omitting [`Self::windows`] for a fine grained access control.':
      '在多 webview 窗口上,建议指定 [`Self::webviews`] 并省略 [`Self::windows`] 以实现细粒度访问控制。',

    'List of webviews that are affected by this capability. Can be a glob pattern.': '受此能力影响的 webview 列表。可以是 glob 模式。',
    "The capability will be enabled on all the webviews whose label matches any of the patterns in this list, regardless of whether the webview's window label matches a pattern in [`Self::windows`].":
      '该能力将在标签匹配此列表中任何模式的所有 webview 上启用,无论 webview 的窗口标签是否匹配 [`Self::windows`] 中的模式。',

    'List of permissions attached to this capability.': '附加到此能力的权限列表。',

    'Must include the plugin name as prefix in the form of `${plugin-name}:${permission-name}`.':
      '必须以 `${plugin-name}:${permission-name}` 的形式包含插件名称作为前缀。',

    'For commands directly implemented in the application itself only `${permission-name}` is required.':
      '对于直接在应用程序本身中实现的命令,只需要 `${permission-name}`。',

    'Limit which target platforms this capability applies to.': '限制此能力应用于哪些目标平台。',
    'By default all platforms are targeted.': '默认情况下,所有平台都被定位。',

    'Configuration for remote URLs that are associated with the capability.': '与能力关联的远程URL的配置。',
    'Remote domains this capability refers to using the [URLPattern standard](https://urlpattern.spec.whatwg.org/).':
      '此能力引用的使用 [URLPattern 标准](https://urlpattern.spec.whatwg.org/)的远程域。',

    'An entry for a permission value in a [`Capability`] can be either a raw permission [`Identifier`] or an object that references a permission and extends its scope.':
      '[`Capability`] 中权限值的条目可以是原始权限 [`Identifier`] 或引用权限并扩展其范围的对象。',
    'Reference a permission or permission set by identifier.': '通过标识符引用权限或权限集。',
    'Reference a permission or permission set by identifier and extends its scope.': '通过标识符引用权限或权限集并扩展其范围。',

    // 新增权限集描述
    'This allows non-recursive read access to metadata of the application folders, including file listing and statistics.':
      '这允许对应用程序文件夹的元数据进行非递归读取访问,包括文件列表和统计信息。',
    'This allows full recursive read access to metadata of the application folders, including file listing and statistics.':
      '这允许对应用程序文件夹的元数据进行完全递归读取访问,包括文件列表和统计信息。',
    'This allows non-recursive read access to the application folders.': '这允许对应用程序文件夹进行非递归读取访问。',
    'This allows full recursive read access to the complete application folders, files and subdirectories.':
      '这允许对完整的应用程序文件夹、文件和子目录进行完全递归读取访问。',
    'This allows non-recursive write access to the application folders.': '这允许对应用程序文件夹进行非递归写入访问。',
    'This allows full recursive write access to the complete application folders, files and subdirectories.':
      '这允许对完整的应用程序文件夹、文件和子目录进行完全递归写入访问。',

    'This allows non-recursive read access to metadata of the `$APPCACHE` folder, including file listing and statistics.':
      '这允许对 `$APPCACHE` 文件夹的元数据进行非递归读取访问,包括文件列表和统计信息。',
    'This allows full recursive read access to metadata of the `$APPCACHE` folder, including file listing and statistics.':
      '这允许对 `$APPCACHE` 文件夹的元数据进行完全递归读取访问,包括文件列表和统计信息。',
    'This allows non-recursive read access to the `$APPCACHE` folder.': '这允许对 `$APPCACHE` 文件夹进行非递归读取访问。',
    'This allows full recursive read access to the complete `$APPCACHE` folder, files and subdirectories.':
      '这允许对完整的 `$APPCACHE` 文件夹、文件和子目录进行完全递归读取访问。',
    'This allows non-recursive write access to the `$APPCACHE` folder.': '这允许对 `$APPCACHE` 文件夹进行非递归写入访问。',
    'This allows full recursive write access to the complete `$APPCACHE` folder, files and subdirectories.':
      '这允许对完整的 `$APPCACHE` 文件夹、文件和子目录进行完全递归写入访问。',

    // 多行权限集描述
    'This set of permissions describes the what kind of': '这组权限描述了',
    'file system access the `fs` plugin has enabled or denied by default.': '文件系统访问类型, `fs` 插件默认启用或拒绝的。',
    'This default permission set enables read access to the': '此默认权限集启用对',
    'application specific directories (AppConfig, AppData, AppLocalData, AppCache,': '应用程序特定目录(AppConfig、AppData、AppLocalData、AppCache、',
    'AppLog) and all files and sub directories created in it.': 'AppLog)及其中创建的所有文件和子目录的读取访问。',
    'The location of these directories depends on the operating system,': '这些目录的位置取决于运行应用程序的操作系统,',
    'where the application is run.': '应用程序运行的位置。',
    'In general these directories need to be manually created': '通常,这些目录需要应用程序手动创建',
    'by the application at runtime, before accessing files or folders': '在运行时,然后才能访问其中的文件或文件夹。',
    'in it is possible.': '。',

    'Therefore, it is also allowed to create all of these folders via': '因此,也允许通过',
    'the `mkdir` command.': '`mkdir` 命令创建所有这些文件夹。',

    '#### Denied Permissions': '#### 拒绝的权限',
    'This default permission set prevents access to critical components': '此默认权限集默认阻止对',
    'of the Tauri application by default.': 'Tauri 应用程序关键组件的访问。',
    'On Windows the webview data folder access is denied.': '在 Windows 上,webview 数据文件夹访问被拒绝。',

    // 更多权限集描述
    'This permission set configures the types of dialogs': '此权限集配置对话框类型',
    'available from the dialog plugin.': '从 dialog 插件可用。',

    'This permission set configures what kind of': '此权限集配置',
    'fetch operations are available from the http plugin.': '从 http 插件可用的 fetch 操作类型。',

    'This enables all fetch operations but does not': '这启用了所有 fetch 操作,但不',
    'allow explicitly any origins to be fetched. This needs to': '明确允许获取任何源。这需要',
    'be manually configured before usage.': '在使用之前手动配置。',

    'This permission set configures which': '此权限集配置',
    'operating system information are available': '可用的操作系统信息',
    'to gather from the frontend.': '从前端收集。',

    'All information except the host name are available.': '除主机名外的所有信息都可用。',

    'process features are by default exposed.': '默认暴露的进程功能。',

    'This enables to quit via `allow-exit` and restart via `allow-restart`': '这允许通过 `allow-exit` 退出和通过 `allow-restart`',
    'the application.': '重启应用程序。',

    'This permission set configures which kind of': '此权限集配置哪种',
    'updater functions are exposed to the frontend.': '更新器功能暴露到前端。',

    'The full workflow from checking for updates to installing them': '从检查更新到安装它们的完整工作流',
    'is enabled.': '已启用。',

    'operations are available from the window state plugin.': '从窗口状态插件可用的操作类型。',

    'All operations are enabled by default.': '默认情况下所有操作都已启用。',

    'This permission allows recursive read functionality on the application': '此权限允许在应用程序特定的基本目录上进行递归读取功能。',
    'specific base directories.': '。',

    'An empty permission you can use to modify the global scope.': '一个可用于修改全局范围的空权限。',
    'No features are enabled by default, as we believe': '默认情况下不启用任何功能,因为我们认为',
    'the shortcuts can be inherently dangerous and it is': '快捷键可能具有固有的危险性,并且',
    'application specific if specific shortcuts should be': '应用程序特定的是否应该',
    'registered or unregistered.': '注册或取消注册特定的快捷键。',

    '#### This permission set includes:': '#### 此权限集包括:',

    // Config translations
    'Sets the window associated with this label to be the parent of the window to be created.': '将与此标签关联的窗口设置为要创建窗口的父窗口。',
    '## Platform-specific': '## 平台特定',
    'This sets the passed parent as an owner window to the window to be created.': '这将传递的父窗口设置为要创建窗口的所有者窗口。',
    'From [MSDN owned windows docs]': '来自 [MSDN 拥有窗口文档]',
    'An owned window is always above its owner in the z-order.': '拥有的窗口在 Z 顺序中始终位于其所有者之上。',
    'The system automatically destroys an owned window when its owner is destroyed.': '当其所有者被销毁时,系统会自动销毁拥有的窗口。',
    'An owned window is hidden when its owner is minimized.': '当其所有者最小化时,拥有的窗口被隐藏。',
    'This makes the new window transient for parent, see': '这使新窗口成为父窗口的临时窗口,参见',
    'This adds the window as a child of parent, see': '这将窗口作为父窗口的子窗口添加,参见',

    // 新增 - FS 和 HTTP scope 相关
    'FS scope entry.': 'FS 范围条目。',
    'FS scope path pattern.': 'FS 范围路径模式。',
    'A path that can be accessed by the webview when using the fs APIs.': '使用 fs API 时 webview 可以访问的路径。',
    'The pattern can start with a variable that resolves to a system base directory. The variables are: `$AUDIO`, `$CACHE`, `$CONFIG`, `$DATA`, `$LOCALDATA`, `$DESKTOP`, `$DOCUMENT`, `$DOWNLOAD`, `$EXE`, `$FONT`, `$HOME`, `$PICTURE`, `$PUBLIC`, `$RUNTIME`, `$TEMPLATE`, `$VIDEO`, `$RESOURCE`, `$APP`, `$LOG`, `$TEMP`, `$APPCONFIG`, `$APPDATA`, `$APPLOCALDATA`, `$APPCACHE`, `$APPLOG`.':
      '模式可以以解析为系统基础目录的变量开头。变量包括:`$AUDIO`、`$CACHE`、`$CONFIG`、`$DATA`、`$LOCALDATA`、`$DESKTOP`、`$DOCUMENT`、`$DOWNLOAD`、`$EXE`、`$FONT`、`$HOME`、`$PICTURE`、`$PUBLIC`、`$RUNTIME`、`$TEMPLATE`、`$VIDEO`、`$RESOURCE`、`$APP`、`$LOG`、`$TEMP`、`$APPCONFIG`、`$APPDATA`、`$APPLOCALDATA`、`$APPCACHE`、`$APPLOG`。',

    'HTTP scope entry.': 'HTTP 范围条目。',
    'A URL that can be accessed by the webview when using the HTTP APIs.': '使用 HTTP API 时 webview 可以访问的 URL。',
    'Wildcards can be used following the URL pattern standard.': '可以按照 URL 模式标准使用通配符。',
    'See [the URL Pattern spec](https://urlpattern.spec.whatwg.org/) for more information.':
      '有关更多信息,请参阅 [URL Pattern 规范](https://urlpattern.spec.whatwg.org/)。',
    'Examples:': '示例:',
    '- "https://*" : allows all HTTPS origin on port 443': '- "https://*" : 允许 443 端口上的所有 HTTPS 源',
    '- "https://*:*" : allows all HTTPS origin on any port': '- "https://*:*" : 允许任何端口上的所有 HTTPS 源',
    '- "https://*.github.com/tauri-apps/tauri": allows any subdomain of "github.com" with the "tauri-apps/api" path':
      '- "https://*.github.com/tauri-apps/tauri": 允许 "github.com" 的任何子域名访问 "tauri-apps/api" 路径',
    '- "https://myapi.service.com/users/*": allows access to any URLs that begins with "https://myapi.service.com/users/"':
      '- "https://myapi.service.com/users/*": 允许访问以 "https://myapi.service.com/users/" 开头的任何 URL',

    'A valid ACL number.': '有效的 ACL 数字。',
    'MacOS.': 'macOS。',

    // Config 新增翻译
    'The app name.': '应用程序名称。',
    'The application version.': '应用程序版本。',
    'An optional string that can be used to describe the capability.': '可用于描述能力的可选字符串。',
    'The list of permissions to be added into the capability.': '要添加到能力的权限列表。',
    'The list of scopes to be added into the capability.': '要添加到能力的范围列表。',
    'The target platform for the capability.': '能力的目标平台。',
    'The list of remote domains to be added into the capability.': '要添加到能力的远程域列表。',
    'Whether the capability is enabled for local app URLs.': '是否为本地应用 URL 启用该能力。',
    'The list of window labels to be added into the capability.': '要添加到能力的窗口标签列表。',
    'The list of webview labels to be added into the capability.': '要添加到能力的 webview 标签列表。',
    'Whether the capability is active.': '能力是否处于活动状态。',

    'X coordinate.': 'X 坐标。',
    'Y coordinate.': 'Y 坐标。',
    'RGB color as an array. Each value must be between 0 and 255.': 'RGB 颜色数组。每个值必须在 0 到 255 之间。',
    'RGBA color as an array. Each value must be between 0 and 255.': 'RGBA 颜色数组。每个值必须在 0 到 255 之间。',
    'RGB color array. Each value has a min value of 0 and a max value of 255.': 'RGB 颜色数组。每个值的最小值为 0,最大值为 255。',
    'RGBA color array. Each value has a min value of 0 and a max value of 255.': 'RGBA 颜色数组。每个值的最小值为 0,最大值为 255。',
    'Fluent UI style overlay scrollbars. **Windows only**': 'Fluent UI 样式的覆盖滚动条。**仅限 Windows**',
    "Requires WebView2 runtime version 125.0.2535.41 or higher, doesn't work on older versions,":
      '需要 WebView2 运行时版本 125.0.2535.41 或更高版本,在旧版本上不起作用,',
    'see https://learn.microsoft.com/en-us/microsoft-edge/webview2/release-notes/?tabs=dotnetcsharp#10253541':
      '参见 https://learn.microsoft.com/en-us/microsoft-edge/webview2/release-notes/?tabs=dotnetcsharp#10253541',

    'Inline list of CSP sources. Same as [`Self::List`] but concatenated with space separator.':
      'CSP 源的内联列表。与 [`Self::List`] 相同,但使用空格分隔符连接。',
    'List of CSP sources. The collection will be concatenated with space separator as CSP string.': 'CSP 源列表。集合将使用空格分隔符连接为 CSP 字符串。',

    'Brownfield mode.': 'Brownfield 模式。',

    'The': '这',
    'Access-Control-Allow-Credentials response header tells the browser': 'Access-Control-Allow-Credentials 响应头告诉浏览器',
    'whether the server allows cross-origin HTTP requests to include credentials.': '服务器是否允许跨域 HTTP 请求包含凭据。',
    'See <https://developer.mozilla.org/en-US/docs/Web/HTTP/Headers/Access-Control-Allow-Credentials>':
      '参阅 <https://developer.mozilla.org/en-US/docs/Web/HTTP/Headers/Access-Control-Allow-Credentials>',

    'The Access-Control-Allow-Headers response header is used in response': 'Access-Control-Allow-Headers 响应头用于响应',
    'to a preflight request which includes the Access-Control-Request-Headers': '包含 Access-Control-Request-Headers 的预检请求,',
    'to indicate which HTTP headers can be used during the actual request.': '以指示在实际请求期间可以使用哪些 HTTP 头。',
    'This header is required if the request has an Access-Control-Request-Headers header.': '如果请求有 Access-Control-Request-Headers 头,则需要此头。',
    'See <https://developer.mozilla.org/en-US/docs/Web/HTTP/Headers/Access-Control-Allow-Headers>':
      '请参阅 <https://developer.mozilla.org/en-US/docs/Web/HTTP/Headers/Access-Control-Allow-Headers>',

    'The Access-Control-Allow-Methods response header specifies one or more methods': 'Access-Control-Allow-Methods 响应头指定一个或多个方法',
    'allowed when accessing a resource in response to a preflight request.': '在响应预检请求访问资源时允许。',
    'See <https://developer.mozilla.org/en-US/docs/Web/HTTP/Headers/Access-Control-Allow-Methods>':
      '请参阅 <https://developer.mozilla.org/en-US/docs/Web/HTTP/Headers/Access-Control-Allow-Methods>',

    'The Access-Control-Expose-Headers response header allows a server to indicate': 'Access-Control-Expose-Headers 响应头允许服务器指示',
    'which response headers should be made available to scripts running in the browser,': '哪些响应头应提供给浏览器中运行的脚本,',
    'in response to a cross-origin request.': '以响应跨域请求。',
    'See <https://developer.mozilla.org/en-US/docs/Web/HTTP/Headers/Access-Control-Expose-Headers>':
      '请参阅 <https://developer.mozilla.org/en-US/docs/Web/HTTP/Headers/Access-Control-Expose-Headers>',

    'The Access-Control-Max-Age response header indicates how long the results of a preflight request': 'Access-Control-Max-Age 响应头指示预检请求的结果',
    '(i.e. the information contained in the Access-Control-Allow-Methods and Access-Control-Allow-Headers headers)':
      '(即 Access-Control-Allow-Methods 和 Access-Control-Allow-Headers 头中包含的信息)',
    'can be cached.': '可以缓存多久。',
    'See <https://developer.mozilla.org/en-US/docs/Web/HTTP/Headers/Access-Control-Max-Age>':
      '参阅 <https://developer.mozilla.org/en-US/docs/Web/HTTP/Headers/Access-Control-Max-Age>',

    'The HTTP Cross-Origin-Embedder-Policy (COEP) response header configures embedding cross-origin resources in a document.':
      'HTTP Cross-Origin-Embedder-Policy (COEP) 响应头配置将跨源资源嵌入到文档中。',
    'See <https://developer.mozilla.org/en-US/docs/Web/HTTP/Headers/Cross-Origin-Embedder-Policy>':
      '参阅 <https://developer.mozilla.org/en-US/docs/Web/HTTP/Headers/Cross-Origin-Embedder-Policy>',

    'The HTTP Cross-Origin-Opener-Policy (COOP) response header allows you to ensure': 'HTTP Cross-Origin-Opener-Policy (COOP) 响应头允许您确保',
    'a top-level document does not share a browsing context group with cross-origin documents.': '顶级文档不与跨源文档共享浏览上下文组。',
    "COOP process-isolate your document and potential attackers can't access your global object if they open it in a popup,":
      'COOP 将对您的文档进行进程隔离,如果潜在攻击者在弹出窗口中打开它,也无法访问您的全局对象,',
    'preventing a set of cross-origin attacks dubbed XS-Leaks.': '从而防止一组被称为 XS-Leaks 的跨源攻击。',
    'See <https://developer.mozilla.org/en-US/docs/Web/HTTP/Headers/Cross-Origin-Opener-Policy>':
      '参阅 <https://developer.mozilla.org/en-US/docs/Web/HTTP/Headers/Cross-Origin-Opener-Policy>',

    'The HTTP Cross-Origin-Resource-Policy response header conveys a desire': 'HTTP Cross-Origin-Resource-Policy 响应头传达',
    'that the browser blocks no-cors cross-origin/cross-site requests to the given resource.': '浏览器应阻止对给定资源的 no-cors 跨源/跨站点请求的愿望。',
    'See <https://developer.mozilla.org/en-US/docs/Web/HTTP/Headers/Cross-Origin-Resource-Policy>':
      '参阅 <https://developer.mozilla.org/en-US/docs/Web/HTTP/Headers/Cross-Origin-Resource-Policy>',

    'The HTTP Permissions-Policy header provides a mechanism to allow and deny': 'HTTP Permissions-Policy 头提供一种机制来允许和拒绝',
    'use of browser features in a document or in any <iframe> elements in the document.': '在文档中或文档的任何 <iframe> 元素中使用浏览器功能。',
    'See <https://developer.mozilla.org/en-US/docs/Web/HTTP/Headers/Permissions-Policy>':
      '参阅 <https://developer.mozilla.org/en-US/docs/Web/HTTP/Headers/Permissions-Policy>',

    'The Referrer-Policy HTTP header controls how much referrer information': 'Referrer-Policy HTTP 头控制多少引用信息',
    '(sent via the Referer header) should be included with requests.': '(通过 Referer 头发送)应包含在请求中。',
    'See <https://developer.mozilla.org/en-US/docs/Web/HTTP/Headers/Referrer-Policy>':
      '参阅 <https://developer.mozilla.org/en-US/docs/Web/HTTP/Headers/Referrer-Policy>',

    'The Timing-Allow-Origin response header specifies origins that are allowed': 'Timing-Allow-Origin 响应头指定允许的源',
    'to see values of attributes retrieved via the Resource Timing API features,': '查看通过 Resource Timing API 功能检索的属性值,',
    'which would otherwise be reported as zero due to cross-origin restrictions.': '否则由于跨源限制,这些值将被报告为零。',
    'See <https://developer.mozilla.org/en-US/docs/Web/HTTP/Headers/Timing-Allow-Origin>':
      '参阅 <https://developer.mozilla.org/en-US/docs/Web/HTTP/Headers/Timing-Allow-Origin>',

    'The X-Content-Type-Options response HTTP header is a marker used by the server': 'X-Content-Type-Options 响应 HTTP 头是服务器使用的标记',
    'to indicate that the MIME types advertised in the Content-Type headers should be followed and not changed.':
      '用于指示应遵循 Content-Type 头中通告的 MIME 类型而不应更改。',
    'The header allows you to avoid MIME type sniffing by saying that the MIME types are intentionally configured.':
      '该头允许您通过说 MIME 类型是故意配置的来避免 MIME 类型嗅探。',
    'See <https://developer.mozilla.org/en-US/docs/Web/HTTP/Headers/X-Content-Type-Options>':
      '参阅 <https://developer.mozilla.org/en-US/docs/Web/HTTP/Headers/X-Content-Type-Options>',
  };

  // 应用翻译
  for (const [en, zh] of Object.entries(translations)) {
    text = text.split(en).join(zh);
  }

  return text;
}

/**
 * 翻译对象
 */
function translateObject(obj: any) {
  if (typeof obj === 'object' && obj !== null) {
    if (Array.isArray(obj)) {
      obj.forEach((item) => translateObject(item));
    } else {
      for (const key in obj) {
        if (key === 'description' || key === 'markdownDescription') {
          if (typeof obj[key] === 'string') {
            obj[key] = translateCommandDescription(obj[key]);
            obj[key] = translateSchemaDescription(obj[key]);
          }
        } else {
          translateObject(obj[key]);
        }
      }
    }
  }
}

/**
 * 翻译文件
 */
function translateFile(filePath: string) {
  console.log(`正在翻译: ${filePath}`);

  try {
    // 读取文件
    const content = fs.readFileSync(filePath, 'utf8');
    const data = JSON.parse(content);

    // 翻译
    translateObject(data);

    // 保存文件
    fs.writeFileSync(filePath, JSON.stringify(data, null, 2), 'utf8');

    console.log(`✓ 完成: ${filePath}`);
    return true;
  } catch (error: any) {
    console.error(`✗ 翻译失败 ${filePath}: ${error.message}`);
    return false;
  }
}

/**
 * 主函数
 */
function main() {
  console.log('='.repeat(60));
  console.log('Tauri Schema 中文翻译脚本');
  console.log('='.repeat(60));
  console.log('');

  const basePath = path.join(__dirname, 'src-tauri', 'gen', 'schemas-zh');

  const files = [
    path.join(basePath, 'desktop-schema.json'),
    path.join(basePath, 'windows-schema.json'),
    path.join(basePath, 'acl-manifests.json'),
    path.join(basePath, 'config.json'),
  ];

  let successCount = 0;
  let failCount = 0;

  files.forEach((filePath) => {
    if (fs.existsSync(filePath)) {
      if (translateFile(filePath)) {
        successCount++;
      } else {
        failCount++;
      }
    } else {
      console.log(`⚠ 文件不存在: ${filePath}`);
      failCount++;
    }
  });

  console.log('');
  console.log('='.repeat(60));
  console.log(`翻译完成! 成功: ${successCount}, 失败: ${failCount}`);
  console.log('='.repeat(60));
}

// 运行
main();
