"""Server-side example using the Python standard library."""
import json
import os
import time
from urllib.error import HTTPError
from urllib.parse import quote, urlencode
from urllib.request import Request, urlopen


def get_transcript(video, *, api_key=None, mode="auto",
                   base_url="https://capslane.com", timeout=1200, interval=2):
    api_key = api_key or os.environ.get("CAPSLANE_API_KEY")
    if not api_key:
        raise ValueError("Set CAPSLANE_API_KEY on your server")
    deadline = time.monotonic() + timeout

    def get(path):
        remaining = deadline - time.monotonic()
        if remaining <= 0:
            raise TimeoutError("Transcript job deadline exceeded")
        request = Request(base_url + path, headers={
            "x-api-key": api_key, "accept": "application/json",
        })
        try:
            with urlopen(request, timeout=min(45, remaining)) as response:
                return json.load(response)
        except HTTPError as error:
            try:
                details = json.load(error)
            except (ValueError, UnicodeError):
                details = {}
            raise RuntimeError(
                f"HTTP {error.code}: {details.get('error', 'request_failed')} "
                f"(request {details.get('requestId', 'unknown')})"
            ) from error

    query = urlencode({"url": video, "mode": mode})
    result = get("/v1/transcript?" + query)
    job_id = result.get("jobId")
    while "content" not in result:
        if result.get("status") in {"failed", "cancelled"}:
            raise RuntimeError(result.get("error", result["status"]))
        if not job_id:
            raise RuntimeError("Response contains neither content nor a job ID")
        remaining = deadline - time.monotonic()
        if remaining <= 0:
            raise TimeoutError("Transcript job deadline exceeded")
        time.sleep(min(max(0.001, interval), remaining))
        result = get("/v1/transcript/" + quote(job_id, safe=""))
    return result


if __name__ == "__main__":
    print(json.dumps(get_transcript("dQw4w9WgXcQ"), indent=2))
