"""Standalone, offline companion for the 手写 Agent series (Python 3.8+)."""

from __future__ import annotations

import argparse
from dataclasses import dataclass, field
from operator import add, sub

TASK = "修好加法配置，并用固定样例验证。"
SOURCE = "calc.txt"
NOTE = "notes.txt"
WRONG = "operation = subtract"
RIGHT = "operation = add"
NOTE_TEXT = "请用固定样例验证加法配置。"
PATCH = "fix_add"
UPDATES = {
    ("edit_file", PATCH): (SOURCE, WRONG, RIGHT),
    ("write_file", "verification_note"): (NOTE, None, NOTE_TEXT),
}
READS = {("read_file", SOURCE), ("read_file", NOTE), ("check_examples", "addition")}
CASES = ((2, 3, 5), (-2, 2, 0), (7, 0, 7))
OPERATIONS = {WRONG: sub, RIGHT: add}


@dataclass(frozen=True)
class Action:
    name: str
    choice: str


@dataclass
class Workspace:
    files: dict[str, str]
    # 授权由调用方给出，绑定工具、选项和该选项所要求的旧状态。
    grants: set[Action] = field(default_factory=set)


def fixed_checks(files):
    operation = OPERATIONS.get(files.get(SOURCE))
    return tuple(
        operation is not None and operation(a, b) == expected
        for a, b, expected in CASES
    )


def execute(workspace, action):
    key = (action.name, action.choice)
    if key not in READS and key not in UPDATES:
        return True, "未知的工具或选项，请从练习菜单选择"

    if action.name == "read_file":
        content = workspace.files.get(action.choice)
        if content is None:
            return True, "这份材料还没创建"
        return False, "\n".join(
            f"{index:>3} | {line}" for index, line in enumerate(content.splitlines(), 1)
        )

    if action.name == "check_examples":
        checks = fixed_checks(workspace.files)
        status = 0 if all(checks) else 1
        return status != 0, f"{sum(checks)}/{len(checks)} 个样例通过（状态 {status}）"

    if action not in workspace.grants:
        return True, "这项修改没有授权，工作区未变"
    target, old, new = UPDATES[key]
    if old is None:
        if target in workspace.files:
            return True, "材料已存在，请先读取"
        workspace.files[target] = new
    else:
        content = workspace.files.get(target, "")
        if content.splitlines().count(old) != 1:
            return True, "旧内容需要唯一匹配，请重新读取"
        if content != old:
            return True, "材料与授权时的状态不同，请重新读取"
        workspace.files[target] = new
    workspace.grants.remove(action)
    return False, f"已更新 {target}"


def text_response(text):
    return "end_turn", [{"type": "text", "text": text}]


def simulate(messages, *, greeting=False, read_only=False):
    """固定决策模拟器，返回与练习所需的 API 字段同形的消息。"""
    if greeting:
        return text_response("Agent 根据反馈决定下一步，再由外壳执行动作。")
    last = messages[-1]
    count = len(messages) // 2 + 1
    if isinstance(last["content"], str):
        action = Action("read_file", SOURCE)
    else:
        result = last["content"][0]
        if result["is_error"]:
            return text_response("停在工具报错处。")
        if read_only:
            return text_response(f"已读到 {result['content']}。")
        if result["tool_use_id"] == "call-1" and WRONG in result["content"]:
            action = Action("edit_file", PATCH)
        elif result["tool_use_id"] in {"call-1", "call-2"} and "样例通过" not in result["content"]:
            action = Action("check_examples", "addition")
        else:
            return text_response("已核对固定样例。")
    return "tool_use", [{"type": "tool_use", "id": f"call-{count}",
                         "name": action.name, "input": {"choice": action.choice}}]


def clip(text, limit=60):
    marker = "\n[…中间省略…]\n"
    if limit <= len(marker):
        raise ValueError("输出预算须大于省略标记的长度")
    if len(text) <= limit:
        return text
    space = limit - len(marker)
    head = space // 2
    tail = space - head
    return text[:head] + marker + text[-tail:]


def handoff(messages, task, stop_reason, blocks):
    # 只在得到完整、非空的纯文本回复后开启新对话。
    if stop_reason != "end_turn" or any(block["type"] != "text" for block in blocks):
        return messages
    note = "\n".join(block["text"] for block in blocks).strip()
    if not note:
        return messages
    return [{"role": "user", "content": f"{task}\n\n交接记录\n{note}"}]


