/**
 * engine/stdio-timestamps.js — Prefix every console.log/warn/error/info line
 * with an ISO-8601 timestamp so dashboard-stdio.log and engine-stdio.log
 * become diagnosable to the second.
 *
 * Required at the very top of dashboard.js and engine.js (and supervisor.js).
 * Without this, "what was the dashboard doing at 01:01:56?" requires fishing
 * through log.json's adjacent engine entries and hoping timing lines up.
 *
 * The wrap is a no-op when MINIONS_NO_STDIO_TIMESTAMPS is truthy (used by
 * tests that compare console output verbatim).
 */

const _STAMP = Symbol.for('minions.stdioTimestampsInstalled');

function _ts() { return new Date().toISOString(); }

function _wrap(method) {
  const original = console[method].bind(console);
  return (...args) => {
    try { original(`[${_ts()}]`, ...args); }
    catch { original(...args); }
  };
}

function installIfNotInstalled() {
  if (globalThis[_STAMP]) return false;
  if (process.env.MINIONS_NO_STDIO_TIMESTAMPS) return false;
  console.log = _wrap('log');
  console.info = _wrap('info');
  console.warn = _wrap('warn');
  console.error = _wrap('error');
  globalThis[_STAMP] = true;
  return true;
}

module.exports = { installIfNotInstalled };
