//! Rhai bindings for monitor functions

use rhai::Engine;

/// Register monitor module with Rhai engine
pub fn register_monitor_module(engine: &mut Engine) -> Result<(), Box<rhai::EvalAltResult>> {
    // Register UtilizationSample type and getters
    engine.register_type::<super::sample::UtilizationSample>();
    engine.register_get("timestamp", |s: &mut super::sample::UtilizationSample| {
        s.timestamp.clone()
    });
    engine.register_get("cpu_percent", |s: &mut super::sample::UtilizationSample| {
        s.cpu_percent
    });
    engine.register_get(
        "memory_percent",
        |s: &mut super::sample::UtilizationSample| s.memory_percent,
    );
    engine.register_get(
        "memory_used_bytes",
        |s: &mut super::sample::UtilizationSample| s.memory_used_bytes as i64,
    );
    engine.register_get(
        "memory_total_bytes",
        |s: &mut super::sample::UtilizationSample| s.memory_total_bytes as i64,
    );
    engine.register_get(
        "io_wait_percent",
        |s: &mut super::sample::UtilizationSample| s.io_wait_percent,
    );
    engine.register_get(
        "io_queue_depth",
        |s: &mut super::sample::UtilizationSample| s.io_queue_depth,
    );

    // Register ResourceMonitor type
    engine.register_type_with_name::<super::utilization::ResourceMonitor>("ResourceMonitor");

    engine.register_fn("ResourceMonitor", |interval_sec: i64| {
        super::utilization::ResourceMonitor::new(std::time::Duration::from_secs(
            interval_sec as u64,
        ))
    });

    engine.register_fn(
        "current_sample",
        |monitor: &mut super::utilization::ResourceMonitor| monitor.current_sample(),
    );

    // Register monitoring functions with simple return types
    engine.register_fn("sample_cpu_utilization", || {
        super::cpu::sample_cpu_utilization()
    });

    engine.register_fn("sample_memory_usage_percent", || {
        let (percent, _used, _total) = super::memory::sample_memory_usage();
        percent
    });

    engine.register_fn("sample_memory_usage_bytes", || {
        let (_percent, used, _total) = super::memory::sample_memory_usage();
        used as i64
    });

    engine.register_fn("sample_memory_total_bytes", || {
        let (_percent, _used, total) = super::memory::sample_memory_usage();
        total as i64
    });

    engine.register_fn("sample_io_wait_percent", || {
        let (wait_percent, _queue_depth) = super::io::sample_io_statistics();
        wait_percent
    });

    engine.register_fn("sample_io_queue_depth", || {
        let (_wait_percent, queue_depth) = super::io::sample_io_statistics();
        queue_depth
    });

    Ok(())
}
