interface DocumentTaskErrorSource {
  lastTaskError?: string;
  lastTaskErrorCode?: string;
  options?: Record<string, unknown>;
}

const ERROR_MESSAGE_KEYS: Record<string, string> = {
  document_source_unavailable:
    'documentCollection.importDoc.documentSourceUnavailable',
  execution_interrupted:
    'documentCollection.importDoc.taskExecutionInterrupted',
  parse_service_timeout: 'documentCollection.importDoc.parseServiceTimeout',
  parse_service_unavailable:
    'documentCollection.importDoc.parseServiceUnavailable',
  pending_timeout: 'documentCollection.importDoc.taskPendingTimeout',
};

const resolveLegacyErrorCode = (message: string) => {
  const normalized = message.toLowerCase();
  if (
    normalized.includes('下载文档 url 失败') ||
    normalized.includes('读取批量导入文件失败') ||
    normalized.includes('远端文档地址不允许访问非公网目标')
  ) {
    return 'document_source_unavailable';
  }
  if (
    normalized.includes('status=502') ||
    normalized.includes('status=503') ||
    normalized.includes('status=504') ||
    normalized.includes('connection refused') ||
    normalized.includes('failed to connect') ||
    normalized.includes('failed to call mineru endpoint') ||
    normalized.includes('no route to host') ||
    normalized.includes('unknown host')
  ) {
    return 'parse_service_unavailable';
  }
  if (
    normalized.includes('timed out') ||
    normalized.includes('timeout') ||
    normalized.includes('超时')
  ) {
    return normalized.includes('排队')
      ? 'pending_timeout'
      : 'parse_service_timeout';
  }
  if (normalized.includes('任务执行中断')) {
    return 'execution_interrupted';
  }
  return '';
};

/**
 * 将后端稳定错误码及历史原始错误转换为面向用户的本地化文案。
 */
export const resolveDocumentTaskErrorText = (
  row: DocumentTaskErrorSource,
  translate: (key: string) => string,
) => {
  const storedCode =
    row.lastTaskErrorCode ||
    String(row.options?.['task.errorCode'] || '') ||
    resolveLegacyErrorCode(row.lastTaskError || '');
  const messageKey = ERROR_MESSAGE_KEYS[storedCode];
  return messageKey ? translate(messageKey) : row.lastTaskError || '';
};
