#!/usr/bin/env bash
# bridge/bridge-service.sh — install thinkpool-pair as an AUTO-UPDATING launchd
# service for a room, with a fast update poll so a new `npm publish` lands in the
# room within ~1 min of an idle moment (no manual restart, no re-install).
#
# The stock `thinkpool-pair install-service <ROOM>` already runs under launchd
# KeepAlive with `npx -y thinkpool-pair@latest` (so each restart fetches the newest
# publish) and sets THINKPOOL_PAIR_AUTOUPDATE=1 — but it leaves the poll interval at
# the 30-min default. This wrapper installs it, then injects the faster poll/idle
# knobs into the generated LaunchAgent plist and reloads it.
#
#   Usage:  bash bridge/bridge-service.sh <ROOM> [-- <extra bridge args>]
#   e.g.    bash bridge/bridge-service.sh P6O6I            # default: --headless --auto=claude
#           bash bridge/bridge-service.sh P6O6I -- --headless --auto=claude
#   Env:    TP_UPDATE_INTERVAL (default 60)   registry poll seconds
#           TP_UPDATE_IDLE     (default 20)   idle seconds before an update restart
#           TP_FORCE=1                        skip the "bare bridge already running" guard
#   Remove: npx thinkpool-pair@latest uninstall-service <ROOM>
set -euo pipefail

ROOM_RAW="${1:-}"
[ -n "$ROOM_RAW" ] && [ "${ROOM_RAW#-}" = "$ROOM_RAW" ] || { echo "usage: bash bridge/bridge-service.sh <ROOM> [-- <extra bridge args>]"; exit 1; }
ROOM="$(printf '%s' "$ROOM_RAW" | tr '[:lower:]' '[:upper:]')"
shift || true
# Everything after a literal `--` is forwarded to the bridge; default to the
# headless auto-claude invocation the rooms run interactively today.
TAIL=()
if [ "${1:-}" = "--" ]; then shift; TAIL=("$@"); else TAIL=(--headless --auto=claude); fi

INTERVAL="${TP_UPDATE_INTERVAL:-60}"
IDLE="${TP_UPDATE_IDLE:-20}"
PLIST="$HOME/Library/LaunchAgents/io.thinkpool.pair.$(printf '%s' "$ROOM" | tr '[:upper:]' '[:lower:]').plist"

[ "$(uname)" = "Darwin" ] || { echo "✗ this wrapper is macOS/launchd only (Linux: use systemd via 'npx thinkpool-pair@latest install-service')"; exit 1; }

# Guard: a bare (foreground) bridge for this room would fight the service —
# two relays on one realtime channel duplicate everything. Stop it first.
# NOTE: macOS pgrep is POSIX-ERE — no \b. Match "bridge.mjs <ROOM>" with the room
# delimited by whitespace or end-of-arg. (A \b guard here once failed silently and
# serviced the live room, restarting its bridge — don't reintroduce it.)
BRIDGE_RE="bridge\.mjs[[:space:]]+${ROOM}([[:space:]]|\$)"
if [ -z "${TP_FORCE:-}" ] && pgrep -f "$BRIDGE_RE" >/dev/null 2>&1; then
  echo "✗ a bare bridge is already running for ${ROOM} (pid $(pgrep -f "$BRIDGE_RE" | tr '\n' ' '))."
  echo "  Stop it first (close its terminal / kill it), then re-run — or TP_FORCE=1 to override."
  echo "  NOTE: if ${ROOM} is hosting the Claude session you're talking to RIGHT NOW, servicing it restarts the bridge and drops that chat."
  exit 2
fi

echo "◆ installing auto-updating service for ${ROOM} (npx thinkpool-pair@latest ${TAIL[*]})…"
npx -y thinkpool-pair@latest install-service "$ROOM" -- "${TAIL[@]}"

[ -f "$PLIST" ] || { echo "✗ expected plist not found at $PLIST — install may have failed"; exit 3; }

# Inject the fast-poll knobs into EnvironmentVariables (Add, or Set if present).
pb() { /usr/libexec/PlistBuddy -c "$1" "$PLIST" >/dev/null 2>&1; }
pb "Add :EnvironmentVariables:THINKPOOL_PAIR_UPDATE_INTERVAL string ${INTERVAL}" || pb "Set :EnvironmentVariables:THINKPOOL_PAIR_UPDATE_INTERVAL ${INTERVAL}"
pb "Add :EnvironmentVariables:THINKPOOL_PAIR_UPDATE_IDLE string ${IDLE}"         || pb "Set :EnvironmentVariables:THINKPOOL_PAIR_UPDATE_IDLE ${IDLE}"

# Reload so the new env takes effect immediately.
launchctl unload "$PLIST" 2>/dev/null || true
launchctl load  "$PLIST"

echo "✓ ${ROOM} is now a launchd service:"
echo "    • tracks thinkpool-pair@latest, polls npm every ${INTERVAL}s, self-restarts at the next idle ≥${IDLE}s"
echo "    • plist: $PLIST"
echo "    • logs:  ~/.thinkpool-pair/${ROOM}.log"
echo "    • remove: npx thinkpool-pair@latest uninstall-service ${ROOM}"
