#!/usr/bin/env bash
# Waits until the pipeline's own OAuth client gets a Sonnet 5 answer, then runs the QUE-370 sample pass and the
# full KREF 10-Q extraction one after the other. Never two extractions at once.
set -u
S=/tmp/claude-1000/-home-mande-repo-quber/bc2f817a-5c6c-4515-9621-2302b82f7f68/scratchpad
REPO=/home/mande/repo/quber
OUT=$REPO/data/que370-review/sample
STATUS=$OUT/status.tsv
LOG=$S/gate_runner.log
set -a; . $REPO/.env; set +a
probe() {
  (cd $REPO && uv run python $S/probe_sonnet.py 2>/dev/null | tail -1)
}
while :; do
  code=$(probe)
  echo "$(date '+%F %T') probe sonnet-5 -> $code" >> $LOG
  [ "$code" = 200 ] && break
  sleep 300
done
echo "--- fourth pass rerun (commit $(cd $REPO && git rev-parse --short HEAD)), window reopened $(date '+%F %T') ---" >> $STATUS
bash $OUT/run_sample.sh
echo "$(date '+%F %T') sample pass finished" >> $LOG
D=$S/branch-review6; rm -rf $D; mkdir -p $D
(cd $REPO && uv run quber extract data/playground/998c8ed06c0be22d.pdf --review -o $D > $D/extract.log 2>&1); rc=$?
echo "$(date '+%F %T') full KREF rc=$rc tables.json=$(ls $D/*.tables.json 2>/dev/null | wc -l)" >> $LOG
if [ $rc = 0 ]; then rm -rf $REPO/data/que370-review/branch-full; cp -r $D $REPO/data/que370-review/branch-full; fi
echo "GATE_RUNNER_DONE rc_full=$rc" >> $LOG
