#!/bin/bash
set +e
CEL=/home/tiara/workspace/byteb4rb1e/cel
DD=$CEL/sek.ddist
XSEK=$CEL/xsek.byteb4rb1e
export VENV_PY=/home/tiara/.local/share/virtualenvs/sek.ddist-JE-PxZHd/bin/python
export SEK_MODEL="phi3:3.8B"
export SEK_MODEL_URL="http://localhost:4000/v1"
export SEK_API_KEY="sk-litellm-dev"
N=5; SECS=120
INSTRUCT_OUT="/tmp/claude-1000/-home-tiara-workspace-byteb4rb1e-cel/bed207a5-80ef-4f85-8131-4d81e693c7de/tasks/brtubqyw6.output"
cd "$DD" || { echo CD_FAIL; exit 0; }
log(){ echo "[$(date +%H:%M:%S)] $*"; }

# 1. Wait for the instruct ladder to finish (its DONE marker is printed
#    AFTER it restores the working tree). Bounded so it cannot hang forever.
log "waiting for instruct ladder (brtubqyw6) to finish..."
waited=0
while ! grep -q "PHI3-INSTRUCT LADDER DONE" "$INSTRUCT_OUT" 2>/dev/null; do
  sleep 20; waited=$((waited+20))
  if [ "$waited" -ge 5400 ]; then log "TIMED OUT waiting for instruct; aborting"; exit 0; fi
done
sleep 5
pkill -9 -f byteb4rb1e.sek.ddist 2>/dev/null; sleep 2
log "instruct done after ${waited}s; starting phi3 C2/C3"

prep(){   # $1 = seed config (c2/c3)   $2 = label
  pkill -9 -f byteb4rb1e.sek.ddist 2>/dev/null; sleep 1
  git -C "$XSEK" checkout 5b2b1c6 >/dev/null 2>&1          # no-stop discipline
  "$VENV_PY" set_seed.py "$1" >/dev/null
  rm -rf "$DD/src/byteb4rb1e/sek/ddist/rootfs"
  "$VENV_PY" -m byteb4rb1e.sek.ddist install >/dev/null 2>&1
  log "$1 ($2): reinstalled, asst=$(grep -c role:assistant src/byteb4rb1e/sek/ddist/installer.py)"
}

log "PHI3 C2/C3 START  N=$N  secs=$SECS  model=$SEK_MODEL"
prep c2 merged-prompt  ; "$VENV_PY" _repl_driver.py phi_c2 $N $SECS
prep c3 failure-only   ; "$VENV_PY" _repl_driver.py phi_c3 $N $SECS

# restore working tree: C4 standalone seed + no-stop discipline
"$VENV_PY" set_seed.py c4 >/dev/null 2>&1
git -C "$XSEK" checkout 5b2b1c6 >/dev/null 2>&1
log "PHI3 C2/C3 DONE"
exit 0
