import { createLogger } from "../../utils/logger/index.js";
import { init_logger } from "../../utils/logger.js";
import { speak } from "./speak-core.js";
import { getChannelOutputFormat, shouldUseTTS } from "./service.js";
import { compressAudio } from "./audio.js";
import { recordTtsFailure, recordTtsSuccess } from "./status-tracker.js";
//#region src/voice/tts/payload.ts
init_logger();
const log = createLogger("TTS/Payload");
async function maybeApplyTtsToPayload(msg, options) {
	const { config, channel, inboundAudio } = options;
	if (!msg.content?.trim()) return msg;
	if (msg.mediaUrl) return msg;
	const ttsDecision = shouldUseTTS(config, inboundAudio);
	if (!ttsDecision.useTTS) {
		log.debug({ reason: ttsDecision.reason }, "TTS skipped");
		return msg;
	}
	const trigger = config?.trigger || "off";
	if (trigger === "off") return msg;
	if (trigger === "tagged") {
		if (!/\[\[tts\]\]/i.test(msg.content)) return msg;
		msg = {
			...msg,
			content: msg.content.replace(/\[\[tts\]\]/gi, "").trim()
		};
	}
	const startTime = Date.now();
	try {
		const outFmt = getChannelOutputFormat(channel);
		const ttsResult = await speak(msg.content, config, {
			appConfig: options.appConfig,
			tts: { format: outFmt.format }
		});
		const wavTarget = outFmt.format === "mp3" ? "mp3" : "opus";
		const { buffer: compressedAudio, format: compressedFormat } = await compressAudio(Buffer.from(ttsResult.audio), ttsResult.format, wavTarget);
		const dataUrl = `data:${compressedFormat === "opus" ? "audio/ogg" : compressedFormat === "mp3" || compressedFormat === "mpeg" ? "audio/mpeg" : `audio/${compressedFormat}`};base64,${compressedAudio.toString("base64")}`;
		const latencyMs = Date.now() - startTime;
		recordTtsSuccess({
			provider: ttsResult.provider,
			latencyMs,
			textLength: msg.content.length,
			audioSize: compressedAudio.length,
			audioFormat: compressedFormat,
			usedFallback: Boolean(ttsResult.fallbackFrom),
			wasSummarized: Boolean(ttsResult.wasSummarized)
		});
		log.info({
			channel,
			provider: ttsResult.provider,
			format: compressedFormat
		}, "TTS generated");
		return {
			...msg,
			mediaUrl: dataUrl,
			mediaType: "audio",
			audioAsVoice: outFmt.voiceCompatible
		};
	} catch (error) {
		recordTtsFailure({
			latencyMs: Date.now() - startTime,
			textLength: msg.content?.length ?? 0,
			error: error instanceof Error ? error.message : String(error)
		});
		log.warn({ error }, "TTS failed, sending text");
		return msg;
	}
}
function isTtsEnabled(config) {
	if (!config?.enabled) return false;
	return config.trigger !== "off";
}
function resolveTtsAutoMode(config, sessionOverride) {
	if (sessionOverride) {
		const normalized = sessionOverride.toLowerCase().trim();
		if ([
			"off",
			"always",
			"inbound",
			"tagged"
		].includes(normalized)) return normalized;
	}
	if (!config?.enabled) return "off";
	return config.trigger || "off";
}
//#endregion
export { isTtsEnabled, maybeApplyTtsToPayload, resolveTtsAutoMode };

//# sourceMappingURL=payload.js.map