#!/usr/bin/env python3
"""One explicit text request; key is read privately and never saved or printed."""
import getpass
import json
import urllib.error
import urllib.request

API_URL = "https://api.ylink.uk/v1/chat/completions"
MODEL = "claude-sonnet-5-5"


class NoRedirect(urllib.request.HTTPRedirectHandler):
    def redirect_request(self, *args, **kwargs):
        return None


def main():
    key = getpass.getpass("粘贴本站 API key（输入不显示）：").strip()
    if not key:
        raise SystemExit("没有输入密钥，未发送请求。")
    body = {
        "model": MODEL,
        "messages": [{"role": "user", "content": "Reply with the single word: OK"}],
        "max_tokens": 32,
        "stream": False,
    }
    request = urllib.request.Request(
        API_URL,
        data=json.dumps(body).encode("utf-8"),
        headers={"Authorization": "Bearer " + key, "Content-Type": "application/json"},
        method="POST",
    )
    try:
        with urllib.request.build_opener(NoRedirect).open(request, timeout=60) as response:
            data = json.load(response)
            print("HTTP:", response.status)
            print("回答:", data["choices"][0]["message"]["content"])
            print("用量:", data.get("usage", {}))
            print("接下来到本站“使用日志”核对这笔调用与费用。")
    except urllib.error.HTTPError as error:
        print("HTTP:", error.code, "；请先到使用日志检查，不自动重试。")
    except (urllib.error.URLError, TimeoutError):
        print("请求超时或连接失败；先查使用日志是否已有记录，再决定是否重试。")
    finally:
        key = None


if __name__ == "__main__":
    main()
