// src/buffer-surprise-report.ts
async function reportBufferSurpriseDistribution(readEvents, options = {}) {
  const limit = typeof options.limit === "number" && options.limit > 0 ? Math.floor(options.limit) : 200;
  const raw = await readEvents({ limit, since: options.since });
  const sinceMs = typeof options.since === "string" && options.since.length > 0 ? Date.parse(options.since) : Number.NaN;
  const rows = raw.filter((row) => {
    if (!row || row.event !== "BUFFER_SURPRISE") return false;
    if (typeof row.surpriseScore !== "number") return false;
    if (!Number.isFinite(row.surpriseScore)) return false;
    if (row.surpriseScore < 0 || row.surpriseScore > 1) return false;
    if (typeof row.triggeredFlush !== "boolean") return false;
    if (Number.isFinite(sinceMs)) {
      const ts = Date.parse(row.timestamp);
      if (!Number.isFinite(ts) || ts <= sinceMs) return false;
    }
    return true;
  });
  if (rows.length === 0) {
    return {
      count: 0,
      triggeredCount: 0,
      triggeredRate: 0,
      mean: 0,
      median: 0,
      p90: 0,
      min: 0,
      max: 0,
      currentThreshold: null
    };
  }
  const scores = rows.map((r) => r.surpriseScore).sort((a, b) => a - b);
  const triggeredCount = rows.reduce(
    (acc, r) => acc + (r.triggeredFlush ? 1 : 0),
    0
  );
  const sum = scores.reduce((acc, v) => acc + v, 0);
  const mean = sum / scores.length;
  const median = percentile(scores, 0.5);
  const p90 = percentile(scores, 0.9);
  const mostRecent = rows[rows.length - 1];
  const currentThreshold = mostRecent && typeof mostRecent.threshold === "number" ? mostRecent.threshold : null;
  return {
    count: scores.length,
    triggeredCount,
    triggeredRate: triggeredCount / scores.length,
    mean,
    median,
    p90,
    min: scores[0],
    max: scores[scores.length - 1],
    currentThreshold
  };
}
function percentile(sorted, p) {
  if (sorted.length === 0) return 0;
  const clamped = Math.max(0, Math.min(1, p));
  const rank = Math.max(1, Math.ceil(clamped * sorted.length));
  return sorted[rank - 1];
}

export {
  reportBufferSurpriseDistribution
};
//# sourceMappingURL=chunk-ASAITVLA.js.map