"""Reproduce and verify the WebSocket receive_timeout fix in rany2/edge-tts#515.

Needs `pip install edge-tts` (which pulls in `aiohttp`). Runs a local WebSocket
server on 127.0.0.1 with no external network calls.

Tests three cases with `Communicate("hello", receive_timeout=3)` under an outer
7-second guard so a hang does not block the script forever:

1. silent-after-upgrade: server accepts the WebSocket upgrade, reads the client
   requests, then stays quiet without closing the socket.
2. silent-mid-stream: server sends one audio frame, then stops without sending
   `Path:turn.end` or closing the socket.
3. slow-alive: server sends an audio frame after 2 s and `Path:turn.end` after
   another 2 s (4 s total, but each gap is under `receive_timeout=3`, so it
   succeeds and shows the timeout is per-frame, not total).
"""

import asyncio
import time
import aiohttp
from aiohttp import web
import edge_tts
import edge_tts.communicate as comm

RECEIVE_TIMEOUT = 3
OUTER_GUARD = 7.0


def make_audio_frame(payload: bytes) -> bytes:
    headers = b"X-Pad:0\r\nContent-Type:audio/mpeg\r\nPath:audio"
    header_length = 2 + len(headers)
    return header_length.to_bytes(2, "big") + headers + b"\r\n" + payload


def make_handler(stop_event: asyncio.Event):
    async def ws_handler(request: web.Request) -> web.WebSocketResponse:
        mode = request.match_info["mode"]
        ws = web.WebSocketResponse()
        await ws.prepare(request)

        # Read speech.config and ssml frames sent by Communicate.__stream().
        for _ in range(2):
            msg = await ws.receive()
            if msg.type != aiohttp.WSMsgType.TEXT:
                return ws

        try:
            if mode == "silent-after-upgrade":
                await stop_event.wait()
            elif mode == "silent-mid-stream":
                await ws.send_bytes(make_audio_frame(b"\x00" * 16))
                await stop_event.wait()
            elif mode == "slow-alive":
                await asyncio.sleep(2.0)
                await ws.send_bytes(make_audio_frame(b"\x00" * 16))
                await asyncio.sleep(2.0)
                await ws.send_str("Path:turn.end\r\n\r\n")
                await ws.close()
        except asyncio.CancelledError:
            pass
        return ws

    return ws_handler


async def run_case(base_url: str, mode: str) -> None:
    comm.WSS_URL = f"{base_url}/ws/{mode}?x=1"
    start = time.monotonic()
    chunks = 0

    async def consume() -> None:
        nonlocal chunks
        c = edge_tts.Communicate("hello", receive_timeout=RECEIVE_TIMEOUT)
        async for chunk in c.stream():
            if chunk["type"] == "audio":
                chunks += 1

    try:
        await asyncio.wait_for(consume(), timeout=OUTER_GUARD)
        elapsed = time.monotonic() - start
        unit = "chunk" if chunks == 1 else "chunks"
        print(f"  {mode:22s}: ok ({chunks} audio {unit}, {elapsed:.2f} s)")
    except (TimeoutError, asyncio.TimeoutError) as exc:
        elapsed = time.monotonic() - start
        unit = "chunk" if chunks == 1 else "chunks"
        if elapsed >= OUTER_GUARD - 0.25:
            print(f"  {mode:22s}: HUNG (hit {OUTER_GUARD:.0f} s outer guard; {chunks} {unit})")
        else:
            print(
                f"  {mode:22s}: raised {type(exc).__name__} after {elapsed:.2f} s ({chunks} {unit})"
            )


async def main() -> None:
    stop_event = asyncio.Event()
    app = web.Application()
    app.router.add_get("/ws/{mode}", make_handler(stop_event))
    runner = web.AppRunner(app, shutdown_timeout=1.0)
    await runner.setup()
    site = web.TCPSite(runner, "127.0.0.1", 0)
    await site.start()
    port = site._server.sockets[0].getsockname()[1]
    base_url = f"ws://127.0.0.1:{port}"

    has_fix = hasattr(comm, "_ws_receive_timeout") or hasattr(comm, "ws_receive_timeout")
    print(
        f"[edge-tts {edge_tts.__version__}, aiohttp {aiohttp.__version__}, "
        f"fix={'present' if has_fix else 'absent'}, receive_timeout={RECEIVE_TIMEOUT}s]"
    )
    try:
        for mode in ("silent-after-upgrade", "silent-mid-stream", "slow-alive"):
            await run_case(base_url, mode)
    finally:
        stop_event.set()
        await runner.cleanup()


if __name__ == "__main__":
    asyncio.run(main())
