#!/usr/bin/env bash
# =============================================================================
# @analytics — Deploy to vps-0 (1984 hosting)
# =============================================================================
# Usage: ./scripts/deploy.sh
#   or via: ./run deploy (once wired into run script)
#
# Requires: quinn-vps SSH alias configured in ~/.ssh/config
# =============================================================================
set -euo pipefail

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

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

echo "==> [2/5] Syncing source to $REMOTE:$REMOTE_DIR ..."
rsync -avz --delete \
  --exclude=node_modules \
  --exclude=dist \
  --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/"

rsync -avz \
  "$ROOT_DIR/package.json" \
  "$ROOT_DIR/bun.lock" \
  "$ROOT_DIR/turbo.json" \
  "$ROOT_DIR/tsconfig.base.json" \
  "$REMOTE:$REMOTE_DIR/"

echo "==> [3/5] Installing dependencies on remote..."
ssh "$REMOTE" "cd $REMOTE_DIR && bun install --production"

echo "==> [4/5] 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 "==> [5/5] Health check..."
sleep 5
ssh "$REMOTE" "curl -sf http://localhost:4001/health/live && echo 'collector OK' || echo 'collector NOT READY'"
ssh "$REMOTE" "curl -sf http://localhost:4003/health/live && echo 'api OK' || echo 'api NOT READY'"

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