"""
Rutas para Text-to-Speech con OpenAI
"""
from flask import Blueprint, request, jsonify, current_app
from backend.services.edge_tts import EdgeTTSService
import asyncio
import os
import uuid
from gtts import gTTS

# Crear blueprint para las rutas TTS
tts_bp = Blueprint('tts', __name__)

# Inicializar servicios
edge_tts = EdgeTTSService()

@tts_bp.route('/api/synthesize-speech', methods=['POST'])
def synthesize_speech():
    """
    Endpoint para sintetizar texto a voz
    Usa Edge TTS como primera opción, fallback a gTTS
    """
    try:
        data = request.json

        if not data or 'text' not in data:
            return jsonify({
                'success': False,
                'error': 'Texto requerido'
            }), 400

        text = data['text'].strip()
        voice_type = data.get('voice_type', 'mujer')
        speed = float(data.get('speed', 1.0))

        if not text:
            return jsonify({
                'success': False,
                'error': 'El texto no puede estar vacío'
            }), 400

        # Intentar con Edge TTS primero
        try:
            loop = asyncio.get_event_loop()
            result = loop.run_until_complete(edge_tts.synthesize_speech(text, voice_type, speed))

            if result['success']:
                return jsonify({
                    'success': True,
                    'audio_url': result['audio_url'],
                    'file_path': result.get('file_path'),
                    'provider': 'edge-tts',
                    'voice_used': result['voice_used'],
                    'voice_name': result['voice_used']
                })

        except Exception as e:
            current_app.logger.error(f"Error en Edge TTS: {e}")
            # Continuar con el fallback si Edge TTS falla

        # Fallback a gTTS (no requiere PulseAudio)
        try:
            tts = gTTS(text=text, lang='es', slow=(speed < 0.8))
            audio_filename = f"fallback_{uuid.uuid4().hex[:8]}.mp3"
            audio_dir = os.path.join(current_app.root_path, 'frontend', 'static', 'assets', 'audio')
            os.makedirs(audio_dir, exist_ok=True)
            audio_path = os.path.join(audio_dir, audio_filename)
            tts.save(audio_path)

            return jsonify({
                'success': True,
                'audio_url': f'/static/assets/audio/{audio_filename}',
                'file_path': audio_path,
                'provider': 'gtts',
                'voice_used': voice_type
            })

        except Exception as e:
            current_app.logger.error(f"Error en gTTS: {e}")
            return jsonify({
                'success': False,
                'error': f'Error en síntesis de voz: {str(e)}'
            }), 500

    except Exception as e:
        current_app.logger.error(f"Error interno en /api/synthesize-speech: {e}")
        return jsonify({
            'success': False,
            'error': 'Error interno del servidor'
        }), 500
