#!/usr/bin/env bash
# dispatch_watch.sh "name:RUN_ID" ["name:RUN_ID" ...]
# Poll Studio dispatch runs until ALL reach a terminal state, then print each
# run's final state + PR url and exit 0. Meant to run in the background so its
# exit re-invokes the caller exactly once (no per-poll wakeups).
#
# bash 3.2 compatible — NO associative arrays (the bug in the throwaway version:
# `declare -A` needs bash 4+, but macOS ships bash 3.2). Uses an indexed array of
# "name:run_id" pairs + parameter expansion (%%/#) instead.
#
# Env: STUDIO (default joeturnerlin@100.105.59.118), POLL_SECS (40), MAX_POLLS (90).
set -uo pipefail

STUDIO="${STUDIO:-joeturnerlin@100.105.59.118}"
POLL_SECS="${POLL_SECS:-40}"
MAX_POLLS="${MAX_POLLS:-90}"
TERMINAL_RE='^(CONVERGED_PR_CREATED|CAPPED_NEEDS_HUMAN|REAPED)$'

PAIRS=("$@")
if [ "${#PAIRS[@]}" -eq 0 ]; then
  echo "usage: dispatch_watch.sh name:RUN_ID [name:RUN_ID ...]" >&2
  exit 2
fi

# Read one run's state (empty string if status.json missing/unreadable).
run_state() {
  local rid="$1"
  ssh -o ConnectTimeout=8 -o BatchMode=yes "$STUDIO" \
    "python3 -c \"import json;print(json.load(open('\$HOME/.recoil/dispatch-runs/$rid/status.json'))['state'])\" 2>/dev/null"
}

poll=0
while [ "$poll" -lt "$MAX_POLLS" ]; do
  poll=$((poll + 1))
  sleep "$POLL_SECS"
  done_count=0
  report=""
  for pair in "${PAIRS[@]}"; do
    name="${pair%%:*}"
    rid="${pair#*:}"
    st="$(run_state "$rid")"
    report="${report}  ${name}: ${st:-pending}\n"
    if printf '%s' "$st" | grep -Eq "$TERMINAL_RE"; then
      done_count=$((done_count + 1))
    fi
  done
  if [ "$done_count" -eq "${#PAIRS[@]}" ]; then
    echo "=== ALL ${#PAIRS[@]} BUILD(S) TERMINAL (poll ${poll}/${MAX_POLLS}) ==="
    for pair in "${PAIRS[@]}"; do
      name="${pair%%:*}"
      rid="${pair#*:}"
      ssh -o ConnectTimeout=8 -o BatchMode=yes "$STUDIO" \
        "python3 -c \"import json;s=json.load(open('\$HOME/.recoil/dispatch-runs/$rid/status.json'));print('${name}:',s['state'],'| pr:',s.get('pr_url') or '-')\" 2>/dev/null"
    done
    exit 0
  fi
done

echo "=== dispatch_watch timed out after $((POLL_SECS * MAX_POLLS))s — current states ==="
printf '%b' "$report"
exit 0
