require('../config/loadEnv')();

const readMonitor = require('../services/ledgerMongoReadMonitorService');

function readNumberArg(name, fallback) {
  const prefix = `--${name}=`;
  const arg = process.argv.find((value) => value.startsWith(prefix));
  if (!arg) return fallback;
  const parsed = Number(arg.slice(prefix.length));
  return Number.isFinite(parsed) && parsed > 0 ? parsed : fallback;
}

function sleep(ms) {
  return new Promise((resolve) => setTimeout(resolve, ms));
}

async function main() {
  const samples = readNumberArg('samples', 3);
  const intervalMs = readNumberArg('interval-ms', 1000);
  const results = [];

  for (let i = 0; i < samples; i += 1) {
    const result = await readMonitor.runSample({ reason: 'cli-read-monitor' });
    results.push(result.monitor.latestSample);
    if (i < samples - 1) await sleep(intervalMs);
  }

  const status = readMonitor.getStatus();
  console.log(JSON.stringify({
    ok: status.ok,
    mode: 'mongo-read-monitor-runner',
    samplesRequested: samples,
    intervalMs,
    window: status.window,
    latestSample: status.latestSample,
    results,
    path: status.path
  }, null, 2));

  if (!status.latestSample || !status.latestSample.ok) process.exitCode = 1;
}

main().catch((err) => {
  console.error(JSON.stringify({ ok: false, error: err.message }, null, 2));
  process.exitCode = 1;
});
