import { c as resolveStateDir } from "./paths-BVqcPirq.js";
import path from "node:path";
import fs from "node:fs";

//#region src/logging/chat-trace.ts
const TRACE_DIR_NAME = "traces";
const GATEWAY_SCOPE = "_gateway";
const CHANNELS_SCOPE = "_channels";
function resolveTraceDir() {
	return path.join(resolveStateDir(), "logs", TRACE_DIR_NAME);
}
function formatValue(value) {
	if (typeof value === "string") return value;
	if (typeof value === "number" || typeof value === "boolean") return String(value);
	try {
		return JSON.stringify(value);
	} catch {
		return String(value);
	}
}
/**
* Derive an 8-char trace ID from a message ID (or random fallback).
*/
function deriveTraceId(messageId) {
	if (messageId && messageId.length >= 8) return messageId.slice(0, 8);
	return Math.random().toString(36).slice(2, 10);
}
function formatTraceLine(traceId, level, stage, data) {
	const parts = [`${(/* @__PURE__ */ new Date()).toISOString()} [${traceId}] ${level}:${stage}`];
	if (data) {
		for (const [key, value] of Object.entries(data)) if (value !== void 0 && value !== null && value !== "") parts.push(`${key}=${formatValue(value)}`);
	}
	return parts.join(" ") + "\n";
}
function appendToScope(scope, line) {
	const today = (/* @__PURE__ */ new Date()).toISOString().slice(0, 10);
	const dir = path.join(resolveTraceDir(), scope);
	fs.mkdirSync(dir, {
		recursive: true,
		mode: 448
	});
	fs.appendFileSync(path.join(dir, `${today}.txt`), line, { encoding: "utf-8" });
}
/**
* Append a trace event for a chat message lifecycle stage (agent scope).
* Best-effort, never throws or blocks.
*/
function traceChatEvent(params) {
	try {
		const line = formatTraceLine(params.traceId, params.level, params.stage, params.data);
		appendToScope(params.agentId, line);
	} catch {}
}
/**
* Append a trace event to the gateway-level log (unified view across all agents).
* Best-effort, never throws or blocks.
*/
function traceGatewayEvent(params) {
	try {
		appendToScope(GATEWAY_SCOPE, formatTraceLine(params.traceId, params.level, params.stage, params.data));
	} catch {}
}
/**
* Append a trace event to the channels-level log (transport/delivery events).
* Best-effort, never throws or blocks.
*/
function traceChannelEvent(params) {
	try {
		appendToScope(CHANNELS_SCOPE, formatTraceLine(params.traceId, params.level, params.stage, params.data));
	} catch {}
}

//#endregion
export { traceGatewayEvent as i, traceChannelEvent as n, traceChatEvent as r, deriveTraceId as t };