postscriptum 0.1.0

Multi-interpreted-language scripting engine for Rust with Rhai and Python backends
Documentation
use js_sys::Function;
use wasm_bindgen::prelude::*;

use crate::{Error, FunctionBundle, Result, python::PythonEngine};

// External function to register all functions with Pyodide (defined in wasm_function_bundle.rs)
use crate::python::wasm_function_bundle::register_all_functions_with_pyodide;

pub fn register_bundle(engine: &mut PythonEngine, bundle: &FunctionBundle) -> Result<()> {
    // For WASM, we register functions with Pyodide when it's available
    match bundle {
        FunctionBundle::Python(_) => {
            // Register all functions from the bundle with Pyodide
            // We'll try to register, but if Pyodide isn't ready yet, we'll just continue
            println!("Registering Python function bundle with Pyodide...");
            web_sys::console::log_1(&format!("Registering Python function bundle...").into());

            // First, register the functions in the global scope
            if let FunctionBundle::Python(py_bundle) = bundle {
                if let Err(e) = py_bundle.register() {
                    eprintln!("Failed to register functions in global scope: {:?}", e);
                    // Don't fail entirely, continue with Pyodide registration
                }
            }

            // Then register them with Pyodide
            match register_all_functions_with_pyodide(bundle) {
                Ok(_) => {
                    println!("Successfully registered Python function bundle with Pyodide");
                    engine._initialized = true;
                }
                Err(e) => {
                    // If Pyodide isn't loaded yet, that's OK - we'll try again later when eval is called
                    eprintln!(
                        "Failed to register Python function bundle with Pyodide, will try again: {:?}",
                        e
                    );
                    // Don't fail the registration entirely, just mark that Pyodide isn't ready yet
                }
            }
        }
        _ => {
            // Ignore other bundle types
        }
    }

    Ok(())
}

pub fn eval(engine: &mut PythonEngine, code: &str) -> Result<String> {
    use js_sys::JsString;
    use wasm_bindgen::prelude::*;
    use web_sys::window;

    // Check that we have window object
    let window = window().ok_or_else(|| Error::Python("No window object available".into()))?;

    // Get the Pyodide object from global scope
    let pyodide_obj = js_sys::Reflect::get(&window.into(), &"pyodide".into()).map_err(|_| {
        console_error_panic_hook::set_once();
        eprintln!("Pyodide not found in global scope");
        Error::Python(
            "Pyodide not available. Make sure Pyodide is loaded before running Python code."
                .to_string(),
        )
    })?;

    if pyodide_obj.is_undefined() {
        return Err(Error::Python(
            "Pyodide is undefined. The Pyodide library may not be fully loaded yet.".to_string(),
        ));
    }

    // Try to register functions again if the engine is not initialized yet
    if !engine._initialized {
        // We can't register the bundle functions in eval because we don't have access to the bundle here
        // This is handled in the register_bundle function when the bundle is available
    }

    // Get the runPython function
    let run_python_fn = js_sys::Reflect::get(&pyodide_obj, &"runPython".into()).map_err(|e| {
        eprintln!("Failed to get runPython function: {:?}", e);
        Error::Python("Failed to get runPython function from Pyodide object".to_string())
    })?;

    if run_python_fn.is_undefined() {
        return Err(Error::Python(
            "runPython function is undefined. Pyodide may not be fully initialized.".to_string(),
        ));
    }

    let run_python_fn = run_python_fn
        .dyn_into::<Function>()
        .map_err(|_| Error::Python("runPython is not a function".into()))?;

    // Execute the Python code
    let result = run_python_fn
        .call1(&pyodide_obj, &JsString::from(code).into())
        .map_err(|e| {
            eprintln!("JS error calling runPython: {:?}", e);
            let error_str = format!("{:?}", e);
            Error::Python(format!(
                "JavaScript error when executing Python code: {}",
                error_str
            ))
        })?;

    // Convert the result to a string
    let result_str = if result.is_string() {
        result
            .as_string()
            .unwrap_or_else(|| "<no result>".to_string())
    } else if result.is_object() {
        // For objects, try to call toString() to get the proper string representation
        let obj = result.dyn_ref::<js_sys::Object>().unwrap();
        let to_string_result = js_sys::Reflect::get(obj, &"toString".into()).ok();
        if let Some(to_string_fn) = to_string_result {
            if let Some(to_string_fn) = to_string_fn.dyn_ref::<Function>() {
                match to_string_fn.call0(obj) {
                    Ok(str_result) => {
                        let str_val = str_result
                            .as_string()
                            .unwrap_or_else(|| "<toString failed>".to_string());
                        str_val
                    }
                    Err(_) => "<object>".to_string(),
                }
            } else {
                // If toString is not available or not a function, use the string representation
                format!("{:?}", result)
            }
        } else {
            format!("{:?}", result)
        }
    } else {
        // For other types (numbers, booleans, etc.), use the string representation but more intelligently
        // We'll use JSON.stringify if available to get a proper representation
        use js_sys::JSON;
        match JSON::stringify(&result) {
            Ok(json_str) => json_str
                .as_string()
                .unwrap_or_else(|| format!("{:?}", result)),
            Err(_) => format!("{:?}", result), // fallback to default representation
        }
    };

    Ok(result_str)
}