//! WASM entrypoint for Rhai scripting integration for the extension.
//! Composes vault and evm_client Rhai bindings and exposes a secure run_rhai API.
#![cfg(target_arch = "wasm32")]

use once_cell::unsync::Lazy;
use std::cell::RefCell;
use wasm_bindgen::prelude::*;

use wasm_bindgen::JsValue;

use rhai::Engine;
use vault::rhai_bindings as vault_rhai_bindings;
use vault::session::SessionManager;

use kvstore::wasm::WasmStore;

// Global singleton engine/session/client (for demonstration; production should scope per user/session)
thread_local! {
    static ENGINE: Lazy<RefCell<Engine>> = Lazy::new(|| RefCell::new(Engine::new()));
    static SESSION_PASSWORD: RefCell<Option<Vec<u8>>> = RefCell::new(None);
}

pub use vault::session_singleton::SESSION_MANAGER;

// Include the keypair bindings module
mod vault_bindings;
pub use vault_bindings::*;

/// Initialize the scripting environment (must be called before run_rhai)
#[wasm_bindgen]
pub fn init_rhai_env() {
    ENGINE.with(|engine_cell| {
        let mut engine = engine_cell.borrow_mut();
        // Register APIs with dummy session; will be replaced by real session after init
        SESSION_MANAGER.with(|cell| {
            if let Some(ref session) = cell.borrow().as_ref() {
                vault_rhai_bindings::register_rhai_api::<WasmStore>(&mut engine);
            }
        });
    });
}

/// Securely run a Rhai script in the extension context (must be called only after user approval)
#[wasm_bindgen]
pub fn run_rhai(script: &str) -> Result<JsValue, JsValue> {
    ENGINE.with(|engine_cell| {
        let mut engine = engine_cell.borrow_mut();
        SESSION_MANAGER.with(|cell| {
            if let Some(ref mut session) = cell.borrow_mut().as_mut() {
                let mut scope = rhai::Scope::new();
                engine
                    .eval_with_scope::<rhai::Dynamic>(&mut scope, script)
                    .map(|res| JsValue::from_str(&format!("{:?}", res)))
                    .map_err(|e| JsValue::from_str(&format!("{}", e)))
            } else {
                Err(JsValue::from_str("Session not initialized"))
            }
        })
    })
}

pub mod wasm_helpers {
    use super::*;

    /// Global function to select keypair (used in Rhai)
    pub fn select_keypair_global(key_id: &str) -> Result<(), String> {
        SESSION_MANAGER.with(|cell| {
            if let Some(session) = cell.borrow_mut().as_mut() {
                session
                    .select_keypair(key_id)
                    .map_err(|e| format!("select_keypair error: {e}"))
            } else {
                Err("Session not initialized".to_string())
            }
        })
    }
}
