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

const fs = require('fs');
const path = require('path');
const mongoReadAdapter = require('../services/mongoLedgerReadAdapter');
const snapshotService = require('../services/mongoReadSnapshotService');

function getDataDir() {
  return path.join(__dirname, '..', 'data');
}

function readCompare() {
  const comparePath = path.join(getDataDir(), 'mongo-read-backend-compare.json');
  try {
    return JSON.parse(fs.readFileSync(comparePath, 'utf8'));
  } catch (err) {
    return { ok: false, error: err.message, path: comparePath };
  }
}

async function main() {
  const compare = readCompare();
  if (!compare.ok || Number(compare.totalActual || 0) !== Number(compare.totalExpected || 0)) {
    throw new Error('Mongo read compare must be OK before materializing read snapshot.');
  }

  const mongo = await mongoReadAdapter.readStateFromMongo({ ignoreGate: true });
  const state = snapshotService.normalizeState(mongo.state);
  const totalDocuments = snapshotService.countRows(state);
  if (totalDocuments !== Number(compare.totalExpected || 0)) {
    throw new Error(`Snapshot count mismatch: ${totalDocuments} != ${compare.totalExpected}`);
  }

  const output = {
    ok: true,
    mode: 'mongo-read-snapshot',
    source: 'mongodb-live-read-candidate',
    sourceReadAt: mongo.readAt,
    compareCheckedAt: compare.checkedAt || null,
    totalDocuments,
    state,
    createdAt: new Date().toISOString(),
    path: snapshotService.snapshotPath
  };

  fs.writeFileSync(snapshotService.snapshotPath, JSON.stringify(output, null, 2) + '\n');
  console.log(JSON.stringify({ ...output, state: undefined }, null, 2));
}

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