#!/usr/bin/env bash
# arq-pr-cascade-watch — watch one PR, then cascade-merge dependents
#
# Pattern: a single "gate" PR (e.g., baseline-bump, schema migration) blocks
# many dependent PRs. Operator runs this primitive once and walks away;
# it watches the gate PR for MERGED, then sequentially attempts to merge
# the dependent set with proper CI-settle pacing.
#
# Every event emits arq://act/operator_notification_pending so operator
# sees status via `arq-operator-inbox` at any session start.
#
# Usage:
#   arq-pr-cascade-watch --gate <PR#> --dependents "PR1 PR2 PR3" \
#                        [--owner Arqera-IO] [--repo ARQERA] \
#                        [--poll-sec 60] [--ci-settle-sec 300] \
#                        [--inter-merge-sec 20]
#
# Designed for nohup / launchd. Logs to /tmp/arq-pr-cascade-watch-<gate>.log
# Substrate-attest at:
#   arq://act/operator_notification_pending/cascade-watcher-armed-<gate>-<ts>
#   arq://act/operator_notification_pending/cascade-completed-<gate>-<ts>

set -euo pipefail

GATE=""
DEPS=""
OWNER="Arqera-IO"
REPO="ARQERA"
POLL=60
SETTLE=300
INTER=20

while [[ $# -gt 0 ]]; do
  case "$1" in
    --gate) GATE="$2"; shift 2 ;;
    --dependents) DEPS="$2"; shift 2 ;;
    --owner) OWNER="$2"; shift 2 ;;
    --repo) REPO="$2"; shift 2 ;;
    --poll-sec) POLL="$2"; shift 2 ;;
    --ci-settle-sec) SETTLE="$2"; shift 2 ;;
    --inter-merge-sec) INTER="$2"; shift 2 ;;
    *) echo "unknown arg: $1" >&2; exit 2 ;;
  esac
done

if [[ -z "$GATE" || -z "$DEPS" ]]; then
  echo "Usage: arq-pr-cascade-watch --gate <PR#> --dependents 'PR1 PR2 ...' [opts]" >&2
  exit 2
fi

LOG="/tmp/arq-pr-cascade-watch-${GATE}.log"
TS_START=$(date -u +%Y%m%dT%H%M%SZ)

log() { echo "[$(date -u +%FT%TZ)] $*" >> "$LOG"; }

# Emit start notification
twin --use-keychain act emit \
  --payload "{\"kind\":\"cascade_watcher_armed\",\"gate_pr\":$GATE,\"dependents\":\"$DEPS\",\"owner\":\"$OWNER\",\"repo\":\"$REPO\",\"poll_sec\":$POLL,\"settle_sec\":$SETTLE,\"inter_merge_sec\":$INTER,\"emitted_at\":\"$(date -u +%FT%TZ)\",\"source\":\"arq-pr-cascade-watch\"}" \
  act operator_notification_pending "cascade-watcher-armed-pr${GATE}-${TS_START}" >/dev/null 2>&1 || true

log "armed: gate=#$GATE dependents={$DEPS} poll=${POLL}s settle=${SETTLE}s inter=${INTER}s"

# Poll the gate
while true; do
  STATE=$(gh pr view "$GATE" --repo "$OWNER/$REPO" --json state --jq .state 2>/dev/null)
  if [[ "$STATE" == "MERGED" ]]; then
    log "gate #$GATE MERGED · waiting ${SETTLE}s for CI settle"
    break
  fi
  log "gate #$GATE still $STATE · sleeping ${POLL}s"
  sleep "$POLL"
done

sleep "$SETTLE"

# Cascade merge
MERGED=0
FAILED=0
TOTAL=0

for pr in $DEPS; do
  TOTAL=$((TOTAL+1))
  log "cascade attempt #$pr"
  OUT=$(arq-github pr merge-via-substrate "$pr" --owner "$OWNER" --repo "$REPO" --squash 2>&1 || true)
  echo "$OUT" >> "$LOG"
  if echo "$OUT" | grep -q "merge_landed"; then
    MERGED=$((MERGED+1))
    SHA=$(echo "$OUT" | grep -oE "[a-f0-9]{12}" | head -1)
    log "  MERGED ✓ $SHA"
  else
    FAILED=$((FAILED+1))
    log "  blocked: $(echo "$OUT" | head -1)"
  fi
  sleep "$INTER"
done

TS_END=$(date -u +%Y%m%dT%H%M%SZ)

# Emit completion notification
twin --use-keychain act emit \
  --payload "{\"kind\":\"cascade_completed\",\"gate_pr\":$GATE,\"total_attempts\":$TOTAL,\"merged\":$MERGED,\"blocked\":$FAILED,\"log\":\"$LOG\",\"started_at\":\"$TS_START\",\"completed_at\":\"$(date -u +%FT%TZ)\",\"source\":\"arq-pr-cascade-watch\"}" \
  act operator_notification_pending "cascade-completed-pr${GATE}-${TS_END}" >/dev/null 2>&1 || true

log "cascade complete · merged=$MERGED blocked=$FAILED total=$TOTAL"
