const express = require('express');
const router  = express.Router();
const axios   = require('axios');
const { synthesizeWithGoogleTTS, isGoogleTTSConfigured } = require('../utils/ttsGoogle');
const { authMiddleware } = require('../middleware/auth');
var logger = require('../utils/logger');
var { gatewayUrl } = require('../utils/errors');

// Provider priority (auto-detect):
// TTS_PROVIDER=litellm    → LiteLLM proxy at /v1/audio/speech (default when LITELLM_API_BASE is set)
// TTS_PROVIDER=google     → Google Cloud TTS direct (HIPAA eligible, opt-in)
// TTS_PROVIDER=elevenlabs → ElevenLabs direct (not HIPAA, opt-in)
// Auto: litellm > google > elevenlabs
//
// Design: the LiteLLM branch is a pure passthrough — model + voice strings
// go straight into the OpenAI-compatible /v1/audio/speech body. No regex
// dispatch on model/voice names; the LiteLLM config decides which provider
// (OpenAI, ElevenLabs, Vertex, Azure) actually serves the request.
function getTTSProvider() {
  var env = process.env.TTS_PROVIDER;
  if (env === 'google')     return 'google';
  if (env === 'litellm')    return 'litellm';
  if (env === 'elevenlabs') return 'elevenlabs';
  // Auto-detect: litellm > google > elevenlabs
  if (process.env.LITELLM_API_BASE)   return 'litellm';
  if (isGoogleTTSConfigured())        return 'google';
  if (process.env.ELEVENLABS_API_KEY) return 'elevenlabs';
  return 'none';
}

var ttsProvider = getTTSProvider();
console.log('🔊 TTS provider:', ttsProvider +
  (ttsProvider === 'google' ? ' (voice: ' + (process.env.GOOGLE_TTS_VOICE || 'en-US-Journey-F') + ')' : ''));

router.post('/text-to-speech', authMiddleware, async (req, res) => {
  try {
    var text = (req.body.text || '').substring(0, 5000);
    if (!text) return res.status(400).json({ error: 'No text provided' });

    // Get user's preferred TTS voice (if set), then fall back to DB admin default, then env
    var db = require('../db/database');
    var userPrefs = await db.get('SELECT tts_voice FROM users WHERE id = ?', [req.user.id]);
    var userVoice = userPrefs?.tts_voice;
    var adminVoice = await db.getSetting('tts.voice') || '';
    var adminModel = await db.getSetting('tts.model') || '';
    var resolvedVoice = userVoice || adminVoice || '';

    if (ttsProvider === 'litellm') {
      if (!process.env.LITELLM_API_BASE) return res.status(400).json({ error: 'LITELLM_API_BASE not set.' });
      var ttsModel = adminModel || process.env.LITELLM_TTS_MODEL || 'tts-1';
      var ttsVoice = resolvedVoice || process.env.LITELLM_TTS_VOICE || 'alloy';
      var headers  = { 'Content-Type': 'application/json' };
      if (process.env.LITELLM_API_KEY) headers['Authorization'] = 'Bearer ' + process.env.LITELLM_API_KEY;

      var ttsResp = await fetch(gatewayUrl('/audio/speech'), {
        method: 'POST',
        headers: headers,
        body: JSON.stringify({ model: ttsModel, input: text, voice: ttsVoice })
      });
      if (!ttsResp.ok) {
        var errBody = await ttsResp.text();
        throw new Error('LiteLLM /audio/speech ' + ttsResp.status + ': ' + errBody.substring(0, 500));
      }
      var audioBuf = Buffer.from(await ttsResp.arrayBuffer());
      res.set('Content-Type', ttsResp.headers.get('content-type') || 'audio/mpeg');
      res.set('X-TTS-Provider', 'litellm/' + ttsModel);
      logger.audit(req.user.id, 'text_to_speech', 'TTS generated', req, { category: 'clinical' });
      return res.send(audioBuf);
    }

    if (ttsProvider === 'google') {
      var voice = resolvedVoice || process.env.GOOGLE_TTS_VOICE || 'en-US-Journey-F';
      var buffer = await synthesizeWithGoogleTTS(text, voice);
      res.set('Content-Type', 'audio/mpeg');
      res.set('X-TTS-Provider', 'google-tts/' + voice);
      logger.audit(req.user.id, 'text_to_speech', 'TTS generated', req, { category: 'clinical' });
      return res.send(buffer);
    }

    if (ttsProvider === 'elevenlabs') {
      if (!process.env.ELEVENLABS_API_KEY) return res.status(400).json({ error: 'ElevenLabs not configured' });
      var resp = await axios({
        method: 'POST',
        url: 'https://api.elevenlabs.io/v1/text-to-speech/pNInz6obpgDQGcFmaJgB',
        headers: { 'xi-api-key': process.env.ELEVENLABS_API_KEY, 'Content-Type': 'application/json' },
        data: { text: text, model_id: 'eleven_turbo_v2_5', voice_settings: { stability: 0.5, similarity_boost: 0.75 } },
        responseType: 'arraybuffer'
      });
      res.set('Content-Type', 'audio/mpeg');
      res.set('X-TTS-Provider', 'elevenlabs');
      logger.audit(req.user.id, 'text_to_speech', 'TTS generated', req, { category: 'clinical' });
      return res.send(Buffer.from(resp.data));
    }

    res.status(400).json({ error: 'TTS not configured. Set LITELLM_API_BASE, GOOGLE_VERTEX_PROJECT, or ELEVENLABS_API_KEY.' });
  } catch (err) {
    var detail = err.response && err.response.data
      ? JSON.stringify(err.response.data).substring(0, 500)
      : err.message;
    console.error('[TTS] Error (' + ttsProvider + '):', detail);
    res.status(500).json({ error: 'TTS failed: ' + detail });
  }
});

module.exports = router;
