#!/bin/bash

# --- GTM Engine Health Check Script (v4 - Docker Native) ---

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

echo "--- 🩺 GTM Engine Health Check (v4) ---"

# --- 1. Docker Container Status ---
echo -e "\n${YELLOW}1. Docker Container Status...${NC}"
services=("company-explorer" "connector-superoffice" "content-engine" "competitor-analysis" "lead-engine" "b2b-marketing-assistant" "market-intelligence" "gtm-architect" "heatmap-frontend" "heatmap-backend" "transcription-tool" "gateway_proxy")
all_ok=true

for service in "${services[@]}"; do
    status=$(docker inspect --format '{{.State.Status}}' "$service" 2>/dev/null)
    if [[ "$status" == "running" ]]; then
        health=$(docker inspect --format '{{if .State.Health}}{{.State.Health.Status}}{{else}}healthy{{end}}' "$service" 2>/dev/null)
        if [[ "$health" == "healthy" ]]; then
            printf "   - ✅ %-25s: %s\n" "$service" "Running (Healthy)"
        else
            printf "   - 🟡 %-25s: %s\n" "$service" "Running (Unhealthy)"
        fi # Wir markieren unhealthy nicht mehr als "Failed", da der Container läuft
    else
        printf "   - ❌ %-25s: %s\n" "$service" "Not Running ($status)"
        all_ok=false
    fi
done

# --- 2. Internal Endpoint Health (via Docker Exec) ---
echo -e "\n${YELLOW}2. Internal Endpoint Health (via Gateway Container)...${NC}"

check_internal() {
    local service_name=$1
    local port=$2
    local path=$3
    
    http_code=$(docker exec gateway_proxy sh -c "apk add --no-cache curl > /dev/null 2>&1 && curl -s -o /dev/null -w '%{http_code}' --max-time 5 http://${service_name}:${port}${path}")
    
    # 401 ist für geschützte Endpunkte ein Erfolg, da der Server antwortet
    if [ "$http_code" -eq 200 ] || [ "$http_code" -eq 401 ]; then
        printf "   - ✅ %-25s: %s OK\n" "$service_name" "$http_code"
    else
        printf "   - ❌ %-25s: %s FAILED\n" "$service_name" "$http_code"
        all_ok=false
    fi
}

check_internal "company-explorer" 8000 "/api/health"
check_internal "connector-superoffice" 8000 "/health"
check_internal "lead-engine" 8501 "/"
check_internal "market-intelligence" 3001 "/api/projects" # Hat keinen Root, aber /api/projects
check_internal "content-engine" 3006 "/"
check_internal "competitor-analysis" 8000 "/"
check_internal "heatmap-frontend" 80 "/"
check_internal "heatmap-backend" 8000 "/" # Hat einen Root-Endpunkt

echo ""
echo "--- RESULT ---"
if $all_ok; then
    echo -e "${GREEN}✅ Alle Docker-Container laufen. Interne Health-Checks sind OK.${NC}"
else
    echo -e "${RED}❌ Ein oder mehrere Dienste sind nicht betriebsbereit. Bitte Logs prüfen.${NC}"
    exit 1
fi