require('../config/loadEnv')();
const fs = require('fs');
const path = require('path');
const { Wallet, getAddress } = require('ethers');
const { auditAcl, unprotect } = require('../lib/operatorDpapi');
const operatorCustodyService = require('../services/operatorCustodyService');

function main() {
  const status = operatorCustodyService.getStatus();
  const vaultPath = operatorCustodyService.resolveVaultPath();
  const metadata = JSON.parse(fs.readFileSync(vaultPath, 'utf8'));
  const recoveredKey = unprotect(metadata.ciphertext);
  const recoveredAddress = new Wallet(recoveredKey).address;
  const configuredAddress = getAddress(process.env.PLAIS_EVM_OPERATOR_ADDRESS);
  const networkPath = path.join(__dirname, '..', 'runtime', 'plais-qbft', 'network.json');
  const network = JSON.parse(fs.readFileSync(networkPath, 'utf8'));
  const networkAddress = getAddress(network.operatorAddress);
  const genesis = JSON.parse(fs.readFileSync(path.resolve(network.genesisFile), 'utf8'));
  const acl = auditAcl(vaultPath);
  const directoryAcl = auditAcl(path.dirname(vaultPath));
  const checks = {
    plaintextKeyAbsent: !/^0x[0-9a-fA-F]{64}$/.test(String(process.env.PLAIS_EVM_OPERATOR_PRIVATE_KEY || '').trim()),
    recoveredAddressMatchesConfigured: recoveredAddress === configuredAddress,
    recoveredAddressMatchesCanonical: recoveredAddress === networkAddress,
    genesisAllocationPresent: Boolean(genesis.alloc && genesis.alloc[recoveredAddress.slice(2).toLowerCase()]),
    vaultAclProtected: acl.ok,
    vaultDirectoryAclProtected: directoryAcl.ok,
    signingDisabled: process.env.PLAIS_EVM_OPERATOR_SIGNING_ENABLED === '0',
    multichainTransfersDisabled: process.env.PLAIS_MULTICHAIN_TRANSFERS_ENABLED === '0',
    webCustodyChecksPass: status.ok
  };
  const ok = Object.values(checks).every(Boolean);
  console.log(JSON.stringify({ ok, protection: metadata.protection, checks }, null, 2));
  if (!ok) process.exitCode = 1;
}

try {
  main();
} catch (error) {
  console.error(JSON.stringify({ ok: false, error: error.code || 'OPERATOR_CUSTODY_AUDIT_FAILED', message: error.message }));
  process.exit(1);
}
