#!/usr/bin/env python3
"""
Calculator tool for Eden - handles all math operations
"""
import re
import math

def calculate(expression):
    """Safely evaluate math expressions"""
    try:
        # Replace common text with operators
        expression = expression.replace('x', '*').replace('×', '*').replace('÷', '/')
        
        # Safe eval with math functions
        allowed_names = {
            'sqrt': math.sqrt, 'pow': math.pow, 'abs': abs,
            'sin': math.sin, 'cos': math.cos, 'tan': math.tan,
            'log': math.log, 'exp': math.exp, 'pi': math.pi,
            'e': math.e
        }
        
        # Evaluate safely
        result = eval(expression, {"__builtins__": {}}, allowed_names)
        return result
    except:
        return None

def extract_and_calculate(text):
    """Extract math from text and calculate"""
    # Find math expressions like "847 * 293" or "what is 5 + 3"
    patterns = [
        r'(\d+\.?\d*)\s*([+\-*/×÷])\s*(\d+\.?\d*)',  # Basic: 5 + 3
        r'what\s+is\s+(\d+\.?\d*)\s*([+\-*/×÷])\s*(\d+\.?\d*)',  # What is 5 + 3
        r'calculate\s+(\d+\.?\d*)\s*([+\-*/×÷])\s*(\d+\.?\d*)',  # Calculate 5 + 3
    ]
    
    for pattern in patterns:
        match = re.search(pattern, text.lower())
        if match:
            if len(match.groups()) == 3:
                num1, op, num2 = match.groups()
                expression = f"{num1}{op}{num2}"
                result = calculate(expression)
                if result is not None:
                    return result
    
    return None

if __name__ == "__main__":
    # Test
    print(calculate("847 * 293"))  # Should print 248071
    print(extract_and_calculate("What is 847 * 293?"))  # Should print 248071
