require('../config/loadEnv')();
const crypto = require('crypto');
const fs = require('fs');
const persistentStore = require('../services/persistentStore');
const service = require('../services/validatorTunnelTopologyService');
const { matchesValidatorTarget } = require('../services/validatorTargetBindingService');

const CLIENT_VERSION = '1.4.123-validator-direct-control-heartbeat-diagnostic-tunnel-fallback-locked';
const CONFIRMATION = 'ACTIVATE validator-1,validator-2,validator-3 DIRECT LAN QUORUM';
const confirm = String(process.argv.find(value => value.startsWith('--confirm=')) || '').slice(10);
if (confirm !== CONFIRMATION) throw new Error('Exact direct LAN quorum activation confirmation is required.');
if (fs.existsSync(service.paths.approvalPath)) throw new Error('Another validator migration approval is already present.');
const topology = JSON.parse(fs.readFileSync(service.paths.topologyPath, 'utf8'));
const direct = service.getDirectQuorum(topology);
if (!direct || direct.state !== 'STAGED') throw new Error('A staged direct LAN quorum topology is required.');
const nodes = persistentStore.readState().nodes || [];
for (const target of direct.targets) {
  const node = nodes.filter(row => matchesValidatorTarget(row, target))
    .sort((a, b) => new Date(b.lastHeartbeatAt || 0) - new Date(a.lastHeartbeatAt || 0))[0];
  const meta = node?.metadata || {};
  const ageMs = Date.now() - new Date(node?.lastHeartbeatAt || 0).getTime();
  if (node?.status !== 'active' || ageMs < 0 || ageMs > 3 * 60_000
    || node.clientVersion !== CLIENT_VERSION
    || meta.validatorRuntimeState !== 'validator-active'
    || Number(meta.validatorRuntimeProcessPid || 0) <= 0
    || Number(meta.validatorRuntimePeerCount || 0) < 1
    || Number(meta.validatorRuntimeGapBlocks || 0) > 10) {
    throw new Error(`Direct LAN activation readiness is incomplete: ${target.nodeName}.`);
  }
}
const approvedAt = new Date();
const approval = {
  schemaVersion: 'plais-validator-tunnel-migration-approval/v1',
  action: 'ACTIVATE_VALIDATOR_DIRECT_LAN_QUORUM',
  approvalId: `validator-direct-lan-quorum-${Date.now()}-${crypto.randomBytes(5).toString('hex')}`,
  targetNodeNames: direct.targetNodeNames,
  topologySha256: crypto.createHash('sha256').update(fs.readFileSync(service.paths.topologyPath)).digest('hex'),
  controls: {
    validatorProcessRestartAllowed: true,
    validatorKeyReadForIdentityCheckOnly: true,
    directLanQuorumMigration: true,
    coordinatedRestartMaxSkewSeconds: 180,
    validatorKeyExportAllowed: false,
    publicRpcAllowed: false,
    externalTransactionAllowed: false,
    operatorSigningAllowed: false
  },
  approvedAt: approvedAt.toISOString(),
  expiresAt: new Date(approvedAt.getTime() + 10 * 60_000).toISOString()
};
const temporaryPath = `${service.paths.approvalPath}.${process.pid}.tmp`;
fs.writeFileSync(temporaryPath, `${JSON.stringify(approval, null, 2)}\n`, { encoding: 'utf8', flag: 'wx' });
fs.renameSync(temporaryPath, service.paths.approvalPath);
console.log(JSON.stringify({
  ok: true,
  status: 'DIRECT_LAN_QUORUM_ACTIVATION_APPROVED',
  approvalId: approval.approvalId,
  targetNodeNames: approval.targetNodeNames,
  expiresAt: approval.expiresAt,
  publicRpcAllowed: false,
  externalTransactionAllowed: false,
  operatorSigningAllowed: false
}, null, 2));
