const MAX_SAFE_INTEGER_BIGINT = BigInt(Number.MAX_SAFE_INTEGER);

function shouldStringifyUnsafeInteger(token: string) {
  if (token.includes('.') || token.includes('e') || token.includes('E')) {
    return false;
  }

  try {
    const value = BigInt(token);
    return value > MAX_SAFE_INTEGER_BIGINT || value < -MAX_SAFE_INTEGER_BIGINT;
  } catch {
    return false;
  }
}

function replaceUnsafeIntegerTokens(raw: string) {
  let result = '';
  let index = 0;
  let inString = false;
  let isEscaping = false;

  while (index < raw.length) {
    const char = raw[index];

    if (inString) {
      result += char;

      if (isEscaping) {
        isEscaping = false;
      } else if (char === '\\') {
        isEscaping = true;
      } else if (char === '"') {
        inString = false;
      }

      index += 1;
    } else if (char === '"') {
      inString = true;
      result += char;
      index += 1;
    } else {
      const nextChar = raw[index + 1] ?? '';
      const isNumberStart = char === '-' ? /\d/.test(nextChar) : /\d/.test(char);

      if (!isNumberStart) {
        result += char;
        index += 1;
      } else {
        let end = index + 1;

        while (end < raw.length && /[\d.+\-Ee]/.test(raw[end])) {
          end += 1;
        }

        const token = raw.slice(index, end);
        result += shouldStringifyUnsafeInteger(token) ? `"${token}"` : token;
        index = end;
      }
    }
  }

  return result;
}

/**
 * 保留超出 JS 安全整数范围的 Long 原始值，避免在 JSON.parse 阶段丢精度。
 */
export function safeJsonTransformResponse(data: unknown) {
  if (typeof data !== 'string') {
    return data;
  }

  const raw = data.trim();

  if (!raw) {
    return data;
  }

  try {
    return JSON.parse(replaceUnsafeIntegerTokens(raw));
  } catch {
    return data;
  }
}
