"""
测试 main_agent.py — execute() 会话恢复时检测中断状态
"""
import sys
from pathlib import Path

sys.path.insert(0, str(Path(__file__).parent.parent))


def test_session_recovery_when_last_message_is_tool():
    """当 history_messages 最后一条是 tool 角色时，注入恢复提示"""
    history_messages = [
        {"role": "user", "content": "do something"},
        {"role": "assistant", "content": "", "tool_calls": [
            {"id": "call_1", "type": "function", "function": {"name": "fetch_url", "arguments": "{}"}}
        ]},
        {"role": "tool", "tool_call_id": "call_1", "content": "Error: search engine unavailable"},
    ]

    # 模拟 execute() 中的恢复逻辑
    assert history_messages[-1]["role"] == "tool"
    recovery_hint = (
        "[系统提示] 上一轮任务在工具执行后中断。"
        " 请直接基于已有的工具执行结果和历史上下文继续，"
        " 不要重复之前的工具调用，优先基于已有信息给出结论或完成任务。"
    )
    history_messages.append({"role": "system", "content": recovery_hint})

    assert len(history_messages) == 4
    assert history_messages[-1]["role"] == "system"
    assert "中断" in history_messages[-1]["content"]
    print("  test_session_recovery_when_last_message_is_tool: PASS")


def test_no_recovery_when_last_message_is_assistant():
    """当 history_messages 最后一条是 assistant 时，不注入提示"""
    history_messages = [
        {"role": "user", "content": "do something"},
        {"role": "assistant", "content": "Task done"},
        {"role": "user", "content": "continue"},
        {"role": "assistant", "content": "OK"},
    ]

    assert history_messages[-1]["role"] == "assistant"
    should_inject = history_messages[-1]["role"] == "tool"
    assert should_inject is False
    print("  test_no_recovery_when_last_message_is_assistant: PASS")


def test_empty_history_no_crash():
    """空 history_messages 不崩溃"""
    history_messages = []

    should_inject = bool(history_messages) and history_messages[-1].get("role") == "tool"
    assert should_inject is False
    print("  test_empty_history_no_crash: PASS")


if __name__ == "__main__":
    test_session_recovery_when_last_message_is_tool()
    test_no_recovery_when_last_message_is_assistant()
    test_empty_history_no_crash()
