const fs = require('fs');
const path = require('path');
const { ethers } = require('ethers');
const root = path.resolve(__dirname, '..');
const artifactRoot = path.resolve(root, '..', '..', 'v3-src', 'out');
const supportManifest = JSON.parse(fs.readFileSync(path.resolve(
  root,
  '..',
  '..',
  'v3-migration',
  'completeness',
  'supported-v3-modules.json',
), 'utf8'));
const supportedModules = new Set(
  supportManifest.modules
    .filter((entry) => entry.supportStatus === 'supported-source')
    .map((entry) => entry.module),
);
const artifacts = {
  accountabilityBond: 'AccountabilityBondV3Safe.sol/AccountabilityBondV3Safe.json',
  partnershipBond: 'PartnershipBondV3Safe.sol/PartnershipBondV3Safe.json',
  governance: 'MultisigGovernanceV3.sol/MultisigGovernanceV3.json',
  mandateRegistry: 'MandateRegistryV3.sol/MandateRegistryV3.json',
};
for (const artifact of Object.values(artifacts)) {
  const module = path.basename(artifact, '.json');
  if (!supportedModules.has(module)) {
    throw new Error(`${module} is absent from the canonical supported V3 closure`);
  }
}
const deployments = {};
for (const [name, artifact] of Object.entries(artifacts)) {
  const artifactPath = path.join(artifactRoot, artifact);
  const snapshotPath = path.join(
    root,
    'tests',
    'fixtures',
    'reviewed-artifacts',
    path.basename(artifact),
  );
  const reviewedPath = fs.existsSync(artifactPath) ? artifactPath : snapshotPath;
  const parsed = JSON.parse(fs.readFileSync(reviewedPath, 'utf8'));
  const functions = new ethers.Interface(parsed.abi).fragments
    .filter((fragment) => fragment.type === 'function')
    .map((fragment) => ({
      signature: fragment.format('sighash'),
      stateMutability: fragment.stateMutability,
    }))
    .sort((left, right) => left.signature < right.signature ? -1 : left.signature > right.signature ? 1 : 0);
  const identity = ethers.keccak256(ethers.toUtf8Bytes(functions.map(({ signature }) => signature).join('\n')));
  deployments[name] = { artifact, identity, functions };
}
const fixture = {
  schema: 'vaultfire.v3.reviewed-abi-signatures.v1',
  sourceAuthority: 'final reviewed Solidity artifacts; repository snapshots used when v3-src/out is absent',
  deployments,
};
fs.writeFileSync(
  path.join(root, 'tests', 'fixtures', 'v3-reviewed-abi-signatures.json'),
  `${JSON.stringify(fixture, null, 2)}\n`,
);
