name: Label Pending Release

on:
  pull_request:
    types: [opened, reopened, edited, synchronize]
    branches: [dev]

jobs:
  label:
    runs-on: ubuntu-latest
    permissions:
      issues: write
      pull-requests: read

    steps:
      - name: Reconcile pending-release labels for open dev PRs
        env:
          GH_TOKEN: ${{ secrets.GITHUB_TOKEN }}
        run: |
          # Recompute the complete open-PR issue set so edited/synchronized PRs
          # can remove stale pending-release labels as well as add new ones.
          OPEN_PRS=$(gh pr list \
            --repo "${{ github.repository }}" \
            --base dev \
            --state open \
            --json number,title,body \
            --jq '.[] | @base64' 2>/dev/null || true)

          ALL_REFERENCED_ISSUES=""
          while IFS= read -r PR_ROW; do
            [[ -z "$PR_ROW" ]] && continue
            PR_JSON=$(printf '%s' "$PR_ROW" | base64 --decode)
            PR_NUM=$(printf '%s' "$PR_JSON" | jq -r '.number')
            PR_TITLE=$(printf '%s' "$PR_JSON" | jq -r '.title')
            PR_BODY=$(printf '%s' "$PR_JSON" | jq -r '.body // ""')
            COMMIT_TEXT=$(gh api "repos/${{ github.repository }}/pulls/${PR_NUM}/commits" --paginate --jq '.[].commit.message' 2>/dev/null || true)
            PR_TEXT="$PR_TITLE
            $PR_BODY
            $COMMIT_TEXT"
            PR_ISSUES=$(printf '%s\n' "$PR_TEXT" | \
              perl -ne 'if (/(fixes|closes|resolves|refs?)(.*)/i) { print "$2\n"; }' | \
              grep -oE '#[0-9]+' || true)
            if [[ -n "$PR_ISSUES" ]]; then
              ALL_REFERENCED_ISSUES=$(printf '%s\n%s\n' "$ALL_REFERENCED_ISSUES" "$PR_ISSUES")
            fi
          done <<< "$OPEN_PRS"

          ISSUES=$(printf '%s\n' "$ALL_REFERENCED_ISSUES" | grep -oE '#[0-9]+' | sort -u || true)
          CURRENT_PENDING=$(gh issue list --repo "${{ github.repository }}" --label "pending-release" --state all --json number --jq '.[].number' 2>/dev/null || true)

          gh label create "pending-release" \
            --color "fbca04" \
            --description "Fix in review, awaiting merge" \
            --repo ${{ github.repository }} 2>/dev/null || true

          if [[ -z "$ISSUES" ]]; then
            echo "No linked issues found across open dev PRs"
          else
            for ISSUE in $ISSUES; do
              NUM=${ISSUE#\#}
              echo "Ensuring issue #$NUM has pending-release"
              gh issue edit "$NUM" --add-label "pending-release" --repo "${{ github.repository }}" || true
            done
          fi

          for NUM in $CURRENT_PENDING; do
            if ! printf '%s\n' "$ISSUES" | grep -qx "#${NUM}"; then
              echo "Removing stale pending-release from issue #$NUM"
              gh issue edit "$NUM" --remove-label "pending-release" --repo "${{ github.repository }}" 2>/dev/null || true
            fi
          done
