name: BugBot Trigger

on:
  pull_request_target:
    types: [opened, synchronize, ready_for_review, reopened]
  workflow_dispatch:
    inputs:
      pr_number:
        description: "PR number to trigger BugBot on (used by pr-review-responder)"
        required: true
        type: string

jobs:
  trigger-bugbot:
    environment: ai-bots
    # Only review code from regular contributors since bug bot has a capped # of PR reviews.
    # For workflow_dispatch, we check skip tags below since the caller may not have validated them.
    if: |
      github.event_name == 'workflow_dispatch' ||
      ((github.event.pull_request.user.login == 'wwwillchen' ||
      github.event.pull_request.user.login == 'azizmejri1' ||
      github.event.pull_request.user.login == 'princeaden1') &&
      !contains(github.event.pull_request.body, '#skip-bugbot') &&
      !contains(github.event.pull_request.body, '#skip-bb'))
    runs-on: ubuntu-latest
    permissions:
      pull-requests: write
    steps:
      - name: Validate pr_number format
        if: github.event_name == 'workflow_dispatch'
        run: |
          if ! [[ "${{ inputs.pr_number }}" =~ ^[0-9]+$ ]]; then
            echo "::error::pr_number must be a numeric value"
            exit 1
          fi

      - name: Check skip tags for workflow_dispatch
        if: github.event_name == 'workflow_dispatch'
        id: check-skip
        env:
          GITHUB_TOKEN: ${{ secrets.GITHUB_TOKEN }}
        run: |
          PR_BODY=$(gh pr view "${{ inputs.pr_number }}" --repo "${{ github.repository }}" --json body --jq '.body') || {
            echo "::error::Failed to fetch PR body for skip tag check"
            exit 1
          }
          if echo "$PR_BODY" | grep -qE '#skip-bugbot|#skip-bb'; then
            echo "skip=true" >> $GITHUB_OUTPUT
            echo "Skipping BugBot: PR contains skip tag"
          else
            echo "skip=false" >> $GITHUB_OUTPUT
          fi

      - name: Comment @BugBot run
        if: steps.check-skip.outputs.skip != 'true'
        uses: peter-evans/create-or-update-comment@e8674b075228eee787fea43ef493e45ece1004c9 # v5
        with:
          # Use a PAT from wwwillchen to post on their behalf
          token: ${{ secrets.WWWILLCHEN_PR_RW_PAT }}
          issue-number: ${{ github.event.pull_request.number || inputs.pr_number }}
          body: "@BugBot run"
