#!/usr/bin/env bash
set -euo pipefail

cd /home/worsch/state-hub

API_BASE="${API_BASE:-http://127.0.0.1:8000}"
HEALTH_URL="${API_BASE%/}/state/health"
LOG_FILE="${STATE_HUB_API_LOG:-/tmp/state-hub-api-for-codex.log}"

api_healthy() {
  curl -sf "$HEALTH_URL" >/dev/null
}

if ! api_healthy; then
  nohup make api >"$LOG_FILE" 2>&1 &
  for _ in $(seq 1 45); do
    api_healthy && break
    sleep 1
  done
fi

if ! api_healthy; then
  echo "state-hub API is not healthy at $HEALTH_URL; see $LOG_FILE" >&2
  exit 1
fi

export API_BASE
export MCP_TRANSPORT=stdio
exec uv run python mcp_server/server.py
