//! LRU (Least Recently Used) cache implementation
//!
//! Simple LRU cache for tracking access order and enabling efficient eviction

use std::collections::HashMap;
use std::hash::Hash;

/// Simple LRU tracker for cache eviction
#[derive(Debug)]
pub struct LruTracker<K>
where
    K: Clone + Hash + Eq,
{
    /// Access order (oldest to newest)
    order: Vec<K>,
    /// Maximum capacity
    capacity: usize,
}

impl<K> LruTracker<K>
where
    K: Clone + Hash + Eq,
{
    /// Create a new LRU tracker with the given capacity
    pub fn new(capacity: usize) -> Self {
        Self {
            order: Vec::with_capacity(capacity),
            capacity,
        }
    }

    /// Record access to a key (moves it to most recently used)
    pub fn touch(&mut self, key: &K) {
        // Remove from current position
        self.order.retain(|k| k != key);
        // Add to end (most recently used)
        self.order.push(key.clone());
    }

    /// Insert a new key (at most recently used position)
    pub fn insert(&mut self, key: K) {
        // Remove if already exists
        self.order.retain(|k| k != &key);
        // Add to end
        self.order.push(key);

        // Trim to capacity if needed
        if self.order.len() > self.capacity {
            self.order.drain(0..(self.order.len() - self.capacity));
        }
    }

    /// Remove a key from tracking
    pub fn remove(&mut self, key: &K) {
        self.order.retain(|k| k != key);
    }

    /// Get the least recently used key
    pub fn get_lru(&self) -> Option<&K> {
        self.order.first()
    }

    /// Get keys that should be evicted to make room for new entries
    pub fn get_eviction_candidates(&self, needed_space: usize) -> Vec<K> {
        let current_len = self.order.len();
        if current_len + needed_space <= self.capacity {
            return Vec::new();
        }

        let evict_count = (current_len + needed_space) - self.capacity;
        self.order.iter().take(evict_count).cloned().collect()
    }

    /// Get current size
    pub fn len(&self) -> usize {
        self.order.len()
    }

    /// Check if empty
    pub fn is_empty(&self) -> bool {
        self.order.is_empty()
    }

    /// Clear all entries
    pub fn clear(&mut self) {
        self.order.clear();
    }

    /// Get capacity
    pub fn capacity(&self) -> usize {
        self.capacity
    }

    /// Set new capacity (may trigger truncation)
    pub fn set_capacity(&mut self, new_capacity: usize) {
        self.capacity = new_capacity;
        if self.order.len() > new_capacity {
            self.order.drain(0..(self.order.len() - new_capacity));
        }
    }

    /// Get access order (oldest to newest)
    pub fn access_order(&self) -> &[K] {
        &self.order
    }
}

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

    #[test]
    fn test_lru_basic_operations() {
        let mut lru = LruTracker::new(3);

        // Insert items
        lru.insert("a");
        lru.insert("b");
        lru.insert("c");

        assert_eq!(lru.len(), 3);
        assert_eq!(lru.get_lru(), Some(&"a"));
    }

    #[test]
    fn test_lru_capacity_enforcement() {
        let mut lru = LruTracker::new(2);

        lru.insert("a");
        lru.insert("b");
        lru.insert("c"); // Should evict "a"

        assert_eq!(lru.len(), 2);
        assert_eq!(lru.get_lru(), Some(&"b"));
    }

    #[test]
    fn test_lru_touch_updates_order() {
        let mut lru = LruTracker::new(3);

        lru.insert("a");
        lru.insert("b");
        lru.insert("c");

        // Touch "a" to make it most recently used
        lru.touch(&"a");

        assert_eq!(lru.get_lru(), Some(&"b"));
    }

    #[test]
    fn test_lru_eviction_candidates() {
        let mut lru = LruTracker::new(3);

        lru.insert("a");
        lru.insert("b");
        lru.insert("c");

        // Need space for 2 more items
        let candidates = lru.get_eviction_candidates(2);
        assert_eq!(candidates, vec!["a", "b"]);
    }

    #[test]
    fn test_lru_remove() {
        let mut lru = LruTracker::new(3);

        lru.insert("a");
        lru.insert("b");
        lru.insert("c");

        lru.remove(&"b");
        assert_eq!(lru.len(), 2);

        let order = lru.access_order();
        assert!(!order.contains(&"b"));
    }

    #[test]
    fn test_lru_clear() {
        let mut lru = LruTracker::new(3);

        lru.insert("a");
        lru.insert("b");

        assert_eq!(lru.len(), 2);

        lru.clear();
        assert_eq!(lru.len(), 0);
        assert!(lru.is_empty());
    }

    #[test]
    fn test_lru_capacity_change() {
        let mut lru = LruTracker::new(3);

        lru.insert("a");
        lru.insert("b");
        lru.insert("c");

        assert_eq!(lru.len(), 3);

        // Reduce capacity
        lru.set_capacity(2);
        assert_eq!(lru.len(), 2);
        assert_eq!(lru.get_lru(), Some(&"b"));
    }
}
