import { createLogger } from "../../utils/logger/index.js";
import { init_logger } from "../../utils/logger.js";
import { mkdir, writeFile } from "fs/promises";
import { join, resolve } from "path";
import { randomBytes } from "crypto";
//#region src/channels/attachments/outbound-tts-persist.ts
/**
* Persist outbound TTS audio under `<agentHome>/tts/<session>/`.
*/
init_logger();
const log = createLogger("OutboundTtsPersist");
const TTS_REL_ROOT = "tts";
function sanitizeSessionSegment(sessionKey) {
	return sessionKey.replace(/[^a-zA-Z0-9_.-]+/g, "_").slice(0, 180) || "session";
}
function extForFormat(format) {
	const f = format.toLowerCase();
	if (f === "opus" || f === "ogg") return "ogg";
	if (f === "mp3" || f === "mpeg") return "mp3";
	if (f === "wav") return "wav";
	return "bin";
}
function resolveUnderRoot(root, rel, requiredPrefix) {
	const normalized = rel.replace(/\\/g, "/").replace(/^\/+/, "");
	if (normalized.includes("..") || !normalized.startsWith(requiredPrefix)) return null;
	const abs = resolve(root, ...normalized.split("/"));
	const rootResolved = resolve(root);
	if (!abs.startsWith(rootResolved)) return null;
	return abs;
}
async function persistOutboundTtsAudio(agentHomeRoot, sessionKey, audioBuffer, format) {
	const sessionSeg = sanitizeSessionSegment(sessionKey);
	const dirAbs = resolve(agentHomeRoot, "tts", sessionSeg);
	await mkdir(dirAbs, { recursive: true });
	const ext = extForFormat(format);
	const fname = `assist_${Date.now()}_${randomBytes(4).toString("hex")}.${ext}`;
	await writeFile(join(dirAbs, fname), audioBuffer);
	const workspaceRelativePath = [
		"tts",
		sessionSeg,
		fname
	].join("/");
	log.debug({
		sessionKey,
		workspaceRelativePath,
		bytes: audioBuffer.length
	}, "TTS audio persisted");
	return {
		workspaceRelativePath,
		name: fname,
		size: audioBuffer.length
	};
}
/**
* Resolve a stored relative path under `tts/`.
*/
function resolveSafeTtsFilePath(roots, relRaw) {
	const rel = relRaw.replace(/\\/g, "/").replace(/^\/+/, "");
	if (rel.includes("..")) return null;
	if (rel.startsWith(`tts/`)) return resolveUnderRoot(roots.agentHome, rel, `tts/`);
	return null;
}
//#endregion
export { TTS_REL_ROOT, persistOutboundTtsAudio, resolveSafeTtsFilePath };

//# sourceMappingURL=outbound-tts-persist.js.map