from typing import Dict, Any
from .base import Tool
import logging

logger = logging.getLogger(__name__)

class CalculatorTool(Tool):
    """Tool for performing basic arithmetic calculations"""
    
    def __init__(self):
        super().__init__(
            name="calculator",
            description="Perform basic arithmetic calculations (+, -, *, /, ^)"
        )
        
    async def execute(self, input_data: str) -> Dict[str, Any]:
        """Execute a calculation based on the input expression"""
        try:
            # Clean and validate the input
            expression = self._clean_expression(input_data)
            if not expression:
                return {
                    "success": False,
                    "error": "Invalid or empty expression"
                }
                
            # Evaluate the expression
            result = self._evaluate_expression(expression)
            
            return {
                "success": True,
                "expression": expression,
                "result": result
            }
            
        except Exception as e:
            logger.error(f"Error in calculation: {str(e)}")
            return {
                "success": False,
                "error": f"Error during calculation: {str(e)}"
            }
            
    def _clean_expression(self, expression: str) -> str:
        """Clean and validate the input expression"""
        # Remove whitespace and convert to lowercase
        cleaned = ''.join(expression.split()).lower()
        
        # Basic validation of characters
        valid_chars = set("0123456789+-*/^(). ")
        if not all(c in valid_chars for c in cleaned):
            raise ValueError("Invalid characters in expression")
            
        return cleaned
        
    def _evaluate_expression(self, expression: str) -> float:
        """Evaluate a mathematical expression"""
        try:
            # Replace ^ with ** for exponentiation
            expression = expression.replace('^', '**')
            
            # Use eval with a restricted set of operations
            # Note: In a production environment, you would want to use a proper
            # parser instead of eval for security reasons
            result = eval(expression, {"__builtins__": {}}, {})
            
            if isinstance(result, (int, float)):
                return float(result)
            else:
                raise ValueError("Invalid result type")
                
        except Exception as e:
            raise ValueError(f"Invalid expression: {str(e)}")
