name: Auto Assign Reviewer

# Use pull_request_target to ensure the workflow has write permissions
# even when the PR originates from a fork.
on:
  pull_request_target:
    types: [opened, ready_for_review, reopened]

# Explicitly grant the required write permissions
permissions:
  pull-requests: write

jobs:
  assign-reviewer:
    # Do not assign reviewers to Draft PRs
    if: github.event.pull_request.draft == false
    runs-on: ubuntu-latest
    steps:
      - name: Checkout base repository
        uses: actions/checkout@v7
        # We checkout the base repository (main) to securely read maintainers.txt.
        # This prevents executing untrusted code from the fork.

      - name: Assign Random Reviewer
        env:
          GH_TOKEN: ${{ secrets.GITHUB_TOKEN }}
          PR_URL: ${{ github.event.pull_request.html_url }}
          AUTHOR: ${{ github.event.pull_request.user.login }}
        run: |
          # 1. Check if reviewers are already assigned
          EXISTING_REVIEWERS=$(gh pr view "$PR_URL" --json reviewRequests -q '.reviewRequests | length')

          if [ "$EXISTING_REVIEWERS" -gt 0 ]; then
            echo "Reviewer already requested. Exiting."
            exit 0
          fi

          # 2. Read maintainers and filter out the author
          # Ignores comments (#), empty lines, and the author (case-insensitive)
          MAINTAINERS=$(grep -v "^#" .github/maintainers.txt | grep -v "^$" | grep -v -i "^${AUTHOR}$" || true)

          if [ -z "$MAINTAINERS" ]; then
            echo "No eligible maintainers found after filtering out the author."
            exit 0
          fi

          # 3. Pick a random reviewer using shuf
          REVIEWER=$(echo "$MAINTAINERS" | shuf -n 1)

          echo "Assigning @$REVIEWER as reviewer..."
          gh pr edit "$PR_URL" --add-reviewer "$REVIEWER"
