#!/usr/bin/env bash
# Run all generated scenarios sequentially to populate the KB.
# Reads tests/multi-agent/scenarios/manifest.json and feeds each file
# to scenario.ts. Each scenario indexes into data/_kb/ automatically
# via the end-of-run hook. Exit code: 0 if all scenarios completed
# (event failures are NOT failures for the batch — we want the KB to
# record both successes AND failures).

set -e
cd "$(dirname "$0")/.."

export OLLAMA_CLOUD_KEY="$(python3 -c "import json; print(json.load(open('/root/llm_team_config.json'))['providers']['ollama_cloud']['api_key'])" 2>/dev/null || echo '')"

MANIFEST="tests/multi-agent/scenarios/manifest.json"
if [ ! -f "$MANIFEST" ]; then
  echo "✗ no manifest at $MANIFEST — run: bun tests/multi-agent/gen_scenarios.ts <N>"
  exit 1
fi

START_TS=$(date -Iseconds)
LOG_DIR="/tmp/lakehouse_kb_batch_$(date +%s)"
mkdir -p "$LOG_DIR"
echo "▶ KB batch start: $START_TS, logs → $LOG_DIR"

python3 -c "
import json
m = json.load(open('$MANIFEST'))
for s in m['scenarios']:
    print(s['file'])
" | while read -r SCEN; do
  SPEC="tests/multi-agent/scenarios/$SCEN"
  BASE=$(basename "$SPEC" .json)
  LOG="$LOG_DIR/${BASE}.log"
  echo "  ▶ $SCEN"
  bun tests/multi-agent/scenario.ts "$SPEC" > "$LOG" 2>&1 || true
  OK=$(grep -oP '\d+/\d+ events succeeded' "$LOG" | tail -1 || echo "no-result")
  SIG=$(grep -oP 'KB indexed: sig=\K[a-f0-9]+' "$LOG" | tail -1 || echo "-")
  echo "    → $OK; sig=$SIG"
done

echo "▶ KB batch done: $(date -Iseconds)"
echo "▶ KB state:"
wc -l data/_kb/*.jsonl 2>/dev/null || true
