#!/usr/bin/env bash
set -euo pipefail

LAB_ROOT=${W3CS_LAB_ROOT:-/home/ubuntu/w3cs-lab}
REPLAY_ROOT=${W3CS_REPLAY_ROOT:-$LAB_ROOT/replays}
REPLAY_ID=${W3CS_REPLAY_ID:?W3CS_REPLAY_ID is required}
REQUESTED_PROFILE=${W3CS_GAME_PROFILE:-auto}
SEAT_STATE=${W3CS_SEAT_STATE:-/tmp/w3cs-seat-state.json}

if [[ ! "$REPLAY_ID" =~ ^[A-Za-z0-9._-]{1,96}$ ]]; then
  echo "invalid replay id" >&2
  exit 2
fi

REPLAY_SOURCE="$REPLAY_ROOT/$REPLAY_ID.w3g"
REPLAY_METADATA="$REPLAY_ROOT/$REPLAY_ID.json"
if [[ ! -f "$REPLAY_SOURCE" ]]; then
  if [[ "$REPLAY_ID" =~ ^[0-9a-f]{40}$ &&
        -f "${W3CS_CATALOG_INDEX:-}" &&
        -n "${W3CS_CATALOG_BUCKET:-}" ]]; then
    python3 "$LAB_ROOT/materialize-catalog-replay.py" \
      --index "$W3CS_CATALOG_INDEX" --source-sha1 "$REPLAY_ID" \
      --output-root "$REPLAY_ROOT" --bucket "$W3CS_CATALOG_BUCKET" \
      --region "${W3CS_CATALOG_REGION:-us-east-1}"
  else
    echo "replay not found: $REPLAY_ID" >&2
    exit 3
  fi
fi
[[ -f "$REPLAY_METADATA" ]] || {
  echo "warm replay switch needs metadata: $REPLAY_ID" >&2
  exit 4
}

for _ in $(seq 1 160); do
  [[ -s "$SEAT_STATE" ]] && break
  sleep .1
done
[[ -s "$SEAT_STATE" ]] || {
  echo "warm seat state is unavailable" >&2
  exit 5
}

readarray -t seat < <(python3 - "$SEAT_STATE" "$REPLAY_METADATA" <<'PY'
import json
import sys

with open(sys.argv[1], encoding="utf-8") as source:
    state = json.load(source)
with open(sys.argv[2], encoding="utf-8") as source:
    metadata = json.load(source)
for key in ("engineProfile", "winePrefix", "gameDirectory",
            "replayDirectory", "display"):
    value = state.get(key)
    if not isinstance(value, str) or not value:
        raise SystemExit(f"warm seat state has no {key}")
print(state["engineProfile"])
print(metadata.get("engineProfile", ""))
print(state["winePrefix"])
print(state["gameDirectory"])
print(state["replayDirectory"])
print(state["display"])
PY
)
ACTIVE_PROFILE=${seat[0]}
REPLAY_PROFILE=${seat[1]}
PREFIX=${seat[2]}
GAME_DIR=${seat[3]}
REPLAY_DIRECTORY=${seat[4]}
DISPLAY_NUMBER=${seat[5]}
if [[ -n "$REPLAY_PROFILE" && "$REPLAY_PROFILE" != "$ACTIVE_PROFILE" ]]; then
  echo "replay needs $REPLAY_PROFILE but warm seat is $ACTIVE_PROFILE" >&2
  exit 6
fi
if [[ "$REQUESTED_PROFILE" != auto &&
      "$REQUESTED_PROFILE" != "$ACTIVE_PROFILE" ]]; then
  echo "requested $REQUESTED_PROFILE but warm seat is $ACTIVE_PROFILE" >&2
  exit 6
fi

python3 "$LAB_ROOT/stage-replay-session.py" \
  --metadata "$REPLAY_METADATA" --replay "$REPLAY_SOURCE" \
  --prefix "$PREFIX" --game-directory "$GAME_DIR" \
  --replay-directory "$REPLAY_DIRECTORY"

export DISPLAY="$DISPLAY_NUMBER"
window=
for _ in $(seq 1 160); do
  while read -r candidate; do
    [[ -n "$candidate" ]] || continue
    geometry=$(xdotool getwindowgeometry --shell "$candidate" 2>/dev/null || true)
    [[ -n "$geometry" ]] || continue
    eval "$geometry"
    if [[ ${WIDTH:-0} -ge 600 && ${HEIGHT:-0} -ge 400 ]]; then
      window=$candidate
      break
    fi
  done < <(xdotool search --onlyvisible --name '.' 2>/dev/null || true)
  [[ -n "$window" ]] && break
  sleep .1
done
[[ -n "$window" ]] || {
  echo "warm Warcraft window is unavailable" >&2
  exit 7
}

geometry=$(xdotool getwindowgeometry --shell "$window")
eval "$geometry"
x=$((WIDTH * 923 / 1000))
y=$((HEIGHT * 960 / 1000))
xdotool windowfocus --sync "$window"
xdotool mousemove --window "$window" "$x" "$y"
xdotool click --window "$window" 1
printf 'warm replay staged and restarted: %s (%s)\n' \
  "$REPLAY_ID" "$ACTIVE_PROFILE"
