import { createLogger } from "../../utils/logger/index.js";
import { init_logger } from "../../utils/logger.js";
import { init_paths, resolveConfigPath } from "../../config/paths.js";
import { loadConfig } from "../../config/loader.js";
import { resolveGatewayEffectiveHost } from "../../config/gateway-bind.js";
import "../../config/index.js";
import { assertSecureGatewayHttpUrl } from "../../gateway/ws-security.js";
import { addGatewayClientOptions, parseGatewayClientOptions } from "./gateway-client-options.js";
//#region src/cli/utils/gateway-client.ts
/**
* Gateway API client — CLI-side HTTP client for gateway REST routes.
*/
init_paths();
init_logger();
const log = createLogger("GatewayClient");
function resolveGatewayUrl(opts) {
	if (opts?.url) {
		const normalized = opts.url.replace(/\/+$/, "");
		assertSecureGatewayHttpUrl(normalized);
		return normalized;
	}
	const envUrl = process.env.XOPC_GATEWAY_URL?.trim();
	if (envUrl) {
		const normalized = envUrl.replace(/\/+$/, "");
		assertSecureGatewayHttpUrl(normalized);
		return normalized;
	}
	try {
		const config = loadConfig(opts?.configPath ?? resolveConfigPath());
		if (config.gateway?.mode === "remote" && config.gateway.remote?.url?.trim()) {
			const normalized = config.gateway.remote.url.trim().replace(/\/+$/, "");
			assertSecureGatewayHttpUrl(normalized);
			return normalized;
		}
		const host = resolveGatewayEffectiveHost(config);
		const port = config?.gateway?.port ?? 18790;
		const url = `http://${host === "0.0.0.0" ? "127.0.0.1" : host}:${port}`;
		assertSecureGatewayHttpUrl(url);
		return url;
	} catch {
		return "http://127.0.0.1:18790";
	}
}
function resolveGatewayToken(opts) {
	if (opts?.token) return opts.token;
	const envToken = process.env.XOPC_GATEWAY_TOKEN;
	if (envToken) return envToken;
	try {
		const config = loadConfig(opts?.configPath ?? resolveConfigPath());
		if (config.gateway?.mode === "remote") {
			const remoteToken = config.gateway.remote?.token?.trim();
			if (remoteToken) return remoteToken;
		}
		return config?.gateway?.auth?.token;
	} catch {
		return;
	}
}
async function callGatewayApi(method, path, opts, body) {
	const baseUrl = resolveGatewayUrl(opts);
	const token = resolveGatewayToken(opts);
	const timeoutMs = opts?.timeoutMs ?? 1e4;
	const url = `${baseUrl}${path.startsWith("/") ? path : `/${path}`}`;
	const headers = { Accept: "application/json" };
	if (token) headers.Authorization = `Bearer ${token}`;
	if (body !== void 0) headers["Content-Type"] = "application/json";
	const startedAt = Date.now();
	try {
		const controller = new AbortController();
		const timer = setTimeout(() => controller.abort(), timeoutMs);
		const response = await fetch(url, {
			method,
			headers,
			body: body !== void 0 ? JSON.stringify(body) : void 0,
			signal: controller.signal
		});
		clearTimeout(timer);
		const durationMs = Date.now() - startedAt;
		if (!response.ok) {
			let errorMessage;
			try {
				const errorBody = await response.json();
				errorMessage = errorBody.error || errorBody.message || response.statusText;
			} catch {
				errorMessage = response.statusText;
			}
			log.debug({
				url,
				status: response.status,
				durationMs
			}, `Gateway call failed: ${errorMessage}`);
			return {
				ok: false,
				status: response.status,
				error: errorMessage,
				durationMs
			};
		}
		const data = await response.json();
		log.debug({
			url,
			status: response.status,
			durationMs
		}, "Gateway call succeeded");
		return {
			ok: true,
			status: response.status,
			data,
			durationMs
		};
	} catch (err) {
		const durationMs = Date.now() - startedAt;
		const errorMessage = err instanceof Error && err.name === "AbortError" ? `Request timed out after ${timeoutMs}ms` : err instanceof Error ? err.message : String(err);
		log.debug({
			url,
			err,
			durationMs
		}, `Gateway call error: ${errorMessage}`);
		return {
			ok: false,
			status: 0,
			error: errorMessage,
			durationMs
		};
	}
}
//#endregion
export { addGatewayClientOptions, callGatewayApi, parseGatewayClientOptions, resolveGatewayToken, resolveGatewayUrl };

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