#!/usr/bin/env python3
"""FrightVoice example 2: one visitor turn.

Sends what a visitor said, prints the character's reply sentence by sentence as
it arrives, and saves the spoken reply. This one call replaces a chat model plus
a text-to-speech service.

    export FV_BASE="https://…"      # the base URL sent with your key
    export FV_KEY="fv_beta_…"
    python3 turn.py "Are you a real skeleton?"
    python3 turn.py "Are you a real skeleton?" --prop prop_3f9a1c07be --out reply.mp3

With no --prop it uses your first prop, and registers one called Bones if you
have none. Needs only Python 3.8 or newer. No packages to install.
"""

import argparse
import base64
import json
import os
import time
import urllib.request

BASE = os.environ["FV_BASE"].rstrip("/")
KEY = os.environ["FV_KEY"]
HEADERS = {"Authorization": f"Bearer {KEY}", "Content-Type": "application/json"}


def call(path, body=None):
    data = json.dumps(body).encode() if body is not None else None
    return urllib.request.urlopen(urllib.request.Request(BASE + path, data=data, headers=HEADERS), timeout=90)


def a_prop() -> str:
    with call("/v1/props") as response:
        props = json.load(response)["props"]
    if props:
        return props[0]["id"]
    with call("/v1/props", {"name": "Bones", "persona": "skelly", "location": "by the front gate"}) as response:
        return json.load(response)["id"]


def main() -> None:
    parser = argparse.ArgumentParser(description=__doc__, formatter_class=argparse.RawDescriptionHelpFormatter)
    parser.add_argument("text", help="what the visitor said")
    parser.add_argument("--prop", help="a prop id; default: your first prop")
    parser.add_argument("--out", default="reply.mp3")
    args = parser.parse_args()
    prop = args.prop or a_prop()

    started = time.monotonic()
    first_sound = None
    audio = bytearray()
    # audio=mp3 asks for the speech as slices of one MP3 stream: join them in order.
    with call(f"/v1/props/{prop}/turn?audio=mp3", {"text": args.text}) as response:
        for line in response:  # one JSON event per line, sent as soon as it exists
            if not line.strip():
                continue
            event = json.loads(line)
            kind = event["type"]
            if kind == "text":
                print(f"  {event['text']}")
            elif kind == "audio":
                if first_sound is None:
                    first_sound = time.monotonic() - started
                audio += base64.b64decode(event["b64"])
            elif kind == "error":
                print(f"  failed at {event.get('stage')}: {event.get('message')}")
            # "transcript" (what was heard) and "done" (timings) are also sent

    if audio:
        with open(args.out, "wb") as out:
            out.write(audio)
        print(f"first sound after {first_sound:.2f} s; saved {args.out} ({len(audio) // 1024} KB)")


if __name__ == "__main__":
    main()
