#!/bin/bash
# deploy-to-vps.sh
# Complete deployment pipeline for CLI sites
#
# Usage: ./deploy-to-vps.sh <site-name> [vps-host]
#
# This script:
# 1. Validates site directory
# 2. Pre-deployment validation
# 3. Site quality evaluation (blocks deploy if score < 60)
# 4. Assigns port (if needed)
# 5. Generates nginx config
# 6. Syncs to VPS
# 7. Sets up PM2
# 8. Configures nginx
# 9. Verifies deployment (post-checks)

set -e

# Source centralized config
SCRIPT_DIR="$(cd "$(dirname "${BASH_SOURCE[0]}")" && pwd)"
source "$SCRIPT_DIR/../../scripts/config.sh"

SITE_NAME=$1
VPS_HOST=${2:-"$WS_VPS_SSH"}

if [ -z "$SITE_NAME" ]; then
  echo "Usage: $0 <site-name> [vps-host]"
  echo ""
  echo "Examples:"
  echo "  $0 silicon-bali"
  echo "  $0 my-site root@example.com"
  exit 1
fi

# Colors
RED='\033[0;31m'
GREEN='\033[0;32m'
YELLOW='\033[1;33m'
BLUE='\033[0;34m'
NC='\033[0m' # No Color

# Get script directory
SCRIPT_DIR="$(cd "$(dirname "${BASH_SOURCE[0]}")" && pwd)"
SITE_DIR="$SCRIPT_DIR/../$SITE_NAME"

echo -e "${BLUE}━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━${NC}"
echo -e "${BLUE}  Complete Deployment Pipeline${NC}"
echo -e "${BLUE}━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━${NC}"
echo ""
echo -e "${BLUE}Site:${NC} $SITE_NAME"
echo -e "${BLUE}VPS:${NC} $VPS_HOST"
echo ""

# ━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━
# Step 1: Validate Site Directory
# ━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━

echo -e "${YELLOW}[1/9]${NC} Validating site directory..."

if [ ! -d "$SITE_DIR" ]; then
  echo -e "${RED}❌ Site directory not found: $SITE_DIR${NC}"
  exit 1
fi

echo -e "${GREEN}✅ Site directory exists${NC}"
echo ""

# ━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━
# Step 2: Pre-Deployment Validation
# ━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━

echo -e "${YELLOW}[2/9]${NC} Running pre-deployment validation..."

if "$SCRIPT_DIR/validate-deployment.sh" "$SITE_DIR"; then
  echo -e "${GREEN}✅ Pre-deployment validation passed${NC}"
else
  echo -e "${RED}❌ Pre-deployment validation failed${NC}"
  echo ""
  echo "Fix the validation issues before deploying"
  exit 1
fi

echo ""

# ━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━
# Step 3: Site Quality Evaluation
# ━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━

echo -e "${YELLOW}[3/9]${NC} Running site quality evaluation..."

EVAL_SCRIPT="$SCRIPT_DIR/../../scripts/evaluate-site.sh"
if [[ -f "$EVAL_SCRIPT" ]]; then
  EVAL_JSON=$(bash "$EVAL_SCRIPT" "$SITE_DIR" --json --no-report 2>/dev/null)
  EVAL_SCORE=$(echo "$EVAL_JSON" | grep '"score"' | head -1 | grep -o '[0-9]*')
  EVAL_GRADE=$(echo "$EVAL_JSON" | grep '"grade"' | head -1 | sed 's/.*: *"\([^"]*\)".*/\1/')

  if [[ -n "$EVAL_SCORE" ]]; then
    echo -e "   Score: ${EVAL_SCORE}/100 (${EVAL_GRADE})"

    if [[ "$EVAL_SCORE" -lt "$WS_EVAL_PASS" ]]; then
      echo -e "${RED}❌ Deployment blocked: score ${EVAL_SCORE} < ${WS_EVAL_PASS} minimum${NC}"
      echo "   Fix critical items and re-run"
      exit 1
    elif [[ "$EVAL_SCORE" -lt "$WS_EVAL_GOOD" ]]; then
      echo -e "${YELLOW}⚠️  Score below GOOD threshold (${WS_EVAL_GOOD})${NC}"
    fi
    echo -e "${GREEN}✅ Quality evaluation passed${NC}"
  else
    echo -e "${YELLOW}⚠️  Could not parse evaluation score, continuing...${NC}"
  fi
else
  echo -e "${YELLOW}⚠️  evaluate-site.sh not found, skipping quality check${NC}"
fi

echo ""

# ━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━
# Step 4: Port Assignment
# ━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━

echo -e "${YELLOW}[4/9]${NC} Checking port assignment..."

PORTS_FILE="$SCRIPT_DIR/../ports.json"
PORT=$(jq -r ".\"$SITE_NAME\" // empty" "$PORTS_FILE" 2>/dev/null || echo "")

if [ -z "$PORT" ] || [ "$PORT" = "null" ]; then
  echo -e "${YELLOW}⚠️  No port assigned, assigning now...${NC}"
  "$SCRIPT_DIR/assign-port.sh" "$SITE_NAME" production

  # Re-read port
  PORT=$(jq -r ".\"$SITE_NAME\"" "$PORTS_FILE")
else
  echo -e "${GREEN}✅ Port already assigned: $PORT${NC}"
fi

echo ""

# ━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━
# Step 5: Generate nginx Config
# ━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━

