use std::mem::MaybeUninit;

/// Retourne (used, free, total) en octets pour le système de fichiers racine "/".
/// Utilise statvfs() directement pour correspondre exactement aux chiffres de `df` :
///   - total = f_blocks × f_frsize
///   - used  = (f_blocks − f_bfree) × f_frsize   (blocs effectivement écrits)
///   - free  = f_bavail × f_frsize                (disponible pour utilisateurs non-root)
pub fn get() -> (u64, u64, u64) {
    let path = b"/\0";
    let mut stat = MaybeUninit::<libc::statvfs>::uninit();
    let ret = unsafe { libc::statvfs(path.as_ptr() as *const libc::c_char, stat.as_mut_ptr()) };
    if ret != 0 {
        return (0, 0, 0);
    }
    let stat = unsafe { stat.assume_init() };
    let bsize = stat.f_frsize as u64;
    let total = stat.f_blocks.saturating_mul(bsize);
    let used  = stat.f_blocks.saturating_sub(stat.f_bfree).saturating_mul(bsize);
    let free  = stat.f_bavail.saturating_mul(bsize);
    (used, free, total)
}

#[cfg(test)]
mod tests {
    use super::*;

    #[test]
    fn test_disk_coherent() {
        let (used, free, total) = get();
        eprintln!("résultat statvfs : used={used} free={free} total={total}");
        if total > 0 {
            assert!(used + free <= total + 1024 * 1024, "used + free > total");
            assert!(total > 0, "total doit être > 0");
        }
    }
}
