use super::{MemoryError, MemorySample};
use std::time::Instant;

pub fn sample_memory(pid: u32) -> Result<MemorySample, MemoryError> {
    use std::mem;

    let mut info: libc::proc_taskinfo = unsafe { mem::zeroed() };
    let size = mem::size_of::<libc::proc_taskinfo>() as i32;

    let ret = unsafe {
        libc::proc_pidinfo(
            pid as i32,
            libc::PROC_PIDTASKINFO,
            0,
            &mut info as *mut _ as *mut libc::c_void,
            size,
        )
    };

    if ret <= 0 {
        return match unsafe { *libc::__error() } {
            libc::ESRCH => Err(MemoryError::ProcessNotFound(pid)),
            libc::EPERM => Err(MemoryError::PermissionDenied(pid)),
            _ => Err(MemoryError::Io(std::io::Error::last_os_error())),
        };
    }

    Ok(MemorySample {
        timestamp: Instant::now(),
        rss_bytes: info.pti_resident_size,
        peak_rss_bytes: info.pti_resident_size, // macOS doesn't track peak separately
        virtual_bytes: info.pti_virtual_size,
        swap_bytes: 0, // Not available via proc_pidinfo
    })
}
