// src/lib/reporting/xyReporter.ts
import { performance } from "node:perf_hooks";
var reporterState = {
  currentCommand: "unknown",
  isEnvelopeEmitted: false,
  isJsonModeEnabled: false,
  isStrictModeEnabled: false,
  originalStdoutWrite: void 0,
  startTime: 0
};
function isJsonMode() {
  return reporterState.isJsonModeEnabled;
}
function setJsonMode(isEnabled) {
  if (reporterState.isJsonModeEnabled === isEnabled) return;
  reporterState.isJsonModeEnabled = isEnabled;
  if (isEnabled && !reporterState.originalStdoutWrite) {
    reporterState.originalStdoutWrite = process.stdout.write.bind(process.stdout);
    const stderrWrite = process.stderr.write.bind(process.stderr);
    process.stdout.write = stderrWrite;
    process.on("exit", emitFallbackEnvelope);
  }
}
function isStrictMode() {
  return reporterState.isStrictModeEnabled || process.env.XY_STRICT === "1";
}
function setStrictMode(isEnabled) {
  reporterState.isStrictModeEnabled = isEnabled;
  if (isEnabled) {
    process.env.XY_STRICT = "1";
  }
}
function setCurrentCommand(name) {
  reporterState.currentCommand = name;
  reporterState.startTime = performance.now();
  reporterState.isEnvelopeEmitted = false;
}
function emitJson(envelope) {
  if (reporterState.isEnvelopeEmitted) return;
  reporterState.isEnvelopeEmitted = true;
  const json = JSON.stringify(envelope) + "\n";
  if (reporterState.originalStdoutWrite) {
    reporterState.originalStdoutWrite(json);
  } else {
    process.stdout.write(json);
  }
}
function emitFallbackEnvelope() {
  if (reporterState.isEnvelopeEmitted) return;
  const raw = process.exitCode ?? 0;
  const code = typeof raw === "number" ? raw : Number(raw) || 0;
  emitJson({
    command: reporterState.currentCommand,
    durationMs: Math.round(performance.now() - reporterState.startTime),
    errorCount: code === 0 ? 0 : 1,
    exitCode: code,
    schemaVersion: 1,
    success: code === 0,
    warningCount: 0
  });
}
function xyLog(...args) {
  if (reporterState.isJsonModeEnabled) {
    process.stderr.write(args.map((arg) => typeof arg === "string" ? arg : String(arg)).join(" ") + "\n");
  } else {
    console.log(...args);
  }
}
function resetReporterForTesting() {
  if (reporterState.originalStdoutWrite) {
    process.stdout.write = reporterState.originalStdoutWrite;
    reporterState.originalStdoutWrite = void 0;
  }
  reporterState.isJsonModeEnabled = false;
  reporterState.isEnvelopeEmitted = false;
  reporterState.currentCommand = "unknown";
  reporterState.startTime = 0;
}
export {
  emitJson,
  isJsonMode,
  isStrictMode,
  resetReporterForTesting,
  setCurrentCommand,
  setJsonMode,
  setStrictMode,
  xyLog
};
//# sourceMappingURL=xyReporter.mjs.map
