#!/bin/sh
# Phase-0 AT-SPI spike driver (docs/LINUX_VM_AX_AGENT.md §8).
#
# Brings up a headless AT-SPI environment, launches the GTK probe app, and runs ax_dump_spike.py to
# prove: (1) the accessibility tree reads into the macOS-identical `node` JSON, (2) act-by-identity
# (do_action / set_text_contents / grab_focus) works, and (3) SCREEN coordinates are real (the reason
# the automation base is X11, not Wayland).
#
# Runs in the Nucleic Linux build container / CI. On a real provisioned guest the X + AT-SPI session is
# already up, so you can skip the Xvfb/dbus bootstrap and just run ax_dump_spike.py against a live app.
#
# Deps (apt): xvfb at-spi2-core libatk-adaptor python3-gi python3-pyatspi gir1.2-gtk-3.0 dbus-x11.
set -e
DIR=$(CDPATH= cd -- "$(dirname -- "$0")" && pwd)

# Re-exec under a private session D-Bus if we don't have one (AT-SPI needs a session bus).
if [ -z "$DBUS_SESSION_BUS_ADDRESS" ]; then
    exec dbus-run-session -- "$0" "$@"
fi

# Headless X if none was provided.
STARTED_XVFB=
if [ -z "$DISPLAY" ]; then
    Xvfb :99 -screen 0 1920x1200x24 >/tmp/spike-xvfb.log 2>&1 &
    XVFB_PID=$!
    STARTED_XVFB=1
    DISPLAY=:99
    export DISPLAY
    # Wait for the X socket.
    i=0
    while [ ! -e /tmp/.X11-unix/X99 ] && [ $i -lt 50 ]; do i=$((i + 1)); sleep 0.1; done
fi

# Force the GTK->AT-SPI bridge on (belt-and-suspenders with libatk-adaptor's environment.d default).
GTK_MODULES="atk-bridge"; export GTK_MODULES
NO_AT_BRIDGE=0; export NO_AT_BRIDGE

# The AT-SPI a11y bus (usually D-Bus-activated; launch explicitly so registryd is reachable).
BUS=$(command -v at-spi-bus-launcher 2>/dev/null || echo /usr/libexec/at-spi-bus-launcher)
"$BUS" --launch-immediately >/tmp/spike-atspi.log 2>&1 &
ATSPI_PID=$!
sleep 1

cleanup() {
    [ -n "$APP_PID" ] && kill "$APP_PID" 2>/dev/null || true
    [ -n "$ATSPI_PID" ] && kill "$ATSPI_PID" 2>/dev/null || true
    [ -n "$STARTED_XVFB" ] && kill "$XVFB_PID" 2>/dev/null || true
}
trap cleanup EXIT INT TERM

# Launch the probe app on the a11y bus.
python3 "$DIR/gtk_probe_app.py" &
APP_PID=$!

# Wait for it to register on the AT-SPI bus (up to ~10s).
i=0
while [ $i -lt 50 ]; do
    if python3 "$DIR/ax_dump_spike.py" --app "Nucleic AX Probe" >/dev/null 2>&1; then break; fi
    i=$((i + 1)); sleep 0.2
done

echo "=== ax_dump (tree as macOS-identical node JSON) ==="
python3 "$DIR/ax_dump_spike.py" --app "Nucleic AX Probe" --act
RC=$?
echo "=== spike exit: $RC ==="
exit $RC
