'use strict';

// Shared parse of a session_conversations cache blob into a sorted message array.
//
// This is the heavy work behind `session-messages:parseCacheBlob`: JSON.parse of a
// 0.5–2MB messages string (real Claude/Codex messages are deeply nested, so the parse
// is 150–360ms on the main thread per the [freeze-probe] samples), a codex-synthetic
// scan, and an in-place timeline sort. Extracted so it runs IDENTICALLY on the main
// thread (cold/first-load + pool-failure fallback) and on a read-pool worker (the
// off-thread re-parse for growing sessions) — parity by construction (same function).
//
// Deliberately dependency-light so a worker can require it without pulling in server.js:
// only lib/timeline-order + lib/session-history (both already worker-safe).

const { sortTimelineMessagesInPlace } = require('./timeline-order');

// Lazy + defensive: if session-history can't load in a worker context, treat nothing as
// synthetic (the main-thread path uses the real predicate; worst case a worker keeps a
// synthetic codex context row that main would have dropped — corrected on the next
// main-served parse). Mirrors lib/session-prompt-index.js's resolution.
let _isCodexSyntheticUserText = null;
function _codexSynthetic() {
  if (_isCodexSyntheticUserText) return _isCodexSyntheticUserText;
  try { _isCodexSyntheticUserText = require('./session-history').isCodexSyntheticUserText; }
  catch { _isCodexSyntheticUserText = () => false; }
  return _isCodexSyntheticUserText;
}

// Returns the parsed+sorted message array, or null when the blob is empty/invalid or the
// conversation is entirely injected codex context (matches the server.js inline behavior
// that this replaces). Throws only on malformed JSON — callers catch and fall back.
function parseConversationBlob(messagesString) {
  if (typeof messagesString !== 'string' || messagesString.length === 0) return null;
  const messages = JSON.parse(messagesString);
  if (!Array.isArray(messages) || messages.length === 0) return null;
  const isSynthetic = _codexSynthetic();
  if (messages.some((m) => m && m.role === 'user' && isSynthetic(m.text))) return null;
  sortTimelineMessagesInPlace(messages);
  return messages;
}

module.exports = { parseConversationBlob };
