#!/bin/bash
# Complete deployment script for tiered architecture

set -e

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

echo "=== SolaceScan Tiered Architecture Deployment ==="
echo ""

# Step 1: Verify prerequisites
echo "Step 1: Verifying prerequisites..."
bash "$SCRIPT_DIR/verify-tiered-architecture.sh"
if [ $? -ne 0 ]; then
    echo "❌ Prerequisites check failed"
    exit 1
fi
echo ""

# Step 2: Check environment variables
echo "Step 2: Checking environment variables..."
MISSING_VARS=()

if [ -z "$DB_HOST" ]; then
    DB_HOST="localhost"
    echo "⚠️  DB_HOST not set, using default: localhost"
fi

if [ -z "$DB_USER" ]; then
    DB_USER="explorer"
    echo "⚠️  DB_USER not set, using default: explorer"
fi

if [ -z "$DB_PASSWORD" ]; then
    DB_PASSWORD="changeme"
    echo "⚠️  DB_PASSWORD not set, using default: changeme"
fi

if [ -z "$DB_NAME" ]; then
    DB_NAME="explorer"
    echo "⚠️  DB_NAME not set, using default: explorer"
fi

if [ -z "$JWT_SECRET" ]; then
    echo "⚠️  WARNING: JWT_SECRET not set!"
    echo "   Using default secret (NOT SECURE FOR PRODUCTION)"
    echo "   Set JWT_SECRET environment variable before production deployment"
    JWT_SECRET="change-me-in-production-use-strong-random-secret"
fi

if [ -z "$RPC_URL" ]; then
    RPC_URL="http://192.168.11.250:8545"
    echo "⚠️  RPC_URL not set, using default: $RPC_URL"
fi

export DB_HOST DB_USER DB_PASSWORD DB_NAME JWT_SECRET RPC_URL
echo ""

# Step 3: Run database migration
echo "Step 3: Running database migration..."
if bash "$SCRIPT_DIR/run-migration-0010.sh"; then
    echo "✅ Migration completed"
else
    echo "❌ Migration failed"
    echo "   Continuing anyway (migration may have already been run)..."
fi
echo ""

# Step 4: Build backend
echo "Step 4: Building backend..."
cd "$PROJECT_ROOT/backend"
if go mod tidy && go build -o bin/api-server ./api/rest/cmd; then
    echo "✅ Backend built successfully"
    ls -lh bin/api-server
else
    echo "❌ Build failed"
    exit 1
fi
echo ""

# Step 5: Check if server is already running
echo "Step 5: Checking for existing server..."
if pgrep -f "api-server" > /dev/null; then
    echo "⚠️  API server is already running"
    read -p "Stop existing server? (y/n) " -n 1 -r
    echo
    if [[ $REPLY =~ ^[Yy]$ ]]; then
        pkill -f "api-server"
        sleep 2
        echo "✅ Stopped existing server"
    else
        echo "⚠️  Keeping existing server running"
    fi
fi
echo ""

# Step 6: Start API server in background
echo "Step 6: Starting API server..."
cd "$PROJECT_ROOT/backend"

# Create log directory
mkdir -p logs

# Start server with environment variables
export JWT_SECRET
export RPC_URL
export DB_HOST
export DB_USER
export DB_PASSWORD
export DB_NAME
export CHAIN_ID=138
export PORT=8080

nohup ./bin/api-server > logs/api-server.log 2>&1 &
SERVER_PID=$!

# Wait for server to start
echo "Waiting for server to start..."
sleep 3

# Check if server is running
if ps -p $SERVER_PID > /dev/null; then
    echo "✅ API server started (PID: $SERVER_PID)"
    echo "   Logs: $PROJECT_ROOT/backend/logs/api-server.log"
    echo $SERVER_PID > "$PROJECT_ROOT/backend/logs/api-server.pid"
else
    echo "❌ Server failed to start"
    echo "   Check logs: $PROJECT_ROOT/backend/logs/api-server.log"
    tail -20 "$PROJECT_ROOT/backend/logs/api-server.log"
    exit 1
fi
echo ""

# Step 7: Test API endpoints
echo "Step 7: Testing API endpoints..."
sleep 2
if bash "$SCRIPT_DIR/test-tiered-api.sh"; then
    echo "✅ API tests passed"
else
    echo "⚠️  Some API tests failed (this may be expected if server needs more time)"
fi
echo ""

# Step 8: Summary
echo "=== Deployment Complete ==="
echo ""
echo "✅ API Server Status:"
echo "   PID: $SERVER_PID"
echo "   Port: 8080"
echo "   Logs: $PROJECT_ROOT/backend/logs/api-server.log"
echo ""
echo "📋 Next Steps:"
echo "1. Approve users for Track 2-4:"
echo "   bash scripts/approve-user.sh <address> <track_level>"
echo ""
echo "2. Add IP whitelist for Track 4 operators:"
echo "   bash scripts/add-operator-ip.sh <operator_address> <ip_address>"
echo ""
echo "3. Start Track 2 indexers (optional):"
echo "   cd backend/indexer && go run main.go"
echo ""
echo "4. Test authentication flow:"
echo "   - Connect wallet in frontend"
echo "   - Verify feature flags update"
echo ""
echo "5. Monitor server:"
echo "   tail -f $PROJECT_ROOT/backend/logs/api-server.log"
echo ""
echo "To stop the server:"
echo "   kill $SERVER_PID"
echo "   or: pkill -f api-server"
echo ""
