"""Small standard-library client shared by the documentation projects (Python 3.10+)."""
import json
import os
from urllib.error import HTTPError, URLError
from urllib.request import Request, urlopen

API_ORIGIN = "https://api.kendr.org"


def post_json(path, payload, request_id):
    """One attempt. Keep request_id and payload unchanged when retrying an operation."""
    request = Request(
        API_ORIGIN + path,
        data=json.dumps(payload).encode("utf-8"),
        headers={
            "Authorization": "Bearer " + os.environ["KENDR_API_KEY"],
            "Content-Type": "application/json",
            "Idempotency-Key": request_id,
        },
        method="POST",
    )
    try:
        with urlopen(request, timeout=180) as response:
            result = json.load(response)
    except HTTPError as error:
        # Do not print response bodies: they may contain private prompt/tool data.
        raise RuntimeError(f"Kendr returned HTTP {error.code}; request {request_id}") from error
    except (URLError, TimeoutError) as error:
        raise RuntimeError(
            f"Connection interrupted; preserve request {request_id} for recovery."
        ) from error
    if result.get("ok") is False or result.get("error"):
        raise RuntimeError(f"Kendr did not complete request {request_id}")
    return result


def response_text(response):
    if response.get("status") in {"failed", "incomplete", "cancelled"}:
        raise ValueError("The response did not finish successfully")
    text = "".join(
        part.get("text", "")
        for item in response.get("output", [])
        if item.get("type") == "message"
        for part in item.get("content", [])
        if part.get("type") == "output_text"
    )
    if not text.strip():
        raise ValueError("No completed assistant text was returned")
    return text
