#!/usr/bin/env bash
# Specter: launches the packaged game, waits for Specter to listen, runs the Playwright tests, then closes the game.
#
#   scripts/ci/run-specter-tests.sh [build dir]     (default: ./ci-build, where BuildCookRun archives the game)
#
# The game must render (screenshots, filmstrips), so run this in a logged-in macOS session, not over plain SSH.
set -uo pipefail

ROOT="$(cd "$(dirname "$0")/../.." && pwd)"
BUILD_DIR="${1:-$ROOT/ci-build}"
LOG_DIR="$ROOT/ci-logs"
SPECTER_PORT=8080
BOOT_TIMEOUT_SECONDS="${BOOT_TIMEOUT_SECONDS:-180}"
mkdir -p "$LOG_DIR"

# 1. The packaged game
APP="$(find "$BUILD_DIR" -maxdepth 3 -name "*.app" -type d | head -1)"
if [[ -z "$APP" ]]; then
  echo "::error::No .app found under $BUILD_DIR. Did the BuildCookRun step archive the game?"
  exit 1
fi
GAME="$(find "$APP/Contents/MacOS" -maxdepth 1 -type f -perm +111 | head -1)"
echo "Game: $GAME"

# 2. Port 8080 must be free, or the tests would talk to something else (a PIE session in an open editor)
if lsof -nP -iTCP:$SPECTER_PORT -sTCP:LISTEN >/dev/null 2>&1; then
  echo "::error::Port $SPECTER_PORT is already in use on the runner (an editor playing in PIE?). Stop it and re-run."
  lsof -nP -iTCP:$SPECTER_PORT -sTCP:LISTEN
  exit 1
fi

# 3. Launch it, and close it whatever happens next
"$GAME" -specterport=$SPECTER_PORT -windowed -resx=1280 -resy=720 -unattended -nosplash \
  -abslog="$LOG_DIR/game.log" >"$LOG_DIR/game-stdout.log" 2>&1 &
GAME_PID=$!
cleanup() {
  if kill -0 "$GAME_PID" 2>/dev/null; then
    kill "$GAME_PID" 2>/dev/null
    sleep 3
    kill -9 "$GAME_PID" 2>/dev/null || true
  fi
}
trap cleanup EXIT

# 4. Wait until Specter listens
echo "Waiting for Specter on port $SPECTER_PORT (up to ${BOOT_TIMEOUT_SECONDS}s)..."
for ((i = 0; i < BOOT_TIMEOUT_SECONDS; i++)); do
  if ! kill -0 "$GAME_PID" 2>/dev/null; then
    echo "::error::The game exited while starting. Last lines of its log:"
    tail -n 60 "$LOG_DIR/game.log" 2>/dev/null || tail -n 60 "$LOG_DIR/game-stdout.log"
    exit 1
  fi
  if lsof -nP -iTCP:$SPECTER_PORT -sTCP:LISTEN -a -p "$GAME_PID" >/dev/null 2>&1; then
    echo "Specter is listening after ${i}s."
    break
  fi
  sleep 1
done
if ! lsof -nP -iTCP:$SPECTER_PORT -sTCP:LISTEN -a -p "$GAME_PID" >/dev/null 2>&1; then
  echo "::error::Specter didn't start listening within ${BOOT_TIMEOUT_SECONDS}s. Last lines of the game log:"
  tail -n 60 "$LOG_DIR/game.log" 2>/dev/null
  exit 1
fi

# 5. Run the tests. The editor probe points at a port nothing listens on, so a CI run can never start PIE in an
#    editor someone has open on this machine.
cd "$ROOT/specter"
CI=1 SPECTER_EDITOR_PORT=1 npx playwright test
STATUS=$?

# The run summary and PR comment come from scripts/ci/report-failures.mjs, a later workflow step
exit $STATUS
