const OPENAI_TRANSCRIPTIONS_URL = 'https://api.openai.com/v1/audio/transcriptions';
const MIME_TO_EXT = {
    'audio/m4a': 'm4a',
    'audio/mp4': 'm4a',
    'audio/x-m4a': 'm4a',
    'audio/mpeg': 'mp3',
    'audio/mp3': 'mp3',
    'audio/wav': 'wav',
    'audio/webm': 'webm',
    'audio/ogg': 'ogg',
    'audio/caf': 'caf',
};
export async function transcribeAudioBuffer(apiKey, audio, mimeType, model) {
    const ext = MIME_TO_EXT[mimeType] ?? 'm4a';
    const form = new FormData();
    form.append('file', new Blob([new Uint8Array(audio)], { type: mimeType }), `recording.${ext}`);
    form.append('model', model);
    form.append('language', 'ru');
    const res = await fetch(OPENAI_TRANSCRIPTIONS_URL, {
        method: 'POST',
        headers: { Authorization: `Bearer ${apiKey}` },
        body: form,
    });
    const body = (await res.json().catch(() => ({})));
    if (!res.ok) {
        throw new Error(body.error?.message ?? `OpenAI transcription failed (${res.status})`);
    }
    const text = body.text?.trim() ?? '';
    if (!text)
        throw new Error('Empty transcription');
    return text;
}
