import json
import os
import sys
from urllib.error import HTTPError, URLError
from urllib.request import Request, urlopen


def main():
    key = os.environ["QUICKROUTER_API_KEY"]
    base = os.getenv("QUICKROUTER_BASE_URL", "https://api.quickrouter.ai/v1").rstrip("/")
    model = os.getenv("QUICKROUTER_MODEL", "glm-5.3")
    payload = {
        "model": model,
        "messages": [{"role": "user", "content": "用一句话解释 API Base URL。"}],
        "max_tokens": 1024,
        "stream": False,
    }
    request = Request(
        base + "/chat/completions",
        data=json.dumps(payload, ensure_ascii=False).encode("utf-8"),
        headers={"Authorization": "Bearer " + key, "Content-Type": "application/json"},
        method="POST",
    )
    try:
        with urlopen(request, timeout=60) as response:
            data = json.load(response)
            request_id = response.headers.get("x-request-id")
    except HTTPError as error:
        print("HTTP:", error.code, "request_id:", error.headers.get("x-request-id"), file=sys.stderr)
        raise SystemExit(1) from None
    except (URLError, TimeoutError):
        print("连接失败或读取超时；检查证书与网络，再查调用记录，不自动重发。", file=sys.stderr)
        raise SystemExit(1) from None
    choices = data.get("choices") or []
    if not choices:
        raise SystemExit("缺少 choices；检查当前模型与接口。")
    choice = choices[0]
    answer = choice.get("message", {}).get("content")
    print("model:", data.get("model"))
    print("request_id:", request_id)
    print("answer:", answer)
    print("finish_reason:", choice.get("finish_reason"))
    print("usage:", json.dumps(data.get("usage"), ensure_ascii=False))
    if not isinstance(answer, str) or not answer.strip() or choice.get("finish_reason") == "length":
        raise SystemExit("输出为空或被截断；调整参数前先核对本次调用记录。")


if __name__ == "__main__":
    main()
