import { createWriteStream } from "node:fs";
import { writeFile } from "node:fs/promises";
import { pipeline } from "node:stream/promises";
import { MsEdgeTTS, OUTPUT_FORMAT } from "msedge-tts";
function ver(base) {
    const b = base.replace(/\/+$/, "");
    return b.endsWith("/v1") ? b : `${b}/v1`;
}
export async function ttsProfile(llm, text, voice, dest) {
    const res = await fetch(`${ver(llm.baseUrl)}/audio/speech`, {
        method: "POST",
        headers: { Authorization: `Bearer ${llm.apiKey}`, "Content-Type": "application/json" },
        body: JSON.stringify({ model: "gpt-4o-mini-tts", input: text, voice: voice || "alloy", response_format: "mp3" }),
    });
    if (!res.ok) {
        throw new Error(`profile TTS HTTP ${res.status}: ${(await res.text().catch(() => "")).slice(0, 200)}`);
    }
    await writeFile(dest, new Uint8Array(await res.arrayBuffer()));
}
/** Free Microsoft Edge TTS. Default voice is Chinese; override per job. */
export async function ttsEdge(text, voice, dest) {
    const tts = new MsEdgeTTS();
    await tts.setMetadata(voice || "zh-CN-XiaoxiaoNeural", OUTPUT_FORMAT.AUDIO_24KHZ_48KBITRATE_MONO_MP3);
    const { audioStream } = tts.toStream(text);
    await pipeline(audioStream, createWriteStream(dest));
}
export async function synthesize(engine, llm, text, voice, dest) {
    if (engine === "profile" && llm) {
        await ttsProfile(llm, text, voice, dest);
    }
    else {
        await ttsEdge(text, voice, dest);
    }
}
//# sourceMappingURL=tts.js.map