#!/bin/bash
set -e

echo "🚀 Starting Normogen Backend Development Environment..."
cd "$(dirname "$0")"

# Build and start containers
echo "📦 Building and starting containers..."
docker-compose -f docker-compose.dev.yml up --build -d

# Wait for MongoDB to be healthy
echo "⏳ Waiting for MongoDB to be healthy..."
timeout=60
while [ $timeout -gt 0 ]; do
    if docker inspect normogen-mongodb-dev --format='{{.State.Health.Status}}' | grep -q "healthy"; then
        echo "✅ MongoDB is healthy!"
        break
    fi
    sleep 2
    timeout=$((timeout - 2))
done

if [ $timeout -eq 0 ]; then
    echo "❌ MongoDB health check timeout"
    exit 1
fi

# Wait for backend to be ready
echo "⏳ Waiting for backend to start..."
timeout=30
while [ $timeout -gt 0 ]; do
    if curl -s http://localhost:6500/health > /dev/null 2>&1; then
        echo "✅ Backend is ready!"
        break
    fi
    sleep 2
    timeout=$((timeout - 2))
done

if [ $timeout -eq 0 ]; then
    echo "⚠️  Backend may still be starting..."
fi

echo ""
echo "🎉 Development environment is ready!"
echo ""
echo "📊 Services:"
docker-compose -f docker-compose.dev.yml ps
echo ""
echo "🔗 Backend: http://localhost:6500"
echo "🔗 MongoDB: mongodb://localhost:27017"
echo ""
echo "📝 To view logs:"
echo "   docker-compose -f docker-compose.dev.yml logs -f"
echo ""
echo "🛑 To stop:"
echo "   ./stop-dev.sh"
