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

const persistentStore = require('../services/persistentStore');
const liveWriter = require('../services/mongoLedgerLiveWriterAdapter');

async function main() {
  const confirmed = process.argv.includes('--confirm-live-sync') || process.env.AISFOR_CHAIN_LEDGER_MONGO_LIVE_SYNC_APPROVED === '1';
  const state = persistentStore.readState();
  const totalDocuments = Object.values(state).reduce((sum, rows) => sum + (Array.isArray(rows) ? rows.length : 0), 0);

  if (!confirmed) {
    const locked = {
      ok: false,
      mode: 'mongo-live-sync-locked',
      reason: 'Pass --confirm-live-sync or set AISFOR_CHAIN_LEDGER_MONGO_LIVE_SYNC_APPROVED=1 to sync live Mongo collections.',
      totalDocuments,
      status: liveWriter.getStatus()
    };
    console.log(JSON.stringify(locked, null, 2));
    process.exitCode = 1;
    return;
  }

  const result = await liveWriter.syncState(state, { reason: 'manual-live-sync' });
  console.log(JSON.stringify(result, null, 2));
}

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