#!/bin/bash
# Production startup script for Sharey with Gunicorn
# Usage: ./start_production.sh

set -e

echo "🚀 Starting Sharey in Production Mode with Gunicorn"
echo "=================================================="

# Check if we're in the right directory
if [ ! -f "wsgi.py" ]; then
    echo "❌ Error: wsgi.py not found. Please run this script from the Sharey root directory."
    exit 1
fi

# Check if virtual environment exists
if [ ! -d ".venv" ]; then
    echo "❌ Virtual environment not found. Please run setup first."
    exit 1
fi

# Activate virtual environment
echo "🔌 Activating virtual environment..."
source .venv/bin/activate

# Check if config exists
if [ ! -f "config.json" ]; then
    echo "⚠️  Warning: config.json not found. Creating from example..."
    cp config.json.example config.json
    echo "✏️  Please edit config.json with your settings and run again."
    exit 1
fi

# Create logs directory
mkdir -p logs

# Validate configuration
echo "🔧 Validating configuration..."
python src/config_util.py validate || {
    echo "❌ Configuration validation failed. Please fix your config.json"
    exit 1
}

# Test storage backend
echo "🧪 Testing storage backend..."
python test_storage.py || {
    echo "❌ Storage test failed. Please check your configuration."
    exit 1
}

echo "✅ All checks passed!"
echo ""
echo "🌟 Starting Gunicorn server..."
echo "🌐 Server will be available at: http://0.0.0.0:8866"
echo "📁 Working directory: $(pwd)"
echo "📊 Workers: $(python -c 'import multiprocessing; print(multiprocessing.cpu_count() * 2 + 1)')"
echo "📝 Logs: logs/gunicorn_access.log, logs/gunicorn_error.log"
echo ""
echo "Press Ctrl+C to stop"
echo "=================================================="

# Start Gunicorn
exec gunicorn --config gunicorn.conf.py wsgi:application
