import { FRAME_DURATION_IN_S, MIN_INTERRUPTION_DURATION_IN_S } from "./defaults.js";
class BoundedCache {
  cache = /* @__PURE__ */ new Map();
  maxLen;
  constructor(maxLen = 10) {
    this.maxLen = maxLen;
  }
  set(key, value) {
    this.cache.set(key, value);
    if (this.cache.size > this.maxLen) {
      const firstKey = this.cache.keys().next().value;
      this.cache.delete(firstKey);
    }
  }
  /**
   * Update existing value fields if present and defined.
   */
  updateValue(key, fields) {
    const value = this.cache.get(key);
    if (!value) return value;
    for (const [fieldName, fieldValue] of Object.entries(fields)) {
      if (fieldValue === void 0) continue;
      if (fieldName in value) {
        value[String(fieldName)] = fieldValue;
      }
    }
    return value;
  }
  /**
   * Set a new value with factory when missing; otherwise update in place.
   * Mirrors python BoundedDict.set_or_update behavior.
   */
  setOrUpdate(key, factory, fields) {
    if (!this.cache.has(key)) {
      this.set(key, factory());
    }
    const result = this.updateValue(key, fields);
    if (!result) {
      throw new Error("setOrUpdate invariant failed: entry should exist after set");
    }
    return result;
  }
  get(key) {
    return this.cache.get(key);
  }
  has(key) {
    return this.cache.has(key);
  }
  delete(key) {
    return this.cache.delete(key);
  }
  /**
   * Pop an entry if it satisfies the predicate.
   * - No predicate: pop oldest (FIFO)
   * - With predicate: search in reverse order and pop first match
   */
  pop(predicate) {
    if (predicate === void 0) {
      const first = this.cache.entries().next().value;
      if (!first) return void 0;
      const [key, value] = first;
      this.cache.delete(key);
      return value;
    }
    const keys = Array.from(this.cache.keys());
    for (let i = keys.length - 1; i >= 0; i--) {
      const key = keys[i];
      const value = this.cache.get(key);
      if (predicate(value)) {
        this.cache.delete(key);
        return value;
      }
    }
    return void 0;
  }
  clear() {
    this.cache.clear();
  }
  get size() {
    return this.cache.size;
  }
  values() {
    return this.cache.values();
  }
  keys() {
    return this.cache.keys();
  }
  entries() {
    return this.cache.entries();
  }
}
function estimateProbability(probabilities, windowSizeInS = MIN_INTERRUPTION_DURATION_IN_S) {
  const nTh = Math.ceil(windowSizeInS / FRAME_DURATION_IN_S);
  if (probabilities.length < nTh) {
    return 0;
  }
  const sorted = [...probabilities].sort((a, b) => b - a);
  return sorted[nTh - 1];
}
export {
  BoundedCache,
  estimateProbability
};
//# sourceMappingURL=utils.js.map