#!/bin/bash

# System Health Check Script
# Проверяет все компоненты Women's Safety Backend

set -e

# Colors
RED='\033[0;31m'
GREEN='\033[0;32m'
YELLOW='\033[1;33m'
BLUE='\033[0;34m'
NC='\033[0m'

echo -e "${BLUE}🏥 Women's Safety Backend - Health Check${NC}"
echo "========================================="

# Check if services are running
echo -e "${YELLOW}🔍 Checking service processes...${NC}"

SERVICES=("user_service" "emergency_service" "location_service" "calendar_service" "notification_service" "api_gateway")
PORTS=(8001 8002 8003 8004 8005 8000)

for i in "${!SERVICES[@]}"; do
    service="${SERVICES[$i]}"
    port="${PORTS[$i]}"
    
    if lsof -i :$port > /dev/null 2>&1; then
        echo -e "${GREEN}✅ $service (port $port) - Running${NC}"
    else
        echo -e "${RED}❌ $service (port $port) - Not running${NC}"
    fi
done

echo
echo -e "${YELLOW}🌐 Testing API endpoints...${NC}"

# Test health endpoints
test_endpoint() {
    local url=$1
    local name=$2
    
    if curl -s -f "$url" > /dev/null 2>&1; then
        echo -e "${GREEN}✅ $name - Healthy${NC}"
    else
        echo -e "${RED}❌ $name - Failed${NC}"
    fi
}

test_endpoint "http://localhost:8000/health" "API Gateway"
test_endpoint "http://localhost:8001/api/v1/health" "User Service"
test_endpoint "http://localhost:8002/api/v1/health" "Emergency Service" 
test_endpoint "http://localhost:8003/api/v1/health" "Location Service"
test_endpoint "http://localhost:8004/api/v1/health" "Calendar Service"
test_endpoint "http://localhost:8005/api/v1/health" "Notification Service"

echo
echo -e "${YELLOW}💾 Checking database connection...${NC}"

if curl -s http://localhost:8001/api/v1/health | grep -q "database.*ok" > /dev/null 2>&1; then
    echo -e "${GREEN}✅ Database - Connected${NC}"
else
    echo -e "${RED}❌ Database - Connection failed${NC}"
fi

echo
echo -e "${YELLOW}🚀 Quick API test...${NC}"

# Test user registration
TEST_EMAIL="healthcheck_$(date +%s)@example.com"
REGISTRATION_RESULT=$(curl -s -X POST "http://localhost:8001/api/v1/register" \
    -H "Content-Type: application/json" \
    -d "{\"email\":\"$TEST_EMAIL\",\"password\":\"test123\",\"first_name\":\"Health\",\"last_name\":\"Check\",\"phone\":\"+1234567890\"}" \
    -w "%{http_code}")

if [[ $REGISTRATION_RESULT == *"201"* ]]; then
    echo -e "${GREEN}✅ User Registration - Working${NC}"
else
    echo -e "${RED}❌ User Registration - Failed${NC}"
fi

echo
echo -e "${BLUE}📊 System Resources:${NC}"
echo -e "CPU Usage: $(top -bn1 | grep "Cpu(s)" | awk '{print $2}' | awk -F'%' '{print $1}')%"
echo -e "Memory: $(free -h | grep Mem | awk '{print $3"/"$2}')"
echo -e "Disk: $(df -h / | tail -1 | awk '{print $3"/"$2" ("$5" used)"}')"

echo
echo -e "${GREEN}🎉 Health check completed!${NC}"