name: Monitor CI Status

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

permissions:
  contents: read
  pull-requests: write
  issues: write

jobs:
  report-status:
    name: Report CI Status
    runs-on: blacksmith-8vcpu-ubuntu-2404-arm
    
    steps:
    - name: Check CI Status
      uses: actions/github-script@v7
      id: check-status
      with:
        script: |
          const workflow_run = context.payload.workflow_run;
          
          console.log(`Workflow ${workflow_run.name} completed with status: ${workflow_run.conclusion}`);
          console.log(`Run ID: ${workflow_run.id}`);
          console.log(`Run URL: ${workflow_run.html_url}`);
          
          // Get workflow jobs
          const jobs = await github.rest.actions.listJobsForWorkflowRun({
            owner: context.repo.owner,
            repo: context.repo.repo,
            run_id: workflow_run.id
          });
          
          console.log('\nJob Summary:');
          for (const job of jobs.data.jobs) {
            console.log(`- ${job.name}: ${job.conclusion || 'in progress'}`);
            if (job.conclusion === 'failure') {
              console.log(`  Failed at step: ${job.steps.find(s => s.conclusion === 'failure')?.name}`);
            }
          }
          
          // Report failures in PR comment if applicable
          if (workflow_run.conclusion === 'failure' && workflow_run.pull_requests.length > 0) {
            const pr = workflow_run.pull_requests[0];
            const failedJobs = jobs.data.jobs.filter(j => j.conclusion === 'failure');
            
            let comment = '## ❌ CI Failed\n\n';
            comment += `[View failed run](${workflow_run.html_url})\n\n`;
            comment += '### Failed Jobs:\n';
            
            for (const job of failedJobs) {
              comment += `- **${job.name}**\n`;
              const failedStep = job.steps.find(s => s.conclusion === 'failure');
              if (failedStep) {
                comment += `  - Failed at: ${failedStep.name}\n`;
              }
            }
            
            // Store comment body for next step
            core.setOutput('comment_body', comment);
            core.setOutput('pr_number', pr.number.toString());
            core.setOutput('should_comment', 'true');
          } else {
            core.setOutput('should_comment', 'false');
          }
    
    - name: Find Comment
      if: steps.check-status.outputs.should_comment == 'true'
      uses: peter-evans/find-comment@v3
      id: fc
      with:
        issue-number: ${{ steps.check-status.outputs.pr_number }}
        comment-author: 'github-actions[bot]'
        body-includes: '<!-- vibetunnel-ci-status -->'
    
    - name: Create or Update Comment
      if: steps.check-status.outputs.should_comment == 'true'
      uses: peter-evans/create-or-update-comment@v4
      with:
        comment-id: ${{ steps.fc.outputs.comment-id }}
        issue-number: ${{ steps.check-status.outputs.pr_number }}
        body: |
          <!-- vibetunnel-ci-status -->
          ${{ steps.check-status.outputs.comment_body }}
        edit-mode: replace