'use strict';
// Hard size cap for whole-conversation parse/stringify operations.
//
// A multi-GB Codex/Claude transcript stored as one JSON blob exceeds Node/V8's
// max string length (0x1fffffe8 ≈ 512 MiB UTF-16 code units) and takes 28-33s to
// JSON.parse / JSON.stringify on the main thread — freezing the event loop and
// starving ALL session input. This module is the single shared predicate that
// lets every whole-conversation code path REFUSE to touch an over-cap payload
// and instead serve a tail/row view.
//
// Design rule: FAIL OPEN. The cap is a pure integer comparison with no I/O and
// never throws. An unknown / non-finite / non-positive size is treated as UNDER
// the cap — we do not block work we cannot measure — so a bug here can never
// itself brick CTM. We only ever block on a concrete, finite measurement that
// exceeds the cap.

// Cap well below V8's ~512 MiB string ceiling: a UTF-8 blob near that byte size
// blows past it once decoded to a JS string, and even comfortably under it the
// synchronous parse/stringify is multi-second. Override with the env var (bytes).
const DEFAULT_MAX_PARSE_BYTES = 256 * 1024 * 1024; // 256 MiB

// Read the active cap each call so an env override applies at runtime (and so
// tests can flip it). Cheap: one Number() + comparison.
function maxParseBytes() {
  const raw = Number(process.env.CTM_MAX_PARSE_BYTES);
  if (Number.isFinite(raw) && raw > 0) return Math.floor(raw);
  return DEFAULT_MAX_PARSE_BYTES;
}

// True ONLY when byteLen is a finite, positive size that exceeds the cap.
// Unknown / NaN / 0 / negative / Infinity → false (fail open).
function isOverParseCap(byteLen) {
  const n = Number(byteLen);
  if (!Number.isFinite(n) || n <= 0) return false;
  return n > maxParseBytes();
}

// Describe a size relative to the cap for response/state plumbing.
function parseCapState(byteLen) {
  const n = Number(byteLen);
  const bytes = Number.isFinite(n) && n > 0 ? Math.floor(n) : 0;
  return { overCap: isOverParseCap(byteLen), bytes, cap: maxParseBytes() };
}

module.exports = { isOverParseCap, parseCapState, maxParseBytes, DEFAULT_MAX_PARSE_BYTES };
