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

const nodeName = String(process.argv.find(value => value.startsWith('--node=')) || '').slice(7);
const previousPid = Number(String(process.argv.find(value => value.startsWith('--previous-pid=')) || '').slice(15));
const confirm = String(process.argv.find(value => value.startsWith('--confirm=')) || '').slice(10);
if (!/^validator-[1-3]$/.test(nodeName) || !Number.isInteger(previousPid) || previousPid <= 0
  || confirm !== `ARCHIVE ${nodeName} SINGLE RESTART AFTER PID ${previousPid}`) {
  throw new Error('Exact observed single-validator restart archive confirmation is required.');
}
if (!fs.existsSync(service.paths.approvalPath)) throw new Error('Validator restart approval is missing.');
const approval = JSON.parse(fs.readFileSync(service.paths.approvalPath, 'utf8'));
if (approval.action !== 'RESTART_SINGLE_VALIDATOR_WITH_DIRECT_TUNNEL_PEERS'
  || approval.nodeName !== nodeName
  || approval.controls?.validatorProcessRestartAllowed !== true) {
  throw new Error('Single-validator restart approval does not match the requested node.');
}
const topology = JSON.parse(fs.readFileSync(service.paths.topologyPath, 'utf8'));
const target = (topology.validators || []).find(row => row.nodeName === nodeName);
const node = (persistentStore.readState().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 currentPid = Number(meta.validatorRuntimeProcessPid || 0);
const heartbeatAgeMs = Date.now() - new Date(node?.lastHeartbeatAt || 0).getTime();
if (node?.status !== 'active' || heartbeatAgeMs < 0 || heartbeatAgeMs > 3 * 60_000
  || !['1.4.120-validator-direct-attestation-refresh-tunnel-fallback-locked',
    '1.4.121-validator-direct-evidence-diagnostic-tunnel-fallback-locked',
    '1.4.122-validator-direct-offer-state-diagnostic-tunnel-fallback-locked',
    '1.4.123-validator-direct-control-heartbeat-diagnostic-tunnel-fallback-locked'].includes(node.clientVersion)
  || meta.validatorRuntimeState !== 'validator-active'
  || currentPid <= 0 || currentPid === previousPid
  || Number(meta.validatorRuntimeBlockNumber || 0) <= 0
  || Number(meta.validatorRuntimePeerCount || 0) < 1) {
  throw new Error('Fresh post-restart validator evidence is incomplete.');
}
const historyRoot = path.join(path.dirname(service.paths.approvalPath), 'approval-history');
fs.mkdirSync(historyRoot, { recursive: true });
const archivePath = path.join(historyRoot, `${approval.approvalId}-restart-observed-awaiting-direct-attestation.json`);
if (fs.existsSync(archivePath)) throw new Error('Observed restart approval archive already exists.');
fs.renameSync(service.paths.approvalPath, archivePath);
console.log(JSON.stringify({
  ok: true,
  status: 'SINGLE_VALIDATOR_RESTART_APPROVAL_ARCHIVED_AWAITING_DIRECT_ATTESTATION',
  nodeName,
  previousPid,
  currentPid,
  blockNumber: Number(meta.validatorRuntimeBlockNumber || 0),
  archivePath
}, null, 2));
