name: "Rerun Failed PR Workflows"
description: "Reruns failed GitHub workflow runs on open PRs by @lucabello and Observability bots"
schedule: "0 */3 * * *"
script: |
  #!/usr/bin/env bash
  set -euo pipefail

  # ─── Configuration ──────────────────────────────────────────────────────
  # PR authors whose failed workflows should be rerun.
  # Use GitHub username. For GitHub Apps, use "app/name" format.
  AUTHORS=(
    "lucabello"
    "observability-noctua-bot"
    "app/renovate"
  )
  # ────────────────────────────────────────────────────────────────────────

  reran=0

  for author in "${AUTHORS[@]}"; do
    # Only fetch PRs that already have failing checks
    echo "── Searching PRs for author: ${author} ──"

    while IFS=$'\t' read -r repo pr_num; do
      [[ -z "$pr_num" ]] && continue

      # Get branch and head SHA from the PR details
      pr_info=$(gh pr view "$pr_num" -R "$repo" --json headRefName,headRefOid \
        --jq '[.headRefName, .headRefOid] | @tsv' 2>/dev/null < /dev/null) || continue
      IFS=$'\t' read -r branch head_sha <<< "$pr_info"
      [[ -z "$branch" ]] && continue

      # Rerun failed workflow runs on this PR's head commit (skip if already rerunning)
      while IFS=$'\t' read -r run_id workflow_name; do
        [[ -z "$run_id" ]] && continue

        # Skip if this workflow already has an in_progress run on the same branch
        in_progress=$(gh run list -R "$repo" --branch "$branch" --status in_progress \
          --workflow "$workflow_name" --limit 1 \
          --json databaseId --jq 'length' \
          2>/dev/null < /dev/null) || in_progress="0"
        if [[ "$in_progress" != "0" ]]; then
          echo "PR ${repo}#${pr_num} (${author}): skipping run ${run_id} — workflow '${workflow_name}' already in progress"
          continue
        fi

        echo "PR ${repo}#${pr_num} (${author}): rerunning failed jobs in run ${run_id}"
        gh run rerun "$run_id" -R "$repo" --failed < /dev/null 2>&1 || echo "  skipped (cannot rerun)"
        (( reran++ )) || true
      done < <(gh run list -R "$repo" --branch "$branch" --status failure \
        --json databaseId,headSha,workflowName \
        --jq ".[] | select(.headSha == \"${head_sha}\") | [(.databaseId | tostring), .workflowName] | @tsv" \
        2>/dev/null < /dev/null || true)

    done < <(gh search prs --author "$author" --state open --checks failure --limit 100 \
      --json repository,number \
      --jq '.[] | [.repository.nameWithOwner, (.number | tostring)] | @tsv' \
      2>/dev/null || true)
  done

  echo "Reran ${reran} failed workflow(s). Done."
