import argparse
import asyncio
import io
import os

import edge_tts
from flask import Flask, jsonify, request, send_file

VOICE = os.getenv("EDGE_TTS_VOICE", "ur-PK-UzmaNeural")
app = Flask(__name__)
app.config["MAX_CONTENT_LENGTH"] = 16 * 1024


async def synthesize(text):
    audio = bytearray()
    communicate = edge_tts.Communicate(text, VOICE, connect_timeout=10, receive_timeout=30)
    async for chunk in communicate.stream():
        if chunk["type"] == "audio":
            audio.extend(chunk["data"])
    if not audio:
        raise RuntimeError("Edge TTS returned no audio.")
    return io.BytesIO(audio)


@app.get("/health")
def health():
    return jsonify(ok=True, engine="Edge TTS", voice=VOICE, online=True)


@app.post("/synthesize")
def synthesize_route():
    body = request.get_json(silent=True)
    text = body.get("text") if isinstance(body, dict) else None
    if not isinstance(text, str) or not text.strip() or len(text) > 1000:
        return jsonify(error="Text must be between 1 and 1000 characters."), 400
    try:
        audio = asyncio.run(asyncio.wait_for(synthesize(text.strip()), timeout=45))
    except Exception:
        app.logger.exception("Edge Urdu speech generation failed")
        return jsonify(error="Edge Urdu voice is unavailable. Check the server internet connection and try again."), 503
    response = send_file(audio, mimetype="audio/mpeg", download_name="urdu.mp3")
    response.headers["Cache-Control"] = "no-store"
    return response


def main():
    parser = argparse.ArgumentParser()
    parser.add_argument("--host", default="127.0.0.1")
    parser.add_argument("--port", type=int, default=15055)
    args = parser.parse_args()
    print(f"Edge Urdu TTS: {VOICE} (online Microsoft service)")
    app.run(host=args.host, port=args.port, threaded=True)


if __name__ == "__main__":
    main()
