#!/usr/bin/env python3
"""FrightVoice example 3: the open microphone.

Plays a WAV file into a prop as if it were the prop's microphone, in real time,
prints what the service sends back, and saves the spoken reply. A real prop does
the same thing with frames from its microphone and a speaker instead of a file.

    pip install websockets
    export FV_BASE="https://…"      # the base URL sent with your key
    export FV_KEY="fv_beta_…"
    python3 live.py prop_3f9a1c07be visitor.wav reply.wav

The WAV must be 16-bit mono at 8000, 16000, 24000 or 48000 Hz.
"""

import asyncio
import json
import os
import sys
import wave

import websockets

BASE = os.environ["FV_BASE"].rstrip("/").replace("https://", "wss://").replace("http://", "ws://")
KEY = os.environ["FV_KEY"]
FRAME_SECONDS = 0.02  # send 20 ms of sound at a time


async def main() -> None:
    if len(sys.argv) < 3:
        sys.exit(__doc__)
    prop, source = sys.argv[1], sys.argv[2]
    out = sys.argv[3] if len(sys.argv) > 3 else "reply.wav"
    with wave.open(source) as clip:
        if clip.getnchannels() != 1 or clip.getsampwidth() != 2:
            sys.exit("the WAV must be 16-bit mono")
        rate = clip.getframerate()
        speech = clip.readframes(clip.getnframes())
    frame = int(rate * FRAME_SECONDS) * 2  # bytes in 20 ms

    async with websockets.connect(f"{BASE}/v1/props/{prop}/live?sample_rate={rate}", max_size=None) as ws:
        # The key can go in an Authorization header. Sending it as the first message
        # works everywhere, including browsers, which cannot set headers here.
        await ws.send(json.dumps({"type": "auth", "key": KEY}))

        async def microphone() -> None:
            for start in range(0, len(speech), frame):
                await ws.send(speech[start:start + frame])
                await asyncio.sleep(FRAME_SECONDS)
            while True:  # a microphone never stops: the quiet is how the service hears the pause
                await ws.send(bytes(frame))
                await asyncio.sleep(FRAME_SECONDS)

        mic = asyncio.create_task(microphone())
        reply, reply_rate = bytearray(), rate
        try:
            async for message in ws:
                if isinstance(message, bytes):  # the prop's voice: 16-bit mono PCM
                    reply += message
                    continue
                event = json.loads(message)
                kind = event["type"]
                if kind == "transcript":
                    print(f"heard: {event['text']}")
                elif kind == "text":
                    print(f"  {event['text']}")
                elif kind == "audio_start":
                    reply_rate = event["sample_rate"]
                    print(f"first sound {event['since_speech_end_ms']} ms after the visitor stopped")
                elif kind == "error":
                    print(f"failed at {event.get('stage')}: {event.get('message')}")
                    break
                elif kind == "done":
                    break
                # also sent: listening, speech_start, speech_end
        finally:
            mic.cancel()

    if reply:
        with wave.open(out, "wb") as saved:
            saved.setnchannels(1)
            saved.setsampwidth(2)
            saved.setframerate(reply_rate)
            saved.writeframes(bytes(reply))
        print(f"saved {out} ({len(reply) / 2 / reply_rate:.1f} s)")


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