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

//#region src/logging/chat-trace.ts
const TRACE_DIR_NAME = "traces";
const GATEWAY_SCOPE = "_gateway";
const CHANNELS_SCOPE = "_channels";
const MAX_AGE_DAYS = 7;
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 {}
}
/**
* Remove trace files older than maxAgeDays. Call on gateway startup.
*/
function pruneOldTraceFiles(maxAgeDays = MAX_AGE_DAYS) {
	try {
		const traceDir = resolveTraceDir();
		if (!fs.existsSync(traceDir)) return;
		const cutoff = Date.now() - maxAgeDays * 24 * 60 * 60 * 1e3;
		for (const agentDir of fs.readdirSync(traceDir)) {
			const agentPath = path.join(traceDir, agentDir);
			let stat;
			try {
				stat = fs.statSync(agentPath);
			} catch {
				continue;
			}
			if (!stat.isDirectory()) continue;
			for (const file of fs.readdirSync(agentPath)) {
				if (!file.endsWith(".txt")) continue;
				const filePath = path.join(agentPath, file);
				try {
					if (fs.statSync(filePath).mtimeMs < cutoff) fs.unlinkSync(filePath);
				} catch {}
			}
			try {
				if (fs.readdirSync(agentPath).length === 0) fs.rmdirSync(agentPath);
			} catch {}
		}
	} catch {}
}

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