"""NEBANAN_API_KEY=... python3 generate.py TEXT OUTPUT.mp3 [REQUEST_UUID]

Minimal client for the Nebanan Voice API v1. It creates an asynchronous
text-to-speech job, polls its status and downloads the audio. Set
NEBANAN_VOICE to use a voice other than lira.
"""
import json
import os
import sys
import time
from urllib.error import HTTPError, URLError
from urllib.request import Request, urlopen
from uuid import UUID, uuid4

BASE = "https://api.nebanan.com/v1"
KEY = os.environ["NEBANAN_API_KEY"]
VOICE = os.environ.get("NEBANAN_VOICE", "lira")
HEADERS = {"Authorization": "Bearer " + KEY, "Content-Type": "application/json"}


def request(path, body=None, audio=False, headers=None):
    payload = json.dumps(body).encode() if body is not None else None
    target = path if path.startswith("http") else BASE + path
    for attempt in range(6):
        try:
            with urlopen(Request(target, data=payload, headers={**HEADERS, **(headers or {})}),
                         timeout=60) as response:
                return response.read() if audio else json.load(response)
        except HTTPError as error:
            if error.code not in (429, 502, 503, 504) or attempt == 5:
                raise
            delay = int(error.headers.get("Retry-After") or 2 ** attempt)
        except (URLError, TimeoutError, ConnectionError):
            if attempt == 5:
                raise
            delay = 2 ** attempt
        time.sleep(min(60, delay))


if __name__ == "__main__":
    if len(sys.argv) not in (3, 4):
        raise SystemExit(__doc__)
    idempotency_key = sys.argv[3] if len(sys.argv) == 4 else str(uuid4())
    print("Idempotency-Key =", idempotency_key, flush=True)
    job = request(
        "/text-to-speech/" + VOICE,
        {"text": sys.argv[1], "output_format": "mp3", "max_audio_seconds": 60},
        headers={"Idempotency-Key": idempotency_key},
    )
    print("job_id =", job["job_id"], flush=True)
    while job["status"] in ("queued", "processing"):
        time.sleep(job.get("poll_after_seconds", 2))
        job = request(job["poll_url"])
    if job["status"] != "ready":
        raise SystemExit(job.get("error") or "Синтез не удался.")
    content = request(job["audio_url"], audio=True)
    with open(sys.argv[2], "wb") as file:
        file.write(content)
    print("Готово:", job["duration_ms"], "мс,", job["charge_cents"], "сотых банана")
