import json
import urllib.request
from pathlib import Path

AZURE_URL = "http://127.0.0.1:3101/api/speech/synthesize"
KEY_FILE = Path("/etc/hermes-nexus/azure_internal.key")

def generar_voz_hermes(texto):
    if not isinstance(texto, str) or not texto.strip():
        raise ValueError("El texto no puede estar vacío")

    if len(texto) > 1500:
        raise ValueError("El texto supera el límite permitido")

    clave = KEY_FILE.read_text(encoding="utf-8").strip()

    datos = json.dumps({
        "texto": texto
    }).encode("utf-8")

    solicitud = urllib.request.Request(
        AZURE_URL,
        data=datos,
        headers={
            "Content-Type": "application/json",
            "X-Hermes-Internal-Key": clave
        },
        method="POST"
    )

    with urllib.request.urlopen(solicitud, timeout=45) as respuesta:
        return json.load(respuesta)
