const fs = require('fs');
const path = require('path');

const root = path.join(__dirname, '..');
const ledgerPath = path.join(root, 'data', 'ledger.json');
const sourcePath = path.join(root, 'data', 'ledger.json.bak-bad-trx-20260704');
const envPath = path.join(root, '.env');

if (fs.existsSync(envPath)) {
  for (const line of fs.readFileSync(envPath, 'utf8').split(/\r?\n/)) {
    const trimmed = line.trim();
    if (!trimmed || trimmed.startsWith('#')) continue;
    const index = trimmed.indexOf('=');
    if (index <= 0) continue;
    const key = trimmed.slice(0, index).trim();
    const value = trimmed.slice(index + 1).trim();
    if (key && process.env[key] === undefined) process.env[key] = value;
  }
}

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

const badEventId = '93145d14-31bf-470b-a544-22dc3d03078a';
const badExternalTxHash = '2905d2a210d4ca5238f5bab33b4813d3866f12370c6e6238277a33bf45dfba29';

function readJson(filePath) {
  return JSON.parse(fs.readFileSync(filePath, 'utf8'));
}

function withoutBadCollateralTx(rows = []) {
  return rows.filter((row) => {
    const metadata = row && row.metadata && typeof row.metadata === 'object' ? row.metadata : {};
    return metadata.collateralEventId !== badEventId && metadata.externalTxHash !== badExternalTxHash;
  });
}

const current = readJson(ledgerPath);
const source = readJson(sourcePath);

const sourceAccounts = Array.isArray(source.trxCollateralAccounts) ? source.trxCollateralAccounts : [];
const sourceEvents = Array.isArray(source.trxCollateralEvents) ? source.trxCollateralEvents : [];

const accounts = sourceAccounts.map((account) => {
  if (account.ownerType === 'node' && account.ownerId === '6a39cc22243323766d429d10') {
    return {
      ...account,
      confirmedAmount: 0,
      pendingAmount: 0,
      lockedAmount: 0,
      status: 'waiting_deposit',
      updatedAt: new Date().toISOString()
    };
  }
  return account;
});

const events = sourceEvents.filter((event) => event.id !== badEventId && event.externalTxHash !== badExternalTxHash);

const repaired = {
  ...current,
  transactions: withoutBadCollateralTx(current.transactions),
  trxCollateralAccounts: accounts,
  trxCollateralEvents: events
};

persistentStore.writeState(repaired);

const saved = persistentStore.readState();
const output = {
  storage: persistentStore.getStorageInfo(),
  totalConfirmed: (saved.trxCollateralAccounts || []).reduce((sum, row) => sum + Number(row.confirmedAmount || 0), 0),
  accountCount: (saved.trxCollateralAccounts || []).length,
  eventCount: (saved.trxCollateralEvents || []).length,
  remainingBadText: JSON.stringify(saved).includes('600.368021') || JSON.stringify(saved).includes(badEventId) || JSON.stringify(saved).includes(badExternalTxHash),
  accounts: (saved.trxCollateralAccounts || []).map((row) => ({
    ownerType: row.ownerType,
    ownerId: row.ownerId,
    label: row.label,
    status: row.status,
    confirmedAmount: row.confirmedAmount,
    pendingAmount: row.pendingAmount,
    requiredCollateral: row.metadata && row.metadata.requiredCollateral,
    capacityTb: row.metadata && row.metadata.capacityTb
  }))
};

console.log(JSON.stringify(output, null, 2));