def run(workspace, *, read_only=False, max_rounds=6, show=False):
    messages = [{"role": "user", "content": TASK}]
    trace = []
    for _ in range(max_rounds):
        stop, blocks = simulate(messages, read_only=read_only)
        messages.append({"role": "assistant", "content": blocks})
        if stop != "tool_use":
            if show:
                print(f"{blocks[0]['text']} [{stop}]")
            return stop, trace

        results = []
        for block in blocks:
            if block["type"] != "tool_use":
                continue
            action = Action(block["name"], block["input"]["choice"])
            if read_only and action != Action("read_file", SOURCE):
                error, output = True, "本章只开放读取"
            else:
                error, output = execute(workspace, action)
            trace.append((action.name, action.choice, error))
            results.append({"type": "tool_result", "tool_use_id": block["id"],
                            "content": clip(output), "is_error": error})
            if show:
                print(f"{block['id']} {action.name}({action.choice}) → {output}")
        if not results:
            return "missing_tool_use", trace
        messages.append({"role": "user", "content": results})
    return "round_limit", trace


def practice_eval():
    read = ("read_file", SOURCE, False)
    verify = ("check_examples", "addition", False)
    edit = ("edit_file", PATCH, False)
    denied = ("edit_file", PATCH, True)
    # 每题固定初始状态、是否授权、轮数和独立的预期结果。
    problems = (
        ("修复加法", WRONG, True, 6, RIGHT, (True, True, True), "end_turn", [read, edit, verify]),
        ("保留正确配置", RIGHT, False, 6, RIGHT, (True, True, True), "end_turn", [read, verify]),
        ("无授权保留原状", WRONG, False, 6, WRONG, (False, False, True), "end_turn", [read, denied]),
        ("预算用尽保留原状", WRONG, True, 1, WRONG, (False, False, True), "round_limit", [read]),
    )
    passed = 0
    for name, initial, grant, rounds, expected, checks, expected_stop, expected_trace in problems:
        fixture = {SOURCE: initial, NOTE: NOTE_TEXT}
        workspace = Workspace(fixture.copy(), {Action("edit_file", PATCH)} if grant else set())
        stop, trace = run(workspace, max_rounds=rounds)
        expected_files = {**fixture, SOURCE: expected}
        ok = workspace.files == expected_files and fixed_checks(workspace.files) == checks
        ok = ok and stop == expected_stop and trace == expected_trace
        print(f"{'PASS' if ok else 'FAIL'} {name}")
        passed += ok
    print(f"{passed}/{len(problems)} 道题通过")
    return passed == len(problems)


def main():
    parser = argparse.ArgumentParser(description=__doc__)
    parser.add_argument("chapter", choices=("110", "111", "112", "113", "114", "115", "116"))
    chapter = parser.parse_args().chapter
    if chapter == "110":
        messages = [{"role": "user", "content": "用一句话解释什么是 Agent。"}]
        stop, blocks = simulate(messages, greeting=True)
        print(blocks[0]["text"], f"[{stop}]")
    elif chapter == "111":
        run(Workspace({SOURCE: WRONG}), read_only=True, show=True)
    elif chapter == "112":
        workspace = Workspace({SOURCE: WRONG}, {Action("edit_file", PATCH),
                                                Action("write_file", "verification_note")})
        action = Action("write_file", "verification_note")
        print(f"{action.name}({action.choice}) → {execute(workspace, action)[1]}")
        run(workspace, show=True)
    elif chapter == "113":
        run(Workspace({SOURCE: WRONG}), show=True)
    elif chapter == "114":
        messages = [{"role": "user", "content": TASK}]
        stop, blocks = text_response("   ")
        if handoff(messages, TASK, stop, blocks) is not messages:
            return 1
        print("空摘要： 保留原会话")
        incomplete = [{"type": "text", "text": "未写完"}]
        tool_use = [{"type": "tool_use", "name": "read_file", "input": {"choice": SOURCE}}]
        if handoff(messages, TASK, "max_tokens", incomplete) is not messages:
            return 1
        if handoff(messages, TASK, "end_turn", tool_use) is not messages:
            return 1
        print("截断或包含工具调用： 保留原会话")
        stop, blocks = text_response("已读到旧配置，下一步检查授权。")
        next_messages = handoff(messages, TASK, stop, blocks)
        if next_messages == messages or not next_messages[0]["content"].startswith(TASK):
            return 1
        print("有效摘要：", next_messages[0]["content"].replace("\n", " "))
        clipped = clip("开头 " + "中" * 100 + " 结尾")
        if len(clipped) != 60 or not (clipped.startswith("开头") and clipped.endswith("结尾")):
            return 1
        print(f"长输出：{len(clipped)} 字符，保留头尾")
    elif chapter == "115":
        return 0 if practice_eval() else 1
    else:
        run(Workspace({SOURCE: WRONG}, {Action("edit_file", PATCH)}), show=True)
        return 0 if practice_eval() else 1
    return 0


if __name__ == "__main__":
    raise SystemExit(main())
