on:
  workflow_dispatch:

name: Add Labels to PR

jobs:
  add_labels:
    runs-on: ubuntu-latest

    steps:
      # Checkout the repository code
      - name: Checkout code
        uses: actions/checkout@v3

      # Extract and format the labels from the comment as "username: label"
      - name: Extract reviewer and labels
        if: ${{ github.event_name == 'issue_comment' && github.event.issue.pull_request && startsWith(github.event.comment.body, '/') }}
        id: extract_labels
        run: |
          comment_body="${{ github.event.comment.body }}"
          reviewer="${{ github.event.comment.user.login }}"
          # Clean up comment and extract labels
          raw_labels=$(echo "$comment_body" | sed 's|^/||')
          formatted_labels=$(echo "$raw_labels" | awk -v reviewer="$reviewer" '{split($0, arr, ","); for (i in arr) {gsub(/^ +| +$/, "", arr[i]); print reviewer ": " arr[i]}}')
          
          # Set the formatted labels as an environment variable (new way, not using set-output)
          echo "labels=$formatted_labels" >> $GITHUB_ENV
          
          # Output labels for debugging
          echo "Formatted labels: $formatted_labels"

      # Add the extracted labels to the PR
      - name: Add labels via PR comment
        if: ${{ github.event_name == 'issue_comment' && github.event.issue.pull_request && startsWith(github.event.comment.body, '/') }}
        uses: actions-ecosystem/action-add-labels@v1
        with:
          github_token: ${{ secrets.GH_TOKEN }}
          labels: ${{ env.labels }}
