#!/usr/bin/env python3
"""Python 3.10+ stdlib client: one bounded, non-streaming Chat Completions call.
No automatic retries: a timeout may already have consumed paid tokens.
"""
import json
import os
import urllib.error
import urllib.parse
import urllib.request


class NoRedirect(urllib.request.HTTPRedirectHandler):
    def redirect_request(self, req, fp, code, msg, headers, newurl):
        return None


def main():
    key = os.environ.get("API_STOCK_KEY")
    origin = os.environ.get("API_STOCK_ORIGIN", "https://api.api-stock.com").rstrip("/")
    if not key:
        raise RuntimeError("Set API_STOCK_KEY in your server environment")
    parsed = urllib.parse.urlsplit(origin)
    if parsed.path or parsed.query or parsed.fragment or parsed.username or not (
        parsed.scheme == "https" and parsed.hostname in {"api.api-stock.com", "api.apihubs.ru"}
        or parsed.scheme == "http" and parsed.hostname in {"127.0.0.1", "localhost"}
    ):
        raise RuntimeError("Use an official API origin or local test server")
    payload = {"model": "gpt-6-luna", "messages": [{"role": "user", "content": "Reply with OK."}],
               "max_tokens": 32, "stream": False}
    request = urllib.request.Request(origin + "/api/v1/chat/completions",
        data=json.dumps(payload).encode(), headers={"Authorization": "Bearer " + key,
        "Content-Type": "application/json", "User-Agent": "APIStockPythonExample/1.0"})
    try:
        with urllib.request.build_opener(NoRedirect()).open(request, timeout=90) as response:
            result = json.load(response)
    except urllib.error.HTTPError as error:
        raise RuntimeError("API HTTP " + str(error.code) + "; check key, balance, model and rate limits") from None
    print(result["choices"][0]["message"]["content"])
    print("Usage:", json.dumps(result.get("usage", {})))


if __name__ == "__main__":
    try:
        main()
    except (RuntimeError, OSError, ValueError, KeyError, IndexError) as error:
        raise SystemExit(str(error))
