"""Python 3.10+, standard library only. Set BTV_API_KEY before running."""
import json
import os
from email.utils import parsedate_to_datetime
from http.client import IncompleteRead
from pathlib import Path
import time
from urllib.error import HTTPError, URLError
from urllib.parse import urljoin, urlsplit
from urllib.request import Request, HTTPRedirectHandler, build_opener
import uuid

BASE = os.getenv("BTV_BASE_URL", "https://api.apexcorelink.org/voice/api/v1").rstrip("/")
KEY = os.environ["BTV_API_KEY"]
REQUEST_ID = os.getenv("BTV_REQUEST_ID") or str(uuid.uuid4())
OUTPUT = Path(os.getenv("BTV_OUTPUT", "voice.mp3"))


class NoRedirect(HTTPRedirectHandler):
    def redirect_request(self, req, fp, code, msg, headers, newurl):
        return None  # Never forward credentials through a redirect.


opener = build_opener(NoRedirect())


def request(method, path, body=None, *, operation_id=None, audio=False):
    relative = path if path.startswith("/voice/") else path.lstrip("/")
    url = urljoin(BASE + "/", relative)
    origin = lambda value: (urlsplit(value).scheme, urlsplit(value).netloc)
    if origin(url) != origin(BASE):
        raise RuntimeError("Refusing to send the key to a different host")
    headers = {"Authorization": "Bearer " + KEY}
    if operation_id: headers["Idempotency-Key"] = operation_id
    data = json.dumps(body, ensure_ascii=False).encode() if body is not None else None
    if data is not None: headers["Content-Type"] = "application/json"
    deadline = time.monotonic() + float(os.getenv("BTV_REQUEST_WAIT_SECONDS", "1800"))
    attempt = 0
    while True:
        try:
            with opener.open(Request(url, data, headers, method=method), timeout=30) as response:
                content = response.read()
                if audio:
                    if response.headers.get_content_type() != "audio/mpeg" or not content:
                        raise RuntimeError("Expected an MP3 download")
                    return content
                return json.loads(content)
        except HTTPError as error:
            if (error.code not in (408, 429, 500, 502, 503, 504, 507) or
                    time.monotonic() >= deadline or (method == "POST" and not operation_id)):
                try:
                    details = json.loads(error.read()).get("error", {})
                except (ValueError, AttributeError):
                    details = {}
                message = f"HTTP {error.code}: {details.get('code')}"
                message += f"; request_id={details.get('request_id')}"
                raise RuntimeError(message) from None
            try:
                value = error.headers.get("Retry-After", "3")
                delay = max(1, float(value))
            except ValueError:
                try: delay = max(1, parsedate_to_datetime(value).timestamp() - time.time())
                except (TypeError, ValueError, OverflowError): delay = 3
        except (TimeoutError, URLError, ConnectionError, IncompleteRead):
            if time.monotonic() >= deadline or (method == "POST" and not operation_id): raise
            delay = min(30, 2 ** min(attempt, 5))
        if time.monotonic() + delay > deadline:
            raise TimeoutError("Retry window ended; keep the same Idempotency-Key or resume polling this ID")
        attempt += 1
        time.sleep(delay)


def main():
    # Save this ID: after a timeout, repeat the same body with this BTV_REQUEST_ID.
    print("Idempotency-Key:", REQUEST_ID)
    request("GET", "me")
    voices = request("GET", "voices?category=catalog&language=ru&limit=1")["voices"]
    if not voices: raise RuntimeError("No suitable voice found")
    voice_id = os.getenv("BTV_VOICE_ID") or voices[0]["id"]
    print("BTV_VOICE_ID:", voice_id)
    receipt = request("POST", "tasks", {
        "text": "Привет! Это проверка API BlooTube Voice.",
        "voice_id": voice_id, "language": "ru",
    }, operation_id=REQUEST_ID)
    task_id = receipt["task"]["task_id"]
    print("Task:", task_id)
    deadline = time.monotonic() + float(os.getenv("BTV_POLL_WAIT_SECONDS", "3600"))
    while time.monotonic() < deadline:
        task = request("GET", "tasks/" + task_id)["task"]
        if task["status"] == "completed":
            audio = request("GET", task["download_url"], audio=True)
            temporary = OUTPUT.with_suffix(OUTPUT.suffix + ".tmp")
            temporary.write_bytes(audio)
            temporary.replace(OUTPUT)
            print("Saved:", OUTPUT)
            return
        if task["status"] in ("failed", "cancelled"):
            raise RuntimeError(f"Task {task_id}: {task['status']}; {task.get('error')}")
        time.sleep(2)
    raise TimeoutError(f"Task {task_id} is still running; resume polling this ID")


if __name__ == "__main__": main()
