#!/usr/bin/env bash
# 00_health.sh — GOLAKE-001 + GOLAKE-002.
# Verifies that gateway and each backing service answer GET /health
# with 200 and a body that includes the service name. Canonical case
# shape — copy this file when adding new cases.

set -uo pipefail
SCRIPT_DIR="$(cd "$(dirname "${BASH_SOURCE[0]}")" && pwd)"
# shellcheck source=../lib/env.sh
source "${SCRIPT_DIR}/../lib/env.sh"
# shellcheck source=../lib/http.sh
source "${SCRIPT_DIR}/../lib/http.sh"
# shellcheck source=../lib/assert.sh
source "${SCRIPT_DIR}/../lib/assert.sh"

CASE_ID="GOLAKE-001-002"
CASE_NAME="health endpoints respond"
CASE_TYPE="contract"

# Allow run_proof.sh to read metadata without executing.
if [ "${1:-}" = "--metadata-only" ]; then return 0 2>/dev/null || exit 0; fi

# Each row: <name> <port>. Service name in /health body must match.
SERVICES=(
    "gateway:3110"
    "storaged:3211"
    "catalogd:3212"
    "ingestd:3213"
    "queryd:3214"
    "vectord:3215"
    "embedd:3216"
)

for spec in "${SERVICES[@]}"; do
    name="${spec%:*}"
    port="${spec#*:}"
    probe="${name}_health"

    # Probe — captures status, body, latency to raw/http/<case>/<probe>.json
    proof_get "$CASE_ID" "$probe" "http://127.0.0.1:${port}/health" >/dev/null

    status=$(proof_status_of "$CASE_ID" "$probe")
    body=$(proof_body_of   "$CASE_ID" "$probe")
    latency=$(proof_latency_of "$CASE_ID" "$probe")

    proof_assert_eq "$CASE_ID" "${name} /health → 200" "200" "$status"
    proof_assert_contains "$CASE_ID" "${name} body identifies service" "$name" "$body"
    # Latency budget — generous so we don't get spurious failures from
    # cold-start or system jitter; tighten if a real budget emerges.
    proof_assert_lt "$CASE_ID" "${name} health latency < 500ms" "$latency" "500"
done
