const { queueDepth, getHealthExtras, getLastPumpAt } = require("./print-queue");

const STALL_THRESHOLD_MS = parseInt(process.env.WATCHDOG_STALL_MS || "120000", 10) || 120000;
let watchdogTimer = null;

function startWatchdog({ logger, onStall }) {
  if (watchdogTimer) return;
  watchdogTimer = setInterval(() => {
    const depth = queueDepth();
    const lastPumpAt = getLastPumpAt();
    const stalled = Date.now() - lastPumpAt > STALL_THRESHOLD_MS;
    if (depth > 0 && stalled) {
      logger?.warn?.(
        `[watchdog] queue stalled depth=${depth} lastPump=${lastPumpAt}`,
      );
      if (typeof onStall === "function") onStall({ depth, lastPumpAt });
    }
  }, 30000);
  if (watchdogTimer.unref) watchdogTimer.unref();
}

function stopWatchdog() {
  if (watchdogTimer) {
    clearInterval(watchdogTimer);
    watchdogTimer = null;
  }
}

module.exports = {
  startWatchdog,
  stopWatchdog,
};
