#!/bin/bash
# CI watcher for InsuRo PR #223 (task-2968) — poll until terminal, NEVER merge.
SHA=0a1c33a9c36b7a7c57207d20c906888113ca44ab
REPO=Jeon-Jonghyuk/InsuRo
LOG=/home/jay/workspace/teams/dev2/.ci-watch-2968.log
MAX_POLLS=30          # 30 * 90s = 45 min
INTERVAL=90

echo "=== watch start $(date -Is) ===" >> "$LOG"

for i in $(seq 1 $MAX_POLLS); do
  OUT=$(gh api "repos/$REPO/commits/$SHA/check-runs" --paginate 2>&1)
  VERDICT=$(printf '%s' "$OUT" | python3 -c '
import json,sys
raw=sys.stdin.read()
try:
    d=json.loads(raw)
except Exception as e:
    print("APIERR"); sys.exit(0)
runs=d.get("check_runs",[])
pending=[c["name"] for c in runs if c["status"]!="completed"]
failed=[c["name"] for c in runs if c["status"]=="completed" and c["conclusion"] not in ("success","neutral","skipped")]
lines=[f"{c[\"name\"]}|{c[\"status\"]}|{c[\"conclusion\"]}" for c in runs]
sys.stderr.write("\n".join(lines)+"\n")
if pending:
    print("PENDING:"+",".join(pending))
elif failed:
    print("FAILED:"+",".join(failed))
else:
    print("ALLGREEN:"+str(len(runs)))
' 2>>"$LOG")

  echo "[poll $i $(date -Is)] $VERDICT" >> "$LOG"

  case "$VERDICT" in
    ALLGREEN:*|FAILED:*)
      echo "TERMINAL_REACHED $VERDICT" >> "$LOG"
      echo "$VERDICT" > /home/jay/workspace/teams/dev2/.ci-watch-2968.verdict
      exit 0
      ;;
  esac

  sleep $INTERVAL
done

echo "LOOP_BOUNDARY: max polls exhausted" >> "$LOG"
echo "LOOP_BOUNDARY" > /home/jay/workspace/teams/dev2/.ci-watch-2968.verdict
exit 0
