const fs = require('fs');
const path = require('path');

const root = path.resolve(__dirname, '..');
const manifestPath = path.resolve(
  root,
  '..',
  '..',
  'v3-migration',
  'completeness',
  'supported-v3-modules.json',
);
const outputPath = path.join(root, 'src', 'v3', 'supported.ts');
const mapping = {
  accountabilityBond: 'AccountabilityBondV3Safe',
  partnershipBond: 'PartnershipBondV3Safe',
  governance: 'MultisigGovernanceV3',
  mandateRegistry: 'MandateRegistryV3',
};

const manifest = JSON.parse(fs.readFileSync(manifestPath, 'utf8'));
const supported = new Map(
  manifest.modules
    .filter((entry) => entry.supportStatus === 'supported-source')
    .map((entry) => [entry.module, entry]),
);

const rows = Object.entries(mapping).map(([deployment, solidityModule]) => {
  const entry = supported.get(solidityModule);
  if (!entry) {
    throw new Error(`${solidityModule} is absent from the canonical supported V3 closure`);
  }
  return `  ${deployment}: {\n` +
    `    solidityModule: '${entry.module}',\n` +
    `    sourcePath: '${entry.path}',\n` +
    '  },';
});

const output = `import { deepFreeze } from './freeze';
import type { V3DeploymentName } from './types';

/**
 * SDK modules selected from the authoritative supported-v3-modules.json closure.
 * This file is generated by scripts/generate-supported-v3-modules.cjs.
 */
export const V3_SUPPORTED_MODULES = deepFreeze({
${rows.join('\n')}
} as const satisfies Record<V3DeploymentName, {
  readonly solidityModule: string;
  readonly sourcePath: string;
}>);

export const V3_SUPPORTED_DEPLOYMENT_NAMES =
  deepFreeze(Object.keys(V3_SUPPORTED_MODULES) as V3DeploymentName[]);
`;

fs.writeFileSync(outputPath, output);
