#!/usr/bin/env bash
# Ask the Jarvis ENGINE to screenshot the screen, wait, print the image path.
#
# Runs permission-free: it only writes a request file and polls for the result.
# The actual capture happens inside the engine process (a child of Jarvis.app,
# which holds Screen Recording), so it works where a direct `screencapture`
# from a tool call does not. Usage: snap.sh [out.png] [display#]
set -euo pipefail
OUT="${1:-/tmp/jarvis_screen.png}"
DISPLAY_ARG="${2:-}"
CTRL="$(cd "$(dirname "$0")" && pwd)/control"
mkdir -p "$CTRL"
rm -f "$CTRL/screenshot.done"

if [ -n "$DISPLAY_ARG" ]; then
  printf '{"path":"%s","display":%s}' "$OUT" "$DISPLAY_ARG" > "$CTRL/screenshot.json"
else
  printf '{"path":"%s"}' "$OUT" > "$CTRL/screenshot.json"
fi

for _ in $(seq 1 50); do
  if [ -f "$CTRL/screenshot.done" ]; then
    if grep -q '"ok": *true' "$CTRL/screenshot.done"; then
      echo "$OUT"
      exit 0
    fi
    echo "SCREENSHOT FAILED: $(cat "$CTRL/screenshot.done")" >&2
    exit 1
  fi
  sleep 0.2
done
echo "SCREENSHOT TIMEOUT — is the Jarvis engine running?" >&2
exit 1
