const KEY     = 'jbot_memory';
const MAX_LEN = 100;

export function getMemories() {
  try { return JSON.parse(localStorage.getItem(KEY) || '[]'); }
  catch { return []; }
}

// Add a fact if it's not already stored (simple text dedup).
// Returns the new entry, or null if it was a duplicate.
export function addMemory(text) {
  const mems = getMemories();
  const norm = text.toLowerCase().trim();
  if (mems.some(m => m.text.toLowerCase().trim() === norm)) return null;
  const entry = { id: crypto.randomUUID(), text: text.trim(), createdAt: Date.now() };
  localStorage.setItem(KEY, JSON.stringify([entry, ...mems].slice(0, MAX_LEN)));
  return entry;
}

export function deleteMemory(id) {
  localStorage.setItem(KEY, JSON.stringify(getMemories().filter(m => m.id !== id)));
}

export function clearMemories() {
  localStorage.removeItem(KEY);
}
