// src/containers/warm-pool.ts
var g = globalThis;
function state() {
  if (!g.__caWarmPool) {
    g.__caWarmPool = { byEnv: /* @__PURE__ */ new Map(), inflight: /* @__PURE__ */ new Map() };
  }
  return g.__caWarmPool;
}
function addWarm(entry) {
  const s = state();
  const list = s.byEnv.get(entry.envId) ?? [];
  list.push(entry);
  s.byEnv.set(entry.envId, list);
}
function claimWarm(envId, engine, provider) {
  const s = state();
  const list = s.byEnv.get(envId);
  if (!list || list.length === 0) return null;
  const idx = list.findIndex(
    (e) => e.engine === engine && e.provider === provider
  );
  if (idx === -1) return null;
  const [entry] = list.splice(idx, 1);
  if (list.length === 0) s.byEnv.delete(envId);
  return entry;
}
function expireWarm(now = Date.now()) {
  const s = state();
  const expired = [];
  for (const [envId, list] of s.byEnv) {
    const keep = [];
    for (const entry of list) {
      if (entry.expiresAt <= now) {
        expired.push(entry);
      } else {
        keep.push(entry);
      }
    }
    if (keep.length === 0) {
      s.byEnv.delete(envId);
    } else {
      s.byEnv.set(envId, keep);
    }
  }
  return expired;
}
function countWarm(envId) {
  return state().byEnv.get(envId)?.length ?? 0;
}
function countInflight(envId) {
  return state().inflight.get(envId) ?? 0;
}
function incrementInflight(envId) {
  const s = state();
  s.inflight.set(envId, (s.inflight.get(envId) ?? 0) + 1);
}
function decrementInflight(envId) {
  const s = state();
  const cur = s.inflight.get(envId) ?? 0;
  const next = cur - 1;
  if (next <= 0) {
    s.inflight.delete(envId);
  } else {
    s.inflight.set(envId, next);
  }
}
function __resetWarmPool() {
  g.__caWarmPool = { byEnv: /* @__PURE__ */ new Map(), inflight: /* @__PURE__ */ new Map() };
}

export {
  addWarm,
  claimWarm,
  expireWarm,
  countWarm,
  countInflight,
  incrementInflight,
  decrementInflight,
  __resetWarmPool
};
