#!/usr/bin/env bash
# One background task: boot -> Stage 02 -> fly the pilot while a second reader
# records EVERY entity's hull, so the escort question ("who is losing, and how
# fast") is answered from memory instead of from the HUD.
#
# Same one-task rule as fly_session.sh: the display and the emulator both die on
# their own in this container, so nothing may depend on surviving between tool
# calls.
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:-300}"
TAG="${2:-escort}"
SHOTS=/sylph-home/re/shots
CFG=/tmp/nav-live.json

"$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")"

echo "=== initial entity table ==="
python3 "$SD/mission_state.py" scan "$CFG"

# The HUD's REMAINING OB counter has no known address yet, so the correlation
# material is a screenshot every 20 s stamped against the same clock as the
# memory samples.
( for i in $(seq 1 20); do
    printf '%s SHOT %02d\n' "$(date +%s.%N)" "$i" >> "/tmp/$TAG-shots.log"
    screenshot "$SHOTS/$TAG-$i.png" >/dev/null 2>&1
    sleep 20
  done ) &
SHOTTER=$!

date +%s.%N > "/tmp/$TAG-t0"
python3 "$SD/mission_state.py" watch "$CFG" "$SECS" 1 "/tmp/$TAG-mission.jsonl" \
    > "/tmp/$TAG-mission.log" 2>&1 &
WATCHER=$!

python3 "$SD/pilot.py" "$CFG" "$SECS" > "/tmp/$TAG-pilot.log" 2>&1
wait $WATCHER 2>/dev/null
kill $SHOTTER 2>/dev/null
screenshot "$SHOTS/$TAG-end.png" >/dev/null 2>&1
echo "SESSION DONE"
