use std::sync::{Arc, Mutex};
use mumu::parser::interpreter::{Interpreter, DynamicFnInfo};
use mumu::parser::types::{FunctionValue, Value};

pub fn register_aws_bye(interp: &mut Interpreter) {
    let f = Arc::new(Mutex::new(|interp: &mut Interpreter, args: Vec<Value>| {
        eprintln!("[aws:bye] called with args: {:?}", args);
        let res = std::panic::catch_unwind(std::panic::AssertUnwindSafe(|| {
            bye_bridge_fn(interp, args)
        }));
        match res {
            Ok(r) => r,
            Err(e) => {
                eprintln!("[aws:bye] PANIC: {e:?}");
                Err(format!("aws:bye: fatal plugin panic: {e:?}"))
            }
        }
    }));
    let info = DynamicFnInfo::new(f, false);
    interp.register_dynamic_function_ex("aws:bye", info);
    interp.set_variable(
        "aws:bye",
        Value::Function(Box::new(FunctionValue::Named("aws:bye".to_string()))),
    );
}

fn bye_bridge_fn(_interp: &mut Interpreter, _args: Vec<Value>) -> Result<Value, String> {
    Ok(Value::SingleString("Sorry to see you go!!".to_string()))
}
