# Shared comment-posting workflow for AI reviews.

name: AI Review Comment

on:
  workflow_call:
    inputs:
      provider:
        description: Provider key, for example "claude" or "codex"
        required: true
        type: string
      result_artifact_name:
        description: Artifact name produced by the analysis workflow
        required: true
        type: string
      comment_file:
        description: Markdown comment file produced by the analysis workflow
        required: true
        type: string

permissions:
  pull-requests: write
  issues: write

jobs:
  comment:
    if: github.event.workflow_run.conclusion == 'success'
    runs-on: ubuntu-latest
    steps:
      - name: Checkout scripts
        uses: actions/checkout@v4
        with:
          sparse-checkout: .github/scripts
          sparse-checkout-cone-mode: true

      - name: Download review artifact
        id: download
        uses: actions/download-artifact@v4
        with:
          name: ${{ inputs.result_artifact_name }}
          run-id: ${{ github.event.workflow_run.id }}
          github-token: ${{ secrets.GITHUB_TOKEN }}
        continue-on-error: true

      - name: Post or update PR comment
        if: steps.download.outcome == 'success'
        env:
          PROVIDER: ${{ inputs.provider }}
          COMMENT_FILE: ${{ inputs.comment_file }}
          RUN_ID: ${{ github.event.workflow_run.id }}
        uses: actions/github-script@v7
        with:
          script: |
            const fs = require('fs');
            if (!fs.existsSync(process.env.COMMENT_FILE) ||
                !fs.existsSync('pr_number.txt')) {
              core.info('No review results found; skipping.');
              return;
            }

            const post = require('./.github/scripts/post-pr-comment.js');
            const provider = process.env.PROVIDER;
            const providerTitle = provider === 'codex' ? 'Codex' : 'Claude';
            const body = fs.readFileSync(process.env.COMMENT_FILE, 'utf8');
            const prNumber = parseInt(
              fs.readFileSync('pr_number.txt', 'utf8').trim(),
              10
            );
            const trigger = fs.existsSync('trigger_type.txt') ?
              fs.readFileSync('trigger_type.txt', 'utf8').trim() :
              'auto';
            const headSha = fs.existsSync('head_sha.txt') ?
              fs.readFileSync('head_sha.txt', 'utf8').trim() :
              '';
            const shortSha = headSha ? headSha.substring(0, 7) : '';
            const runId = process.env.RUN_ID;

            let marker = '';
            let legacyMarkers = [];
            let prunePrefix = '';
            let preserveLatest = 0;
            let obsoleteMarker = '';
            let obsoleteTitle = '';

            if (trigger === 'auto') {
              if (!shortSha) {
                core.warning(
                  'Missing head_sha.txt for auto review; skipping comment.'
                );
                return;
              }
              marker = `<!-- ${provider}-review-auto-run-${runId} -->`;
              legacyMarkers = [`<!-- ${provider}-review-auto -->`];
              prunePrefix = `<!-- ${provider}-review-auto-`;
              preserveLatest = 1;
              obsoleteMarker = `<!-- ${provider}-review-obsolete -->`;
              obsoleteTitle = `${providerTitle} Code Review - OBSOLETE`;
            } else {
              marker = `<!-- ${provider}-review-manual-run-${runId} -->`;
            }

            await post({
              github,
              context,
              core,
              prNumber,
              body,
              marker,
              legacyMarkers,
              prunePrefix,
              preserveLatest,
              obsoleteMarker,
              obsoleteTitle,
            });

      - name: Add reaction to trigger comment
        if: steps.download.outcome == 'success'
        uses: actions/github-script@v7
        with:
          script: |
            const fs = require('fs');
            if (!fs.existsSync('trigger_type.txt')) return;
            const trigger = fs.readFileSync('trigger_type.txt', 'utf8').trim();
            if (trigger !== 'manual') return;
            if (!fs.existsSync('comment_id.txt')) return;
            const commentId = parseInt(
              fs.readFileSync('comment_id.txt', 'utf8').trim(),
              10
            );
            if (!commentId) return;

            await github.rest.reactions.createForIssueComment({
              owner: context.repo.owner,
              repo: context.repo.repo,
              comment_id: commentId,
              content: 'rocket'
            });

  failure-notice:
    if: github.event.workflow_run.conclusion == 'failure'
    runs-on: ubuntu-latest
    steps:
      - name: Download artifact for PR number
        id: download
        uses: actions/download-artifact@v4
        with:
          name: ${{ inputs.result_artifact_name }}
          run-id: ${{ github.event.workflow_run.id }}
          github-token: ${{ secrets.GITHUB_TOKEN }}
        continue-on-error: true

      - name: React with failure
        if: steps.download.outcome == 'success'
        uses: actions/github-script@v7
        with:
          script: |
            const fs = require('fs');
            if (!fs.existsSync('comment_id.txt')) return;
            const commentId = parseInt(
              fs.readFileSync('comment_id.txt', 'utf8').trim(),
              10
            );
            if (!commentId) return;

            await github.rest.reactions.createForIssueComment({
              owner: context.repo.owner,
              repo: context.repo.repo,
              comment_id: commentId,
              content: 'confused'
            });

  unauthorized-notice:
    runs-on: ubuntu-latest
    if: >-
      github.event.workflow_run.event == 'issue_comment' &&
      github.event.workflow_run.conclusion == 'skipped'
    steps:
      - name: Log skipped unauthorized request
        uses: actions/github-script@v7
        with:
          script: |
            core.info(
              'Analysis workflow was skipped, which usually means the ' +
              'issue_comment requester was not in the authorized list.'
            );
