import { init_loader, loadConfig } from "../config/loader.js";
import { resolveGatewayLocalClientHost } from "../config/gateway-bind.js";
import { fetch } from "undici";
//#region src/mcp/gateway-http-client.ts
init_loader();
function resolveGatewayTokenFromConfig(cfg) {
	const fromConfig = cfg.gateway?.auth?.token?.trim();
	if (fromConfig) return fromConfig;
	return process.env.XOPC_GATEWAY_TOKEN?.trim() || void 0;
}
var GatewayHttpClient = class {
	constructor(opts) {
		this.opts = opts;
	}
	headers(extra) {
		const h = {
			Accept: "application/json",
			...extra
		};
		if (this.opts.token) h.Authorization = `Bearer ${this.opts.token}`;
		return h;
	}
	async getJson(path) {
		const res = await fetch(`${this.opts.baseUrl}${path}`, { headers: this.headers() });
		if (!res.ok) throw new Error(`Gateway GET ${path} failed: ${res.status}`);
		const body = await res.json();
		if (body && typeof body === "object" && "payload" in body) return body.payload;
		return body;
	}
	async postJson(path, data) {
		const res = await fetch(`${this.opts.baseUrl}${path}`, {
			method: "POST",
			headers: this.headers({ "Content-Type": "application/json" }),
			body: JSON.stringify(data)
		});
		if (!res.ok) throw new Error(`Gateway POST ${path} failed: ${res.status}`);
		const body = await res.json();
		if (body && typeof body === "object" && "payload" in body) return body.payload;
		return body;
	}
};
function resolveGatewayHttpBaseUrl(config, override) {
	if (override?.trim()) return override.replace(/\/$/, "");
	return `http://${resolveGatewayLocalClientHost(config)}:${config.gateway?.port ?? 18790}`;
}
function createGatewayHttpClientFromConfig(params) {
	const cfg = params.config ?? loadConfig();
	const token = params.gatewayToken ?? resolveGatewayTokenFromConfig(cfg) ?? void 0;
	return new GatewayHttpClient({
		baseUrl: resolveGatewayHttpBaseUrl(cfg, params.gatewayUrl),
		token
	});
}
//#endregion
export { GatewayHttpClient, createGatewayHttpClientFromConfig, resolveGatewayHttpBaseUrl };

//# sourceMappingURL=gateway-http-client.js.map