// Parse Codex review artifacts and produce a markdown review comment.
//
// Usage from actions/github-script:
//   const parse = require('./.github/scripts/parse-codex-review.js');
//   const markdown = parse({ responseFile, recoveryFile, findingsFile, logFile,
//   exitCode, meta });
//
// Parameters:
//   responseFile - path to Codex final response output
//   recoveryFile - path to recovery output formatted from review-findings.md
//   findingsFile - path to incremental findings file written during review
//   logFile      - path to Codex stdout/stderr log
//   exitCode     - Codex process exit code
//   meta         - { trigger, autoMode, headSha, reviewer, isQuery, isPartial }

const fs = require('fs');
const buildComment = require('./build-ai-review-comment.js');

module.exports = function parseCodex(
    {responseFile, recoveryFile, findingsFile, logFile, exitCode, meta}) {
  function getTriggerLine() {
    if (meta.trigger !== 'auto') {
      return `*Requested by @${meta.reviewer}*`;
    }
    const shortSha = meta.headSha ? meta.headSha.substring(0, 7) : 'unknown';
    if (meta.autoMode === 'early') {
      return `*Auto-triggered after CI reached the early-review threshold — reviewing commit ${
          shortSha}*`;
    }
    return `*Auto-triggered after CI passed — reviewing commit ${shortSha}*`;
  }

  function readIfPresent(path) {
    if (!path || !fs.existsSync(path)) {
      return '';
    }
    const text = fs.readFileSync(path, 'utf8').trim();
    return text;
  }

  function tailFile(path, maxChars = 12000) {
    const text = readIfPresent(path);
    if (!text) {
      return '';
    }
    if (text.length <= maxChars) {
      return text;
    }
    return text.slice(text.length - maxChars);
  }

  let responseBody = '';
  const recovered = readIfPresent(recoveryFile);
  const direct = readIfPresent(responseFile);
  const findings = readIfPresent(findingsFile);

  if (recovered) {
    responseBody = recovered;
  } else if (direct) {
    responseBody = direct;
  } else if (findings) {
    responseBody =
        '⚠️ **Review incomplete — Codex did not produce a final response.**\n\n' +
        'Below are the incremental findings recovered from `review-findings.md`.\n\n---\n\n' +
        findings;
  } else {
    const logTail = tailFile(logFile);
    responseBody = logTail ?
        `❌ **Codex review failed before producing findings.**\n\n\`\`\`\n${
            logTail}\n\`\`\`` :
        '❌ Codex review failed before producing any output.';
  }

  const isPartial = !!meta.isPartial;
  const code = Number.parseInt(exitCode || '1', 10);
  const icon = isPartial ? '🟡' : (code === 0 ? '✅' : '⚠️');
  const triggerLine = getTriggerLine();

  return buildComment({
    icon,
    headerTitle: meta.isQuery ? 'Codex Response' : 'Codex Code Review',
    triggerLine,
    responseBody,
    footerLines: [
      'Generated by Codex CLI.',
      'Review methodology: `claude_md/code_review.md`',
      '',
      '**Limitations:**',
      '- Codex may miss context from files not in the diff',
      '- Large PRs may be truncated',
      '- Always apply human judgment to AI suggestions',
      '',
      '**Commands:**',
      '- `/codex-review [context]` — Request a code review',
      '- `/codex-query <question>` — Ask about the PR or codebase',
    ],
  });
};
