#!/bin/bash
# Healthcheck for llm-gateway (FastAPI router -> Ollama @ SOLARIA)

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

# The port is bound to the Tailscale 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="${TAILSCALE_BIND_IP:-127.0.0.1}"

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

# Health endpoint must answer with the gateway-ok marker
if ! curl -sf "http://${BIND_IP}:8080/" | grep -q "gateway ok"; then
    echo "[FAIL] llm-gateway is not responding on ${BIND_IP}:8080"
    exit 1
fi

echo "[OK] llm-gateway is healthy"
exit 0
