use crate::parser::types::{Value, LambdaParam};
use crate::parser::interpreter::Interpreter;

pub fn call_inline_lambda_ast(
    interp: &mut Interpreter,
    params: &[LambdaParam],
    body_expr: &crate::parser::ast::Expr,
    arg_vals: Vec<Value>,
) -> Result<Value, String> {
    let mut old_vals = Vec::new();

    for (i, param) in params.iter().enumerate() {
        let var_name = match param {
            LambdaParam::Named(n) => n.clone(),
            LambdaParam::Ref(n) => n.clone(),
            LambdaParam::Variadic => "$".to_string(),
        };

        let old = interp.get_variables().get(&var_name).cloned();
        old_vals.push((var_name.clone(), old));

        interp.set_variable(&var_name, arg_vals[i].clone());
    }

    let out = interp.eval_expression(body_expr);

    for (p, maybe_val) in old_vals {
        if let Some(v) = maybe_val {
            interp.set_variable(&p, v);
        } else {
            interp.get_variables_mut().remove(&p);
        }
    }

    out
}
