#!/usr/bin/env bash
# drive.sh <batches> <threadsPerBatch> : each thread = start + 2 follow-up turns, 8 in parallel
set -eu
B=$RUN_DIR
SRV=$SERVER_DIR
cd "$SRV"
models=(command-output todo-list multi-turn)
one() {
  local i=$1; local models=(command-output todo-list multi-turn); local m=${models[$((i % 3))]}
  local tid
  tid=$(node src/bin.ts thread start --base-dir $B/home --provider devReplay --model "$m" --wait --json $B/proj "go $i" 2>>"$B/cli-errors.log" | grep -o '"threadId":"[^"]*"' | head -1 | cut -d'"' -f4)
  [ -z "$tid" ] && { echo "start failed $i" >&2; return 1; }
  node src/bin.ts thread send --base-dir $B/home --wait "$tid" "again" >>"$B/cli-output.log" 2>>"$B/cli-errors.log"
  node src/bin.ts thread send --base-dir $B/home --wait "$tid" "once more" >>"$B/cli-output.log" 2>>"$B/cli-errors.log"
}
export -f one; export B
echo "batch=0 $(node "$HEAP_SCRIPT" "$INSPECT_PORT")"
n=0
for b in $(seq 1 "$1"); do
  seq $(( (b-1)*$2+1 )) $((b*$2)) | xargs -P 8 -I{} bash -c 'one {}'
  echo "batch=$b threads=$((b*$2)) $(node "$HEAP_SCRIPT" "$INSPECT_PORT")"
done
