#!/bin/bash
# Quick deployment helper script for FoundationsAI
# Run this on your production server after copying the application files

set -e  # Exit on error

echo "╔════════════════════════════════════════════════════════╗"
echo "║   FoundationsAI Production Deployment Setup           ║"
echo "╔════════════════════════════════════════════════════════╗"
echo ""

# Check if running as root
if [ "$EUID" -ne 0 ]; then
    echo "❌ Please run as root (sudo ./deploy.sh)"
    exit 1
fi

# Variables (customize these)
APP_DIR="/opt/foundationsai"
APP_USER="foundationsai"
DOMAIN="your-domain.com"  # CHANGE THIS

echo "Configuration:"
echo "  - App Directory: $APP_DIR"
echo "  - App User: $APP_USER"
echo "  - Domain: $DOMAIN"
echo ""
read -p "Continue with these settings? (y/n) " -n 1 -r
echo ""
if [[ ! $REPLY =~ ^[Yy]$ ]]; then
    echo "Edit the variables in this script and try again."
    exit 1
fi

# Step 1: System updates
echo "📦 Step 1: Updating system packages..."
apt update -qq
apt upgrade -y -qq

# Step 2: Install dependencies
echo "📦 Step 2: Installing dependencies..."
apt install -y python3.11 python3.11-venv python3-pip nginx curl git htop

# Step 3: Install Ollama
echo "🤖 Step 3: Installing Ollama..."
if ! command -v ollama &> /dev/null; then
    curl -fsSL https://ollama.com/install.sh | sh
    systemctl enable ollama
    systemctl start ollama
    echo "✓ Ollama installed"
else
    echo "✓ Ollama already installed"
fi

# Step 4: Install MongoDB
echo "🍃 Step 4: Installing MongoDB..."
if ! command -v mongod &> /dev/null; then
    curl -fsSL https://www.mongodb.org/static/pgp/server-7.0.asc | gpg --dearmor -o /etc/apt/trusted.gpg.d/mongodb-server-7.0.gpg
    echo "deb [ arch=amd64,arm64 ] https://repo.mongodb.org/apt/ubuntu jammy/mongodb-org/7.0 multiverse" > /etc/apt/sources.list.d/mongodb-org-7.0.list
    apt update -qq
    apt install -y mongodb-org
    systemctl enable mongod
    systemctl start mongod
    echo "✓ MongoDB installed"
else
    echo "✓ MongoDB already installed"
fi

# Step 5: Create application user
echo "👤 Step 5: Creating application user..."
if ! id "$APP_USER" &>/dev/null; then
    useradd -r -m -s /bin/bash $APP_USER
    usermod -aG video $APP_USER  # For GPU access
    echo "✓ User $APP_USER created"
else
    echo "✓ User $APP_USER already exists"
fi

# Step 6: Create directories
echo "📁 Step 6: Creating directories..."
mkdir -p $APP_DIR
mkdir -p /var/log/foundationsai
mkdir -p /var/run/foundationsai
mkdir -p /var/cache/nginx/foundationsai
mkdir -p /var/www/letsencrypt

chown $APP_USER:$APP_USER $APP_DIR
chown $APP_USER:$APP_USER /var/log/foundationsai
chown $APP_USER:$APP_USER /var/run/foundationsai
chown www-data:www-data /var/cache/nginx/foundationsai
chown www-data:www-data /var/www/letsencrypt

echo "✓ Directories created"

# Step 7: Check if application files exist
echo "📋 Step 7: Checking application files..."
if [ ! -f "$APP_DIR/LLMAPI.py" ]; then
    echo "❌ Application files not found in $APP_DIR"
    echo "   Please copy your application files to $APP_DIR first:"
    echo "   - LLMAPI.py"
    echo "   - requirements.txt"
    echo "   - gunicorn_config.py"
    echo "   - foundationsai.service"
    echo "   - nginx_foundationsai.conf"
    echo "   - All other Python files"
    echo ""
    echo "   Then run this script again."
    exit 1
fi

# Step 8: Setup Python virtual environment
echo "🐍 Step 8: Setting up Python virtual environment..."
if [ ! -d "$APP_DIR/venv" ]; then
    sudo -u $APP_USER python3.11 -m venv $APP_DIR/venv
    echo "✓ Virtual environment created"
else
    echo "✓ Virtual environment exists"
fi

echo "📦 Installing Python dependencies..."
sudo -u $APP_USER $APP_DIR/venv/bin/pip install --upgrade pip -q
sudo -u $APP_USER $APP_DIR/venv/bin/pip install -r $APP_DIR/requirements.txt -q
sudo -u $APP_USER $APP_DIR/venv/bin/pip install gunicorn -q
echo "✓ Python dependencies installed"

