#!/bin/bash
# bot-test-game.sh — 봇으로 게임 테스트 + 봇 업그레이드
#
# 모드 1: 신규 게임 → 봇 v1~v4 생성 (timeout 20분)
# 모드 2: 기존 게임 업데이트 → 기존 봇으로 테스트 → 봇 1버전 업그레이드
#
# Usage: bash bot-test-game.sh <game-slug> [new|update]
#   new    = 봇 v1~v4까지 생성 (주간 게임 추가 시)
#   update = 기존 봇으로 테스트 + 1버전 업 (매일 제안 반영 시)

GAME=$1
MODE=${2:-update}
ARCADE_DIR="/home/ubuntu/sites/arcade"
BOT_DIR="/tmp/bots"
LOG_DIR="/tmp/bot_logs"
INSTRUCTIONS="$ARCADE_DIR/pipeline/agent-instructions.md"
METHODOLOGY="$ARCADE_DIR/pipeline/game-testing-methodology.md"

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

LATEST_BOT=$(ls -t "$BOT_DIR"/bot_${GAME}_v*.js 2>/dev/null | head -1)
LATEST_VER=$(echo "$LATEST_BOT" | grep -o 'v[0-9]*' | tail -1 | tr -d 'v')

echo "[BOT-TEST] Game: $GAME, Mode: $MODE, Current bot: v${LATEST_VER:-none}"

if [ "$MODE" = "new" ]; then
  #############################################
  # NEW: 봇 v1~v4까지 생성 (timeout 20분)
  #############################################
  echo "[BOT-TEST] Creating new bot (v1→v4)..."

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

  # Chrome 탭 열기
  cd "$ARCADE_DIR"
  NODE_PATH=./node_modules node -e "
    const CDP = require('chrome-remote-interface');
    (async () => {
      const client = await CDP({ port: 9222 });
      await client.Target.createTarget({ url: 'https://patchme.lol/games/$GAME/' });
      await client.close();
    })().catch(() => {});
  " 2>/dev/null
  sleep 3

  timeout 1200 claude -p "Read $INSTRUCTIONS and $METHODOLOGY.

Game: $GAME
Source: $ARCADE_DIR/games/$GAME/
URL: https://patchme.lol/games/$GAME/
Bots: $BOT_DIR/
Snapshots: /tmp/bot_snapshots/${GAME}/

No previous bot. Create v1 from scratch.
Iterate up to v4. Each version should fix issues from previous.
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
  pkill -f "bot_${GAME}" 2>/dev/null

  # 결과 확인
  FINAL_BOT=$(ls -t "$BOT_DIR"/bot_${GAME}_v*.js 2>/dev/null | head -1)
  if [ -n "$FINAL_BOT" ]; then
    echo "[BOT-TEST] NEW complete. Final: $(basename $FINAL_BOT)"
    exit 0
  else
    echo "[BOT-TEST] NEW failed. No bot created."
    exit 1
  fi

elif [ "$MODE" = "update" ]; then
  #############################################
  # UPDATE: 기존 봇으로 테스트 → 봇 1버전 업
  #############################################

  if [ -z "$LATEST_BOT" ]; then
    echo "[BOT-TEST] No existing bot. Switching to 'new' mode."
    exec bash "$0" "$GAME" new
  fi

  echo "[BOT-TEST] Running existing bot v${LATEST_VER} to test game..."

  # Chrome 탭 열기
  cd "$ARCADE_DIR"
  NODE_PATH=./node_modules node -e "
    const CDP = require('chrome-remote-interface');
    (async () => {
      const client = await CDP({ port: 9222 });
      const tabs = await CDP.List({ port: 9222 });
      if (!tabs.find(t => t.url.includes('$GAME'))) {
        await client.Target.createTarget({ url: 'https://patchme.lol/games/$GAME/' });
      }
      await client.close();
    })().catch(() => {});
  " 2>/dev/null
  sleep 3

  # 기존 봇 실행 (90초)
  cd "$ARCADE_DIR"
  NODE_PATH=./node_modules timeout 120 node "$LATEST_BOT" > "$LOG_DIR/${GAME}_test.log" 2>&1
  TEST_EXIT=$?

  # 로그에서 결과 확인
  KILLS=$(grep -o 'K:[0-9]*' "$LOG_DIR/${GAME}_test.log" 2>/dev/null | tail -1 | cut -d: -f2)
  ERRORS=$(grep -c 'ERROR\|CRASH\|FAIL' "$LOG_DIR/${GAME}_test.log" 2>/dev/null)
  STUCK=$(grep -c 'STUCK' "$LOG_DIR/${GAME}_test.log" 2>/dev/null)

  echo "[BOT-TEST] Result: exit=$TEST_EXIT kills=${KILLS:-0} errors=${ERRORS:-0} stuck=${STUCK:-0}"

  if [ "$TEST_EXIT" -ne 0 ] || [ "${ERRORS:-0}" -gt 5 ]; then
    echo "[BOT-TEST] FAIL — game update may have broken something"
    exit 1
  fi

  echo "[BOT-TEST] PASS — game works. Now upgrading bot..."

  # 봇 1버전 업그레이드
  NEXT_VER=$((LATEST_VER + 1))

  timeout 600 claude -p "Read $METHODOLOGY.

Game: $GAME
Source: $ARCADE_DIR/games/$GAME/
URL: https://patchme.lol/games/$GAME/

The current bot is at: $LATEST_BOT (v${LATEST_VER})
Test log from running it: $LOG_DIR/${GAME}_test.log

Read the current bot and test log. The game was just updated.
Write an improved bot v${NEXT_VER} to $BOT_DIR/bot_${GAME}_v${NEXT_VER}.js

Focus on:
- Fix any issues from the test log (STUCK, errors)
- Adapt to any game changes from the update
- Play better (smarter combat, better navigation, etc)

Just write ONE improved version, not multiple." \
    --allowedTools "Read,Write,Edit,Bash,Glob,Grep" \
    2>&1 >> "$LOG_DIR/${GAME}_agent.log"

  UPGRADED=$(ls "$BOT_DIR/bot_${GAME}_v${NEXT_VER}.js" 2>/dev/null)
  if [ -n "$UPGRADED" ]; then
    echo "[BOT-TEST] Bot upgraded to v${NEXT_VER}"
  else
    echo "[BOT-TEST] Bot upgrade skipped (no changes needed)"
  fi

  exit 0
fi
