import { init_agent_scope, resolveAgentHomeDir } from "../agent-scope.js";
import { extractProfileAgentId } from "../../config/agent-profile.js";
import { isTTSAvailable } from "../../voice/tts/factory.js";
import { speak } from "../../voice/tts/speak-core.js";
import { mergeTtsConfigFromAppConfig } from "../../voice/tts/merge-config.js";
import { getChannelOutputFormat, shouldUseTTS } from "../../voice/tts/service.js";
import { compressAudio } from "../../voice/tts/audio.js";
import "../../voice/tts/index.js";
import { persistOutboundTtsAudio } from "../../channels/attachments/outbound-tts-persist.js";
//#region src/agent/service/webchat-tts.ts
init_agent_scope();
/**
* Generate TTS for webchat when config allows; persist under agent home `tts/`.
*/
async function maybeEmitWebchatTts(deps, sessionKey, hadInboundVoice) {
	const ttsConfig = mergeTtsConfigFromAppConfig(deps.config?.messages?.tts);
	if (!isTTSAvailable(ttsConfig)) return null;
	if (!shouldUseTTS(ttsConfig, hadInboundVoice).useTTS) return null;
	const text = deps.getLastAssistantPlainText(sessionKey).trim();
	if (!text) return null;
	try {
		const webOut = getChannelOutputFormat("webchat");
		const fmt = webOut.format;
		const ttsResult = await speak(text, ttsConfig, {
			appConfig: deps.config,
			tts: { format: fmt }
		});
		const { buffer, format } = await compressAudio(Buffer.from(ttsResult.audio), ttsResult.format, webOut.format === "mp3" ? "mp3" : "opus");
		const normalizedMime = format === "opus" || format === "ogg" ? "audio/ogg" : format === "mp3" || format === "mpeg" ? "audio/mpeg" : format === "wav" ? "audio/wav" : `audio/${format}`;
		const cfg = deps.config;
		const persisted = await persistOutboundTtsAudio(resolveAgentHomeDir(cfg, extractProfileAgentId(sessionKey, cfg)), sessionKey, buffer, format);
		await appendAttachmentToLastAssistant(deps.sessionStore, sessionKey, {
			type: "audio",
			mimeType: normalizedMime,
			name: persisted.name,
			size: persisted.size,
			workspaceRelativePath: persisted.workspaceRelativePath
		});
		return {
			type: "tts_audio",
			workspaceRelativePath: persisted.workspaceRelativePath,
			mimeType: normalizedMime,
			name: persisted.name
		};
	} catch (err) {
		deps.log.warn({
			err,
			sessionKey
		}, "Webchat TTS failed");
		return null;
	}
}
async function appendAttachmentToLastAssistant(sessionStore, sessionKey, att) {
	const loaded = await sessionStore.load(sessionKey);
	for (let i = loaded.length - 1; i >= 0; i--) {
		const m = loaded[i];
		if (m.role === "assistant") {
			const prev = m.attachments ?? [];
			if (prev.some((x) => x.workspaceRelativePath === att.workspaceRelativePath)) return;
			const next = [...prev, att];
			loaded[i] = {
				...m,
				attachments: next
			};
			await sessionStore.saveMessages(sessionKey, loaded);
			return;
		}
	}
}
//#endregion
export { appendAttachmentToLastAssistant, maybeEmitWebchatTts };

//# sourceMappingURL=webchat-tts.js.map