import { config } from '../config.js';

type DeepgramResponse = {
  results?: {
    channels?: Array<{
      alternatives?: Array<{
        transcript?: string;
        paragraphs?: {
          transcript?: string;
        };
      }>;
    }>;
  };
};

export async function transcribeAudioContent(input: {
  audioContentBase64: string;
  audioMimeType: string;
}) {
  if (!config.deepgramApiKey) {
    throw new Error('DEEPGRAM_API_KEY is required for voice place filters.');
  }
  if (input.audioContentBase64.trim() === '') {
    throw new Error('Voice filter audio is required.');
  }
  if (input.audioMimeType.trim() === '') {
    throw new Error('Voice filter audio MIME type is required.');
  }

  const params = new URLSearchParams({
    model: config.deepgramModel,
    language: config.deepgramLanguage,
    smart_format: 'true',
    punctuate: 'true',
  });
  const response = await fetch(
    `https://api.deepgram.com/v1/listen?${params.toString()}`,
    {
      method: 'POST',
      headers: {
        authorization: `Token ${config.deepgramApiKey}`,
        'content-type': input.audioMimeType,
      },
      body: Buffer.from(input.audioContentBase64, 'base64'),
    },
  );

  if (!response.ok) {
    const body = await response.text();
    throw new Error(
      `Deepgram voice filter transcription failed with ${response.status}: ${body.slice(0, 500)}`,
    );
  }

  const payload = (await response.json()) as DeepgramResponse;
  const alternative = payload.results?.channels?.[0]?.alternatives?.[0];
  const transcript =
    alternative?.paragraphs?.transcript?.trim() ??
    alternative?.transcript?.trim() ??
    '';
  if (!transcript) {
    throw new Error('Deepgram returned an empty voice filter transcript.');
  }

  return transcript;
}
