"""Python 3.10+; --demo uses a scripted model, otherwise uses Anthropic API."""
import argparse
import json
import os
from pathlib import Path
from urllib.request import Request, urlopen

TOOLS = [{
    "name": "read_file",
    "description": "读取工作目录内一个 UTF-8 文本文件，最多返回 4000 字符。",
    "input_schema": {
        "type": "object",
        "properties": {"path": {"type": "string"}},
        "required": ["path"], "additionalProperties": False,
    },
}]


def execute(call, root):
    """Validate locally. This teaching guard is not an OS sandbox."""
    result = {"type": "tool_result", "tool_use_id": call["id"]}
    try:
        args = call.get("input")
        if call.get("name") != "read_file":
            raise ValueError("工具不存在；只支持 read_file")
        if not isinstance(args, dict) or set(args) != {"path"}:
            raise ValueError("参数必须且只能包含 path")
        if not isinstance(args["path"], str) or not args["path"]:
            raise ValueError("path 必须是非空字符串")
        relative = Path(args["path"])
        if relative.is_absolute():
            raise ValueError("请使用工作目录内的相对路径")
        root = root.resolve()
        target = (root / relative).resolve()
        if not target.is_relative_to(root):
            raise ValueError("拒绝读取工作目录以外的文件")
        parts = target.relative_to(root).parts
        if any(p.startswith(".") for p in relative.parts + parts):
            raise ValueError("本示例拒绝隐藏路径和上级路径")
        if not target.is_file():
            raise ValueError("文件不存在或不是普通文件")
        with target.open("rb") as stream:
            data = stream.read(65537)
        if len(data) > 65536:
            raise ValueError("文件超过 64 KiB，请改读更小的文件")
        text = data.decode("utf-8")
        if "\x00" in text:
            raise ValueError("不支持二进制文件")
        result["content"] = text[:4000]
        if len(text) > 4000:
            result["content"] += "\n[已截断，仅返回前 4000 字符]"
    except (OSError, ValueError) as error:
        result.update(content=str(error), is_error=True)
    return result


def ask_api(messages):
    model = os.environ.get("ANTHROPIC_MODEL")
    key = os.environ.get("ANTHROPIC_API_KEY")
    if not model or not key:
        raise ValueError("请设置 ANTHROPIC_MODEL 和 ANTHROPIC_API_KEY")
    body = {
        "model": model, "max_tokens": 1024, "tools": TOOLS,
        "system": "你是只读项目助手。先读取相关文件，再据内容回答；不要猜测文件内容。",
        "messages": messages,
    }
    request = Request(
        "https://api.anthropic.com/v1/messages",
        data=json.dumps(body).encode(),
        headers={"Content-Type": "application/json", "x-api-key": key,
                 "anthropic-version": "2023-06-01"},
    )
    with urlopen(request, timeout=45) as response:
        return json.load(response)


def demo_model(messages, path="README.md"):
    """Fixed response plan: demonstrates protocol, not model intelligence."""
    if len(messages) == 1:
        return {"stop_reason": "tool_use", "content": [{
            "type": "tool_use", "id": "demo-read-1",
            "name": "read_file", "input": {"path": path},
        }]}
    result = messages[-1]["content"][0]
    text = ("读取失败：" if result.get("is_error") else "已读取文件，内容如下：\n")
    return {"stop_reason": "end_turn", "content": [{
        "type": "text", "text": text + result["content"],
    }]}


def run(question, root, ask, max_steps=6):
    messages = [{"role": "user", "content": question}]
    for step in range(max_steps):
        reply = ask(messages)
        if reply.get("stop_reason") == "max_tokens":
            raise RuntimeError("模型输出被截断；本示例停止，不执行不完整调用")
        blocks = reply["content"]
        messages.append({"role": "assistant", "content": blocks})
        calls = [block for block in blocks if block["type"] == "tool_use"]
        if not calls:
            if reply.get("stop_reason") != "end_turn":
                raise RuntimeError("未正常结束：" + str(reply.get("stop_reason")))
            return "\n".join(b["text"] for b in blocks if b["type"] == "text")
        if len(calls) > 4:
            raise RuntimeError("单轮工具调用超过 4 次，本示例停止")
        results = []
        for call in calls:
            print(f"第 {step + 1} 轮：{call['name']}({call.get('input')})")
            results.append(execute(call, root))
        messages.append({"role": "user", "content": results})
    raise RuntimeError("已到最大轮数，任务未完成")


if __name__ == "__main__":
    parser = argparse.ArgumentParser()
    parser.add_argument("question", nargs="?", default="读取 README.md，告诉我发布命令。")
    parser.add_argument("--root", type=Path, default=Path.cwd())
    parser.add_argument("--demo", action="store_true")
    parser.add_argument("--demo-file", default="README.md", help="离线演示要读取的相对路径")
    args = parser.parse_args()
    ask = (lambda messages: demo_model(messages, args.demo_file)) if args.demo else ask_api
    try:
        print(run(args.question, args.root, ask))
    except (OSError, ValueError, RuntimeError, KeyError) as error:
        parser.exit(1, f"运行停止：{error}\n")
