#!/bin/bash
# Quick start script for Soprano + RVC Docker services

set -e

cd "$(dirname "$0")"

echo "🎤 Starting Soprano + RVC Services"
echo "===================================="
echo ""

# Check if containers exist
if ! docker-compose ps | grep -q "soprano"; then
    echo "⚠️  Containers not built yet. Building now..."
    ./build_docker.sh
fi

# Start services
echo "🚀 Starting services..."
docker-compose up -d

echo ""
echo "⏳ Waiting for services to be ready..."
echo "   (This may take 60-120 seconds for model loading)"
echo ""

# Wait for health checks
MAX_WAIT=180
WAITED=0

while [ $WAITED -lt $MAX_WAIT ]; do
    if curl -f -s http://localhost:8765/health > /dev/null 2>&1; then
        echo ""
        echo "✅ Services are ready!"
        
        # Show health status
        echo ""
        echo "📊 Health Status:"
        curl -s http://localhost:8765/health | python3 -m json.tool || echo "  (Health check passed but response not JSON)"
        
        echo ""
        echo "🎵 Service is ready to use!"
        echo ""
        echo "Try it out:"
        echo "  curl -X POST http://localhost:8765/api/speak \\"
        echo "       -H 'Content-Type: application/json' \\"
        echo "       -d '{\"text\": \"Hello, I am Miku!\"}' \\"
        echo "       -o test.wav"
        echo ""
        echo "View logs:"
        echo "  docker-compose logs -f"
        echo ""
        echo "Stop services:"
        echo "  docker-compose down"
        exit 0
    fi
    
    echo -n "."
    sleep 5
    WAITED=$((WAITED + 5))
done

echo ""
echo "❌ Services did not become ready within ${MAX_WAIT} seconds"
echo ""
echo "Check logs for errors:"
echo "  docker-compose logs soprano"
echo "  docker-compose logs rvc"
echo ""
echo "Check container status:"
echo "  docker-compose ps"

exit 1
