#!/bin/bash
# ═══════════════════════════════════════════════════════════════
# LOOPUMAN SEO SERVER - DEPLOY SCRIPT
# Run this on your Oracle Cloud server
# ═══════════════════════════════════════════════════════════════
#
# STEP 1: Copy seo-server.js to your server
# Run this from your LOCAL machine (Windows Git Bash):
#
#   scp -i your-key.key seo-server.js ubuntu@YOUR_SERVER_IP:~/loopuman-backend/
#
# STEP 2: SSH into server, then run this script
#   ssh -i your-key.key ubuntu@YOUR_SERVER_IP
#   cd ~/loopuman-backend
#   bash deploy-seo.sh
# ═══════════════════════════════════════════════════════════════

set -e

echo ""
echo "═══════════════════════════════════════════════════════"
echo "  LOOPUMAN SEO SERVER DEPLOYMENT"
echo "═══════════════════════════════════════════════════════"
echo ""

# ── 1. Verify seo-server.js is here ──
if [ ! -f "seo-server.js" ]; then
  echo "❌ seo-server.js not found in $(pwd)"
  echo "   Upload it first: scp seo-server.js ubuntu@SERVER_IP:~/loopuman-backend/"
  exit 1
fi
echo "✅ seo-server.js found"

# ── 2. Verify .env has required keys ──
echo ""
echo "🔍 Checking environment variables..."
if grep -q "SUPABASE_URL" .env && grep -q "SUPABASE_SERVICE_KEY" .env; then
  echo "✅ Supabase credentials found in .env"
else
  echo "❌ Missing SUPABASE_URL or SUPABASE_SERVICE_KEY in .env"
  exit 1
fi

# ── 3. Test server starts correctly ──
echo ""
echo "🔍 Testing seo-server.js starts..."
timeout 5 node seo-server.js &
TEST_PID=$!
sleep 3

if kill -0 $TEST_PID 2>/dev/null; then
  kill $TEST_PID 2>/dev/null
  echo "✅ seo-server.js starts correctly"
else
  echo "❌ seo-server.js failed to start. Check for errors above."
  exit 1
fi

# ── 4. Add to ecosystem.config.js ──
echo ""
echo "📝 Updating ecosystem.config.js..."

# Check if seo-server already in ecosystem
if grep -q "seo-server" ecosystem.config.js; then
  echo "✅ seo-server already in ecosystem.config.js"
else
  # Backup first
  cp ecosystem.config.js ecosystem.config.js.bak
  
  # Add seo-server entry before the closing bracket
  # This uses Python for reliable JSON-like editing
  node -e "
const fs = require('fs');
let config = fs.readFileSync('ecosystem.config.js', 'utf8');

const newApp = \`    {
      name: 'seo-server',
      script: 'seo-server.js',
      instances: 1,
      autorestart: true,
      watch: false,
      max_memory_restart: '200M',
      env: { NODE_ENV: 'production', SEO_PORT: 3003 },
      error_file: './logs/seo-error.log',
      out_file: './logs/seo-out.log',
      time: true,
    },\`;

// Insert before the last closing bracket of the apps array
config = config.replace(/(\s*\]\s*};?\s*$)/, '\n' + newApp + '\$1');
fs.writeFileSync('ecosystem.config.js', config);
console.log('Added seo-server to ecosystem.config.js');
"
  echo "✅ ecosystem.config.js updated"
fi

# ── 5. Start with PM2 ──
echo ""
echo "🚀 Starting seo-server with PM2..."
pm2 start ecosystem.config.js --only seo-server
sleep 2
pm2 save
echo "✅ seo-server running with PM2"

# ── 6. Test the server responds ──
echo ""
echo "🔍 Testing server response..."
sleep 2
RESPONSE=$(curl -s -o /dev/null -w "%{http_code}" http://localhost:3003/tasks 2>/dev/null || echo "000")

if [ "$RESPONSE" = "200" ]; then
  echo "✅ /tasks responds with 200"
else
  echo "⚠️  /tasks responded with $RESPONSE (may still be starting)"
  echo "   Check logs: pm2 logs seo-server --lines 20"
fi

SITEMAP=$(curl -s -o /dev/null -w "%{http_code}" http://localhost:3003/sitemap.xml 2>/dev/null || echo "000")
if [ "$SITEMAP" = "200" ]; then
  echo "✅ /sitemap.xml responds with 200"
fi

# ── 7. Update nginx ──
echo ""
echo "═══════════════════════════════════════════════════════"
echo "  NEXT STEP: UPDATE NGINX"
echo "═══════════════════════════════════════════════════════"
echo ""
echo "Run this to see your current nginx config:"
echo ""
echo "  cat /etc/nginx/sites-enabled/loopuman"
echo ""
echo "Then add these location blocks BEFORE 'location / {':"
echo ""
cat << 'NGINX'
    location /tasks {
        proxy_pass http://127.0.0.1:3003;
        proxy_http_version 1.1;
        proxy_set_header Host $host;
        proxy_set_header X-Real-IP $remote_addr;
        proxy_set_header X-Forwarded-Proto $scheme;
    }

    location = /sitemap.xml {
        proxy_pass http://127.0.0.1:3003;
        proxy_http_version 1.1;
        proxy_set_header Host $host;
    }

    location = /robots.txt {
        proxy_pass http://127.0.0.1:3003;
        proxy_http_version 1.1;
        proxy_set_header Host $host;
    }
NGINX
echo ""
echo "Then reload nginx:"
echo "  sudo nginx -t && sudo systemctl reload nginx"
echo ""
echo "═══════════════════════════════════════════════════════"
echo "  ✅ DEPLOYMENT COMPLETE"
echo "═══════════════════════════════════════════════════════"
echo ""
echo "  Local test:  http://localhost:3003/tasks"
echo "  Live:        https://loopuman.com/tasks"
echo "  Sitemap:     https://loopuman.com/sitemap.xml"
echo ""
echo "  Submit sitemap in Google Search Console:"
echo "  https://search.google.com/search-console"
echo ""
pm2 status
