#!/bin/bash

# Women Safety App - Start All Services Script

# Colors for output
RED='\033[0;31m'
GREEN='\033[0;32m'
YELLOW='\033[1;33m'
NC='\033[0m' # No Color

echo -e "${GREEN}🚀 Starting Women Safety App Services${NC}"

# Check if virtual environment exists
if [ ! -d "venv" ]; then
    echo -e "${YELLOW}⚠️  Virtual environment not found. Creating...${NC}"
    python3 -m venv venv
    echo -e "${GREEN}✅ Virtual environment created${NC}"
fi

# Activate virtual environment
echo "🔧 Activating virtual environment..."
if [ -f "venv/bin/activate" ]; then
    source venv/bin/activate
else
    echo "⚠️  Virtual environment not found. Creating..."
    python3 -m venv venv
    source venv/bin/activate
fi

# Install dependencies
echo -e "${YELLOW}📦 Installing dependencies...${NC}"
pip install -r requirements.txt

# Create .env file if it doesn't exist
if [ ! -f ".env" ]; then
    echo -e "${YELLOW}⚠️  .env file not found. Creating from example...${NC}"
    cp .env.example .env
    
    # Update .env with external PostgreSQL configuration
    sed -i 's|postgresql+asyncpg://admin:password@localhost:5432/women_safety|postgresql+asyncpg://admin:password@192.168.0.102:5432/women_safety|g' .env
    echo -e "${GREEN}✅ .env file created and updated with external PostgreSQL configuration.${NC}"
else
    echo -e "${YELLOW}⚠️  Updating .env with external PostgreSQL configuration...${NC}"
    sed -i 's|postgresql+asyncpg://admin:password@localhost:5432/women_safety|postgresql+asyncpg://admin:password@192.168.0.102:5432/women_safety|g' .env
    echo -e "${GREEN}✅ .env file updated with external PostgreSQL configuration.${NC}"
fi

# Start infrastructure services
echo "🐳 Starting infrastructure services..."
docker compose up -d redis kafka zookeeper

# Wait for services to be ready
echo -e "${YELLOW}⏳ Waiting for services to be ready...${NC}"
sleep 10

# Test PostgreSQL connection
echo -e "${YELLOW}🔌 Testing PostgreSQL connection (192.168.0.102:5432)...${NC}"
if pg_isready -h 192.168.0.102 -p 5432 -U admin; then
    echo -e "${GREEN}✅ PostgreSQL connection successful!${NC}"
else
    echo -e "${YELLOW}⚠️ Cannot connect to PostgreSQL. Continuing anyway...${NC}"
    echo -e "${YELLOW}⚠️ Some features may not work correctly.${NC}"
fi

# Run database migrations
echo -e "${YELLOW}🗃️  Running database migrations...${NC}"
alembic upgrade head

# Start microservices in background
echo -e "${GREEN}🎯 Starting microservices...${NC}"

echo -e "${YELLOW}Starting User Service (port 8001)...${NC}"
python -m uvicorn services.user_service.main:app --port 8001 &
USER_PID=$!

echo -e "${YELLOW}Starting Emergency Service (port 8002)...${NC}"
python -m uvicorn services.emergency_service.main:app --port 8002 &
EMERGENCY_PID=$!

echo -e "${YELLOW}Starting Location Service (port 8003)...${NC}"
python -m uvicorn services.location_service.main:app --port 8003 &
LOCATION_PID=$!

echo -e "${YELLOW}Starting Calendar Service (port 8004)...${NC}"
python -m uvicorn services.calendar_service.main:app --port 8004 &
CALENDAR_PID=$!

echo -e "${YELLOW}Starting Notification Service (port 8005)...${NC}"
python -m uvicorn services.notification_service.main:app --port 8005 &
NOTIFICATION_PID=$!

echo -e "${YELLOW}Starting Nutrition Service (port 8006)...${NC}"
python -m uvicorn services.nutrition_service.main:app --port 8006 &
NUTRITION_PID=$!

# Wait a bit for services to start
sleep 5

echo -e "${YELLOW}Starting API Gateway (port 8000)...${NC}"
python -m uvicorn services.api_gateway.main:app --port 8000 &
GATEWAY_PID=$!

# Store PIDs for cleanup
echo $USER_PID > user_service.pid
echo $EMERGENCY_PID > emergency_service.pid
echo $LOCATION_PID > location_service.pid
echo $CALENDAR_PID > calendar_service.pid
echo $NOTIFICATION_PID > notification_service.pid
echo $NUTRITION_PID > nutrition_service.pid
echo $GATEWAY_PID > api_gateway.pid

echo -e "${GREEN}🎉 All services started successfully!${NC}"
echo -e "${GREEN}📋 Services Overview:${NC}"
echo -e "   📡 API Gateway: http://localhost:8000"
echo -e "   👤 User Service: http://localhost:8001"
echo -e "   🚨 Emergency Service: http://localhost:8002"
echo -e "   📍 Location Service: http://localhost:8003"
echo -e "   📅 Calendar Service: http://localhost:8004"
echo -e "   🔔 Notification Service: http://localhost:8005"
echo -e "   🍎 Nutrition Service: http://localhost:8006"
echo -e "${GREEN}📖 API Documentation: http://localhost:8000/docs${NC}"

# Keep script running and show logs
echo -e "${YELLOW}📊 Monitoring services... Press Ctrl+C to stop all services${NC}"

# Trap Ctrl+C and cleanup
cleanup() {
    echo -e "\n${YELLOW}🛑 Shutting down services...${NC}"
    
    # Kill all background processes
    if [ -f "user_service.pid" ]; then kill "$(cat user_service.pid)" 2>/dev/null && rm user_service.pid; fi
    if [ -f "emergency_service.pid" ]; then kill "$(cat emergency_service.pid)" 2>/dev/null && rm emergency_service.pid; fi
    if [ -f "location_service.pid" ]; then kill "$(cat location_service.pid)" 2>/dev/null && rm location_service.pid; fi
    if [ -f "calendar_service.pid" ]; then kill "$(cat calendar_service.pid)" 2>/dev/null && rm calendar_service.pid; fi
    if [ -f "notification_service.pid" ]; then kill "$(cat notification_service.pid)" 2>/dev/null && rm notification_service.pid; fi
    if [ -f "nutrition_service.pid" ]; then kill "$(cat nutrition_service.pid)" 2>/dev/null && rm nutrition_service.pid; fi
    if [ -f "api_gateway.pid" ]; then kill "$(cat api_gateway.pid)" 2>/dev/null && rm api_gateway.pid; fi
    
    echo -e "${GREEN}✅ All services stopped${NC}"
    exit 0
}

trap cleanup INT

# Wait for any service to exit
wait