#!/usr/bin/env python3
"""
Debug the exact parameter flow from LangGraph agent to MCP tools
"""

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

def debug_parameter_flow():
    """Debug how parameters flow from agent to tool"""
    
    print("=== LANGRAPH PARAMETER FLOW DEBUG ===")
    
    workflow = CleanSWEWorkflow(Path.cwd(), Path.cwd() / 'output', False)
    
    # Check the MCP tool wrapper
    security_tool = None
    for tool in workflow.mcp_tools:
        if tool.name == 'security_check':
            security_tool = tool
            break
    
    if security_tool:
        print(f"\n1. MCP Tool Inspection:")
        print(f"   Name: {security_tool.name}")
        print(f"   Schema: {json.dumps(security_tool.args_schema, indent=2)}")
        
        print(f"\n2. Direct Tool Call Test:")
        test_args = {'code_files': [{'filename': 'test.py', 'content': 'eval(input())'}]}
        try:
            result = security_tool.invoke(test_args)
            print(f"   ✅ Direct call works: {len(str(result))} chars returned")
        except Exception as e:
            print(f"   ❌ Direct call failed: {e}")
        
        print(f"\n3. Simulated Agent Tool Call:")
        # Simulate what the agent would send
        from langchain_core.messages import AIMessage
        
        tool_call_message = AIMessage(
            content="I'll use the security_check tool",
            tool_calls=[{
                'name': 'security_check',
                'args': {'code_files': [{'filename': 'test.py', 'content': 'eval(input())'}]},
                'id': 'call_123'
            }]
        )
        
        # Test if ToolNode can handle this
        from langgraph.prebuilt import ToolNode
        tool_node = ToolNode([security_tool])
        
        state = {
            'messages': [tool_call_message],
            'sender': 'agent'
        }
        
        try:
            result = tool_node.invoke(state)
            print(f"   ✅ ToolNode call works")
            if 'messages' in result:
                for msg in result['messages']:
                    if hasattr(msg, 'content') and msg.content:
                        content_preview = str(msg.content)[:200]
                        print(f"   Response: {content_preview}...")
        except Exception as e:
            print(f"   ❌ ToolNode call failed: {e}")
            import traceback
            traceback.print_exc()

if __name__ == "__main__":
    debug_parameter_flow()