#!/bin/bash
# Healthcheck for kb-query (FastAPI search API -> kb-postgres + Ollama @ SOLARIA)

SCRIPT_DIR="$(cd "$(dirname "${BASH_SOURCE[0]}")" && pwd)"

# The port is bound to the LAN interface only, so localhost won't answer.
# Read the bind IP from .env (same file compose uses for the port mapping).
if [ -f "$SCRIPT_DIR/.env" ]; then
    # shellcheck disable=SC1091
    source "$SCRIPT_DIR/.env"
fi
BIND_IP="${LAN_BIND_IP:-127.0.0.1}"

# Container must be running
if ! docker ps --filter "name=kb-query" --filter "status=running" | grep -qw "kb-query"; then
    echo "[FAIL] kb-query container is not running"
    exit 1
fi

# Health endpoint must answer with the ok marker
if ! curl -sf "http://${BIND_IP}:8230/healthz" | grep -q '"status":"ok"\|"status": "ok"'; then
    echo "[FAIL] kb-query is not responding on ${BIND_IP}:8230"
    exit 1
fi

echo "[OK] kb-query is healthy"
exit 0
