"""
实验目的: 对比测试 streaming=True/False 对 create_agent 工具调用的影响
测试方法: 同一任务分别用 streaming=True 和 streaming=False 执行，对比结果
关键结论: streaming=True 会导致 create_agent 无法正确触发工具调用
实际价值: 验证了必须禁用 streaming 才能让 create_agent 正常工作的关键发现
"""

import os
import sys
current_dir = os.path.dirname(os.path.abspath(__file__))
parent_dir = os.path.join(current_dir, '..')
sys.path.insert(0, parent_dir)
parent_dir = os.path.join(current_dir, '../..')
sys.path.insert(0, parent_dir)

import asyncio
from langchain_agentx import create_opencode_style_agent
from langchain.agents.middleware.todo import TodoListMiddleware
from langchain_core.tools import tool
from langchain_core.messages import HumanMessage
from model.chat_llm import get_chat_llm

@tool
def get_weather(location: str) -> str:
    """获取指定地点的天气信息"""
    return f"{location}的天气是晴天"

async def test_create_opencode_style_agent_streaming():
    print("=" * 80)
    print("测试 create_agent 在不同 streaming 配置下的表现")
    print("=" * 80)

    # 测试 1: streaming=True
    print("\n测试 1: create_agent with streaming=True")
    print("-" * 80)

    llm1 = get_chat_llm('nublar-mass', '10041713')
    llm1.streaming = True
    print(f"LLM streaming: {llm1.streaming}")

    agent1 = create_opencode_style_agent(
        model=llm1,
        tools=[get_weather],
        middleware=[TodoListMiddleware()],
        debug=False
    )

    result1 = await agent1.ainvoke({
        "messages": [HumanMessage("请使用 write_todos 工具创建一个待办清单，包含：1. 查询北京天气。然后执行这个任务。")]
    })

    print(f"\n结果分析:")
    print(f"  消息数量: {len(result1.get('messages', []))}")
    print(f"  是否有 todos: {'todos' in result1}")

    if 'todos' in result1 and result1['todos']:
        print(f"  ✅ Todos 创建成功: {len(result1['todos'])} 个")
        for i, todo in enumerate(result1['todos'], 1):
            print(f"    {i}. {todo.get('content')} [{todo.get('status')}]")
    else:
        print(f"  ❌ Todos 未创建")

    # 检查是否调用了工具
    tool_messages = [m for m in result1.get('messages', []) if hasattr(m, 'name')]
    if tool_messages:
        print(f"  ✅ 工具调用成功: {len(tool_messages)} 次")
        for tm in tool_messages:
            print(f"    - {tm.name}")
    else:
        print(f"  ❌ 没有工具调用")

    # 测试 2: streaming=False
    print("\n" + "=" * 80)
    print("测试 2: create_agent with streaming=False")
    print("-" * 80)

    llm2 = get_chat_llm('nublar-mass', '10041713')
    llm2.streaming = False
    print(f"LLM streaming: {llm2.streaming}")

    agent2 = create_opencode_style_agent(
        model=llm2,
        tools=[get_weather],
        middleware=[TodoListMiddleware()],
        debug=False
    )

    result2 = await agent2.ainvoke({
        "messages": [HumanMessage("请使用 write_todos 工具创建一个待办清单，包含：1. 查询北京天气。然后执行这个任务。")]
    })

    print(f"\n结果分析:")
    print(f"  消息数量: {len(result2.get('messages', []))}")
    print(f"  是否有 todos: {'todos' in result2}")

    if 'todos' in result2 and result2['todos']:
        print(f"  ✅ Todos 创建成功: {len(result2['todos'])} 个")
        for i, todo in enumerate(result2['todos'], 1):
            print(f"    {i}. {todo.get('content')} [{todo.get('status')}]")
    else:
        print(f"  ❌ Todos 未创建")

    # 检查是否调用了工具
    tool_messages = [m for m in result2.get('messages', []) if hasattr(m, 'name')]
    if tool_messages:
        print(f"  ✅ 工具调用成功: {len(tool_messages)} 次")
        for tm in tool_messages:
            print(f"    - {tm.name}")
    else:
        print(f"  ❌ 没有工具调用")

    print("\n" + "=" * 80)
    print("结论")
    print("=" * 80)

    streaming_works = 'todos' in result1 and result1['todos']
    non_streaming_works = 'todos' in result2 and result2['todos']

    print(f"streaming=True:  {'✅ 工作正常' if streaming_works else '❌ 失败'}")
    print(f"streaming=False: {'✅ 工作正常' if non_streaming_works else '❌ 失败'}")

    if not streaming_works and non_streaming_works:
        print("\n⚠️  确认：streaming=True 导致 create_agent 中的工具调用失败")
    elif streaming_works and non_streaming_works:
        print("\n✅ 两种模式都工作正常，问题可能在其他地方")
    elif not streaming_works and not non_streaming_works:
        print("\n❌ 两种模式都失败，问题不在 streaming 配置")

if __name__ == "__main__":
    asyncio.run(test_create_opencode_style_agent_streaming())
