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

const persistentStore = require('../services/persistentStore');
const mongoObservation = require('../services/mongoLedgerObservationAdapter');

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 state = persistentStore.readState();
    const result = await mongoObservation.compareState(state);
    results.push({
      ok: result.ok,
      checkedAt: result.checkedAt,
      totalExpected: result.totalExpected,
      totalActual: result.totalActual,
      failedCollections: result.failedCollections,
      window: result.window ? {
        ok: result.window.ok,
        sampleCount: result.window.sampleCount,
        consecutiveOk: result.window.consecutiveOk,
        failedSamples: result.window.failedSamples
      } : null
    });
    if (i < samples - 1) await sleep(intervalMs);
  }

  const latest = results[results.length - 1] || null;
  console.log(JSON.stringify({
    ok: Boolean(latest && latest.ok && latest.window && latest.window.ok),
    mode: 'mongo-observation-window-runner',
    samplesRequested: samples,
    intervalMs,
    latest,
    results
  }, null, 2));

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

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