use crate::fact::MemoFact;
use std::collections::HashMap;

pub struct ResonantMemory {
    facts: Vec<MemoFact>,
    hot_index: HashMap<String, f32>,
}

impl ResonantMemory {
    pub fn new() -> Self {
        Self {
            facts: Vec::new(),
            hot_index: HashMap::new(),
        }
    }

    pub fn insert(&mut self, fact: MemoFact) {
        self.hot_index.insert(fact.key.clone(), fact.confidence);
        self.facts.push(fact);
    }

    pub fn search(&self, keyword: &str) -> Vec<MemoFact> {
        // normalise separators so "entry point" matches "entry_point"
        let kw = keyword.to_lowercase().replace(['-', '_'], " ");
        self.facts
            .iter()
            .filter(|f| {
                let key = f.key.to_lowercase().replace(['-', '_'], " ");
                let value = f.value.to_lowercase().replace(['-', '_'], " ");
                let tags = f.tags.join(" ").to_lowercase();
                key.contains(&kw) || value.contains(&kw) || tags.contains(&kw)
            })
            .cloned()
            .collect()
    }

    pub fn all(&self) -> Vec<&MemoFact> {
        self.facts.iter().collect()
    }
    pub fn facts_mut(&mut self) -> &mut Vec<MemoFact> {
        &mut self.facts
    }
    pub fn len(&self) -> usize {
        self.facts.len()
    }
    pub fn is_empty(&self) -> bool {
        self.facts.is_empty()
    }
}

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