#!/bin/bash
# test-and-deploy.sh — Run game tester before deploying changes
# Usage: test-and-deploy.sh <game-dir> <game-url> [log-file]

set -e

GAME_DIR="$1"
GAME_URL="$2"
LOG_FILE="${3:-/tmp/game-test.log}"
TESTER="/home/ubuntu/sites/arcade/pipeline/game-tester.js"

if [ -z "$GAME_DIR" ] || [ -z "$GAME_URL" ]; then
  echo "Usage: test-and-deploy.sh <game-dir> <game-url> [log-file]"
  exit 1
fi

echo "[TEST] Testing game at $GAME_URL"

# Ensure Chrome is running with CDP
if ! curl -s http://localhost:9222/json > /dev/null 2>&1; then
  echo "[TEST] Chrome CDP not running, starting..."
  source /home/ubuntu/scripts/start-chrome-cdp.sh
  sleep 3
fi

# Run the tester (8 cycles = ~40 seconds of testing)
if node "$TESTER" "$GAME_URL" 8 "$LOG_FILE"; then
  echo "[TEST] ✓ PASSED — Game is ready for deploy"
  exit 0
else
  echo "[TEST] ✗ FAILED — Game did not pass testing"
  echo "[TEST] Check log: $LOG_FILE"
  echo "[TEST] Screenshots: /tmp/game-test-screenshots/"
  exit 1
fi
