import { createLogger } from "../utils/logger/index.js";
import { init_logger } from "../utils/logger.js";
import { monitorEventLoopDelay, performance } from "node:perf_hooks";
//#region src/gateway/startup-trace.ts
init_logger();
const log = createLogger("GatewayStartup");
function isTruthyEnvValue(value) {
	const normalized = value?.trim().toLowerCase();
	return normalized === "1" || normalized === "true" || normalized === "yes" || normalized === "on";
}
function isGatewayStartupTraceEnabled(env = process.env) {
	return isTruthyEnvValue(env.XOPC_GATEWAY_STARTUP_TRACE);
}
function createGatewayStartupTrace(enabled = isGatewayStartupTraceEnabled()) {
	const eventLoopDelay = enabled ? monitorEventLoopDelay({ resolution: 10 }) : void 0;
	eventLoopDelay?.enable();
	const started = performance.now();
	let last = started;
	const formatMetric = (key, value) => `${key}=${typeof value === "number" ? value.toFixed(1) : value}`;
	const readEventLoopMaxMs = () => {
		if (!eventLoopDelay) return 0;
		const maxMs = eventLoopDelay.max / 1e6;
		eventLoopDelay.reset();
		return maxMs;
	};
	const emit = (name, durationMs, totalMs, extras = []) => {
		if (!enabled) return;
		const metrics = [`eventLoopMax=${readEventLoopMaxMs().toFixed(1)}ms`, ...extras.map(([key, value]) => formatMetric(key, value))].join(" ");
		log.info(`startup trace: ${name} ${durationMs.toFixed(1)}ms total=${totalMs.toFixed(1)}ms ${metrics}`);
	};
	return {
		mark(name) {
			const now = performance.now();
			emit(name, now - last, now - started);
			last = now;
			if (name === "ready") eventLoopDelay?.disable();
		},
		detail(name, metrics) {
			if (!enabled) return;
			log.info(`startup trace: ${name} ${metrics.map(([key, value]) => formatMetric(key, value)).join(" ")}`);
		},
		async measure(name, run) {
			const before = performance.now();
			try {
				return await run();
			} finally {
				const now = performance.now();
				emit(name, now - before, now - started);
				last = now;
			}
		}
	};
}
//#endregion
export { createGatewayStartupTrace, isGatewayStartupTraceEnabled };

//# sourceMappingURL=startup-trace.js.map