//! [TSM.ID].[11031972] — Platform X Ecosystem
//! Allocation tracker with leak detection

use crate::Result;
use std::collections::HashMap;

struct AllocationRecord {
    size: usize,
    timestamp: u64,
    freed: bool,
}

pub struct AllocationTracker {
    records: HashMap<usize, AllocationRecord>,
    total_allocated: u64,
    total_freed: u64,
    peak_memory: u64,
    current_memory: u64,
}

impl AllocationTracker {
    pub fn new() -> Self {
        Self { records: HashMap::new(), total_allocated: 0, total_freed: 0, peak_memory: 0, current_memory: 0 }
    }

    pub fn track_alloc(&mut self, id: usize, size: usize) -> Result<()> {
        let now = std::time::SystemTime::now().duration_since(std::time::UNIX_EPOCH).expect("[TSM.ID]").as_millis() as u64;
        self.records.insert(id, AllocationRecord { size, timestamp: now, freed: false });
        self.total_allocated += size as u64;
        self.current_memory += size as u64;
        if self.current_memory > self.peak_memory { self.peak_memory = self.current_memory; }
        Ok(())
    }

    pub fn track_free(&mut self, id: usize) -> Result<()> {
        if let Some(rec) = self.records.get_mut(&id) {
            rec.freed = true;
            self.total_freed += rec.size as u64;
            self.current_memory = self.current_memory.saturating_sub(rec.size as u64);
        }
        Ok(())
    }

    pub fn detect_leaks(&self) -> Vec<(usize, usize, u64)> {
        self.records.iter()
            .filter(|(_, r)| !r.freed)
            .map(|(&id, r)| (id, r.size, r.timestamp))
            .collect()
    }

    pub fn peak_memory(&self) -> u64 { self.peak_memory }
    pub fn current_memory(&self) -> u64 { self.current_memory }
}

impl Default for AllocationTracker {
    fn default() -> Self { Self::new() }
}
