"""FlexiSLM realtime example. Python 3.10+, websockets 15 and python-socks[asyncio] 2.x."""
import argparse
import asyncio
import json
import os
from pathlib import Path
import time
from urllib.parse import urlsplit, urlunsplit
from urllib.request import Request
import wave

from websockets.asyncio.client import connect


def connection_info(base_url, key, model):
    base = urlsplit(base_url.rstrip("/"))
    if base.scheme not in ("https", "http") or not base.netloc or base.query or base.fragment or base.username:
        raise ValueError("Invalid base URL")
    if base.scheme == "http" and base.hostname not in ("localhost", "127.0.0.1", "::1"):
        raise ValueError("HTTPS is required outside localhost")
    # Do not follow redirects carrying a credential to another host.
    from urllib.request import HTTPRedirectHandler, build_opener
    class NoRedirect(HTTPRedirectHandler):
        def redirect_request(self, req, fp, code, msg, headers, newurl):
            return None
    request = Request(base_url.rstrip("/") + "/models", headers={"Authorization": f"Bearer {key}"})
    with build_opener(NoRedirect).open(request, timeout=15) as response:
        catalog = json.load(response)
    if model not in [item["id"] for item in catalog["data"]]:
        raise ValueError("Model is not available")
    return urlunsplit(("wss" if base.scheme == "https" else "ws", base.netloc,
                       base.path.rstrip("/") + "/realtime", "model=" + model, ""))


async def run(args):
    key = os.environ.get("LIVECODE_API_KEY", "").strip()
    if not key:
        raise ValueError("Set LIVECODE_API_KEY first")
    url = await asyncio.to_thread(connection_info, args.base_url, key, args.model)
    with wave.open(args.wav, "rb") as source:
        if (source.getframerate(), source.getnchannels(), source.getsampwidth()) != (16000, 1, 2):
            raise ValueError("Input must be a 16 kHz mono PCM16 WAV")
        if not 0 < source.getnframes() <= 16000 * 300:
            raise ValueError("Input must be between 0 and 300 seconds")
        pcm = source.readframes(source.getnframes())
    output = Path(args.output)
    # Never overwrite an existing recording; keep the generated audio private.
    with os.fdopen(os.open(output, os.O_WRONLY | os.O_CREAT | os.O_EXCL, 0o600), "wb") as raw:
        with wave.open(raw, "wb") as sink:
            sink.setparams((1, 2, 48000, 0, "NONE", "not compressed"))
            async with connect(url, additional_headers={"Authorization": f"Bearer {key}"},
                               max_size=2**22, open_timeout=15) as ws:
                await ws.send(json.dumps({"type": "session.start", "mode": "qa", "voice": "serena"}))
                deadline = time.monotonic() + 90
                while True:
                    frame = json.loads(await asyncio.wait_for(ws.recv(), max(.01, deadline - time.monotonic())))
                    if frame.get("type") == "error":
                        raise RuntimeError("Session rejected: " + str(frame.get("code")))
                    if frame.get("type") == "session.ready":
                        if (frame.get("input_sample_rate"), frame.get("output_sample_rate")) != (16000, 48000):
                            raise RuntimeError("Unexpected audio format")
                        break
                print("Connected: 16 kHz input / 48 kHz output")

                async def receive():
                    async for message in ws:
                        if isinstance(message, bytes):
                            sink.writeframesraw(message)
                        else:
                            event = json.loads(message)
                            if event.get("type") == "error":
                                raise RuntimeError("Session error: " + str(event.get("code")))
                            if event.get("type") == "reply.done":
                                print(event.get("text", ""))
                            if event.get("type") == "session.closed":
                                return

                receiver = asyncio.create_task(receive())
                try:
                    # Keep receiving while sending 20 ms PCM frames at real-time speed.
                    audio = pcm + bytes(32000 * args.tail_seconds)
                    start = time.monotonic()
                    for offset in range(0, len(audio), 640):
                        if receiver.done():
                            await receiver
                            raise RuntimeError("Session ended before input completed")
                        await asyncio.sleep(max(0, start + offset / 32000 - time.monotonic()))
                        await ws.send(audio[offset:offset + 640])
                    await ws.send(json.dumps({"type": "session.end"}))
                    await asyncio.wait_for(receiver, 15)
                finally:
                    receiver.cancel()
                    await asyncio.gather(receiver, return_exceptions=True)
    print(f"Saved: {output}")


if __name__ == "__main__":
    parser = argparse.ArgumentParser(description=__doc__)
    parser.add_argument("wav")
    parser.add_argument("--base-url", default=os.environ.get("LIVECODE_BASE_URL", "https://livecode.amphiondev.com/v1"))
    parser.add_argument("--model", default="flexislm", choices=["flexislm"])
    parser.add_argument("--output", default="reply.wav")
    parser.add_argument("--tail-seconds", type=int, default=15, choices=range(1, 61), metavar="1..60")
    try:
        asyncio.run(run(parser.parse_args()))
    except Exception as failure:
        # Never print request headers or credentials.
        parser.exit(1, f"Request failed ({type(failure).__name__}); check input, credentials and service status.\n")
