#!/bin/bash

# Women's Safety App - No Docker Startup Script
echo "🚀 Starting Women Safety App Services (No Docker Mode)"

# Set Python path
export PYTHONPATH=$PWD:$PYTHONPATH

echo "🔧 Activating virtual environment..."
if [ -f ".venv/bin/activate" ]; then
    source .venv/bin/activate
else
    echo "❌ Virtual environment not found at .venv/"
    exit 1
fi

echo "📦 Installing dependencies..."
pip install -r requirements.txt

echo "🗃️  Checking 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())
"

# Function to kill processes by port
kill_port() {
    local port=$1
    echo "🛑 Stopping service on port $port..."
    lsof -ti:$port | xargs kill -9 2>/dev/null || true
}

# Function to cleanup on exit
cleanup() {
    echo "🛑 Shutting down services..."
    kill_port 8000
    kill_port 8001
    kill_port 8002
    kill_port 8003
    kill_port 8004
    kill_port 8005
    kill_port 8006
    echo "✅ All services stopped"
    exit 0
}

# Trap cleanup on script exit
trap cleanup EXIT

# Clean up any existing processes
echo "🧹 Cleaning up existing processes..."
kill_port 8000
kill_port 8001
kill_port 8002
kill_port 8003
kill_port 8004
kill_port 8005
kill_port 8006

echo "⏳ Waiting for ports to be freed..."
sleep 3

echo "🎯 Starting microservices..."

export PYTHONPATH="${PWD}:${PYTHONPATH}"

# Start User Service
echo "Starting User Service (port 8001)..."
(cd services/user_service && PYTHONPATH="${PWD}/../..:${PYTHONPATH}" python -m uvicorn main:app --host 0.0.0.0 --port 8001 --reload) &

# Start Emergency Service  
echo "Starting Emergency Service (port 8002)..."
(cd services/emergency_service && PYTHONPATH="${PWD}/../..:${PYTHONPATH}" python -m uvicorn main:app --host 0.0.0.0 --port 8002 --reload) &

# Start Location Service
echo "Starting Location Service (port 8003)..."
(cd services/location_service && PYTHONPATH="${PWD}/../..:${PYTHONPATH}" python -m uvicorn main:app --host 0.0.0.0 --port 8003 --reload) &

# Start Calendar Service
echo "Starting Calendar Service (port 8004)..."
(cd services/calendar_service && PYTHONPATH="${PWD}/../..:${PYTHONPATH}" python -m uvicorn main:app --host 0.0.0.0 --port 8004 --reload) &

# Start Notification Service
echo "Starting Notification Service (port 8005)..."
(cd services/notification_service && PYTHONPATH="${PWD}/../..:${PYTHONPATH}" python -m uvicorn main:app --host 0.0.0.0 --port 8005 --reload) &

# Start Nutrition Service
echo "Starting Nutrition Service (port 8006)..."
(cd services/nutrition_service && PYTHONPATH="${PWD}/../..:${PYTHONPATH}" python -m uvicorn main:app --host 0.0.0.0 --port 8006 --reload) &

# Start API Gateway
echo "Starting API Gateway (port 8000)..."
(cd services/api_gateway && PYTHONPATH="${PWD}/../..:${PYTHONPATH}" python -m uvicorn main:app --host 0.0.0.0 --port 8000 --reload) &

# Wait for services to start
echo "⏳ Waiting for services to start..."
sleep 10

echo "🎉 All services started successfully!"
echo "📋 Services Overview:"
echo "   📡 API Gateway: http://localhost:8000"
echo "   👤 User Service: http://localhost:8001"
echo "   🚨 Emergency Service: http://localhost:8002"
echo "   📍 Location Service: http://localhost:8003"
echo "   📅 Calendar Service: http://localhost:8004"
echo "   🔔 Notification Service: http://localhost:8005"
echo "   🍎 Nutrition Service: http://localhost:8006"
echo ""
echo "📖 API Documentation: http://localhost:8000/docs"
echo "📊 Monitoring services... Press Ctrl+C to stop all services"

# Monitor services
while true; do
    sleep 30
    # Check if services are still running
    if ! curl -s http://localhost:8000/health > /dev/null 2>&1; then
        echo "⚠️  API Gateway seems to be down, restarting..."
        (cd services/api_gateway && python -m uvicorn main:app --host 0.0.0.0 --port 8000 --reload) &
    fi
    
    if ! curl -s http://localhost:8001/health > /dev/null 2>&1; then
        echo "⚠️  User Service seems to be down, restarting..."
        (cd services/user_service && python -m uvicorn main:app --host 0.0.0.0 --port 8001 --reload) &
    fi
done

curl -s -X POST "http://localhost:8000/api/v1/auth/register" \
     -H "Content-Type: application/json" \
     -d '{
       "email": "test@example.com",
       "password": "password123",
       "first_name": "Test",
       "last_name": "User"
     }'