echo -e "${YELLOW}[5/9]${NC} Generating nginx config..."

NGINX_CONFIG=$("$SCRIPT_DIR/generate-nginx-block.sh" "$SITE_NAME")

# Save to temp file
TMP_NGINX="/tmp/${SITE_NAME}-nginx.conf"
echo "$NGINX_CONFIG" > "$TMP_NGINX"

echo -e "${GREEN}✅ nginx config generated${NC}"
echo ""

# ━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━
# Step 6: Sync to VPS
# ━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━

echo -e "${YELLOW}[6/9]${NC} Syncing files to VPS..."

# Create remote directory
ssh "$VPS_HOST" "mkdir -p $WS_VPS_CLI_SITES/$SITE_NAME" || {
  echo -e "${RED}❌ Failed to create remote directory${NC}"
  exit 1
}

# Sync site files
echo "   Syncing site files..."
rsync -avz --exclude 'node_modules' --exclude '.next' --exclude 'out' \
  "$SITE_DIR/" "$VPS_HOST:$WS_VPS_CLI_SITES/$SITE_NAME/" || {
  echo -e "${RED}❌ Failed to sync files${NC}"
  exit 1
}

echo -e "${GREEN}✅ Files synced to VPS${NC}"
echo ""

# ━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━
# Step 7: Setup PM2 on VPS
# ━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━

echo -e "${YELLOW}[7/9]${NC} Setting up PM2 on VPS..."

# Check if ecosystem.config.js exists
if [ -f "$SITE_DIR/ecosystem.config.js" ]; then
  echo "   Using existing ecosystem.config.js"
else
  echo "   Creating ecosystem.config.js..."

  # Generate basic PM2 config
  cat > "/tmp/${SITE_NAME}-ecosystem.config.js" <<EOF
module.exports = {
  apps: [{
    name: 'cli-$SITE_NAME',
    script: 'node_modules/next/dist/bin/next',
    args: 'start',
    cwd: '$WS_VPS_CLI_SITES/$SITE_NAME',
    instances: 1,
    autorestart: true,
    watch: false,
    max_memory_restart: '1G',
    env: {
      NODE_ENV: 'production',
      PORT: '$PORT'
    }
  }]
}
EOF

  # Upload config
  scp "/tmp/${SITE_NAME}-ecosystem.config.js" "$VPS_HOST:$WS_VPS_CLI_SITES/$SITE_NAME/ecosystem.config.js"
fi

# Install dependencies and start PM2
ssh "$VPS_HOST" <<REMOTE_SCRIPT
cd $WS_VPS_CLI_SITES/$SITE_NAME

# Install dependencies if needed
if [ ! -d "node_modules" ]; then
  echo "   Installing dependencies..."
  npm install --production
fi

# Build if needed
if [ ! -d ".next" ]; then
  echo "   Building Next.js..."
  npm run build
fi

# Stop existing PM2 process (if any)
pm2 delete cli-$SITE_NAME 2>/dev/null || true

# Start new PM2 process
pm2 start ecosystem.config.js
pm2 save

echo "   PM2 process started"
REMOTE_SCRIPT

echo -e "${GREEN}✅ PM2 setup complete${NC}"
echo ""

# ━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━
# Step 8: Configure nginx
# ━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━

echo -e "${YELLOW}[8/9]${NC} Configuring nginx..."

echo ""
echo -e "${BLUE}━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━${NC}"
echo -e "${YELLOW}Manual Step Required:${NC}"
echo -e "${BLUE}━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━${NC}"
echo ""
echo "Add this to $WS_NGINX_CONFIG:"
echo ""
cat "$TMP_NGINX"
echo ""
echo -e "${BLUE}━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━${NC}"
echo ""
echo "Steps:"
echo "  1. ssh $VPS_HOST"
echo "  2. sudo nano $WS_NGINX_CONFIG"
echo "  3. Add the location block above (alphabetically sorted)"
echo "  4. sudo nginx -t"
echo "  5. sudo systemctl reload nginx"
echo ""

read -p "Press Enter after nginx is configured..."

echo ""

# ━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━
# Step 9: Verify Deployment
# ━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━

echo -e "${YELLOW}[9/9]${NC} Verifying deployment..."
echo ""

sleep 3  # Give services a moment to stabilize

if "$SCRIPT_DIR/verify-deployment.sh" "$SITE_NAME" "https://$WS_DOMAIN"; then
  echo ""
  echo -e "${BLUE}━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━${NC}"
  echo -e "${GREEN}  ✅ DEPLOYMENT SUCCESSFUL!${NC}"
  echo -e "${BLUE}━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━${NC}"
  echo ""
  echo -e "${GREEN}Site:${NC} https://$WS_DOMAIN/$WS_URL_CLI/$SITE_NAME/"
  echo -e "${GREEN}Port:${NC} $PORT"
  echo -e "${GREEN}PM2:${NC} cli-$SITE_NAME"
  echo ""
else
  echo ""
  echo -e "${BLUE}━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━${NC}"
  echo -e "${YELLOW}  ⚠️  DEPLOYMENT COMPLETE WITH WARNINGS${NC}"
  echo -e "${BLUE}━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━${NC}"
  echo ""
  echo "Review verification output above"
  echo ""
fi

# Cleanup temp files
rm -f "$TMP_NGINX" "/tmp/${SITE_NAME}-ecosystem.config.js" 2>/dev/null || true

exit 0
