/**
 * transcription.js — Audio transcription via Lemonfox (Whisper-compatible API)
 *
 * Usage:
 *   const text = await transcribeAudio(buffer, 'audio/ogg', 'en');
 */

import fetch from 'node-fetch';
import FormData from 'form-data';
import { downloadContentFromMessage } from '@whiskeysockets/baileys';

const LEMONFOX_API = 'https://api.lemonfox.ai/v1/audio/transcriptions';
const LEMONFOX_KEY = '4K9ZhgawrV4iBnZZFPMOufwXwWtSdtM9';

// Map detected language names to ISO 639-1 codes
const LANG_CODES = {
  English:    'en',
  French:     'fr',
  Portuguese: 'pt',
  Spanish:    'es',
};

/**
 * Transcribe an audio buffer using Lemonfox.
 *
 * @param {Buffer} audioBuffer - raw audio bytes
 * @param {string} mimeType    - e.g. 'audio/ogg; codecs=opus'
 * @param {string} language    - detected language name ('English', 'French', etc.)
 * @returns {Promise<string>}  - transcribed text, or empty string on failure
 */
export async function transcribeAudio(audioBuffer, mimeType, language = 'English') {
  try {
    const langCode = LANG_CODES[language] || 'en';
    const ext      = mimeType?.includes('mp4') ? 'mp4'
                   : mimeType?.includes('mpeg') ? 'mp3'
                   : 'ogg';

    const form = new FormData();
    form.append('file', audioBuffer, { filename: `audio.${ext}`, contentType: mimeType || 'audio/ogg' });
    form.append('model', 'whisper-1');
    form.append('language', langCode);

    const res = await fetch(LEMONFOX_API, {
      method:  'POST',
      headers: { 'Authorization': `Bearer ${LEMONFOX_KEY}`, ...form.getHeaders() },
      body:    form,
      signal:  AbortSignal.timeout(30_000),
    });

    if (!res.ok) {
      const err = await res.text().catch(() => res.status);
      console.error('[transcription] Lemonfox error:', err);
      return '';
    }

    const data = await res.json();
    return (data.text || '').trim();
  } catch (e) {
    console.error('[transcription] failed:', e.message);
    return '';
  }
}

/**
 * Download and transcribe a WhatsApp audio message.
 *
 * @param {object} audioMsg - msg.message.audioMessage
 * @param {string} language - detected language name
 * @returns {Promise<string>} - transcribed text
 */
export async function transcribeWhatsAppAudio(audioMsg, language = 'English') {
  try {
    const stream = await downloadContentFromMessage(audioMsg, 'audio');
    let buffer = Buffer.alloc(0);
    for await (const chunk of stream) buffer = Buffer.concat([buffer, chunk]);
    const mime = audioMsg.mimetype || 'audio/ogg; codecs=opus';
    return transcribeAudio(buffer, mime, language);
  } catch (e) {
    console.error('[transcription] download failed:', e.message);
    return '';
  }
}
