export const MIN_CAPTCHA_RETRY_ATTEMPTS = 3;
const DEFAULT_CAPTCHA_RETRY_BACKOFF_MS = 1500;

export function resolveCaptchaRetryLimit(value, fallback = MIN_CAPTCHA_RETRY_ATTEMPTS) {
  const parsed = Number.isInteger(value)
    ? value
    : Number.parseInt(String(value ?? ""), 10);
  const safeFallback = Number.isInteger(fallback) ? fallback : MIN_CAPTCHA_RETRY_ATTEMPTS;

  return Math.max(MIN_CAPTCHA_RETRY_ATTEMPTS, Number.isFinite(parsed) ? parsed : safeFallback);
}

export function resolveCaptchaRetryBackoffMs(value, fallback = DEFAULT_CAPTCHA_RETRY_BACKOFF_MS) {
  const parsed = Number.isInteger(value)
    ? value
    : Number.parseInt(String(value ?? ""), 10);
  const safeFallback = Number.isInteger(fallback) && fallback >= 0 ? fallback : DEFAULT_CAPTCHA_RETRY_BACKOFF_MS;

  return Number.isFinite(parsed) && parsed >= 0 ? parsed : safeFallback;
}

export function buildCaptchaRetryExhaustedMessage(message, query, attemptCount) {
  const headline = String(message ?? "").trim() || "1688 搜索被验证码/风控拦截";
  const normalizedQuery = String(query ?? "").trim();
  const normalizedAttempts = resolveCaptchaRetryLimit(attemptCount);

  return `${headline}${normalizedQuery ? ` [关键词=${normalizedQuery}]` : ""} [退出重进已重试 ${normalizedAttempts} 次]`;
}