#!/usr/bin/env bash
# drive.sh <batches> <threadsPerBatch> : each thread = start + 2 follow-up turns, 8 in parallel
set -u
B=/tmp/factory-issue-12584-a1794473726-triage-2
SRV=$HOME/wt/factory-issue-12584-a1794473726-triage-2/apps/server
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>/dev/null | grep -o '"threadId":"[^"]*"' | head -1 | cut -d'"' -f4)
  [ -z "$tid" ] && { echo "start failed $i" >&2; return; }
  node src/bin.ts thread send --base-dir $B/home --wait "$tid" "again" >/dev/null 2>&1
  node src/bin.ts thread send --base-dir $B/home --wait "$tid" "once more" >/dev/null 2>&1
}
export -f one; export B
echo "batch=0 $(node $B/heap.mjs 9333)"
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 $B/heap.mjs 9333)"
done
