/// Simple Math Tool - Demonstrates basic tool implementation
/// 
/// This tool performs basic arithmetic operations.
/// It demonstrates:
/// - Simple tool implementation
/// - Input validation
/// - Deterministic execution

use crate::tool::Tool;
use async_trait::async_trait;
use lumina_engine::Event;
use serde_json::Value;
use tracing::debug;

/// Simple Math Tool
/// 
/// Performs basic arithmetic operations.
/// 
/// Input format:
/// ```json
/// {
///   "operation": "add",  // "add", "subtract", "multiply", "divide"
///   "a": 10,
///   "b": 5
/// }
/// ```
/// 
/// Output format:
/// ```json
/// {
///   "result": 15,
///   "operation": "add"
/// }
/// ```
#[derive(Debug, Clone, Copy)]
pub struct SimpleMathTool;

impl SimpleMathTool {
    /// Create a new SimpleMathTool
    pub fn new() -> Self {
        Self
    }
}

#[async_trait]
impl Tool for SimpleMathTool {
    fn name(&self) -> &'static str {
        "math"
    }
    
    fn description(&self) -> &'static str {
        "Performs basic arithmetic operations: add, subtract, multiply, divide"
    }
    
    fn schema(&self) -> Option<Value> {
        Some(serde_json::json!({
            "type": "object",
            "properties": {
                "operation": {
                    "type": "string",
                    "enum": ["add", "subtract", "multiply", "divide"],
                    "description": "Operation to perform"
                },
                "a": {
                    "type": "number",
                    "description": "First number"
                },
                "b": {
                    "type": "number",
                    "description": "Second number"
                }
            },
            "required": ["operation", "a", "b"]
        }))
    }
    
    async fn execute(&self, input: Value, _event: &Event) -> Result<Value, String> {
        // Extract parameters
        let operation = input
            .get("operation")
            .and_then(|v| v.as_str())
            .ok_or("Missing required parameter: 'operation'")?;
        
        let a = input
            .get("a")
            .and_then(|v| v.as_f64())
            .ok_or("Missing or invalid parameter: 'a' (must be a number)")?;
        
        let b = input
            .get("b")
            .and_then(|v| v.as_f64())
            .ok_or("Missing or invalid parameter: 'b' (must be a number)")?;
        
        // Perform operation
        let result = match operation {
            "add" => a + b,
            "subtract" => a - b,
            "multiply" => a * b,
            "divide" => {
                if b == 0.0 {
                    return Err("Division by zero".to_string());
                }
                a / b
            }
            _ => return Err(format!("Unknown operation: '{}'. Must be: add, subtract, multiply, divide", operation)),
        };
        
        debug!("Math operation: {} {} {} = {}", a, operation, b, result);
        
        Ok(serde_json::json!({
            "result": result,
            "operation": operation,
            "a": a,
            "b": b
        }))
    }
}

impl Default for SimpleMathTool {
    fn default() -> Self {
        Self::new()
    }
}

