"""一封合成电报的真实 API 对照。默认离线；--live 仅发送内置的虚构电报一次。"""
import argparse
import json
import os
import sys
import time
from urllib import error, request

RADIO = "千帆渡的接收簿上，J17 记为：已靠岸。上一行 J16 写着：等候。请只交回 J17。"
EXPECTED = {"job_id": "J17", "status": "arrived", "evidence": "已靠岸"}
SCHEMA = {
    "type": "object", "additionalProperties": False,
    "properties": {"job_id": {"type": "string"}, "status": {"type": "string", "enum": ["waiting", "arrived"]},
                   "evidence": {"type": "string"}},
    "required": ["job_id", "status", "evidence"]
}


def make_request(model):
    return {"model": model, "max_tokens": 256,
            "system": "从电报提取指定船号。已靠岸映射 arrived，等候映射 waiting。evidence 只录与该船号对应的状态原词。",
            "messages": [{"role": "user", "content": RADIO}],
            "output_config": {"format": {"type": "json_schema", "schema": SCHEMA}}}


def judge(message):
    if message.get("stop_reason") != "end_turn":
        return "待复核", "调用结束原因 " + str(message.get("stop_reason"))
    try:
        text = "".join(item["text"] for item in message["content"] if item.get("type") == "text")
        claim = json.loads(text)
    except (KeyError, TypeError, ValueError, AttributeError):
        return "待复核", "正文不能解析为 JSON"
    if not isinstance(claim, dict) or set(claim) != set(EXPECTED):
        return "待复核", "字段不完整或多余"
    mismatches = [key for key in EXPECTED if claim[key] != EXPECTED[key]]
    return ("待复核", "不符字段 " + ",".join(mismatches)) if mismatches else ("通过", "船号、状态与原文引句均吻合")


def fixture(claim, stop="end_turn"):
    return {"stop_reason": stop, "content": [{"type": "text", "text": json.dumps(claim, ensure_ascii=False)}]}


def offline():
    for name, msg, verdict in [
        ("基准", fixture(EXPECTED), "通过"),
        ("错船", fixture({**EXPECTED, "job_id": "J16"}), "待复核"),
        ("截断", fixture(EXPECTED, "max_tokens"), "待复核"),
        ("拒答", fixture({}, "refusal"), "待复核")
    ]:
        state, detail = judge(msg)
        assert state == verdict
        print(f"{name} | {state} | {detail}")


def live():
    model, key = os.getenv("ANTHROPIC_MODEL"), os.getenv("ANTHROPIC_API_KEY")
    if not (model and key):
        sys.exit("请先在自己的终端设置 ANTHROPIC_MODEL 和 ANTHROPIC_API_KEY。")
    payload = json.dumps(make_request(model)).encode()
    req = request.Request("https://api.anthropic.com/v1/messages", data=payload, method="POST",
                          headers={"content-type": "application/json", "anthropic-version": "2023-06-01", "x-api-key": key})
    start = time.monotonic()
    try:
        with request.urlopen(req, timeout=50) as response:
            doc = json.load(response)
    except error.HTTPError as exc:
        sys.exit(f"HTTP {exc.code}，核对凭证、模型权限及账户配额。未自动重试。")
    except (error.URLError, OSError, ValueError) as exc:
        sys.exit(f"未取得可读的服务端回执 ({type(exc).__name__})。")
    if not isinstance(doc, dict):
        sys.exit("响应格式异常。")
    state, detail = judge(doc)
    print("真实 API |", state, "|", detail)
    print("模型", doc.get("model"), "| stop_reason", doc.get("stop_reason"), "| 耗时毫秒", round(1000*(time.monotonic()-start)))
    print("服务端回报的 usage", json.dumps(doc.get("usage", {}), ensure_ascii=False))
    return 0 if state == "通过" else 1


if __name__ == "__main__":
    parser = argparse.ArgumentParser(description=__doc__)
    parser.add_argument("--live", action="store_true", help="向 Anthropic 发送一次虚构电报，可能产生 API 费用")
    if parser.parse_args().live:
        sys.exit(live())
    offline()
