/**
 * Voice Transcription Service for HumanOracle
 * Transcribes voice notes using Groq Whisper API
 */

const FormData = require('form-data');
const fetch = require('node-fetch');

const GROQ_API_KEY = process.env.GROQ_API_KEY;

/**
 * Transcribe audio buffer to text using Groq Whisper
 */
async function transcribeVoice(audioBuffer, mimeType = 'audio/ogg', language = null) {
  if (!GROQ_API_KEY) {
    console.error('No GROQ_API_KEY set');
    return null;
  }

  try {
    const form = new FormData();
    const ext = mimeType.includes('ogg') ? 'ogg' :
                mimeType.includes('mp3') ? 'mp3' :
                mimeType.includes('wav') ? 'wav' :
                mimeType.includes('m4a') ? 'm4a' : 'ogg';

    form.append('file', audioBuffer, { filename: `audio.${ext}`, contentType: mimeType });
    form.append('model', 'whisper-large-v3');
    form.append('response_format', 'json');

    if (language) {
      form.append('language', language);
    }

    const response = await fetch('https://api.groq.com/openai/v1/audio/transcriptions', {
      method: 'POST',
      headers: {
        'Authorization': `Bearer ${GROQ_API_KEY}`,
        ...form.getHeaders()
      },
      body: form
    });

    if (!response.ok) {
      const err = await response.text();
      console.error('Groq API error:', response.status, err);
      return null;
    }

    const data = await response.json();
    return {
      text: data.text?.trim() || '',
      language: data.language || 'auto',
      duration: data.duration || 0
    };
  } catch (e) {
    console.error('Voice transcription error:', e.message);
    return null;
  }
}

/**
 * Download WhatsApp media by ID and return buffer
 */
async function downloadWhatsAppMedia(mediaId, accessToken) {
  try {
    // Get media URL
    const mediaRes = await fetch(`https://graph.facebook.com/v18.0/${mediaId}`, {
      headers: { 'Authorization': `Bearer ${accessToken}` }
    });
    const mediaData = await mediaRes.json();

    if (!mediaData.url) {
      console.error('No media URL returned');
      return null;
    }

    // Download the actual file
    const fileRes = await fetch(mediaData.url, {
      headers: { 'Authorization': `Bearer ${accessToken}` }
    });
    const buffer = Buffer.from(await fileRes.arrayBuffer());
    return buffer;
  } catch (e) {
    console.error('Media download error:', e.message);
    return null;
  }
}

/**
 * Parse transcribed text into task details using AI
 */
async function parseVoiceToTask(transcription) {
  try {
    const response = await fetch('https://api.groq.com/openai/v1/chat/completions', {
      method: 'POST',
      headers: {
        'Authorization': `Bearer ${GROQ_API_KEY}`,
        'Content-Type': 'application/json'
      },
      body: JSON.stringify({
        model: 'llama-3.3-70b-versatile',
        messages: [
          {
            role: 'system',
            content: `You extract task details from voice transcriptions. Return JSON only, no other text.
{
  "title": "short task title max 60 chars",
  "description": "clear task description",
  "category": "one of: writing, research, data, survey, image, local, mystery, translation, audio, other",
  "estimated_budget_vae": number between 50 and 5000,
  "location": "city/country if mentioned, or null",
  "is_local": true if task requires physical presence, false otherwise
}`
          },
          {
            role: 'user',
            content: `Extract task details from this voice message: "${transcription}"`
          }
        ],
        temperature: 0.1,
        max_tokens: 300
      })
    });

    if (!response.ok) return null;

    const data = await response.json();
    const text = data.choices?.[0]?.message?.content || '';
    
    // Parse JSON from response
    const jsonMatch = text.match(/\{[\s\S]*\}/);
    if (jsonMatch) {
      return JSON.parse(jsonMatch[0]);
    }
    return null;
  } catch (e) {
    console.error('Voice task parsing error:', e.message);
    return null;
  }
}

module.exports = { transcribeVoice, downloadWhatsAppMedia, parseVoiceToTask };
