#!/usr/bin/env bash
# actions-audit.sh: a read-only audit of one repository's GitHub Actions minutes.
# Usage: ./actions-audit.sh owner/repo [days]   (needs gh, signed in, and jq)
# It only reads (GET) workflow runs and jobs. Nothing is changed or sent anywhere.
set -euo pipefail
repo=${1:?usage: actions-audit.sh owner/repo [days]}
days=${2:-30}
max_runs=${MAX_RUNS:-1000}   # one API call per run; GitHub allows 5,000 an hour
private=$(gh api "repos/$repo" -q .private)
since=$(date -u -d "-$days days" +%F 2>/dev/null || date -u -v-"$days"d +%F)

gh api --paginate "repos/$repo/actions/runs?per_page=100&created=%3E%3D$since" \
  -q '.workflow_runs[].id' |
awk -v m="$max_runs" 'NR <= m { print }
  END { if (NR >= 1000) print "warning: GitHub lists at most 1,000 runs for a date filter; use fewer days" > "/dev/stderr"
        else if (NR > m) print "warning: stopped at MAX_RUNS=" m " of " NR " runs" > "/dev/stderr" }' |
while read -r run; do
  # A run that cannot be read (deleted, or a rate limit) is counted as skipped, not silently lost.
  gh api --paginate "repos/$repo/actions/runs/$run/jobs?filter=all&per_page=100" \
    -q '.jobs[] | select(.runner_name != null and .runner_name != "" and .completed_at != null)
        | {run: .run_id, name, start: .started_at, end: .completed_at,
           wf: .workflow_name, attempt: .run_attempt, result: .conclusion,
           label: (.labels | join(",")),
           secs: ((.completed_at | fromdateiso8601) - (.started_at | fromdateiso8601))}' \
    || echo '{"skipped": true}'
done | jq -rs --arg repo "$repo" --arg days "$days" --arg private "$private" '
  # GitHub list prices per minute (GitHub Actions runner pricing reference).
  def gh_rate: if test("^ubuntu-slim$") then 0.002
    elif test("^ubuntu-[0-9.]+-arm$") then 0.005
    elif test("^ubuntu-(latest|[0-9.]+)$") then 0.006
    elif test("^windows-(latest|[0-9]+)$") then 0.010
    elif test("^macos-(latest|[0-9]+)$") then 0.062
    else null end;   # self-hosted and larger runners: not priced
  def linux_x64: test("^ubuntu-(latest|[0-9.]+|slim)$");
  (map(select(.skipped)) | length) as $skipped | map(select(.skipped | not))
  # Re-running failed jobs lists the jobs that had passed again under the new attempt, with
  # their original start and finish times (seen November 2026): count each of those once.
  | group_by([.run, .name, .start, .end]) | map(min_by(.attempt))
  | map(select(.secs > 0) | . + {billed: ((.secs / 60) | ceil), rate: (.label | gh_rate)}) as $jobs
  | ($jobs | map(select(.rate != null))) as $priced
  | def sum(f): map(f) | add // 0;
    def usd: (. * 100 | round / 100 | tostring) as $s
      | "$" + ($s | if test("\\.") then (split(".") | .[0] + "." + (.[1] + "0")[0:2]) else . + ".00" end);
    def pct(a; b): if b == 0 then "0%" else ((a / b * 1000 | round) / 10 | tostring) + "%" end;
  ($priced | sum(.billed)) as $billed
  | ($priced | sum(.secs / 60)) as $used
  | ($priced | map(select(.attempt > 1)) | sum(.billed)) as $rerun
  | ($priced | map(select(.result == "cancelled")) | sum(.billed)) as $cancel
  | ($priced | map(select(.secs < 60)) | length) as $short
  | ($priced | map(select(.label | linux_x64))) as $lx
  | "Repository \($repo), last \($days) days: \($jobs | length) jobs that ran",
    "Billed minutes (GitHub rounds each job up): \($billed)",
    "Minutes actually used:                     \($used * 10 | round / 10)",
    "Lost to per-job rounding:                  \(($billed - $used) * 10 | round / 10) (\(pct($billed - $used; $billed)))",
    "Jobs under one minute:                     \($short) of \($priced | length)",
    "Minutes on re-run attempts:                \($rerun) (\(pct($rerun; $billed)))",
    "Minutes on cancelled jobs:                 \($cancel) (\(pct($cancel; $billed)))",
    "At GitHub list prices:                     \($priced | sum(.billed * .rate) | usd)",
    (if $private == "false" then "  (public repository: standard runners are free here and ubuntu-latest has 4 vCPU; figures are at private-repository rates)" else empty end),
    "",
    "Top workflows by billed minutes:",
    ($priced | group_by(.wf) | map({wf: .[0].wf, m: sum(.billed), n: length})
      | sort_by(-.m) | .[:5][] | "  \(.m) min  \(.n) jobs  \(.wf)"),
    "",
    ($priced | map(select(.label | test("^(windows|macos)-"))) as $wm
      | if ($wm | length) > 0 then "Windows and macOS jobs: \($wm | sum(.billed)) min, \($wm | sum(.billed * .rate) | usd) (these stay on GitHub)" else empty end),
    "Linux x64 jobs (\($lx | sum(.billed)) min, \($lx | sum(.billed * .rate) | usd) at GitHub prices) on Sengi, also rounded up per job:",
    "  Basic 2 vCPU at $0.001/min:   \($lx | sum(.billed) * 0.001 | usd)",
    "  Premium 2 vCPU at $0.003/min: \($lx | sum(.billed) * 0.003 | usd)",
    (if ($jobs | length) > ($priced | length)
     then "Not priced (self-hosted or larger-runner labels): \($jobs | length - ($priced | length)) jobs, \($jobs | map(select(.rate == null)) | sum(.billed)) min" else empty end),
    (if $skipped > 0 then "Runs that could not be read and are not counted: \($skipped)" else empty end)'
