from fastapi import FastAPI
from google.cloud import texttospeech
import os
from fastapi.responses import FileResponse
from google.api_core.exceptions import GoogleAPIError

# Inicializar FastAPI
app = FastAPI()

# Configurar la ruta de la clave JSON (debe estar en la misma carpeta que este archivo)
KEY_PATH = os.path.join(os.path.dirname(__file__), "clave.json")
os.environ["GOOGLE_APPLICATION_CREDENTIALS"] = KEY_PATH

# Crear cliente de Google Text-to-Speech
client = texttospeech.TextToSpeechClient()

# Directorio donde se guardarán los audios
AUDIO_DIR = os.path.join(os.path.dirname(__file__), "audios")
if not os.path.exists(AUDIO_DIR):
    os.makedirs(AUDIO_DIR)

@app.get("/convertir")
async def convertir_texto_a_audio(texto: str, id_peticion: int, voz: str = "es-US-Standard-A"):
    """
    Convierte texto a audio usando Google Cloud Text-to-Speech.
    - `texto`      : El texto a convertir en audio.
    - `id_peticion`: Un ID único para nombrar el archivo.
    - `voz`        : La voz a usar (por defecto es una voz en español de México más natural).
    """
    archivo_audio = os.path.join(AUDIO_DIR, f"audio_{id_peticion}.mp3")
    
    try:
        # Configuración del SSML (Speech Synthesis Markup Language)
        ssml_texto = f"""
        <speak>
            <prosody rate="medium" pitch="medium" volume="medium">
                {texto}
            </prosody>
        </speak>
        """

        # Configuración del texto y la voz con SSML
        synthesis_input = texttospeech.SynthesisInput(ssml=ssml_texto)
        voice = texttospeech.VoiceSelectionParams(
            language_code="es-US",  # Español Latinoamericano, puede probar con es-US o es-ES
            name=voz,               # Puedes cambiar la voz aquí, por ejemplo es-US-Standard-A
            ssml_gender=texttospeech.SsmlVoiceGender.MALE  # O FEMALE según lo prefieras
        )
        audio_config = texttospeech.AudioConfig(audio_encoding=texttospeech.AudioEncoding.MP3)

        # Generar el audio
        response = client.synthesize_speech(
            input=synthesis_input, voice=voice, audio_config=audio_config
        )

        # Guardar el archivo MP3
        with open(archivo_audio, "wb") as out:
            out.write(response.audio_content)

        # Retornar el archivo de audio
        return FileResponse(archivo_audio, media_type="audio/mpeg", headers={"Content-Disposition": f"attachment; filename=audio_{id_peticion}.mp3"})
    
    except GoogleAPIError as e:
        # Captura errores de la API de Google
        return {"error": f"Error de Google API: {str(e)}"}
    except Exception as e:
        # Captura otros posibles errores
        return {"error": f"Ocurrió un error inesperado: {str(e)}"}


# from fastapi import FastAPI
# from gtts import gTTS
# import os
# from fastapi.responses import FileResponse

# app = FastAPI()

# BASE_DIR  = os.path.dirname(os.path.abspath(__file__))
# AUDIO_DIR = os.path.join(BASE_DIR, "audios")

# if not os.path.exists(AUDIO_DIR): 
#     os.makedirs(AUDIO_DIR)

# @app.get("/convertir")
# async def convertir_texto_a_audio(texto: str, id_peticion: int): 
#     archivo_audio = os.path.join(AUDIO_DIR, f"audio_{id_peticion}.mp3")

#     # Generar el archivo de audio
#     tts = gTTS(texto, lang='es')
#     tts.save(archivo_audio)

#     # Retornar el archivo de audio
#     return FileResponse(archivo_audio, media_type="audio/mpeg", headers={"Content-Disposition": f"attachment; filename=audio_{id_peticion}.mp3"})

