#!/bin/bash

# SAR Production Deployment (No Sudo Required)
# Deploys to user's home directory with full production features

set -e

# Configuration
SAR_HOME="$HOME/.sar"
LOG_DIR="$SAR_HOME/logs"
PID_DIR="$SAR_HOME/pid"
DATA_DIR="$SAR_HOME/data"

echo "🚀 Deploying Sovereign AI Router to $SAR_HOME"

# Create directories
mkdir -p "$SAR_HOME"
mkdir -p "$LOG_DIR"
mkdir -p "$PID_DIR"
mkdir -p "$DATA_DIR"

# Copy from workspace
cp -r /home/hugo/.openclaw/workspace/toolpillar/sovereign-ai-router/* "$SAR_HOME/"

# Install dependencies
cd "$SAR_HOME"
npm ci --only=production

# Initialize database
if [ ! -f "$DATA_DIR/database.sqlite" ]; then
    node init-db.js
fi

# Configure environment
cat > "$SAR_HOME/.env" << EOF
JWT_SECRET=$(openssl rand -base64 32 2>/dev/null || echo "default-secret-change-in-production")
DB_PATH=$DATA_DIR/database.sqlite
PORT=3000
METRICS_PORT=9090
MAX_WORKERS=$(nproc 2>/dev/null || echo 4)
NODE_ENV=production
EOF

# Create log rotation
cat > "$HOME/.logrotate/sar" << 'LOGEOF'
$SAR_HOME/logs/*.log {
    daily
    rotate 7
    compress
    missingok
    notifempty
    create 644 $USER $USER
    sharedscripts
    postrotate
        kill -USR1 `cat $SAR_HOME/pid/sar.pid 2>/dev/null` 2>/dev/null || true
    endscript
}
LOGEOF

# Start service
echo "Starting SAR service..."
cd "$SAR_HOME"
JWT_SECRET=$(grep JWT_SECRET .env | cut -d'=' -f2) \
PORT=$(grep PORT .env | cut -d'=' -f2) \
MAX_WORKERS=$(grep MAX_WORKERS .env | cut -d'=' -f2) \
node index.js > "$LOG_DIR/sar.log" 2>&1 &
echo $! > "$PID_DIR/sar.pid"

# Wait for startup
sleep 10

# Test deployment
if curl -f http://localhost:3000/health > /dev/null 2>&1; then
    echo "✅ SAR deployed successfully!"
    echo ""
    echo "🚀 Access Points:"
    echo "   Health: http://localhost:3000/health"
    echo "   Metrics: http://localhost:9090/metrics"
    echo "   API: http://localhost:3000/v1/chat/completions"
    echo ""
    echo "📋 Management:"
    echo "   Status: ps aux | grep sar"
    echo "   Logs: tail -f $LOG_DIR/sar.log"
    echo "   Stop: kill \$(cat $PID_DIR/sar.pid)"
    echo "   JWT Token: $(node -e "console.log(require('jsonwebtoken').sign({sub:'admin',role:'admin'}, process.env.JWT_SECRET,{expiresIn:'15m'}))" JWT_SECRET=$(grep JWT_SECRET .env | cut -d'=' -f2))"
else
    echo "❌ Deployment failed - check logs: $LOG_DIR/sar.log"
    exit 1
fi