const KEY     = 'jbot_history';
const MAX_LEN = 60;
const AUDIO_KEEP = 12;

function stripAudio(entry) {
  return {
    ...entry,
    userAudioBase64: null,
    userAudioMime: null,
    botAudioBase64: null,
    botAudioMime: null,
  };
}

function persist(entries) {
  const trimmed = entries.slice(0, MAX_LEN);

  for (let keep = Math.min(AUDIO_KEEP, trimmed.length); keep >= 0; keep -= 1) {
    const candidate = trimmed.map((entry, idx) => (idx < keep ? entry : stripAudio(entry)));
    try {
      localStorage.setItem(KEY, JSON.stringify(candidate));
      return candidate;
    } catch (err) {
      if (err?.name !== 'QuotaExceededError' && err?.code !== 22) throw err;
    }
  }

  for (let count = Math.min(trimmed.length, 20); count >= 1; count -= 1) {
    const candidate = trimmed.slice(0, count).map(stripAudio);
    try {
      localStorage.setItem(KEY, JSON.stringify(candidate));
      return candidate;
    } catch (err) {
      if (err?.name !== 'QuotaExceededError' && err?.code !== 22) throw err;
    }
  }

  localStorage.removeItem(KEY);
  return [];
}

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

export function addEntry(entry) {
  const history = getHistory();
  const full = [{ id: crypto.randomUUID(), timestamp: Date.now(), ...entry }, ...history];
  const stored = persist(full);
  return stored[0] || full[0];
}

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

export function deleteEntry(id) {
  persist(getHistory().filter(e => e.id !== id));
}