# Step 9: Setup environment file
echo "⚙️  Step 9: Setting up .env file..."
if [ ! -f "$APP_DIR/.env" ]; then
    if [ -f "$APP_DIR/.env.example" ]; then
        cp $APP_DIR/.env.example $APP_DIR/.env
        chown $APP_USER:$APP_USER $APP_DIR/.env
        chmod 600 $APP_DIR/.env

        # Generate secrets
        SECRET_KEY=$(python3 -c "import secrets; print(secrets.token_urlsafe(32))")
        JWT_SECRET=$(python3 -c "import secrets; print(secrets.token_urlsafe(32))")

        # Update .env
        sed -i "s/SECRET_KEY=.*/SECRET_KEY=$SECRET_KEY/" $APP_DIR/.env
        sed -i "s/JWT_SECRET_KEY=.*/JWT_SECRET_KEY=$JWT_SECRET/" $APP_DIR/.env
        sed -i "s/FLASK_ENV=.*/FLASK_ENV=production/" $APP_DIR/.env

        echo "✓ .env file created with generated secrets"
        echo "⚠️  IMPORTANT: Edit $APP_DIR/.env and configure:"
        echo "   - HEALTHLEVEL_API_BASE_URL"
        echo "   - HEALTHLEVEL_AUTH_TOKEN"
        echo "   - Other required settings"
    else
        echo "❌ .env.example not found. Create one manually."
        exit 1
    fi
else
    echo "✓ .env file already exists"
fi

# Step 10: Download LLM model
echo "🧠 Step 10: Downloading LLM model..."
read -p "Download llama3.3:70b model? (y/n, ~40GB, takes 30-60min) " -n 1 -r
echo ""
if [[ $REPLY =~ ^[Yy]$ ]]; then
    ollama pull llama3.3:70b
    echo "✓ Model downloaded"
else
    echo "⚠️  Skipped model download. Download manually: ollama pull llama3.3:70b"
fi

# Step 11: Install systemd service
echo "🔧 Step 11: Installing systemd service..."
if [ -f "$APP_DIR/foundationsai.service" ]; then
    cp $APP_DIR/foundationsai.service /etc/systemd/system/
    systemctl daemon-reload
    systemctl enable foundationsai
    echo "✓ Systemd service installed"
else
    echo "❌ foundationsai.service not found"
    exit 1
fi

# Step 12: Configure Nginx
echo "🌐 Step 12: Configuring Nginx..."
if [ -f "$APP_DIR/nginx_foundationsai.conf" ]; then
    cp $APP_DIR/nginx_foundationsai.conf /etc/nginx/sites-available/foundationsai

    # Update domain in config
    sed -i "s/your-domain.com/$DOMAIN/g" /etc/nginx/sites-available/foundationsai

    # Enable site
    ln -sf /etc/nginx/sites-available/foundationsai /etc/nginx/sites-enabled/
    rm -f /etc/nginx/sites-enabled/default

    # Test configuration
    nginx -t
    echo "✓ Nginx configured"
else
    echo "❌ nginx_foundationsai.conf not found"
    exit 1
fi

# Step 13: Configure firewall
echo "🔥 Step 13: Configuring firewall..."
if command -v ufw &> /dev/null; then
    ufw --force enable
    ufw allow 22/tcp
    ufw allow 80/tcp
    ufw allow 443/tcp
    echo "✓ Firewall configured"
else
    echo "⚠️  UFW not installed, skipping firewall setup"
fi

# Step 14: Start services
echo "🚀 Step 14: Starting services..."
systemctl start foundationsai
systemctl restart nginx

echo ""
echo "╔════════════════════════════════════════════════════════╗"
echo "║   ✓ Deployment Complete!                              ║"
echo "╔════════════════════════════════════════════════════════╗"
echo ""
echo "Next steps:"
echo ""
echo "1. Edit configuration:"
echo "   sudo nano $APP_DIR/.env"
echo ""
echo "2. Check service status:"
echo "   sudo systemctl status foundationsai"
echo ""
echo "3. View logs:"
echo "   sudo journalctl -u foundationsai -f"
echo ""
echo "4. Test health endpoint:"
echo "   curl http://localhost:7654/api/health"
echo ""
echo "5. Setup SSL certificate:"
echo "   sudo apt install certbot python3-certbot-nginx"
echo "   sudo certbot --nginx -d $DOMAIN"
echo ""
echo "6. Access your API:"
echo "   http://$DOMAIN/api/health"
echo ""
echo "Troubleshooting:"
echo "   - Logs: /var/log/foundationsai/"
echo "   - Service: sudo systemctl status foundationsai"
echo "   - Nginx: sudo nginx -t"
echo "   - Ollama: ollama list"
echo ""
