import { init_loader, loadConfig } from "../../../../config/loader.js";
import { resolveGatewayLocalClientHost } from "../../../../config/gateway-bind.js";
import { existsSync } from "node:fs";
//#region src/cli/commands/doctor/checks/gateway-health.ts
init_loader();
function resolveGatewayBaseUrl(cfg) {
	return `http://${resolveGatewayLocalClientHost(cfg)}:${cfg.gateway?.port ?? 18790}`;
}
const FETCH_TIMEOUT_MS = 5e3;
async function checkGatewayHealth(ctx) {
	if (!existsSync(ctx.configPath)) return {
		id: "gateway-health",
		label: "Gateway HTTP",
		status: "skip",
		message: "No config file; skipped.",
		hints: []
	};
	let cfg;
	try {
		cfg = loadConfig(ctx.configPath);
	} catch {
		return {
			id: "gateway-health",
			label: "Gateway HTTP",
			status: "skip",
			message: "Config could not be loaded; skipped.",
			hints: []
		};
	}
	const base = resolveGatewayBaseUrl(cfg);
	const url = `${base.replace(/\/$/, "")}/health`;
	const controller = new AbortController();
	const timer = setTimeout(() => controller.abort(), FETCH_TIMEOUT_MS);
	try {
		const res = await fetch(url, { signal: controller.signal });
		clearTimeout(timer);
		if (res.ok) return {
			id: "gateway-health",
			label: "Gateway HTTP",
			status: "pass",
			message: `Gateway responded OK at ${url}.`,
			hints: []
		};
		return {
			id: "gateway-health",
			label: "Gateway HTTP",
			status: "warn",
			message: `Gateway returned HTTP ${res.status} at ${url}.`,
			hints: ["Start the gateway: xopc gateway service start (or xopc gateway for foreground)"]
		};
	} catch (e) {
		clearTimeout(timer);
		return {
			id: "gateway-health",
			label: "Gateway HTTP",
			status: "warn",
			message: e instanceof Error && e.name === "AbortError" ? `Gateway did not respond within ${FETCH_TIMEOUT_MS / 1e3}s (${url}).` : `Gateway not reachable (${url}).`,
			hints: ["Start the gateway: xopc gateway service start (or xopc gateway for foreground)", `Configured base: ${base}`]
		};
	}
}
//#endregion
export { checkGatewayHealth };

//# sourceMappingURL=gateway-health.js.map