import { useEffect, useState } from "react";
import { GATEWAY } from "./api";

export interface Health {
  gateway: boolean;
  persisted: boolean; // Postgres（兼容旧字段名）
  db: boolean;
  redis: boolean;
  nats: boolean;
  milvus: boolean;
  neo4j: boolean;
}

const DOWN: Health = { gateway: false, persisted: false, db: false, redis: false, nats: false, milvus: false, neo4j: false };

// useHealth 轮询 Gateway /health 聚合端点，回报全部依赖子系统的实时状态。
// gateway/nats/db/redis 由网关本地判定，milvus/neo4j 经 mcp-go health 工具取。
export function useHealth(intervalMs = 4000): Health {
  const [h, setH] = useState<Health>(DOWN);
  useEffect(() => {
    let alive = true;
    const ping = async () => {
      try {
        const res = await fetch(`${GATEWAY}/api/v1/health`);
        const d = (await res.json()) as Partial<Health>;
        if (alive)
          setH({
            gateway: res.ok && Boolean(d.gateway),
            db: Boolean(d.db),
            persisted: Boolean(d.db),
            redis: Boolean(d.redis),
            nats: Boolean(d.nats),
            milvus: Boolean(d.milvus),
            neo4j: Boolean(d.neo4j),
          });
      } catch {
        if (alive) setH(DOWN);
      }
    };
    ping();
    const id = setInterval(ping, intervalMs);
    return () => {
      alive = false;
      clearInterval(id);
    };
  }, [intervalMs]);
  return h;
}
