// ============================================================
// TTS GOOGLE — Google Cloud Text-to-Speech (direct, no LiteLLM)
// Uses google-auth-library (transitive dep of @google-cloud/vertexai)
// Voices: en-US-Journey-F (female), en-US-Journey-D (male),
//         en-US-Studio-O, en-US-Neural2-C, etc.
// Requires: GOOGLE_VERTEX_PROJECT, ADC or GOOGLE_APPLICATION_CREDENTIALS
// ============================================================

async function synthesizeWithGoogleTTS(text, voiceName) {
  var GoogleAuth = require('google-auth-library').GoogleAuth;
  var axios = require('axios');

  var auth = new GoogleAuth({
    scopes: ['https://www.googleapis.com/auth/cloud-platform']
  });

  var client    = await auth.getClient();
  var tokenData = await client.getAccessToken();
  var token     = tokenData.token;
  var voice     = voiceName || process.env.GOOGLE_TTS_VOICE || 'en-US-Journey-F';
  var langCode  = voice.substring(0, 5); // e.g. en-US

  var resp = await axios.post(
    'https://texttospeech.googleapis.com/v1/text:synthesize',
    {
      input: { text: text },
      voice: { languageCode: langCode, name: voice },
      audioConfig: { audioEncoding: 'MP3' }
    },
    {
      headers: {
        'Authorization': 'Bearer ' + token,
        'Content-Type': 'application/json'
      },
      timeout: 30000
    }
  );

  return Buffer.from(resp.data.audioContent, 'base64');
}

function isGoogleTTSConfigured() {
  if (!process.env.GOOGLE_VERTEX_PROJECT) return false;
  try { require('google-auth-library'); return true; } catch(e) { return false; }
}

module.exports = { synthesizeWithGoogleTTS, isGoogleTTSConfigured };
