use super::device::{Device, DeviceType};
use std::fs::File;
use std::io::{BufRead, BufReader};

pub struct Cpu;

impl Cpu {
    pub fn new() -> Self {
        Cpu
    }

    fn get_total_memory(&self) -> Option<u64> {
        if let Ok(file) = File::open("/proc/meminfo") {
            let reader = BufReader::new(file);
            for line in reader.lines() {
                if let Ok(l) = line {
                    if l.starts_with("MemTotal:") {
                        // Format: MemTotal:       16306560 kB
                        let parts: Vec<&str> = l.split_whitespace().collect();
                        if parts.len() >= 2 {
                            if let Ok(kb) = parts[1].parse::<u64>() {
                                return Some(kb * 1024);
                            }
                        }
                    }
                }
            }
        }
        None
    }
}

impl Device for Cpu {
    fn name(&self) -> String {
        "Host CPU".to_string()
    }

    fn device_type(&self) -> DeviceType {
        DeviceType::Cpu
    }

    fn memory_info(&self) -> String {
        match self.get_total_memory() {
            Some(bytes) => format!("{:.2} GB", bytes as f64 / (1024.0 * 1024.0 * 1024.0)),
            None => "Unknown".to_string(),
        }
    }
}
