#!/usr/bin/env python3
"""FrightVoice example 1: text in, character voice out.

These are the same addresses ElevenLabs uses, so code written for ElevenLabs
works after changing the base URL and the key.

    export FV_BASE="https://…"      # the base URL sent with your key
    export FV_KEY="fv_beta_…"
    python3 speak.py "Welcome to my yard." welcome.mp3
    python3 speak.py "Welcome to my yard." welcome.mp3 VOICE_ID

Needs only Python 3.8 or newer. No packages to install.
"""

import json
import os
import sys
import urllib.request

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


def main() -> None:
    if len(sys.argv) < 2:
        sys.exit(__doc__)
    text = sys.argv[1]
    out = sys.argv[2] if len(sys.argv) > 2 else "speech.mp3"
    voice = sys.argv[3] if len(sys.argv) > 3 else None

    if not voice:  # no voice given: list them and take the first
        with urllib.request.urlopen(urllib.request.Request(f"{BASE}/v1/voices", headers=HEADERS), timeout=30) as response:
            voices = json.load(response)["voices"]
        print("voices:", ", ".join(v["voice_id"] for v in voices))
        voice = voices[0]["voice_id"]

    request = urllib.request.Request(
        f"{BASE}/v1/text-to-speech/{voice}/stream?output_format=mp3_44100_128",
        data=json.dumps({"text": text}).encode(),
        headers=HEADERS,
    )
    with urllib.request.urlopen(request, timeout=60) as response, open(out, "wb") as audio:
        if response.headers.get("X-FV-Voice-Fallback"):
            print(f"note: '{voice}' is not a FrightVoice voice, so the default voice was used")
        while chunk := response.read(8192):  # arrives as it is spoken
            audio.write(chunk)
    print(f"saved {out} in the voice '{voice}'")


if __name__ == "__main__":
    main()
