#!/bin/bash

# SAR Deployment Script - Production Ready
# This script handles the complete deployment of Sovereign AI Router

set -e

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

# Configuration
SAR_DIR="/opt/sovereign-ai-router"
CONFIG_DIR="$HOME/.sar"
LOG_DIR="/var/log/sar"
PID_DIR="/var/run/sar"

# Check if running as root
if [[ $EUID -ne 0 ]]; then
   echo -e "${RED}This script must be run as root${NC}"
   exit 1
fi

# Logging function
log() {
    echo -e "${BLUE}[$(date +'%Y-%m-%d %H:%M:%S')]${NC} $1"
}

error() {
    echo -e "${RED}[$(date +'%Y-%m-%d %H:%M:%S')] ERROR:${NC} $1"
}

success() {
    echo -e "${GREEN}[$(date +'%Y-%m-%d %H:%M:%S')] SUCCESS:${NC} $1"
}

# Check system requirements
check_requirements() {
    log "Checking system requirements..."
    
    # Check Node.js
    if ! command -v node &> /dev/null; then
        error "Node.js is not installed"
        return 1
    fi
    
    local node_version=$(node --version | cut -d'v' -f2 | cut -d'.' -f1)
    if (( node_version < 18 )); then
        error "Node.js version 18+ required, found $node_version"
        return 1
    fi
    
    # Check npm
    if ! command -v npm &> /dev/null; then
        error "npm is not installed"
        return 1
    fi
    
    # Check disk space
    local free_space=$(df -BG . | awk 'NR==2 {print $4}' | sed 's/G//')
    if (( free_space < 10 )); then
        error "Insufficient disk space (need 10GB, found $free_space GB)"
        return 1
    fi
    
    log "System requirements met"
    return 0
}

# Install dependencies
install_dependencies() {
    log "Installing dependencies..."
    
    # Install Node.js dependencies
    cd "$SAR_DIR"
    npm install --production
    
    if [ $? -ne 0 ]; then
        error "Failed to install dependencies"
        return 1
    fi
    
    log "Dependencies installed successfully"
    return 0
}

# Initialize database
init_database() {
    log "Initializing database..."
    
    # Create data directory
    mkdir -p "$SAR_DIR/data"
    
    # Initialize SQLite database
    if [ -f "$SAR_DIR/data/database.sqlite" ]; then
        log "Database already exists, skipping initialization"
        return 0
    fi
    
    # Run database initialization
    if ! node init-db.js; then
        error "Failed to initialize database"
        return 1
    fi
    
    log "Database initialized successfully"
    return 0
}

# Configure environment
configure_environment() {
    log "Configuring environment..."
    
    # Create .env file
    cat > "$SAR_DIR/.env" << EOF
# SAR Configuration
JWT_SECRET=$(openssl rand -base64 32)
DB_PATH=$SAR_DIR/data/database.sqlite
PORT=3000
METRICS_PORT=9090
MAX_WORKERS=8
NODE_ENV=production
EOF
    
    # Set permissions
    chmod 600 "$SAR_DIR/.env"
    
    log "Environment configured successfully"
    return 0
}

