// Parse Claude Code execution log and produce a markdown review comment.
//
// Usage from actions/github-script:
//   const parse = require('./.github/scripts/parse-claude-review.js');
//   const markdown = parse({ executionFile, conclusion, meta });
//
// Parameters:
//   executionFile - path to the JSON execution log from claude-code-base-action
//   conclusion    - 'success' or 'failure' from the action output
//   meta          - { trigger, autoMode, headSha, reviewer, isQuery, isPartial
//   }

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

module.exports = function parseClaude({executionFile, conclusion, 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}*`;
  }

  let responseBody = '';

  try {
    const executionLog = JSON.parse(fs.readFileSync(executionFile, 'utf8'));

    if (!Array.isArray(executionLog)) {
      throw new Error('Expected array format from claude-code-base-action');
    }

    const resultMessage = executionLog.find(m => m.type === 'result');

    // Helper: extract the last substantial assistant text from the log.
    // Used as a fallback when Claude ran out of turns and the recovery
    // session also failed to produce a result.
    function getLastAssistantText(log, minLength = 200) {
      for (let i = log.length - 1; i >= 0; i--) {
        const m = log[i];
        if (m.type !== 'assistant') continue;
        const content = m.message && m.message.content;
        if (!Array.isArray(content)) continue;
        for (let j = content.length - 1; j >= 0; j--) {
          if (content[j].type === 'text' && content[j].text &&
              content[j].text.trim().length >= minLength) {
            const text = content[j].text.trim();
            // Truncate to avoid enormous PR comments
            return text.length > 50000 ? text.substring(0, 50000) +
                    '\n\n*[Truncated — full output in execution log artifact]*' :
                                         text;
          }
        }
      }
      return null;
    }

    if (!resultMessage) {
      responseBody = '⚠️ No result message found in execution log.';
    } else if (resultMessage.subtype === 'success' && resultMessage.result) {
      responseBody = resultMessage.result;
    } else if (resultMessage.is_error || resultMessage.subtype === 'error') {
      const errorInfo =
          resultMessage.result || resultMessage.error || 'Unknown error';
      responseBody = `❌ **Claude encountered an error:**\n\n${errorInfo}`;
    } else if (resultMessage.subtype === 'error_max_turns') {
      // The workflow runs a recovery session when this happens, so this
      // branch is typically only hit if recovery wasn't attempted (e.g.,
      // no findings file was written). Extract what we can.
      const partial = getLastAssistantText(executionLog);
      if (partial) {
        responseBody =
            `⚠️ **Review incomplete — Claude hit the turn limit.**\n\nBelow is the last partial output. You can request a fresh review with \`/claude-review\`.\n\n---\n\n${
                partial}`;
      } else {
        responseBody =
            '⚠️ **Review incomplete — Claude hit the turn limit before producing output.** You can request a fresh review with `/claude-review`.';
      }
    } else if (resultMessage.result) {
      responseBody = `⚠️ **Completed with status: ${
          resultMessage.subtype}**\n\n${resultMessage.result}`;
    } else {
      responseBody = '⚠️ Claude completed but produced no output.';
    }
  } catch (error) {
    responseBody = `❌ Error parsing Claude response: ${error.message}`;
  }

  const isPartial = !!meta.isPartial;
  const icon = isPartial ? '🟡' : (conclusion === 'success' ? '✅' : '⚠️');
  const headerTitle = meta.isQuery ? 'Claude Response' : 'Claude Code Review';
  const triggerLine = getTriggerLine();

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