//! CPU utilization sampling

/// Sample CPU utilization using sysinfo
/// Returns a fraction (0.0 to 1.0) representing CPU usage percentage.
/// Note: sysinfo requires a delay between refresh calls to calculate accurate CPU usage.
pub fn sample_cpu_utilization() -> f64 {
    let mut system = sysinfo::System::new();

    // First refresh to initialize baseline
    system.refresh_cpu_usage();

    // Wait for measurement interval (200ms is sufficient for accurate readings)
    std::thread::sleep(std::time::Duration::from_millis(200));

    // Second refresh to get actual CPU usage
    system.refresh_cpu_usage();

    let cpus = system.cpus();
    if cpus.is_empty() {
        0.0
    } else {
        // Average CPU usage across all cores (each core reports 0-100%)
        let total: f32 = cpus.iter().map(|cpu| cpu.cpu_usage()).sum();
        let avg_percent = total / cpus.len() as f32;

        // Convert to fraction (0.0-1.0) and clamp to valid range
        (avg_percent as f64 / 100.0).clamp(0.0, 1.0)
    }
}
