import type { VoiceSessionMode } from './types';
import { blobToWav16kMono } from './audioWav';

function blobExtension(mimeType: string) {
  if (mimeType.includes('wav')) return 'wav';
  if (mimeType.includes('webm')) return 'webm';
  if (mimeType.includes('mp4')) return 'm4a';
  if (mimeType.includes('ogg')) return 'ogg';
  return 'wav';
}

async function parseAsrError(res: Response) {
  const text = await res.text().catch(() => '');
  try {
    const body = JSON.parse(text) as Record<string, unknown>;
    const nested =
      body.error && typeof body.error === 'object'
        ? (body.error as Record<string, unknown>)
        : body;
    return (
      (typeof nested.message === 'string' && nested.message) ||
      (typeof body.message === 'string' && body.message) ||
      text ||
      `${res.status} ${res.statusText}`
    );
  } catch {
    return text || `${res.status} ${res.statusText}`;
  }
}

/** 一次性识别（push-to-talk）；call 模式后续可扩展 openStream() */
export async function transcribeOneShot(blob: Blob, _mode: VoiceSessionMode = 'push-to-talk') {
  const prepared = await blobToWav16kMono(blob);
  const form = new FormData();
  form.append('file', prepared, `recording.${blobExtension(prepared.type)}`);
  const res = await fetch('/api/asr/oneshot', { method: 'POST', body: form });
  if (!res.ok) throw new Error(await parseAsrError(res));
  const body = (await res.json()) as { data?: { text?: string } };
  return (body.data?.text ?? '').trim();
}
