# Servidor TTS "quente" do gpt-cli: importa o edge_tts UMA vez e fica pronto, evitando o
# ~1.4s de import a cada fala. Protocolo (stdin linha a linha): "<voz>\t<base64(texto utf-8)>".
# Para cada pedido, streama os bytes do mp3 no STDOUT e escreve "END" no STDERR ao terminar.
# Assim o Node pipa o stdout direto no ffplay (baixa latência) e fecha quando vê "END".
import sys, asyncio, base64
import edge_tts


async def synth(voice, text):
    comm = edge_tts.Communicate(text, voice)
    async for chunk in comm.stream():
        if chunk.get("type") == "audio" and chunk.get("data"):
            sys.stdout.buffer.write(chunk["data"])
            sys.stdout.buffer.flush()


def main():
    sys.stderr.write("READY\n")
    sys.stderr.flush()
    for line in sys.stdin:
        line = line.strip()
        if not line:
            continue
        try:
            voice, b64 = line.split("\t", 1)
            text = base64.b64decode(b64).decode("utf-8")
            asyncio.run(synth(voice, text))
        except Exception as e:  # noqa: BLE001
            sys.stderr.write("ERR " + str(e).replace("\n", " ") + "\n")
            sys.stderr.flush()
        sys.stderr.write("END\n")
        sys.stderr.flush()


if __name__ == "__main__":
    main()
