name: Gemini PR Triage

on:
  workflow_run:
    workflows: ["PR coverage report", "PR sonar report"]
    types: [completed]
  pull_request_review:
    types: [submitted]
  issue_comment:
    types: [created]

jobs:
  triage:
    name: Triage Gemini review comments
    runs-on: ubuntu-latest
    # Run when: coverage/sonar workflow completes, Gemini bot posts a review, or dev uses @agent fix
    if: |
      github.event_name == 'workflow_run' ||
      (github.event_name == 'pull_request_review' && github.event.review.user.login == 'gemini-code-assist[bot]') ||
      (github.event_name == 'issue_comment' && github.event.issue.pull_request != null && startsWith(github.event.comment.body, '@agent fix'))

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

    steps:
      - uses: actions/checkout@v4
        with:
          fetch-depth: 0
          token: ${{ secrets.GITHUB_TOKEN }}

      - uses: actions/setup-node@v4
        with:
          node-version: "20"

      - name: Install dependencies
        run: npm install node-fetch

      - name: Resolve PR number for workflow_run event
        if: github.event_name == 'workflow_run'
        id: pr
        env:
          GITHUB_TOKEN: ${{ secrets.GITHUB_TOKEN }}
        run: |
          PR=$(gh pr list --head "${{ github.event.workflow_run.head_branch }}" --json number -q '.[0].number')
          echo "number=$PR" >> $GITHUB_OUTPUT

      - name: Run triage
        env:
          GITHUB_TOKEN: ${{ secrets.GITHUB_TOKEN }}
          OPENROUTER_API_KEY: ${{ secrets.OPENROUTER_API_KEY }}
          PR_NUMBER: ${{ github.event.pull_request.number || github.event.issue.number || steps.pr.outputs.number }}
          COMMENT_BODY: ${{ github.event.comment.body || '' }}
          REPO_FULL_NAME: ${{ github.repository }}
          EVENT_NAME: ${{ github.event_name }}
        run: node scripts/triage.js
