import { translateFailureReason } from '@/lib/failureReasonMessages';

const OUTPUT_BLOCK_PATTERN = /\n\[(?:stdout|stderr)\]\n/i;

function normalizeRuntimeFailureLine(line: string) {
  if (/Target page, context or browser has been closed/i.test(line)) {
    return '浏览器页面已关闭，可能是人工验证窗口被关闭';
  }

  const timeoutMatch = line.match(/(page\.[a-z]+|locator\.[a-z]+|browserType\.[a-z]+)?:?\s*Timeout\s+(\d+)ms exceeded/i);
  if (timeoutMatch) {
    const operation = timeoutMatch[1] ? timeoutMatch[1].trim() : '页面操作';
    return `页面操作超时：${operation} 超过 ${timeoutMatch[2]}ms`;
  }

  if (/user data directory is already in use|ProcessSingleton|SingletonLock|profile.*in use/i.test(line)) {
    return 'Chrome 用户数据目录被占用，请关闭残留浏览器后重试';
  }

  return '';
}

function extractReadableFailure(message: string) {
  const businessFailurePatterns = [
    /(?:Error:\s*)?(搜索前登录态预热(?:暂停|失败)[^\n\r]*)/,
    /(?:Error:\s*)?(有头模式人工验证未完成[^\n\r]*)/,
    /(?:Error:\s*)?(自动密码登录失败[^\n\r]*)/,
    /(?:Error:\s*)?(未提供 account_id[^\n\r]*)/,
    /(?:Error:\s*)?(1688 账户 [^\n\r]*(?:缺少|错误|异常)[^\n\r]*)/,
    /(?:Error:\s*)?(HEADLESS_MANUAL_VERIFICATION_HANDOFF[^\n\r]*)/,
    /(?:Error:\s*)?(1688 搜索被验证码\/风控拦截[^\n\r]*)/,
    /(?:Error:\s*)?(验证码拦截[^\n\r]*)/,
    /(?:Error:\s*)?(HTTP \d+ 搜索页服务异常[^\n\r]*)/,
    /(?:Error:\s*)?(搜索页服务异常[^\n\r]*)/,
  ];

  for (const line of message.split(/\r?\n/).map((item) => item.trim()).filter(Boolean)) {
    const runtimeFailure = normalizeRuntimeFailureLine(line);
    if (runtimeFailure) {
      return runtimeFailure;
    }

    for (const pattern of businessFailurePatterns) {
      const match = line.match(pattern);
      if (match?.[1]) {
        return match[1].trim();
      }
    }
  }

  return '';
}

export function summarizeSearchProgressMessage(message?: string | null) {
  const trimmed = String(message ?? '').trim();
  if (!trimmed) {
    return '';
  }

  const readableFailure = extractReadableFailure(trimmed);
  if (readableFailure) {
    return readableFailure;
  }

  const headlineBlock = trimmed.split(OUTPUT_BLOCK_PATTERN)[0]?.trim() ?? '';
  const summary = headlineBlock
    .split('\n')
    .map((line) => line.trim())
    .find(Boolean) ?? '';

  return translateFailureReason(summary);
}

export function buildSearchDisplayErrors(errors?: string[] | null, resultError?: string | null) {
  const messages = [...(errors ?? [])];
  if (resultError) {
    messages.push(resultError);
  }

  return messages
    .map((message) => summarizeSearchProgressMessage(message))
    .filter(Boolean)
    .filter((message, index, list) => list.indexOf(message) === index);
}
