#!/bin/bash
# test-all-parallel.sh — 8개 게임 병렬 BOT 테스트 (게임은 이미 존재)

ARCADE_DIR="/home/ubuntu/sites/arcade"
BOT_DIR="/tmp/bots"
LOG_DIR="/tmp/bot_logs"

mkdir -p "$BOT_DIR" "$LOG_DIR"

ALL_GAMES=$(ls "$ARCADE_DIR/games/")

echo "============================================"
echo "=== PatchMe: Parallel Bot Test ==="
echo "Time: $(date)"
echo "============================================"

# Chrome에 모든 게임 탭 열기
echo "Opening game tabs..."
cd "$ARCADE_DIR"
NODE_PATH=./node_modules node -e "
const CDP = require('chrome-remote-interface');
(async () => {
  const games = '$ALL_GAMES'.split(' ');
  const client = await CDP({ port: 9222 });
  for (const g of games) {
    try {
      const { targetId } = await client.Target.createTarget({ url: 'https://patchme.lol/games/' + g + '/' });
      console.log('Tab: ' + g);
    } catch(e) { console.log('Error: ' + g + ' ' + e.message); }
  }
  await client.close();
})().catch(console.error);
"
sleep 3

# 병렬 테스트 시작
echo ""
echo "Launching parallel tests..."

for GAME in $ALL_GAMES; do
  mkdir -p "/tmp/bot_snapshots/${GAME}"

  LATEST_BOT=$(ls -t "$BOT_DIR"/bot_${GAME}_v*.js 2>/dev/null | head -1)
  if [ -n "$LATEST_BOT" ]; then
    LATEST_VER=$(echo "$LATEST_BOT" | grep -o 'v[0-9]*' | tail -1 | tr -d 'v')
    CONTEXT="Previous bot at $LATEST_BOT (v${LATEST_VER}). Improve from there."
  else
    CONTEXT="No previous bot. Create v1 from scratch."
  fi

  (
    bash "$ARCADE_DIR/pipeline/bot-runner.sh" "$GAME" &
    RUNNER_PID=$!

    cd "$ARCADE_DIR"
    claude -p "Read $ARCADE_DIR/pipeline/agent-instructions.md and follow instructions.
Game: $GAME
Source: $ARCADE_DIR/games/$GAME/
URL: https://patchme.lol/games/$GAME/
Bots: $BOT_DIR/
Snapshots: /tmp/bot_snapshots/${GAME}/
$CONTEXT
Connect to the tab containing '$GAME' in URL via CDP.List().
Never delete bot files. Write report to $LOG_DIR/${GAME}_report.md" \
      --allowedTools "Read,Write,Edit,Bash,Glob,Grep" \
      2>&1 | tee "$LOG_DIR/${GAME}_agent.log"

    kill $RUNNER_PID 2>/dev/null
    echo "[COMPLETE] $GAME at $(date)"
  ) &

  echo "  Launched: $GAME"
done

echo ""
echo "All 8 tests launched. Waiting..."
wait

echo ""
echo "============================================"
echo "=== ALL COMPLETE: $(date) ==="
echo ""
for GAME in $ALL_GAMES; do
  LATEST=$(ls -t "$BOT_DIR"/bot_${GAME}_v*.js 2>/dev/null | head -1)
  VER=$(echo "$LATEST" | grep -o 'v[0-9]*' | tail -1)
  RPT=$([ -f "$LOG_DIR/${GAME}_report.md" ] && echo "report" || echo "no report")
  echo "  $GAME: ${VER:-none} ($RPT)"
done
echo "============================================"
