/**
 * Localize rsync/SSH push error text to Chinese for push history and live progress.
 * Mirrors server/utils/sync_error_message.py for records already stored in English.
 */

const PATTERNS: [RegExp, string][] = [
  [/rsync:\s*connection unexpectedly closed/gi, 'rsync：连接意外关闭'],
  [/rsync error:\s*some files\/attrs were not transferred/gi, 'rsync 错误：部分文件或属性未能传输'],
  [/rsync error:\s*error in rsync protocol data stream/gi, 'rsync 错误：协议数据流异常'],
  [/rsync error:\s*/gi, 'rsync 错误：'],
  [/rsync:\s*/gi, 'rsync：'],
  [/Host key verification failed/gi, 'SSH 主机密钥验证失败'],
  [/Could not resolve hostname/gi, '无法解析主机名'],
  [/Permission denied,\s*please try again/gi, '权限被拒绝，请重试'],
  [/Permission denied\s*\(publickey/gi, '公钥认证失败，权限被拒绝'],
  [/Permission denied/gi, '权限被拒绝'],
  [/No such file or directory/gi, '文件或目录不存在'],
  [/Connection refused/gi, '连接被拒绝'],
  [/Connection timed out/gi, '连接超时'],
  [/Connection reset by peer/gi, '连接被对端重置'],
  [/Network is unreachable/gi, '网络不可达'],
  [/No route to host/gi, '无法路由到主机'],
  [/No space left on device/gi, '磁盘空间不足'],
  [/Read-only file system/gi, '文件系统为只读'],
  [/Operation timed out/gi, '操作超时'],
  [/Operation not permitted/gi, '操作不允许'],
  [/Authentication failed/gi, '认证失败'],
  [/Broken pipe/gi, '连接中断（管道破裂）'],
  [/Protocol error/gi, '协议错误'],
  [/Too many open files/gi, '打开的文件过多'],
  [/Name or service not known/gi, '无法解析主机名或服务名'],
  [/ssh:\s*connect to host/gi, 'ssh：无法连接到主机'],
  [/ssh:\s*/gi, 'ssh：'],
  [/Command failed\s*\(exit\s*(\d+)\)/gi, '命令失败（退出码 $1）'],
  [/rsync exited with code\s*(\d+)/gi, 'rsync 退出码 $1'],
  [/\bexit code\s*(\d+)/gi, '退出码 $1'],
  [/Server not found/gi, '服务器不存在'],
  [/failed to set times on/gi, '无法设置文件时间戳：'],
  [/\bsender\b/gi, '发送端'],
  [/\breceiver\b/gi, '接收端'],
]

const CJK_RE = /[\u4e00-\u9fff\u3400-\u4dbf]/g

function isPrimarilyChinese(text: string): boolean {
  const cjk = text.match(CJK_RE)
  if (!cjk?.length) return false
  const compact = text.replace(/\s+/g, '')
  if (!compact.length) return false
  return cjk.length / compact.length >= 0.2
}

/** Localize push/sync error text for display. Returns empty string for null/undefined. */
export function formatPushErrorMessage(message: string | null | undefined): string {
  if (message == null) return ''
  const text = message.trim()
  if (!text) return ''
  if (isPrimarilyChinese(text)) return message

  let result = text
  for (const [pattern, repl] of PATTERNS) {
    result = result.replace(pattern, repl)
  }
  return result
}
