#!/usr/bin/env bash
# Deploy MentorCore runtime (port 8000) and web (port 3002) via launchd + Tailscale.
#
# Run from the repo root:
#   ANTHROPIC_API_KEY=sk-ant-... ./scripts/deploy.sh
#
# Requires: tailscale, uv, node/npm

set -euo pipefail

REPO="$(cd "$(dirname "$0")/.." && pwd)"
LOG_DIR="$HOME/projects/logs"
LAUNCH_AGENTS="$HOME/Library/LaunchAgents"

RUNTIME_PORT=8000
WEB_PORT=3002
RUNTIME_LABEL="com.james.mentorcore-runtime"
WEB_LABEL="com.james.mentorcore-web"

# ── Verify env ────────────────────────────────────────────────────────────────
if [[ -z "${ANTHROPIC_API_KEY:-}" ]]; then
    echo "ERROR: ANTHROPIC_API_KEY must be set in env"
    exit 1
fi

# ── Check ports ───────────────────────────────────────────────────────────────
for PORT in $RUNTIME_PORT $WEB_PORT; do
    if lsof -nP -iTCP:"$PORT" -sTCP:LISTEN &>/dev/null; then
        echo "WARNING: port $PORT already in use — stopping existing process first"
        launchctl kickstart -k "gui/$UID/$RUNTIME_LABEL" 2>/dev/null || true
        launchctl kickstart -k "gui/$UID/$WEB_LABEL" 2>/dev/null || true
        sleep 1
    fi
done

# ── Build web ─────────────────────────────────────────────────────────────────
echo "[deploy] Building Next.js…"
npm run build --prefix "$REPO/web"

# ── Create log dir ────────────────────────────────────────────────────────────
mkdir -p "$LOG_DIR"

# ── Write runtime plist (with actual key) ────────────────────────────────────
echo "[deploy] Writing runtime plist…"
sed "s/REPLACE_WITH_KEY/$ANTHROPIC_API_KEY/" \
    "$REPO/scripts/mentorcore-runtime.plist" \
    > "$LAUNCH_AGENTS/$RUNTIME_LABEL.plist"

# ── Write web plist ───────────────────────────────────────────────────────────
echo "[deploy] Writing web plist…"
cp "$REPO/scripts/mentorcore-web.plist" "$LAUNCH_AGENTS/$WEB_LABEL.plist"

# ── Load / restart services ───────────────────────────────────────────────────
echo "[deploy] Loading runtime (port $RUNTIME_PORT)…"
launchctl unload "$LAUNCH_AGENTS/$RUNTIME_LABEL.plist" 2>/dev/null || true
launchctl load "$LAUNCH_AGENTS/$RUNTIME_LABEL.plist"

echo "[deploy] Loading web (port $WEB_PORT)…"
launchctl unload "$LAUNCH_AGENTS/$WEB_LABEL.plist" 2>/dev/null || true
launchctl load "$LAUNCH_AGENTS/$WEB_LABEL.plist"

# ── Tailscale serve ───────────────────────────────────────────────────────────
echo "[deploy] Setting up Tailscale HTTPS…"
tailscale serve --bg --https=$RUNTIME_PORT http://localhost:$RUNTIME_PORT || true
tailscale serve --bg --https=$WEB_PORT http://localhost:$WEB_PORT || true

TAILSCALE_HOST=$(tailscale status --json 2>/dev/null | python3 -c "
import sys, json
d = json.load(sys.stdin)
me = d.get('Self', {})
dns = me.get('DNSName', '').rstrip('.')
print(dns)
" 2>/dev/null || echo "jamess-mac-mini.tail02a1a0.ts.net")

# ── Write redirectTo.md ───────────────────────────────────────────────────────
echo "https://$TAILSCALE_HOST:$WEB_PORT" > "$REPO/redirectTo.md"

# ── Verify ────────────────────────────────────────────────────────────────────
echo "[deploy] Waiting for services…"
sleep 3

if curl -sf "http://localhost:$RUNTIME_PORT/health" | grep -q '"ok"'; then
    echo "[deploy] ✓ runtime healthy at http://localhost:$RUNTIME_PORT"
else
    echo "[deploy] ✗ runtime not responding — check $LOG_DIR/mentorcore-runtime.log"
fi

echo ""
echo "[deploy] Done."
echo "  Local:   http://localhost:$WEB_PORT"
echo "  Remote:  https://$TAILSCALE_HOST:$WEB_PORT"
echo "  API:     http://localhost:$RUNTIME_PORT"
echo ""
echo "  Run ./verify-tailscale.sh to confirm Tailscale connectivity."
