#!/bin/bash
# create-and-test-all.sh — Coming Soon 게임 생성 + 전체 테스트
# tmux에서 실행: tmux new -s patchme "bash ~/sites/arcade/pipeline/create-and-test-all.sh"

ARCADE_DIR="/home/ubuntu/sites/arcade"
BOT_DIR="/tmp/bots"
LOG_DIR="/tmp/bot_logs"
METHODOLOGY="$ARCADE_DIR/pipeline/game-testing-methodology.md"
AGENT_INSTRUCTIONS="$ARCADE_DIR/pipeline/agent-instructions.md"

mkdir -p "$BOT_DIR" "$LOG_DIR"

COMING_SOON_GAMES="crimson-eclipse crimson-spire eternal-throne nexus-of-fate void-settlers"
EXISTING_GAMES="abyssal-descent elemental-forge oh-no-yes"
ALL_GAMES="$EXISTING_GAMES $COMING_SOON_GAMES"

echo "============================================"
echo "=== PatchMe: Create & Test All Games ==="
echo "Time: $(date)"
echo "============================================"
echo ""

# ── PHASE 1: Coming Soon 게임 생성 ──
echo "=== PHASE 1: Creating Coming Soon games ==="

for GAME in $COMING_SOON_GAMES; do
  echo ""
  echo "--- Creating: $GAME ---"

  cd "$ARCADE_DIR"
  timeout 300 claude -p "Create a complete, playable browser game for '$GAME' at ~/sites/arcade/games/$GAME/.

The current index.html is just a 'Coming Soon' placeholder. Replace it with a real game.

GAME NAME IDEAS (interpret creatively):
- crimson-eclipse: dark action/combat game with blood moon theme
- crimson-spire: tower climbing / roguelike vertical progression
- eternal-throne: strategy/kingdom management or chess-like
- nexus-of-fate: card game or fate/destiny themed puzzle
- void-settlers: space colony builder or survival

REQUIREMENTS:
1. Fully playable in browser, single HTML file + JS files
2. Unique visual style (NOT same as abyssal-descent)
3. Include <script src='/shared/patchme-sdk.js'></script>
4. Fun and immediately playable
5. Clear game loop (start → play → score/end → replay)
6. Must work on 500x810 canvas or responsive

Keep it simple but fun. This should take 1-2 files max.
Write ALL files needed." \
    --allowedTools "Read,Write,Edit,Bash,Glob,Grep" \
    2>&1 | tee "$LOG_DIR/${GAME}_create.log"

  echo "Created: $GAME at $(date)"
done

echo ""
echo "=== PHASE 1 COMPLETE: All games created ==="
echo ""

# ── PHASE 2: Chrome에 모든 게임 탭 열기 ──
echo "=== PHASE 2: 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 + ' (' + targetId + ')');
    } catch(e) { console.log('Tab exists or error: ' + g); }
  }
  await client.close();
})().catch(console.error);
"

echo ""

# ── PHASE 3: 전체 게임 병렬 테스트 ──
echo "=== PHASE 3: Testing all games in parallel ==="

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

  # 기존 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 at $LATEST_BOT (v${LATEST_VER}). Improve from there."
  else
    CONTEXT="No previous bot. Create v1 from scratch."
  fi

  # 각 게임을 병렬로 테스트
  (
    # bot-runner 시작
    bash "$ARCADE_DIR/pipeline/bot-runner.sh" "$GAME" &
    RUNNER_PID=$!

    cd "$ARCADE_DIR"
    timeout 600 claude -p "Read $AGENT_INSTRUCTIONS 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 "Done: $GAME at $(date)"
  ) &

  echo "Launched test: $GAME (bg)"
done

echo ""
echo "All tests launched. Waiting for completion..."
wait

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