import { getActiveContext } from "./context.js";
import { randomUUID } from "node:crypto";

//#region src/propagation.ts
let _defaultPropagateContext = false;
function setDefaultPropagateContext(enabled) {
	_defaultPropagateContext = enabled;
}
function getDefaultPropagateContext() {
	return _defaultPropagateContext;
}
function injectContext(headers) {
	const result = headers ? { ...headers } : {};
	const ctx = getActiveContext();
	if (ctx == null) return result;
	result.traceparent = `00-${(ctx.traceId ?? randomUUID()).replace(/-/g, "").slice(0, 32).padEnd(32, "0")}-${randomUUID().replace(/-/g, "").slice(0, 16)}-01`;
	if (ctx.sessionId) result["x-amplitude-session-id"] = ctx.sessionId;
	if (ctx.agentId) result["x-amplitude-agent-id"] = ctx.agentId;
	if (ctx.userId) result["x-amplitude-user-id"] = ctx.userId;
	return result;
}
function extractContext(headers) {
	const result = {};
	const traceparent = headers.traceparent ?? "";
	if (traceparent) {
		const parts = traceparent.split("-");
		if (parts.length >= 2 && parts[1]) result.traceId = parts[1];
	}
	if (!result.traceId) {
		const xTrace = headers["x-trace-id"];
		if (xTrace) result.traceId = xTrace;
	}
	for (const [header, key] of [
		["x-amplitude-session-id", "sessionId"],
		["x-amplitude-agent-id", "agentId"],
		["x-amplitude-user-id", "userId"]
	]) {
		const val = headers[header];
		if (val) result[key] = val;
	}
	return result;
}

//#endregion
export { extractContext, getDefaultPropagateContext, injectContext, setDefaultPropagateContext };
//# sourceMappingURL=propagation.js.map