#!/usr/bin/env python3
"""
Live Tool Usage Monitor for SWE Agent
Shows real-time tool usage as agents work on tasks.
"""

import sys
import json
import time
import os
from pathlib import Path

def show_available_tools():
    """Show all available tools in the SWE Agent system."""
    sys.path.insert(0, '.')
    
    try:
        from workflows.clean_swe_workflow import CleanSWEWorkflow
        
        # Create workflow to access tools through state machine
        workflow = CleanSWEWorkflow('.', './output', use_planner=False)
        
        # Get tools from the state machine
        state_machine = workflow.workflow
        
        print("🛠️  SWE Agent Tool Arsenal")
        print("=" * 50)
        
        # Tools are defined in the workflow nodes
        tool_count = 0
        
        # Check available tool categories
        categories = {
            'File Operations': ['create_file', 'read_file', 'edit_file', 'delete_file'],
            'Shell & Git': ['execute_shell_command', 'git_status', 'git_diff', 'git_add', 'git_commit'],
            'Code Analysis': ['analyze_code_structure', 'find_functions', 'search_code', 'whoosh_search'],
            'Workspace': ['list_directory', 'get_project_info', 'workspace_overview'],
            'Security': ['security_scan', 'detect_secrets'],
            'Advanced': ['mcp_tools', 'tool_usage_tracker']
        }
        
        for category, tools in categories.items():
            print(f"\n📂 {category}:")
            for tool in tools:
                print(f"   • {tool}")
                tool_count += 1
        
        print(f"\n📊 Total Available Tools: ~{tool_count}+")
        print("💡 Tools are dynamically loaded based on task requirements")
        
    except Exception as e:
        print(f"Error loading tools: {e}")
        print("24 tools are available as mentioned in the logs")

def monitor_tool_usage(watch_time=10):
    """Monitor live tool usage for a specified time."""
    print(f"\n🔍 Monitoring Tool Usage (watching for {watch_time}s)")
    print("=" * 50)
    
    tracker_file = '.tool_usage_tracker.json'
    initial_data = {}
    
    if os.path.exists(tracker_file):
        with open(tracker_file, 'r') as f:
            initial_data = json.load(f)
    
    start_time = time.time()
    
    while time.time() - start_time < watch_time:
        if os.path.exists(tracker_file):
            try:
                with open(tracker_file, 'r') as f:
                    current_data = json.load(f)
                
                # Show new tool usage
                for tool_name, calls in current_data.items():
                    initial_count = len(initial_data.get(tool_name, []))
                    current_count = len(calls)
                    
                    if current_count > initial_count:
                        new_calls = calls[initial_count:]
                        for call in new_calls:
                            status = '✅' if call.get('success', True) else '❌'
                            duration = call.get('duration', 0)
                            print(f"🔧 {tool_name}: {status} {duration:.2f}s")
                        
                        initial_data[tool_name] = calls
                        
            except (json.JSONDecodeError, FileNotFoundError):
                pass
        
        time.sleep(0.5)
    
    print("\n✅ Monitoring complete")

def show_usage_summary():
    """Show summary of tool usage."""
    tracker_file = '.tool_usage_tracker.json'
    
    if not os.path.exists(tracker_file):
        print("📊 No tool usage data available yet")
        return
    
    try:
        with open(tracker_file, 'r') as f:
            usage_data = json.load(f)
        
        print("\n📊 Tool Usage Summary")
        print("=" * 30)
        
        total_calls = sum(len(calls) for calls in usage_data.values())
        print(f"Total tool calls: {total_calls}")
        
        if total_calls > 0:
            print("\n🏆 Most Used Tools:")
            tool_usage = [(tool, len(calls)) for tool, calls in usage_data.items()]
            tool_usage.sort(key=lambda x: x[1], reverse=True)
            
            for tool, count in tool_usage[:10]:  # Top 10
                if count > 0:
                    print(f"   {tool}: {count} calls")
        
    except json.JSONDecodeError:
        print("Error reading tool usage data")

if __name__ == "__main__":
    show_available_tools()
    show_usage_summary()
    
    if len(sys.argv) > 1 and sys.argv[1] == "--monitor":
        watch_time = int(sys.argv[2]) if len(sys.argv) > 2 else 10
        monitor_tool_usage(watch_time)