# Deploy systemd service
deploy_systemd() {
    log "Deploying systemd service..."
    
    # Create directories
    mkdir -p /etc/sar
    mkdir -p "$LOG_DIR"
    mkdir -p "$PID_DIR"
    
    # Copy service file
    cp "$SAR_DIR/sar.service" /etc/systemd/system/
    
    # Create log rotation
    cat > /etc/logrotate.d/sar << EOF
/var/log/sar/*.log {
    daily
    rotate 7
    compress
    missingok
    notifempty
    create 644 root root
}
EOF
    
    # Reload systemd
    systemctl daemon-reload
    
    log "Systemd service deployed successfully"
    return 0
}

# Start SAR service
start_service() {
    log "Starting SAR service..."
    
    # Enable and start service
    systemctl enable sar
    systemctl start sar
    
    # Wait for service to start
    sleep 5
    
    # Check status
    if systemctl is-active --quiet sar; then
        success "SAR service started successfully"
        return 0
    else
        error "Failed to start SAR service"
        return 1
    fi
}

# Test deployment
test_deployment() {
    log "Testing deployment..."
    
    # Wait for service to be ready
    sleep 10
    
    # Test health endpoint
    if curl -f http://localhost:3000/health > /dev/null 2>&1; then
        success "Health check passed"
    else
        error "Health check failed"
        return 1
    fi
    
    # Test metrics endpoint
    if curl -f http://localhost:9090/metrics > /dev/null 2>&1; then
        success "Metrics endpoint working"
    else
        error "Metrics endpoint failed"
        return 1
    fi
    
    log "Deployment test passed"
    return 0
}

# Cleanup function
cleanup() {
    log "Cleaning up..."
    # Remove temporary files
    rm -f /tmp/sar-deploy.log
    
    log "Cleanup complete"
}

# Main deployment function
main() {
    echo "⚡ Sovereign AI Router - Production Deployment"
    echo "============================================="
    echo ""
    
    # Check requirements
    if ! check_requirements; then
        error "System requirements not met"
        exit 1
    fi
    
    # Create SAR directory
    mkdir -p "$SAR_DIR"
    
    # Copy files from workspace
    cp -r /home/hugo/.openclaw/workspace/toolpillar/sovereign-ai-router/* "$SAR_DIR/"
    
    # Install dependencies
    if ! install_dependencies; then
        error "Failed to install dependencies"
        exit 1
    fi
    
    # Initialize database
    if ! init_database; then
        error "Failed to initialize database"
        exit 1
    fi
    
    # Configure environment
    if ! configure_environment; then
        error "Failed to configure environment"
        exit 1
    fi
    
    # Deploy systemd service
    if ! deploy_systemd; then
        error "Failed to deploy systemd service"
        exit 1
    fi
    
    # Start service
    if ! start_service; then
        error "Failed to start SAR service"
        exit 1
    fi
    
    # Test deployment
    if ! test_deployment; then
        error "Deployment test failed"
        exit 1
    fi
    
    # Cleanup
    cleanup
    
    echo ""
    success "🎉 Sovereign AI Router deployed successfully!"
    echo ""
    echo "🚀 Next Steps:"
    echo "1. Access health check: http://localhost:3000/health"
    echo "2. View metrics: http://localhost:9090/metrics"
    echo "3. Monitor logs: journalctl -u sar -f"
    echo "4. Check status: systemctl status sar"
    echo ""
    echo "📋 Configuration:"
    echo "   JWT Secret: $(cat $SAR_DIR/.env | grep JWT_SECRET | cut -d'=' -f2)"
    echo "   Database: $SAR_DIR/data/database.sqlite"
    echo "   Workers: $(grep MAX_WORKERS $SAR_DIR/.env | cut -d'=' -f2)"
    echo ""
    echo "📚 Documentation:"
    echo "   - /opt/sovereign-ai-router/PRODUCTION.md"
    echo "   - /opt/sovereign-ai-router/README.md"
    echo ""
    echo "⚙️  Management Commands:"
    echo "   Start: systemctl start sar"
    echo "   Stop: systemctl stop sar"
    echo "   Restart: systemctl restart sar"
    echo "   Status: systemctl status sar"
    echo "   Logs: journalctl -u sar -f"
    echo ""
    echo "🔒 Security:"
    echo "   - JWT authentication enabled"
    echo "   - Rate limiting active"
    echo "   - Circuit breaker protection"
    echo "   - Input validation in place"
    echo ""
    echo "📊 Monitoring:"
    echo "   - Health checks every 30 seconds"
    echo "   - Metrics collection enabled"
    echo "   - Alert thresholds configured"
    echo ""
    echo "Production deployment completed successfully!"
}

# Execute main function
main "$@"