#!/usr/bin/env bash
# bin/up — run the Dispatch backend + web frontend together, both live-reloading.
# Ctrl-C stops BOTH cleanly (including the backend's spawned observability collector).
#
#   backend  (this repo)        bun --watch  → HTTP :24203 + surface WS :24205  (FULL restart on change)
#   frontend (../dispatch-web)   vite         → http://localhost:24204           (HMR, in-place)
#
# Assumes dispatch-web is a sibling of this repo. Run:  bin/up   (or:  bun run dev:all)

set -uo pipefail

HERE="$(cd "$(dirname "${BASH_SOURCE[0]}")" && pwd)"   # .../arch-rewrite/bin
BACKEND="$(cd "$HERE/.." && pwd)"                       # backend repo root
FRONTEND="$(cd "$HERE/../.." && pwd)/dispatch-web"      # sibling repo

if [ ! -d "$FRONTEND" ]; then
	echo "up: frontend repo not found at $FRONTEND" >&2
	echo "up: check out 'dispatch-web' beside this repo and retry." >&2
	exit 1
fi

cleanup() {
	echo
	echo "[up] stopping backend + frontend..."
	# Each child runs in its OWN process group (setsid) → signal the whole subtree.
	[ -n "${BACK_PG:-}" ]  && kill -TERM "-$BACK_PG"  2>/dev/null
	[ -n "${FRONT_PG:-}" ] && kill -TERM "-$FRONT_PG" 2>/dev/null
	sleep 1
	# Safety net for the backend's collector child + any straggler (bracket trick:
	# the literal pattern '[h]ost-bin' can't match the pkill command line itself).
	pkill -9 -f '[h]ost-bin/src/main'                2>/dev/null
	pkill -9 -f '[o]bservability-collector/src/main' 2>/dev/null
	[ -n "${BACK_PG:-}" ]  && kill -KILL "-$BACK_PG"  2>/dev/null
	[ -n "${FRONT_PG:-}" ] && kill -KILL "-$FRONT_PG" 2>/dev/null
	echo "[up] stopped."
	return 0
}
trap cleanup EXIT
trap 'exit 130' INT TERM

echo "[up] backend  → http://localhost:24203   (surface WS :24205)   [bun --watch — restarts on change]"
echo "[up] frontend → http://localhost:24204                          [vite HMR]"
echo "[up] Ctrl-C to stop both."
echo

setsid bash -c "cd '$BACKEND' && exec bun --watch packages/host-bin/src/main.ts" \
	> >(sed -u 's/^/[backend]  /') 2>&1 &
BACK_PG=$!

setsid bash -c "cd '$FRONTEND' && exec bun run dev" \
	> >(sed -u 's/^/[frontend] /') 2>&1 &
FRONT_PG=$!

wait
