#!/bin/bash
set -e

echo "🚀 Starting CuCu Note Backend..."

# Wait for MongoDB to be ready
if [ -n "$MONGODB_URI" ]; then
    echo "⏳ Waiting for MongoDB..."
    until python -c "import motor.motor_asyncio; import asyncio; asyncio.run(motor.motor_asyncio.AsyncIOMotorClient('$MONGODB_URI').admin.command('ping'))" 2>/dev/null; do
        echo "MongoDB is unavailable - sleeping"
        sleep 2
    done
    echo "✅ MongoDB is ready!"
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)
echo "📊 Setting up database indexes..."
python -c "
import asyncio
from common.mongo_client import mongodb_client

async def setup():
    await mongodb_client.connect()
    print('✅ Database indexes ready')

asyncio.run(setup())
" || echo "⚠️  Could not set up indexes (may already exist)"

# Start the server
echo "🌟 Starting Gunicorn server..."
exec gunicorn \
    --workers 4 \
    --worker-class uvicorn.workers.UvicornWorker \
    --bind 0.0.0.0:5000 \
    --timeout 120 \
    --access-logfile - \
    --error-logfile - \
    --log-level info \
    server:app
