#!/usr/bin/env bash
# Console v2 — local-MacBook dev startup.
#
# Spins up the read-local / write-remote pair documented in
# `morning-read/host-arch-spec.md`:
#
#   • FastAPI on localhost:8431 with RECOIL_WRITE_UPSTREAM set to Studio.
#     All GETs serve from the local Dropbox-synced tree (~1ms reads).
#     All mutations (POST/PUT/PATCH/DELETE) proxy to Studio.
#   • Vite on localhost:5173 (strictPort), proxies /api → localhost:8431.
#     Same `pnpm dev` config as Studio — vite.config.ts hasn't changed.
#   • ttyd stays on Studio. /api/config returns TTYD_HOST=Studio so the
#     chat iframe loads from `http://100.105.59.118:7681+`.
#
# Run from anywhere; the script normalizes its own cwd.
#
# Usage:
#   ./recoil/console-v2/scripts/dev-local.sh
#
# Tips:
#   - This script foregrounds Vite. ^C exits Vite; FastAPI is started in a
#     background subshell and gets killed on EXIT trap.
#   - Studio must be reachable over Tailscale (writes proxy there). If
#     Studio is unreachable, GETs still work; mutations 502.

set -euo pipefail

REPO=/Users/joeturnerlin/CLAUDE_PROJECTS
RECOIL=$REPO/recoil
CONSOLE=$RECOIL/console-v2
VENV=$RECOIL/.venv
STUDIO_HOST=100.105.59.118
LOG_DIR=$HOME/.recoil/local-logs
mkdir -p "$LOG_DIR"

# Sanity: must be on MacBook, not Studio. Bail loudly if the script is
# launched on Studio — running it there would point Studio's writes back
# at itself, which is harmless but pointless.
if [[ "$(scutil --get LocalHostName 2>/dev/null || hostname -s)" == *Studio* ]]; then
  echo "❌ dev-local.sh is for the MacBook. On Studio, the LaunchAgent handles startup."
  exit 1
fi

# Sanity: venv must exist on this machine. Recoil's own .venv is repo-local
# but shared across machines via Dropbox — except site-packages, which is
# per-machine. If the venv is stale, recreate.
if [[ ! -x "$VENV/bin/uvicorn" ]]; then
  echo "❌ $VENV/bin/uvicorn missing. Run:"
  echo "    cd $RECOIL && python3 -m venv .venv && .venv/bin/pip install -r api/requirements.txt"
  exit 1
fi

# Verify Studio is reachable. Cheap HEAD on /api/health.
if ! curl -fsS -o /dev/null --max-time 3 "http://$STUDIO_HOST:8431/api/health"; then
  echo "⚠  Studio API unreachable at $STUDIO_HOST:8431."
  echo "   Reads will still work locally. Mutations will 502."
  echo "   Continue? [y/N]"
  read -r yn
  [[ "$yn" =~ ^[Yy]$ ]] || exit 1
fi

# Kill anything already on our local dev ports.
for port in 5173 8431; do
  pid=$(lsof -ti:$port 2>/dev/null || true)
  if [[ -n "$pid" ]]; then
    echo "→ killing existing process on :$port (pid $pid)"
    kill -9 "$pid" 2>/dev/null || true
  fi
done

# Start the local FastAPI.
echo "→ starting local FastAPI on :8431 (write-proxy → $STUDIO_HOST:8431)"
cd "$REPO"
(
  export PYTHONPATH=$REPO
  export RECOIL_WRITE_UPSTREAM="http://$STUDIO_HOST:8431"
  export TTYD_HOST="$STUDIO_HOST"
  # --reload off intentionally — same rationale as Studio (Dropbox sync
  # would trigger spurious reloads). Restart the script for backend edits.
  exec "$VENV/bin/uvicorn" recoil.api.main:app \
    --host 127.0.0.1 \
    --port 8431 \
    --log-level info \
    > "$LOG_DIR/api.log" 2>&1
) &
API_PID=$!
trap 'echo; echo "→ stopping local FastAPI (pid $API_PID)"; kill -9 $API_PID 2>/dev/null || true' EXIT

# Wait for it to bind.
for i in 1 2 3 4 5 6 7 8 9 10; do
  if curl -fsS -o /dev/null --max-time 1 http://127.0.0.1:8431/api/health; then
    echo "✓ local FastAPI up at http://localhost:8431 (proxies writes to $STUDIO_HOST)"
    break
  fi
  sleep 0.5
  if [[ $i -eq 10 ]]; then
    echo "❌ local FastAPI failed to bind. Last log lines:"
    tail -20 "$LOG_DIR/api.log"
    exit 1
  fi
done

# Verify /api/config reports the expected ttyd host.
config_host=$(curl -fsS http://127.0.0.1:8431/api/config | python3 -c 'import sys,json;print(json.load(sys.stdin)["ttydHost"])')
if [[ "$config_host" != "$STUDIO_HOST" ]]; then
  echo "❌ /api/config returned ttydHost=$config_host, expected $STUDIO_HOST"
  exit 1
fi
echo "✓ /api/config reports ttydHost=$config_host"

# Foreground Vite so ^C exits cleanly.
cd "$CONSOLE"
echo "→ starting local Vite on :5173 (proxies /api → localhost:8431)"
echo "  Open: http://localhost:5173"
exec pnpm --filter @recoil/desktop dev
