'use strict';

function stripAnsi(value) {
  return String(value || '')
    .replace(/\x1b\[[0-9;?]*[a-zA-Z]/g, '')
    .replace(/\x1b\][^\x07\x1b]*(?:\x07|\x1b\\)/g, '')
    .replace(/\x1b[()][A-Z0-9]/g, '')
    .replace(/\x1b>[0-9]*[a-zA-Z]/g, '')
    .replace(/\x1b<[a-zA-Z]/g, '')
    .replace(/\x1b=[0-9]*/g, '')
    .replace(/\x1b\s/g, '')
    .replace(/\r/g, '')
    .replace(/[\x00-\x08\x0b\x0c\x0e-\x1f\x7f]/g, '');
}

function normalizeText(value) {
  return stripAnsi(value)
    .replace(/\u00a0/g, ' ')
    .split('\n')
    .map((line) => line.replace(/[ \t]+/g, ' ').replace(/\s+$/g, ''))
    .join('\n')
    .trim();
}

function normalizeAgentType(value) {
  const text = String(value || '').trim().toLowerCase();
  if (!text) return '';
  if (text === 'codex' || text === 'codex-cli' || text === 'codex_cli' || text === 'codex_cli_rs') return 'codex';
  return text;
}

function looksLikeCodexTranscriptPagerSnapshot(agentType, value) {
  if (normalizeAgentType(agentType) !== 'codex') return false;
  const text = normalizeText(value);
  if (!text) return false;

  const compact = text.replace(/[ \t]+/g, ' ');
  const hasTranscriptHeading = /(?:^|\n)\s*(?:[\/\\]\s*){1,}\s*T\s*R\s*A\s*N\s*S\s*C\s*R\s*I\s*P\s*T\b/i.test(compact)
    || /(?:^|\n)\s*T\s*R\s*A\s*N\s*S\s*C\s*R\s*I\s*P\s*T\s*(?:[\/\\]\s*){1,}/i.test(compact);
  const hasQuitInstruction = /\bq\s+to\s+quit\b/i.test(compact);
  const hasScrollInstruction = /\bj\/k\s+to\s+scroll\b/i.test(compact) || /\bpgup\/pgdn\s+to\s+page\b/i.test(compact);
  const hasEditInstruction = /\benter\s+to\s+edit\s+message\b/i.test(compact)
    || /\besc\/.{0,24}\bto\s+edit\s+(?:prev|previous|next)\b/i.test(compact);

  return hasTranscriptHeading && hasQuitInstruction && hasScrollInstruction && hasEditInstruction;
}

module.exports = {
  looksLikeCodexTranscriptPagerSnapshot,
  normalizeText,
};
