#!/bin/bash
set -e

echo "🚀 Starting CuCu Note Backend..."

# Try to connect to MongoDB (non-blocking, app will retry on startup)
if [ -n "$MONGODB_URI" ]; then
    echo "⏳ Testing MongoDB connection..."
    if python -c "import motor.motor_asyncio; import asyncio; asyncio.run(motor.motor_asyncio.AsyncIOMotorClient('$MONGODB_URI', serverSelectionTimeoutMS=3000).admin.command('ping'))" 2>/dev/null; then
        echo "✅ MongoDB connection successful!"
    else
        echo "⚠️  MongoDB connection failed. App will start and retry on first request."
        echo "⚠️  Please ensure Network Access in MongoDB Atlas allows your IP (or 0.0.0.0/0 for testing)."
    fi
fi

# Wait for Redis to be ready (if configured)
if [ -n "$REDIS_HOST" ]; then
    echo "⏳ Waiting for Redis..."
    until python -c "import redis; r = redis.Redis(host='$REDIS_HOST', port=${REDIS_PORT:-6379}, decode_responses=True); r.ping()" 2>/dev/null; do
        echo "Redis is unavailable - sleeping"
        sleep 2
    done
    echo "✅ Redis is ready!"
fi

# Run database migrations/indexes (if needed) - skip if MongoDB not available
echo "📊 Setting up database indexes..."
python -c "
import asyncio
import sys
from common.mongo_client import mongodb_client

async def setup():
    try:
        await mongodb_client.connect()
        print('✅ Database indexes ready')
    except Exception as e:
        print(f'⚠️  Could not set up indexes: {e}')
        sys.exit(0)  # Don't fail startup

asyncio.run(setup())
" || echo "⚠️  Could not set up indexes (will retry on first request)"

# Start the server
echo "🌟 Starting Gunicorn server..."

# Allow overriding number of workers via env, default to 1 for simplicity
WORKERS="${GUNICORN_WORKERS:-1}"
echo "🔧 Using Gunicorn workers: $WORKERS"

exec gunicorn \
    --workers "$WORKERS" \
    --worker-class uvicorn.workers.UvicornWorker \
    --bind 0.0.0.0:5000 \
    --timeout 120 \
    --access-logfile - \
    --error-logfile - \
    --log-level info \
    server:app
