name: CI Summary

# Analyzes CI results and posts/updates a structured PR comment.
# On failure: downloads artifacts, analyzes errors, posts diagnostics.
# On success: updates any existing failure comment to reflect all-passing status.
# Uses pure pattern-matching on cargo/clippy/nextest output — no LLM required.
# Logic lives in .github/scripts/analyze-ci-failures.sh for testability.

on:
  workflow_run:
    workflows: ["CI"]
    types: [completed]

jobs:
  ci-summary:
    if: github.event.workflow_run.event == 'pull_request'
    runs-on: ubuntu-latest
    permissions:
      contents: read
      pull-requests: write
      actions: read

    steps:
      # ── Get the PR number (always needed) ──────────────────────────
      - name: Get PR number
        id: pr
        run: |
          PR_NUMBER=$(gh api "repos/${{ github.repository }}/commits/${{ github.event.workflow_run.head_sha }}/pulls" \
            --jq '.[0].number // empty')
          echo "number=$PR_NUMBER" >> "$GITHUB_OUTPUT"
        env:
          GH_TOKEN: ${{ secrets.GITHUB_TOKEN }}

      # ── Failure path: checkout, download artifacts, analyze ────────
      - uses: actions/checkout@v5
        if: github.event.workflow_run.conclusion == 'failure'
        with:
          ref: ${{ github.event.workflow_run.head_sha }}

      - name: Download test results
        if: github.event.workflow_run.conclusion == 'failure'
        uses: actions/download-artifact@v7
        with:
          pattern: test-results-*
          run-id: ${{ github.event.workflow_run.id }}
          github-token: ${{ secrets.GITHUB_TOKEN }}
          path: ci-artifacts/
          merge-multiple: true
        continue-on-error: true

      - name: Download clippy results
        if: github.event.workflow_run.conclusion == 'failure'
        uses: actions/download-artifact@v7
        with:
          pattern: clippy-results*
          run-id: ${{ github.event.workflow_run.id }}
          github-token: ${{ secrets.GITHUB_TOKEN }}
          path: ci-artifacts/
          merge-multiple: true
        continue-on-error: true

      - name: Download build results
        if: github.event.workflow_run.conclusion == 'failure'
        uses: actions/download-artifact@v7
        with:
          pattern: build-results-*
          run-id: ${{ github.event.workflow_run.id }}
          github-token: ${{ secrets.GITHUB_TOKEN }}
          path: ci-artifacts/
          merge-multiple: true
        continue-on-error: true

      - name: Download fmt results
        if: github.event.workflow_run.conclusion == 'failure'
        uses: actions/download-artifact@v7
        with:
          pattern: fmt-results*
          run-id: ${{ github.event.workflow_run.id }}
          github-token: ${{ secrets.GITHUB_TOKEN }}
          path: ci-artifacts/
          merge-multiple: true
        continue-on-error: true

      - name: Download integration test results
        if: github.event.workflow_run.conclusion == 'failure'
        uses: actions/download-artifact@v7
        with:
          pattern: integration-test-results-*
          run-id: ${{ github.event.workflow_run.id }}
          github-token: ${{ secrets.GITHUB_TOKEN }}
          path: ci-artifacts/
          merge-multiple: true
        continue-on-error: true

      - name: List downloaded artifacts
        if: github.event.workflow_run.conclusion == 'failure'
        run: find ci-artifacts/ -type f 2>/dev/null || echo "No artifacts downloaded"

      - name: Get failed jobs
        if: github.event.workflow_run.conclusion == 'failure'
        run: |
          gh run view ${{ github.event.workflow_run.id }} --json jobs \
            --jq '.jobs[] | select(.conclusion == "failure") | .name' \
            > failed-jobs.txt || true
          echo "Failed jobs:"
          cat failed-jobs.txt
        env:
          GH_TOKEN: ${{ secrets.GITHUB_TOKEN }}

      - name: Analyze failures
        if: github.event.workflow_run.conclusion == 'failure'
        run: |
          bash .github/scripts/analyze-ci-failures.sh \
            ci-artifacts \
            failed-jobs.txt \
            "${{ github.repository }}" \
            "${{ github.event.workflow_run.id }}" \
            > /tmp/ci-comment-body.md
          echo "Generated comment:"
          cat /tmp/ci-comment-body.md

      # ── Post or update PR comment ──────────────────────────────────
      - name: Post or update CI summary comment
        if: steps.pr.outputs.number != ''
        uses: actions/github-script@v8
        env:
          CI_CONCLUSION: ${{ github.event.workflow_run.conclusion }}
          RUN_URL: https://github.com/${{ github.repository }}/actions/runs/${{ github.event.workflow_run.id }}
        with:
          script: |
            const fs = require('fs');
            const prNumber = ${{ steps.pr.outputs.number }};
            const marker = '<!-- cqlsh-rs-ci-summary -->';
            const conclusion = process.env.CI_CONCLUSION;
            const runUrl = process.env.RUN_URL;

            // Find existing CI summary comment
            const comments = await github.rest.issues.listComments({
              owner: context.repo.owner,
              repo: context.repo.repo,
              issue_number: prNumber
            });
            const existing = comments.data.find(c => c.body.includes(marker));

            let body;
            if (conclusion === 'failure') {
              // Read the analysis script output
              try {
                body = fs.readFileSync('/tmp/ci-comment-body.md', 'utf8');
              } catch (e) {
                console.log('No comment body file found:', e.message);
                return;
              }
              if (!body || body.trim() === '') {
                console.log('Empty comment body — skipping');
                return;
              }
            } else {
              // Success: only update if a previous failure comment exists
              if (!existing) {
                console.log('CI passed, no existing failure comment — nothing to do');
                return;
              }
              body = [
                marker,
                '## CI Summary',
                '',
                '**Status:** ✅ All jobs passed',
                '',
                '<details>',
                '<summary>✅ <b>Rustfmt</b> — passed</summary>',
                'No issues.',
                '</details>',
                '',
                '<details>',
                '<summary>✅ <b>Clippy</b> — passed</summary>',
                'No issues.',
                '</details>',
                '',
                '<details>',
                '<summary>✅ <b>Tests</b> — passed</summary>',
                'No issues.',
                '</details>',
                '',
                '<details>',
                '<summary>✅ <b>Build</b> — passed</summary>',
                'No issues.',
                '</details>',
                '',
                '---',
                `*🤖 Generated by CI Summary • [Full logs](${runUrl})*`
              ].join('\n');
            }

            if (existing) {
              await github.rest.issues.updateComment({
                owner: context.repo.owner,
                repo: context.repo.repo,
                comment_id: existing.id,
                body
              });
              console.log(`Updated existing comment ${existing.id}`);
            } else {
              await github.rest.issues.createComment({
                owner: context.repo.owner,
                repo: context.repo.repo,
                issue_number: prNumber,
                body
              });
              console.log('Created new comment');
            }
