#!/usr/bin/env bash
set -euo pipefail
PASSES="${1:-5}"
CWD=/home/sebas/work/projects/vending-status-pages
PROMPT=/home/sebas/work/tasks/T-ourvend-real-ui/CHAIN-WORKER-PROMPT.txt
UPDATES=/home/sebas/work/tasks/T-ourvend-real-ui/UPDATES.md
STATE=/home/sebas/work/tasks/T-ourvend-real-ui/STATE.md
LOGROOT=/home/sebas/runtime/ourvend-real-ui-chain
mkdir -p "$LOGROOT"

echo "chain_start=$(date -u +%Y-%m-%dT%H:%M:%SZ) passes=$PASSES" >> "$LOGROOT/chain.log"
for i in $(seq 1 "$PASSES"); do
  out=$(/home/sebas/pi-config/bin/pi-job-start --cwd "$CWD" --name "ourvend-chain-pass-$i" --prompt-file "$PROMPT")
  job_id=$(printf '%s
' "$out" | awk -F= '/^job_id=/{print $2}')
  job_dir=$(printf '%s
' "$out" | awk -F= '/^job_dir=/{print $2}')
  printf '%s
' "- $(date -u +%Y-%m-%dT%H:%M:%SZ) chain launched pass $i job $job_id" >> "$UPDATES"
  ~/.agents/skills/telegram-notify/telegram-notify "OurVend chain: launched pass $i/$PASSES ($job_id)"
  /home/sebas/pi-config/bin/pi-job-wait "$job_id" >/tmp/ourvend-chain-wait-$i.log 2>&1 || true
  status=$(/home/sebas/pi-config/bin/pi-job-check "$job_id" | awk -F= '/^status=/{print $2}')
  printf '%s
' "pass=$i job_id=$job_id status=$status" >> "$LOGROOT/chain.log"
  tail -n 40 "$job_dir/output.log" > "$LOGROOT/${job_id}.tail" || true
  if [[ "$status" != "succeeded" ]]; then
    ~/.agents/skills/telegram-notify/telegram-notify "OurVend chain: pass $i/$PASSES failed ($job_id). Check logs."
    exit 1
  fi
  ~/.agents/skills/telegram-notify/telegram-notify "OurVend chain: pass $i/$PASSES done ($job_id)."
  if grep -q '^status: done' "$STATE" 2>/dev/null; then
    ~/.agents/skills/telegram-notify/telegram-notify "OurVend chain: state is done early after pass $i/$PASSES."
    exit 0
  fi
done
~/.agents/skills/telegram-notify/telegram-notify "OurVend chain: all $PASSES passes finished. Check validator/revalidation state."
