#!/bin/bash
# deploy-frontend.sh — Build Vuetify frontend and deploy to server
#
# Usage: bash deploy/deploy-frontend.sh
# Run from the Nexus project root directory.

set -euo pipefail

echo "═══ Nexus Frontend Deploy ═══"

# 1. Build
echo "▶ Building frontend..."
cd frontend && npx vite build && cd ..
echo "✓ Build complete"

# 2. Tar the build output (index.html + assets/)
echo "▶ Packaging..."
tar czf /tmp/nexus-frontend.tar.gz -C web/app index.html assets/
echo "✓ Package ready ($(du -h /tmp/nexus-frontend.tar.gz | cut -f1))"

# 3. Upload to server
echo "▶ Uploading to server..."
scp /tmp/nexus-frontend.tar.gz nexus:/tmp/nexus-frontend.tar.gz
echo "✓ Upload complete"

# 4. Extract on server + prune orphaned legacy chunks
echo "▶ Deploying on server..."
ssh nexus "cd /www/wwwroot/api.synaglobal.vip/web/app && tar xzf /tmp/nexus-frontend.tar.gz && rm /tmp/nexus-frontend.tar.gz"
echo "▶ Pruning orphaned assets (dry-run first)..."
if ! ssh nexus "python3 /www/wwwroot/api.synaglobal.vip/deploy/prune_frontend_assets.py --dry-run"; then
  echo "✗ Prune dry-run failed — aborting (no files deleted)"
  exit 1
fi
if ! ssh nexus "python3 /www/wwwroot/api.synaglobal.vip/deploy/prune_frontend_assets.py"; then
  echo "✗ Prune failed — check index.html references before retry"
  exit 1
fi
echo "✓ Extracted and pruned"

# 5. Restart backend
echo "▶ Restarting backend..."
ssh nexus "supervisorctl restart nexus"
echo "✓ Restarted"

# 6. Health check
sleep 3
HEALTH=$(ssh nexus "curl -s -o /dev/null -w '%{http_code}' http://127.0.0.1:8600/health" 2>/dev/null || echo "000")
SPA=$(ssh nexus "curl -s -o /dev/null -w '%{http_code}' http://127.0.0.1:8600/app/" 2>/dev/null || echo "000")

echo ""
echo "═══ Verification ═══"
echo "  /health → $HEALTH"
echo "  /app/   → $SPA"

if [ "$HEALTH" = "200" ] && [ "$SPA" = "200" ]; then
  echo "✓ Deploy successful!"
else
  echo "✗ Verification failed — check server logs"
  exit 1
fi
