'use strict';

// Pure data-shaping for the persisted prompt-index cache (prompt-index-cache.json). The fs I/O,
// the write throttle, and the live in-memory Map stay in server.js; this module is the testable
// serialize/deserialize core. Phase 2a: a cold RESTART used to evict the in-memory prompt-index,
// so every post-restart first-load of apiSessionPrompts paid the ~1.6s compute. Persisting + seeding
// the last-good indexes lets the storm fallback serve a warm list instead of stormEmpty/_deferred.

// Pick the most-recently-remembered N entries (Map iteration order = insertion order; remember()
// re-inserts on each refresh, so the tail is hottest) and drop pathologically large indexes (keeps
// the file small + the cold-boot read fast). Returns the on-disk `indexes` object.
function buildPromptIndexSnapshot(entries, { max = 40, maxPrompts = 2000 } = {}) {
  const list = Array.isArray(entries) ? entries : [];
  const tail = list.slice(Math.max(0, list.length - Math.max(1, max)));
  const indexes = {};
  for (const [sid, r] of tail) {
    if (!sid || !r || !Array.isArray(r.messages)) continue;
    if (r.messages.length > maxPrompts) continue;
    indexes[sid] = { messages: r.messages, summary: r.summary || null };
  }
  return indexes;
}

// Parse a persisted file's JSON text into [{ sid, value }] ready to seed the live Map. Returns []
// on any malformed/empty input — this is a best-effort cache and must never throw into the boot path.
function parsePromptIndexSnapshot(jsonText) {
  try {
    const parsed = JSON.parse(jsonText);
    const indexes = parsed && parsed.indexes && typeof parsed.indexes === 'object' ? parsed.indexes : null;
    if (!indexes) return [];
    const out = [];
    for (const sid of Object.keys(indexes)) {
      const r = indexes[sid];
      if (r && Array.isArray(r.messages)) {
        out.push({ sid, value: { messages: r.messages, summary: r.summary || null } });
      }
    }
    return out;
  } catch {
    return [];
  }
}

module.exports = { buildPromptIndexSnapshot, parsePromptIndexSnapshot };
