#!/bin/bash
# ================================================
# Math Platform - Health Check Script
# ================================================

set -e

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

echo -e "${BLUE}============================================${NC}"
echo -e "${BLUE}Math Platform - Health Check${NC}"
echo -e "${BLUE}============================================${NC}"

# Function to check service health
check_service() {
    local service_name=$1
    local url=$2
    local expected_code=${3:-200}

    echo -n "Checking $service_name... "

    local response=$(curl -s -o /dev/null -w "%{http_code}" "$url" 2>/dev/null || echo "000")

    if [ "$response" = "$expected_code" ]; then
        echo -e "${GREEN}OK${NC} (HTTP $response)"
        return 0
    else
        echo -e "${RED}FAILED${NC} (HTTP $response, expected $expected_code)"
        return 1
    fi
}

# Function to check Docker container
check_container() {
    local container_name=$1

    echo -n "Checking container $container_name... "

    if docker ps | grep -q "$container_name"; then
        local status=$(docker inspect --format='{{.State.Health.Status}}' "$container_name" 2>/dev/null || echo "no-health-check")

        if [ "$status" = "healthy" ] || [ "$status" = "no-health-check" ]; then
            echo -e "${GREEN}RUNNING${NC} ($status)"
            return 0
        else
            echo -e "${YELLOW}UNHEALTHY${NC} ($status)"
            return 1
        fi
    else
        echo -e "${RED}NOT RUNNING${NC}"
        return 1
    fi
}

# Function to check disk space
check_disk_space() {
    echo -n "Checking disk space... "

    local usage=$(df -h / | awk 'NR==2 {print $5}' | sed 's/%//')

    if [ "$usage" -lt 80 ]; then
        echo -e "${GREEN}OK${NC} (${usage}% used)"
        return 0
    elif [ "$usage" -lt 90 ]; then
        echo -e "${YELLOW}WARNING${NC} (${usage}% used)"
        return 1
    else
        echo -e "${RED}CRITICAL${NC} (${usage}% used)"
        return 1
    fi
}

# Function to check memory usage
check_memory() {
    echo -n "Checking memory usage... "

    local mem_usage=$(free | awk 'NR==2{printf "%.0f", $3*100/$2 }')

    if [ "$mem_usage" -lt 80 ]; then
        echo -e "${GREEN}OK${NC} (${mem_usage}% used)"
        return 0
    elif [ "$mem_usage" -lt 90 ]; then
        echo -e "${YELLOW}WARNING${NC} (${mem_usage}% used)"
        return 1
    else
        echo -e "${RED}CRITICAL${NC} (${mem_usage}% used)"
        return 1
    fi
}

# Function to check Docker resources
check_docker_resources() {
    echo -n "Checking Docker resources... "

    local available=$(docker info 2>/dev/null | grep "CPUs" | head -1 | awk '{print $2}')

    if [ -n "$available" ]; then
        echo -e "${GREEN}OK${NC} ($available CPUs available)"
        return 0
    else
        echo -e "${RED}FAILED${NC} (Docker not available)"
        return 1
    fi
}

# Main health check
main() {
    local failed=0

    echo -e "\n${BLUE}Container Status${NC}"
    echo "----------------------------------------"

    check_container "math-postgres" || failed=$((failed + 1))
    check_container "math-redis" || failed=$((failed + 1))
    check_container "math-backend" || failed=$((failed + 1))
    check_container "math-frontend" || failed=$((failed + 1))
    check_container "math-nginx" || failed=$((failed + 1))

    echo -e "\n${BLUE}Service Health${NC}"
    echo "----------------------------------------"

    check_service "Backend API" "http://localhost:3001/health" "200" || failed=$((failed + 1))
    check_service "Frontend" "http://localhost:3000" "200" || failed=$((failed + 1))
    check_service "Nginx" "http://localhost/" "200" || failed=$((failed + 1))

    echo -e "\n${BLUE}System Resources${NC}"
    echo "----------------------------------------"

    check_disk_space || failed=$((failed + 1))
    check_memory || failed=$((failed + 1))
    check_docker_resources || failed=$((failed + 1))

    echo -e "\n${BLUE}Database Connection${NC}"
    echo "----------------------------------------"

    echo -n "Checking PostgreSQL connection... "
    if docker exec math-postgres pg_isready -U mathuser -d mathdb &>/dev/null; then
        echo -e "${GREEN}OK${NC}"
    else
        echo -e "${RED}FAILED${NC}"
        failed=$((failed + 1))
    fi

    echo -n "Checking Redis connection... "
    if docker exec math-redis redis-cli -a "${REDIS_PASSWORD:-redis_secure_password_2024}" ping &>/dev/null; then
        echo -e "${GREEN}OK${NC}"
    else
        echo -e "${RED}FAILED${NC}"
        failed=$((failed + 1))
    fi

    # Summary
    echo -e "\n${BLUE}============================================${NC}"
    echo -e "${BLUE}Summary${NC}"
    echo -e "${BLUE}============================================${NC}"

    if [ $failed -eq 0 ]; then
        echo -e "${GREEN}All checks passed!${NC}\n"
        exit 0
    else
        echo -e "${RED}$failed check(s) failed!${NC}\n"
        exit 1
    fi
}

# Run main function
main
