#!/usr/bin/env bash
# Full production deploy: push (optional) + backend pull + frontend tar + health
#
# Prerequisites on YOUR machine:
#   - SSH: ~/.ssh/config Host nexus  OR  export NEXUS_SSH="root@47.254.123.106"
#   - Key:  export NEXUS_SSH_KEY=~/.ssh/id_rsa_nexus
#   - Gitea push access for origin main
#
# Usage:
#   cd "$NEXUS_ROOT"
#   git add ... && git commit ... && git push origin main   # if not pushed yet
#   bash deploy/pre_deploy_check.sh
#   bash deploy/deploy-production.sh

set -euo pipefail

ROOT="$(cd "$(dirname "${BASH_SOURCE[0]}")/.." && pwd)"
cd "${ROOT}"

NEXUS_SSH_HOST="${NEXUS_SSH:-nexus}"
SSH_OPTS=(-o BatchMode=yes -o ConnectTimeout=15)
if [ -n "${NEXUS_SSH_KEY:-}" ]; then
  SSH_OPTS+=(-i "${NEXUS_SSH_KEY}")
fi
ssh_cmd() { ssh "${SSH_OPTS[@]}" "${NEXUS_SSH_HOST}" "$@"; }
scp_cmd() { scp "${SSH_OPTS[@]}" "$@"; }

DEPLOY_PATH="${NEXUS_DEPLOY_PATH:-/www/wwwroot/api.synaglobal.vip}"

echo "═══ Nexus production deploy ═══"
echo "SSH target: ${NEXUS_SSH_HOST}"
echo "Deploy path: ${DEPLOY_PATH}"

if ! ssh_cmd "echo SSH OK" >/dev/null 2>&1; then
  echo "ERROR: Cannot SSH to ${NEXUS_SSH_HOST}" >&2
  echo "  Configure ~/.ssh/config (Host nexus) or set NEXUS_SSH / NEXUS_SSH_KEY" >&2
  exit 1
fi

echo "▶ Backend: git pull + restart..."
ssh_cmd "cd ${DEPLOY_PATH} && git fetch --all && git reset --hard origin/main && supervisorctl restart nexus"

echo "▶ Frontend: build + upload..."
cd frontend && npx vite build && cd ..
tar czf /tmp/nexus-frontend.tar.gz -C web/app index.html assets/
scp_cmd /tmp/nexus-frontend.tar.gz "${NEXUS_SSH_HOST}:/tmp/nexus-frontend.tar.gz"
ssh_cmd "cd ${DEPLOY_PATH}/web/app && tar xzf /tmp/nexus-frontend.tar.gz && rm /tmp/nexus-frontend.tar.gz"
if ssh_cmd "test -f ${DEPLOY_PATH}/deploy/prune_frontend_assets.py"; then
  ssh_cmd "python3 ${DEPLOY_PATH}/deploy/prune_frontend_assets.py --dry-run"
  ssh_cmd "python3 ${DEPLOY_PATH}/deploy/prune_frontend_assets.py"
fi

sleep 3
HEALTH=$(ssh_cmd "curl -s http://127.0.0.1:8600/health" 2>/dev/null || true)
SPA=$(ssh_cmd "curl -s -o /dev/null -w '%{http_code}' http://127.0.0.1:8600/app/" 2>/dev/null || echo "000")
echo "  /health → ${HEALTH}"
echo "  /app/   → ${SPA}"
if [ "${HEALTH}" = "ok" ] && [ "${SPA}" = "200" ]; then
  echo "✓ Deploy successful"
else
  echo "✗ Verification failed — check supervisor logs on server" >&2
  exit 1
fi
