#!/bin/bash
# =========================================================
# BreakPilot — Health Check for All Projects
# =========================================================

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

check_service() {
    local name=$1
    local url=$2
    local timeout=${3:-5}

    if curl -sf --max-time $timeout "$url" > /dev/null 2>&1; then
        echo -e "  ${GREEN}✓${NC} $name"
        return 0
    else
        echo -e "  ${RED}✗${NC} $name ($url)"
        return 1
    fi
}

echo "========================================="
echo " BreakPilot Health Check"
echo "========================================="

TOTAL=0
OK=0

echo ""
echo "CORE Infrastructure:"
for svc in \
    "Health Aggregator|http://127.0.0.1:8099/health" \
    "PostgreSQL|http://127.0.0.1:8099/health" \
    "Backend Core|http://127.0.0.1:8000/health|10" \
    "Embedding Service|http://127.0.0.1:8087/health|10" \
    "RAG Service|http://127.0.0.1:8097/health|10" \
    "Consent Service|http://127.0.0.1:8081/health|5" \
    "Gitea|http://127.0.0.1:3003/api/healthz" \
    "Mailpit|http://127.0.0.1:8025/" \
; do
    IFS='|' read -r name url timeout <<< "$svc"
    TOTAL=$((TOTAL + 1))
    if check_service "$name" "$url" "$timeout"; then
        OK=$((OK + 1))
    fi
done

echo ""
echo "LEHRER Platform:"
for svc in \
    "Studio v2|https://127.0.0.1/|5" \
    "Admin Lehrer|https://127.0.0.1:3002/|5" \
    "Backend Lehrer|https://127.0.0.1:8001/health|10" \
    "Klausur Service|https://127.0.0.1:8086/health|10" \
    "Voice Service|https://127.0.0.1:8091/health|5" \
    "Website|https://127.0.0.1:3000/|5" \
; do
    IFS='|' read -r name url timeout <<< "$svc"
    TOTAL=$((TOTAL + 1))
    if check_service "$name" "$url" "$timeout"; then
        OK=$((OK + 1))
    fi
done

echo ""
echo "COMPLIANCE Platform:"
for svc in \
    "Admin Compliance|https://127.0.0.1:3007/|5" \
    "Backend Compliance|https://127.0.0.1:8002/health|10" \
    "AI Compliance SDK|https://127.0.0.1:8093/health|10" \
    "Developer Portal|https://127.0.0.1:3006/|5" \
; do
    IFS='|' read -r name url timeout <<< "$svc"
    TOTAL=$((TOTAL + 1))
    if check_service "$name" "$url" "$timeout"; then
        OK=$((OK + 1))
    fi
done

echo ""
echo "========================================="
echo -e " Result: ${OK}/${TOTAL} services healthy"
if [ $OK -eq $TOTAL ]; then
    echo -e " ${GREEN}All services are up!${NC}"
else
    echo -e " ${RED}$((TOTAL - OK)) services are down${NC}"
fi
echo "========================================="
