#!/usr/bin/env bash
# ONE blocking session: boot -> Stage 02 in flight -> fly AT a capital ship and
# dump an F10 draw capture at each distance band (approach_capture.py).
#
# Supersedes ship_capture_session.sh for correlation work: that one pressed F10
# wherever the craft happened to be, and the 2026-07-31 run proved that captures
# nothing — inverting the match showed no capital-ship hull was drawn in any of
# those frames, only the player's own craft and particles. Range is the variable
# that matters, so range is what this controls.
#
# Usage: ship_capture_close.sh [seconds] [out_dir] [target_regex]
set -u
export HOME=/sylph-home/re SDL_AUDIODRIVER=dummy DISPLAY=:98
export PYTHONPATH=/sylph-home/.local/lib/python3.12/site-packages
SD="$(cd "$(dirname "$0")" && pwd)"
SECS="${1:-240}"
OUT="${2:-/sylph-home/re/shipcap-close}"
TARGET="${3:-}"
BINDIR="/home/fabi/RE - Project Sylpheed/xenia-canary-native/build/bin/Linux/Release"
CFG=/tmp/nav-close.json
mkdir -p "$OUT"
rm -f "$BINDIR"/xenia_ship_capture_*.log "$OUT"/approach-bands.jsonl

"$SD/launch_mission.sh" fly || { echo "BOOT FAILED"; exit 1; }
python3 "$SD/entities2.py" self 0x130 "$CFG" || { echo "BIND FAILED"; exit 1; }
echo "--- config: $(cat "$CFG")"

# F10 goes to the emulator window through XTEST; the window must be focused.
win="$(xdotool search --class -- xenia | tail -1)"
[ -z "$win" ] && win="$(xdotool search --name -- Xenia | tail -1)"
echo "WINDOW=$win"
[ -n "$win" ] && { xdotool windowactivate "$win" 2>/dev/null; xdotool windowfocus "$win" 2>/dev/null; }

export SYLPH_CAPTURE_WIN="$win" SYLPH_CAPTURE_OUT="$OUT"
if [ -n "$TARGET" ]; then
  python3 "$SD/approach_capture.py" "$CFG" "$SECS" --target "$TARGET" 2>&1 | tail -80
else
  python3 "$SD/approach_capture.py" "$CFG" "$SECS" 2>&1 | tail -80
fi

sleep 2
cp -v "$BINDIR"/xenia_ship_capture_*.log "$OUT"/ 2>/dev/null
echo "--- bands ---"; cat "$OUT/approach-bands.jsonl" 2>/dev/null
grep -c '^DRAW' "$OUT"/xenia_ship_capture_*.log 2>/dev/null
echo "CLOSE CAPTURE SESSION DONE"
