import { TRANSCRIPTION_TIMEOUT_MS } from "./constants.js";
import { createFalClient } from "./fal-client.js";
import { toArrayBuffer } from "./utils.js";
export async function transcribeWithFal(bytes, mediaType, apiKey) {
    const fal = createFalClient({ credentials: apiKey });
    const blob = new Blob([toArrayBuffer(bytes)], { type: mediaType });
    const audioUrl = await fal.storage.upload(blob);
    const result = await Promise.race([
        fal.subscribe("fal-ai/wizper", {
            input: { audio_url: audioUrl, language: "en" },
        }),
        new Promise((_, reject) => setTimeout(() => reject(new Error("FAL transcription timeout")), TRANSCRIPTION_TIMEOUT_MS)),
    ]);
    return extractText(result);
}
function extractText(result) {
    if (typeof result !== "object" || result === null)
        return null;
    const data = "data" in result ? result.data : result;
    if (typeof data !== "object" || data === null)
        return null;
    if ("text" in data && typeof data.text === "string") {
        const text = data.text.trim();
        return text.length > 0 ? text : null;
    }
    if ("chunks" in data && Array.isArray(data.chunks)) {
        const chunks = data.chunks;
        const lines = [];
        for (const chunk of chunks) {
            if (typeof chunk === "object" && chunk !== null && "text" in chunk) {
                const text = chunk.text;
                if (typeof text === "string" && text.trim()) {
                    lines.push(text.trim());
                }
            }
        }
        return lines.length > 0 ? lines.join(" ") : null;
    }
    return null;
}
//# sourceMappingURL=fal.js.map