#!/usr/bin/env bash
set -euo pipefail

# ── Configuration ──────────────────────────────────────────────
DEPLOY_HOST="${DEPLOY_HOST:-1000co.fr}"
DEPLOY_USER="${DEPLOY_USER:-millian}"
DEPLOY_PATH="${DEPLOY_PATH:-/opt/supabase/volumes/functions}"
WORKER_PATH="${WORKER_PATH:-/opt/supabase/youtube-worker}"
# ───────────────────────────────────────────────────────────────

SCRIPT_DIR="$(cd "$(dirname "$0")" && pwd)"
FUNCTIONS_DIR="$SCRIPT_DIR/../supabase/functions"
WORKER_DIR="$SCRIPT_DIR/../youtube-worker"

# ── Deploy edge functions ──────────────────────────────────────
echo "==> Deploying edge functions"
rsync -avz --delete \
  --exclude='node_modules' \
  --exclude='.DS_Store' \
  "$FUNCTIONS_DIR/" \
  "$DEPLOY_USER@$DEPLOY_HOST:$DEPLOY_PATH/"

echo "Restarting supabase-edge-functions..."
ssh "$DEPLOY_USER@$DEPLOY_HOST" "docker restart supabase-edge-functions"

# ── Deploy youtube-worker sidecar ──────────────────────────────
echo ""
echo "==> Deploying youtube-worker sidecar"
rsync -avz --delete \
  --exclude='node_modules' \
  --exclude='.DS_Store' \
  "$WORKER_DIR/" \
  "$DEPLOY_USER@$DEPLOY_HOST:$WORKER_PATH/"

echo "Building and restarting youtube-worker..."
ssh "$DEPLOY_USER@$DEPLOY_HOST" "\
  cd $WORKER_PATH && \
  docker build -t youtube-worker:latest . && \
  docker stop youtube-worker 2>/dev/null || true && \
  docker rm youtube-worker 2>/dev/null || true && \
  docker run -d \
    --name youtube-worker \
    --restart unless-stopped \
    --network supabase_supabase-network \
    -e SUPABASE_URL=\$(docker exec supabase-edge-functions printenv SUPABASE_URL) \
    -e SUPABASE_SERVICE_ROLE_KEY=\$(docker exec supabase-edge-functions printenv SUPABASE_SERVICE_ROLE_KEY) \
    -e SUPABASE_PUBLIC_URL=https://supabase.1000co.fr \
    -e GEMINI_API_KEY=\$(cat /opt/supabase/.env.gemini 2>/dev/null || echo '') \
    -e STORAGE_BUCKET=workout-audio \
    -e PORT=3001 \
    youtube-worker:latest"

echo ""
echo "Done. Verifying youtube-worker health..."
sleep 3
ssh "$DEPLOY_USER@$DEPLOY_HOST" "docker logs youtube-worker --tail 5"
