#!/usr/bin/env bash
# =============================================================================
# @analytics — Deploy to vps-0 (1984 hosting)
# =============================================================================
# Usage: ./scripts/deploy.sh
#   or via: ./run deploy
#
# Requires: quinn-vps SSH alias configured in ~/.ssh/config
#
# Strategy:
#   - Services are built locally (turbo) — dist/ files are pre-compiled.
#   - dist/ is rsynced to VPS alongside Dockerfiles; no build step needed on VPS.
#   - Docker images are built on VPS from pre-compiled dist/ via docker compose --build.
#   - @lilith/* workspace deps are compiled into dist/ by SWC — stripped from
#     package.json in each Dockerfile so npm install only fetches registry packages.
# =============================================================================
set -euo pipefail

SCRIPT_DIR="$(cd "$(dirname "$0")" && pwd)"
ROOT_DIR="$(cd "$SCRIPT_DIR/.." && pwd)"
REMOTE="quinn-vps"
REMOTE_DIR="~/analytics"

echo "==> [1/4] Building services..."
cd "$ROOT_DIR" && bun run build:services

echo "==> [2/4] Syncing to $REMOTE:$REMOTE_DIR ..."
# Include dist/ — Docker images copy from pre-built dist, no VPS build needed
rsync -avz --delete \
  --exclude=node_modules \
  --exclude=.env \
  --exclude=.env.* \
  "$ROOT_DIR/services/" "$REMOTE:$REMOTE_DIR/services/"

rsync -avz \
  "$ROOT_DIR/infrastructure/docker-compose.prod.yaml" \
  "$ROOT_DIR/infrastructure/init.sql" \
  "$REMOTE:$REMOTE_DIR/infrastructure/"

echo "==> [3/4] Rebuilding and restarting Docker stack..."
ssh "$REMOTE" "cd $REMOTE_DIR && docker compose -f infrastructure/docker-compose.prod.yaml --env-file infrastructure/.env.prod up -d --build"

echo "==> [4/4] Health check..."
sleep 8
ssh "$REMOTE" "curl -sf http://localhost:4001/health && echo 'collector OK' || echo 'collector NOT READY'"
ssh "$REMOTE" "curl -sf http://localhost:4003/health && echo 'api OK' || echo 'api NOT READY'"
ssh "$REMOTE" "curl -sf http://localhost:4005/health && echo 'website-bff OK' || echo 'website-bff NOT READY'"

echo ""
echo "Deployed at $(date '+%Y-%m-%d %H:%M:%S %Z')"
echo "Collector: https://data.transquinnftw.com/analytics/track/"
echo "API:       https://data.transquinnftw.com/api/"
