"""云验证 · Python 示例（仅使用标准库）"""

import json
import urllib.parse
import urllib.request

# 替换成你在后台「我的应用」页面中的信息
API_KEY = "pk_请替换成你的APIKey"
API_URL = "https://你的域名/api/verify.php"
QUERY_URL = "https://你的域名/api/query.php"


def verify_card(card: str, device: str) -> dict:
    """验证卡密，成功会扣减 1 次；失败不扣次。"""
    payload = json.dumps({
        "key": API_KEY,
        "card": card,
        "device": device,
    }).encode("utf-8")

    request = urllib.request.Request(
        API_URL,
        data=payload,
        headers={"Content-Type": "application/json"},
        method="POST",
    )

    try:
        with urllib.request.urlopen(request, timeout=8) as response:
            return json.loads(response.read().decode("utf-8"))
    except Exception as exc:
        return {"ok": False, "code": -1, "msg": f"请求失败: {exc}"}


def query_card(card: str) -> dict:
    """查询卡密剩余次数，不扣次数。"""
    url = f"{QUERY_URL}?key={urllib.parse.quote(API_KEY)}&card={urllib.parse.quote(card)}"
    try:
        with urllib.request.urlopen(url, timeout=8) as response:
            return json.loads(response.read().decode("utf-8"))
    except Exception as exc:
        return {"ok": False, "code": -1, "msg": f"请求失败: {exc}"}


if __name__ == "__main__":
    result = verify_card("ABCD-EFGH-JKLM-NPQR", "desktop-device-001")

    if result.get("ok"):
        print("验证成功，剩余", result["data"]["remaining"], "次")
    else:
        print("验证失败：", result.get("msg"))
