"""复跑 2026-11-04 的订单核对题。默认离线，--live 才向所选服务发送请求。"""

import argparse
import http.client
import json
import os
import sys
import time

ROWS = [
    {"id": "A01", "state": "paid", "cents": 1299},
    {"id": "A02", "state": "refunded", "cents": 550},
    {"id": "A01", "state": "paid", "cents": 1299},
    {"id": "A03", "state": "paid", "cents": 750},
    {"id": "A04", "state": "pending", "cents": 100},
]
MODELS = ("deepseek-flash", "deepseek-v4-pro")
SERVICES = {
    "deepseek": ("api.deepseek.com", "/chat/completions", "DEEPSEEK_API_KEY"),
    "lidayun": ("api.lidayun.com", "/v1/chat/completions", "LIDAYUN_API_KEY"),
}


def expected_answer():
    paid = {row["id"]: row["cents"] for row in ROWS if row["state"] == "paid"}
    return {"ids": sorted(paid), "paid_count": len(paid), "total_cents": sum(paid.values())}


def prompt():
    return (
        "只保留 paid 行。按 id 去重，同 id 在本题中金额相同。只输出一个 JSON 对象，"
        "ids 是按字典序排列的订单号数组，paid_count 和 total_cents 是整数，"
        "分别表示订单数和总金额（分）。不要增加字段。输入："
        + json.dumps(ROWS, ensure_ascii=False)
    )


def run_model(host, path, key, model):
    body = {
        "model": model,
        "messages": [{"role": "user", "content": prompt()}],
        "thinking": {"type": "disabled"},
        "response_format": {"type": "json_object"},
        "max_tokens": 256,
        "stream": False,
    }
    connection = http.client.HTTPSConnection(host, timeout=90)
    start = time.perf_counter()
    try:
        connection.request("POST", path, body=json.dumps(body).encode("utf-8"),
                           headers={"Authorization": "Bearer " + key, "Content-Type": "application/json"})
        response = connection.getresponse()
        data = response.read()
        if response.status != 200:
            raise ValueError(f"HTTP {response.status}，请核对该端点的模型权限与额度")
        elapsed = time.perf_counter() - start
        result = json.loads(data)
        answer = result["choices"][0]["message"]["content"]
        print(f"回包模型：{result['model']}；耗时：{elapsed:.2f} 秒；用量：{result.get('usage')}")
        print("模型回答：", answer)
        # 序列化后比较，忽略键序，同时严格区分 JSON 布尔值和整数。
        return json.dumps(json.loads(answer), sort_keys=True) == json.dumps(expected_answer(), sort_keys=True)
    finally:
        connection.close()


def main():
    parser = argparse.ArgumentParser(description=__doc__)
    parser.add_argument("--live", choices=SERVICES, help="实际调用指定服务；使用该服务自己的密钥")
    args = parser.parse_args()
    print("同一输入：", prompt())
    print("离线标准答案：", json.dumps(expected_answer(), ensure_ascii=False))
    if not args.live:
        print("离线核对完成，发出的 API 请求数为 0。")
        return 0
    host, path, key_name = SERVICES[args.live]
    key = os.getenv(key_name)
    if not key:
        parser.error(f"请先在本机设置 {key_name}")
    passed = True
    for model in MODELS:
        print(f"\n实际调用 {host} / {model}")
        try:
            correct = run_model(host, path, key, model)
            print("核对结果：", "通过" if correct else "答案不符")
            passed = passed and correct
        except (OSError, http.client.HTTPException, ValueError, LookupError, TypeError) as exc:
            print(f"本次无法核对：{exc}", file=sys.stderr)
            passed = False
    return 0 if passed else 1


if __name__ == "__main__":
    sys.exit(main())
