#!/bin/bash
# test-game-parallel.sh — 단일 게임 테스트 (병렬 실행용)
# Usage: bash test-game-parallel.sh <game-slug>
# 여러 게임을 동시에 실행할 때 각각 이 스크립트를 호출

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

mkdir -p "$LOG_DIR" "$BOT_DIR" "/tmp/bot_snapshots/${GAME}"

# 기존 프로세스 정리
pkill -f "bot_${GAME}" 2>/dev/null
sleep 1

# 기존 BOT 확인
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 exists at $LATEST_BOT (v${LATEST_VER}). Read it, run it to see performance, then improve to v$((LATEST_VER+1))."
else
  CONTEXT="No previous bot. Create v1 from scratch."
fi

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

# Claude Code 실행
cd "$ARCADE_DIR"
timeout 600 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

IMPORTANT: This game runs in its own Chrome tab. When connecting via CDP, find the tab with URL containing '$GAME' using CDP.List(), then connect to that specific tab.
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 "Done: $GAME"
