#!/bin/bash
# 健康檢查 API
# 輸出 JSON 格式的服務狀態

echo "Content-Type: application/json"
echo "Access-Control-Allow-Origin: *"
echo "Cache-Control: no-cache, no-store, must-revalidate"
echo ""

check_service() {
    local name=$1
    local url=$2
    local start_time=$(date +%s%N)

    local response=$(curl -s -o /dev/null -w "%{http_code}" --connect-timeout 3 --max-time 5 "$url" 2>/dev/null)

    local end_time=$(date +%s%N)
    local response_time=$(( (end_time - start_time) / 1000000 ))

    if [[ "$response" == "200" ]] || [[ "$response" == "302" ]] || [[ "$response" == "401" ]]; then
        echo "\"$name\": {\"status\": \"online\", \"code\": $response, \"responseTime\": $response_time}"
    else
        echo "\"$name\": {\"status\": \"offline\", \"code\": $response, \"responseTime\": $response_time}"
    fi
}

echo '{"services": {'

# 核心服務
check_service "momo-uat" "https://mo.wooo.work/health"
echo ","
check_service "momo-gcp" "https://momo.wooo.work/health"
echo ","

# 開發工具
check_service "gitlab" "http://127.0.0.1:8929/"
echo ","
check_service "registry" "http://127.0.0.1:5002/v2/"
echo ","
check_service "n8n" "http://127.0.0.1:5678/"
echo ","

# 監控服務
check_service "grafana" "http://127.0.0.1:30030/"
echo ","
check_service "prometheus" "http://10.43.25.78:9090/-/healthy"
echo ","
check_service "alertmanager" "http://10.43.79.187:9093/-/healthy"
echo ","

# BI 平台
check_service "superset" "http://127.0.0.1:8088/health"
echo ","
check_service "metabase" "http://127.0.0.1:3030/api/health"

echo '},'
echo "\"timestamp\": \"$(date -Iseconds)\""
echo '}'
