/** Containers the backend accepts, in the order we prefer to record them. */
const PREFERRED_MIME_TYPES = [
  'audio/webm;codecs=opus',
  'audio/webm',
  'audio/mp4',
  'audio/aac',
  'audio/ogg;codecs=opus',
  'audio/ogg',
] as const;

/**
 * Pick a container this browser can record AND the backend accepts. Chrome and Android give
 * webm/opus, Safari and iPad mp4/aac; both go to the vendor unmodified, so there is no
 * transcode step and the list is an intersection, not a preference.
 */
export function pickRecordingMimeType(): string | null {
  if (typeof MediaRecorder === 'undefined') return null;
  if (typeof MediaRecorder.isTypeSupported !== 'function') {
    // Safari <14.1 shipped MediaRecorder without the feature check; let it choose.
    return '';
  }
  for (const type of PREFERRED_MIME_TYPES) {
    if (MediaRecorder.isTypeSupported(type)) return type;
  }
  return null;
}

/** `audio/webm;codecs=opus` → `webm`, which is what the API's `format` field wants. */
export function mimeTypeToFormat(mimeType: string): string {
  const base = mimeType.split(';')[0]?.trim().toLowerCase() ?? '';
  const subtype = base.startsWith('audio/') ? base.slice('audio/'.length) : base;
  // Safari/iOS records `audio/mp4`, but the transcription endpoint's documented container
  // list names m4a, not mp4. Same container; send the name the vendor documents, so iPad
  // recordings do not fail while Chrome's webm works.
  if (subtype === 'x-m4a' || subtype === 'm4a' || subtype === 'mp4') return 'm4a';
  if (subtype === 'mpeg') return 'mp3';
  return subtype || 'webm';
}

/** Blob → base64 without the `data:` prefix, which the API does not want. */
export async function blobToBase64(blob: Blob): Promise<string> {
  const buffer = await blob.arrayBuffer();
  let binary = '';
  const bytes = new Uint8Array(buffer);
  // Chunked to avoid blowing the argument limit on a two-minute recording.
  const chunkSize = 0x8000;
  for (let i = 0; i < bytes.length; i += chunkSize) {
    binary += String.fromCharCode(...bytes.subarray(i, i + chunkSize));
  }
  return btoa(binary);
}

export function isMediaRecorderSupported(): boolean {
  return (
    typeof window !== 'undefined' &&
    typeof MediaRecorder !== 'undefined' &&
    typeof navigator !== 'undefined' &&
    Boolean(navigator.mediaDevices?.getUserMedia)
  );
}
