#!/bin/bash

echo "🚀 Starting Women Safety App Services - Simple Mode"

# Clean up any existing processes
echo "🧹 Cleaning up existing processes..."
pkill -f uvicorn 2>/dev/null || true
sleep 2

# Set environment
export PYTHONPATH=$PWD:$PYTHONPATH
source .venv/bin/activate

# Test database connection
echo "🔍 Testing database connection..."
python -c "
import asyncio
import asyncpg
from shared.config import settings

async def test_db():
    try:
        conn = await asyncpg.connect(settings.DATABASE_URL.replace('+asyncpg', ''))
        print('✅ Database connection successful!')
        await conn.close()
    except Exception as e:
        print(f'❌ Database connection failed: {e}')
        exit(1)

asyncio.run(test_db())
"

echo "🎯 Starting services one by one..."

# Start User Service
echo "Starting User Service on port 8001..."
cd services/user_service
python -m uvicorn main:app --host 127.0.0.1 --port 8001 &
USER_PID=$!
cd ../..
sleep 3

# Test User Service
echo "Testing User Service..."
if python -c "import httpx; import sys; sys.exit(0 if httpx.get('http://localhost:8001/health').status_code == 200 else 1)" 2>/dev/null; then
    echo "✅ User Service is running"
else
    echo "❌ User Service failed to start"
    kill $USER_PID 2>/dev/null
    exit 1
fi

echo ""
echo "🎉 Services started successfully!"
echo "📋 Active Services:"
echo "   👤 User Service: http://localhost:8001"
echo "   📖 User Service Docs: http://localhost:8001/docs"
echo ""
echo "Press Ctrl+C to stop the service"

# Wait for interrupt
trap "echo 'Stopping services...'; kill $USER_PID 2>/dev/null; echo 'Done'; exit 0" INT

# Keep script running
while true; do
    sleep 10
    # Check if user service is still running
    if ! kill -0 $USER_PID 2>/dev/null; then
        echo "User service stopped unexpectedly"
        exit 1
    fi
done