"""Read a saved Anthropic Messages JSON response locally; no API calls."""

import json
from pathlib import Path
import sys


def extract_text(response):
    if not isinstance(response, dict):
        raise ValueError("响应必须是 JSON 对象。")
    if response.get("error"):
        raise ValueError("响应含有 error，请结合 HTTP 状态和响应头排查。")
    blocks = response.get("content")
    if not isinstance(blocks, list):
        raise ValueError("响应没有 content 数组。")
    text = "".join(
        block["text"] for block in blocks
        if isinstance(block, dict) and block.get("type") == "text"
        and isinstance(block.get("text"), str)
    )
    if not text:
        raise ValueError(f"没有文本块；stop_reason={response.get('stop_reason', 'unknown')}")
    return text


def main():
    path = Path(sys.argv[1] if len(sys.argv) > 1 else "claude-response.json")
    response = json.loads(path.read_text(encoding="utf-8"))
    print(extract_text(response))
    reason = response.get("stop_reason")
    if reason == "max_tokens":
        print("注意：达到输出上限，回答可能被截断。", file=sys.stderr)
    elif reason == "tool_use":
        print("注意：模型请求工具调用，仍需应用处理 tool_use 块。", file=sys.stderr)


if __name__ == "__main__":
    try:
        main()
    except (OSError, ValueError, UnicodeError) as exc:
        print(f"读取失败：{exc}", file=sys.stderr)
        sys.exit(1)
