//! Rhai bindings for EVM Client module
//! Provides a single source of truth for scripting integration for EVM actions.

use rhai::{Engine, Map};
pub use crate::EvmClient; // Ensure EvmClient is public and defined in lib.rs

/// Register EVM Client APIs with the Rhai scripting engine.
#[cfg(not(target_arch = "wasm32"))]
pub fn register_rhai_api(engine: &mut Engine, evm_client: std::sync::Arc<EvmClient>) {
    /// Rhai-friendly wrapper for EvmClient, allowing method registration and instance sharing.
    #[derive(Clone)]
    struct RhaiEvmClient {
        inner: std::sync::Arc<EvmClient>,
    }
    impl RhaiEvmClient {
        /// Get balance using the EVM client.
        pub fn get_balance(&self, address_hex: String) -> Result<String, String> {
            use ethers_core::types::Address;
            let address = Address::from_slice(&hex::decode(address_hex.trim_start_matches("0x")).map_err(|e| format!("hex decode error: {e}"))?);
            crate::rhai_sync_helpers::get_balance_sync(&self.inner, address)
        }


    }
    engine.register_type::<RhaiEvmClient>();
    engine.register_fn("get_balance", RhaiEvmClient::get_balance);
    // Register instance for scripts
    let rhai_ec = RhaiEvmClient { inner: evm_client.clone() };
    // Rhai does not support register_global_constant; pass the client as a parameter or use module scope.
}

#[cfg(target_arch = "wasm32")]
pub fn register_rhai_api(engine: &mut Engine) {
    // In WASM, register global functions that operate on the singleton/global EvmClient
    engine.register_fn("get_balance", |provider_url: String, public_key: rhai::Blob| -> Result<String, String> {
        // WASM: get_balance is async, so error if called from Rhai
        Err("get_balance is async in WASM; use the WASM get_balance() API from JS instead".to_string())
    });
    engine.register_fn("send_transaction", |provider_url: String, key_id: String, password: rhai::Blob, tx_data: rhai::Map| -> Result<String, String> {
        // WASM: send_transaction is async, so error if called from Rhai
        Err("send_transaction is async in WASM; use the WASM send_transaction() API from JS instead".to_string())
    });
    // No global evm object in WASM; use JS/WASM API for EVM ops
}

