"""Tool call parser"""

import json
from typing import Dict, Any, Optional


class ToolCallParser:
    """Tool call parser for parsing AI tool call requests"""
    
    def parse(self, response: str) -> Optional[Dict[str, Any]]:
        """Parse tool call from AI response
        
        Args:
            response: AI response text
            
        Returns:
            Tool call dictionary or None if no tool call found
        """
        # Extract tool call from response
        tool_call_start = response.find('```tool_call')
        
        if tool_call_start != -1:
            tool_call_end = response.find('```', tool_call_start + 12)  # Use 12 instead of 10
            
            if tool_call_end != -1:
                tool_call_json = response[tool_call_start + 12:tool_call_end].strip()
                try:
                    tool_call = json.loads(tool_call_json)
                    return tool_call
                except json.JSONDecodeError as e:
                    print(f"JSON decode error: {e}")
                    return None
        
        return None
    
    def format_tool_response(self, tool_name: str, result: Any) -> str:
        """Format tool response for AI
        
        Args:
            tool_name: Tool name
            result: Tool execution result
            
        Returns:
            Formatted tool response
        """
        response = {
            "tool": tool_name,
            "result": str(result)
        }
        
        return f"```tool_result\n{json.dumps(response, indent=2)}\n```"
