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

const fs = require('fs');
const path = require('path');
const persistentStore = require('../services/persistentStore');
const validatorKeyDeliveryService = require('../services/validatorKeyDeliveryService');
const { matchesValidatorTarget } = require('../services/validatorTargetBindingService');

const topologyPath = path.join(__dirname, '..', 'runtime', 'plais-qbft-canonical-migration', 'topology.json');

function latestNodeForTarget(nodes, target) {
  return nodes
    .filter((node) => matchesValidatorTarget(node, target))
    .sort((left, right) => new Date(right.lastHeartbeatAt || 0) - new Date(left.lastHeartbeatAt || 0))[0] || null;
}

function main() {
  const topology = JSON.parse(fs.readFileSync(topologyPath, 'utf8'));
  const nodes = persistentStore.readState().nodes || [];
  const rows = (topology.validators || []).map((target) => {
    const node = latestNodeForTarget(nodes, target);
    if (!node) throw new Error(`Validator candidate node is missing: ${target.pcName}`);
    const offerResult = validatorKeyDeliveryService.buildOffer(node);
    if (!offerResult.ok) throw new Error(`Validator key delivery offer failed: ${target.pcName} ${offerResult.reason}`);
    const offer = offerResult.offer;
    const downloadResult = validatorKeyDeliveryService.getEncryptedEnvelope(node);
    const controls = offer.controls || {};
    if (
      offer.state !== 'locked-awaiting-delivery-approval'
      || controls.encryptedEnvelopeDownloadAllowed !== false
      || controls.validatorKeyDecryptAllowed !== false
      || controls.validatorKeyImportAllowed !== false
      || controls.validatorStartAllowed !== false
      || controls.arbitraryCommandAllowed !== false
      || downloadResult.ok !== false
      || downloadResult.status !== 423
      || downloadResult.reason !== 'VALIDATOR_KEY_DELIVERY_LOCKED'
    ) {
      throw new Error(`Validator key delivery lock is unsafe: ${target.pcName}`);
    }
    return { pcName: target.pcName, nodeName: target.nodeName, offerLocked: true, downloadStatus: 423 };
  });
  console.log(JSON.stringify({
    ok: true,
    state: 'LOCKED_AWAITING_DELIVERY_APPROVAL',
    validatorCount: rows.length,
    encryptedEnvelopeDownloaded: false,
    validatorKeyDecrypted: false,
    validatorKeyImported: false,
    validatorsStarted: false,
    rows
  }, null, 2));
}

try {
  main();
} catch (error) {
  console.error(JSON.stringify({ ok: false, error: error.message }, null, 2));
  process.exit(1);
}
