#!/bin/sh
set -e

echo "🚀 Starting CuCu Note Backend..."

# Install runtime deps not in base image (workaround until requirements.txt is fixed)
pip install --quiet --no-cache-dir meilisearch 2>/dev/null || echo "⚠️  Could not install meilisearch SDK"

# 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 Uvicorn server..."

exec uvicorn server:app \
    --host 0.0.0.0 \
    --port 5000 \
    --log-level info
