#!/usr/bin/env bash
# 🚀 DEPLOY POI DATABASE TO VPS
# Uploads the SQLite POI index to the production server.
#
# Prerequisites:
# - poi-index.db must exist (run build-poi-index.mjs first)
# - SSH access to VPS configured
#
# Usage:
#   ./scripts/deploy-poi-db.sh
#   ./scripts/deploy-poi-db.sh --file=europe-poi-index.db

set -euo pipefail

SCRIPT_DIR="$(cd "$(dirname "${BASH_SOURCE[0]}")" && pwd)"
PROJECT_ROOT="$(dirname "$SCRIPT_DIR")"

# Configuration
VPS_HOST="vps-4d8abcb7.vps.ovh.net"
VPS_USER="myroadtrip"
REMOTE_APP_DIR="/srv/myroadtrip"
REMOTE_DB_PATH="${REMOTE_APP_DIR}/poi-index.db"

# Parse arguments
DB_FILE="${1:-poi-index.db}"
if [[ "$DB_FILE" == --file=* ]]; then
  DB_FILE="${DB_FILE#--file=}"
fi

LOCAL_DB="${PROJECT_ROOT}/${DB_FILE}"

echo "============================================="
echo "🗄️  DEPLOYING POI DATABASE TO VPS"
echo "============================================="
echo ""

# 1. Check local database
if [ ! -f "$LOCAL_DB" ]; then
    echo "❌ Error: Database not found: $LOCAL_DB"
    echo ""
    echo "   Generate it first with:"
    echo "   node scripts/build-poi-index.mjs --file=europe-roadtrip.osm.pbf"
    exit 1
fi

LOCAL_SIZE=$(ls -lh "$LOCAL_DB" | awk '{print $5}')
POI_COUNT=$(sqlite3 "$LOCAL_DB" "SELECT COUNT(*) FROM pois" 2>/dev/null || echo "?")
echo "📦 Local database: $LOCAL_DB"
echo "   Size: $LOCAL_SIZE"
echo "   POIs: $POI_COUNT"
echo ""

# 2. Test SSH connectivity
echo "🔗 Testing SSH connection..."
if ! ssh -o BatchMode=yes -o ConnectTimeout=10 ${VPS_HOST} "echo ok" > /dev/null 2>&1; then
    echo "❌ Error: Cannot connect to VPS via SSH."
    echo "   Configure SSH access for ${VPS_HOST}"
    exit 1
fi
echo "✅ SSH connection OK"
echo ""

# 3. Check if API is running
echo "🔍 Checking API status on VPS..."
API_PID=$(ssh ${VPS_HOST} "pgrep -f 'node.*dist/server.js' || echo ''")
if [ -n "$API_PID" ]; then
    echo "   API is running (PID: $API_PID)"
    RESTART_API=true
else
    echo "   API is not running"
    RESTART_API=false
fi
echo ""

# 4. Backup existing database (if exists)
echo "📦 Checking for existing database..."
if ssh ${VPS_HOST} "[ -f ${REMOTE_DB_PATH} ]"; then
    BACKUP_NAME="poi-index.db.backup.$(date +%Y%m%d_%H%M%S)"
    echo "   Backing up to ${BACKUP_NAME}..."
    ssh ${VPS_HOST} "cp ${REMOTE_DB_PATH} ${REMOTE_APP_DIR}/${BACKUP_NAME}"
    echo "   ✅ Backup created"
else
    echo "   No existing database to backup"
fi
echo ""

# 5. Upload new database
echo "🚀 Uploading database (this may take a few minutes)..."
rsync -avz --progress "$LOCAL_DB" "${VPS_HOST}:${REMOTE_DB_PATH}"
echo "✅ Upload complete"
echo ""

# 6. Set permissions
echo "🔒 Setting permissions..."
ssh ${VPS_HOST} "chown ${VPS_USER}:${VPS_USER} ${REMOTE_DB_PATH} && chmod 644 ${REMOTE_DB_PATH}"
echo "✅ Permissions set"
echo ""

# 7. Verify upload
echo "🔍 Verifying upload..."
REMOTE_SIZE=$(ssh ${VPS_HOST} "ls -lh ${REMOTE_DB_PATH} | awk '{print \$5}'")
REMOTE_COUNT=$(ssh ${VPS_HOST} "sqlite3 ${REMOTE_DB_PATH} 'SELECT COUNT(*) FROM pois'" 2>/dev/null || echo "?")
echo "   Remote size: $REMOTE_SIZE"
echo "   Remote POIs: $REMOTE_COUNT"

if [ "$POI_COUNT" != "$REMOTE_COUNT" ]; then
    echo "⚠️  Warning: POI count mismatch (local: $POI_COUNT, remote: $REMOTE_COUNT)"
fi
echo ""

# 8. Restart API if it was running
if [ "$RESTART_API" = true ]; then
    echo "🔄 Restarting API to pick up new database..."
    ssh ${VPS_HOST} "cd ${REMOTE_APP_DIR} && pm2 restart api 2>/dev/null || systemctl --user restart myroadtrip-api 2>/dev/null || echo 'Manual restart may be required'"
    echo "✅ API restart triggered"
else
    echo "ℹ️  API was not running, skipping restart"
fi

echo ""
echo "============================================="
echo "✅ POI DATABASE DEPLOYED SUCCESSFULLY"
echo "============================================="
echo ""
echo "   Database: ${REMOTE_DB_PATH}"
echo "   Size: ${REMOTE_SIZE}"
echo "   POIs: ${REMOTE_COUNT}"
echo ""
echo "   Test with:"
echo "   curl https://api.roadtripper.io/api/pois/health"
echo "   curl https://api.roadtripper.io/api/pois/stats"
echo ""
