#!/usr/bin/env python3
"""
Debug agent tool calls vs direct tool calls to identify the workflow issue
"""

from workflows.clean_swe_workflow import CleanSWEWorkflow
from pathlib import Path
from langchain_core.messages import HumanMessage
import json

def debug_agent_tool_calls():
    """Debug how agents call tools vs direct calls"""
    
    # Create workflow
    workflow = CleanSWEWorkflow(Path.cwd(), Path.cwd() / 'output', False)
    
    # Create a simple state for testing
    test_state = {
        "messages": [HumanMessage(content="Use security_check tool to scan this code: print('test')\neval(input())")],
        "sender": "human"
    }
    
    print("=== AGENT TOOL CALL DEBUG ===")
    
    # Check how tools are bound to the agent
    print(f"\nAgent has {len(workflow.all_agent_tools)} total tools")
    
    # Find the ChatAnthropic model with tools
    software_engineer = None
    for node_name, node_func in workflow.app.nodes.items():
        if 'software' in node_name.lower():
            software_engineer = node_func
            break
    
    if software_engineer:
        print(f"Found software engineer node")
        
        # Check if tools are properly bound
        try:
            # Get the agent function
            agent_func = software_engineer
            print(f"Agent function: {type(agent_func)}")
            
            # Try to inspect the bound tools
            # This is tricky as the binding is internal to LangChain
            
        except Exception as e:
            print(f"Error inspecting agent: {e}")
    
    # Let's check the tool node directly
    tool_nodes = [name for name in workflow.app.nodes.keys() if 'tool' in name.lower()]
    print(f"Tool nodes found: {tool_nodes}")
    
    if tool_nodes:
        tool_node = workflow.app.nodes[tool_nodes[0]]
        print(f"Tool node type: {type(tool_node)}")
        
        # Check if we can access the tools in the tool node
        if hasattr(tool_node, 'tools'):
            print(f"Tool node has {len(tool_node.tools)} tools")
            
            # Check for security_check
            security_tools = [t for t in tool_node.tools if t.name == 'security_check']
            if security_tools:
                tool = security_tools[0]
                print(f"Found security_check in tool node: {type(tool)}")
                
                # Test direct call vs tool node call
                test_args = {
                    'code_files': [{'filename': 'test.py', 'content': "eval(input())"}]
                }
                
                print(f"\n=== DIRECT TOOL CALL TEST ===")
                try:
                    result = tool.invoke(test_args)
                    print(f"✅ Direct tool call successful")
                    print(f"Result: {str(result)[:100]}...")
                except Exception as e:
                    print(f"❌ Direct tool call failed: {e}")
                
                print(f"\n=== TOOL NODE CALL TEST ===")
                try:
                    # Create a tool call message like the agent would
                    from langchain_core.messages import AIMessage, ToolMessage
                    
                    tool_call_msg = AIMessage(
                        content="",
                        tool_calls=[{
                            'name': 'security_check',
                            'args': test_args,
                            'id': 'test_call_123'
                        }]
                    )
                    
                    # Test with tool node
                    state_with_tool_call = {
                        "messages": [tool_call_msg],
                        "sender": "agent"
                    }
                    
                    result = tool_node.invoke(state_with_tool_call)
                    print(f"✅ Tool node call successful")
                    print(f"Result type: {type(result)}")
                    
                except Exception as e:
                    print(f"❌ Tool node call failed: {e}")
                    import traceback
                    traceback.print_exc()
                    
        else:
            print(f"Tool node has no 'tools' attribute")

if __name__ == "__main__":
    debug_agent_tool_calls()