/**
 * Triple-check the deployed VaultfireForumRegistry on all 4 chains.
 * - Confirms code exists at address
 * - Calls a read function (getCategories) to prove ABI matches
 * - Confirms initial state is empty (no groups registered yet)
 */
const { ethers } = require('ethers');
const fs = require('fs');
const path = require('path');

const DEPLOYMENTS = [
  { chain: 'Base',      rpc: 'https://mainnet.base.org',                     chainId: 8453,  address: '0xB6Ac5aFfF7e5934fc19b16007F26b1866B976240', explorer: 'https://basescan.org/address/' },
  { chain: 'Avalanche', rpc: 'https://api.avax.network/ext/bc/C/rpc',        chainId: 43114, address: '0x80f64F6dcdB7aceAfA6762Cd33b14abfF32BcA27', explorer: 'https://snowtrace.io/address/' },
  { chain: 'Arbitrum',  rpc: 'https://arb1.arbitrum.io/rpc',                 chainId: 42161, address: '0x87404357B9D978E4754c542f54E6724E0cda846e', explorer: 'https://arbiscan.io/address/' },
  { chain: 'Polygon',   rpc: 'https://polygon-bor-rpc.publicnode.com',       chainId: 137,   address: '0x80f64F6dcdB7aceAfA6762Cd33b14abfF32BcA27', explorer: 'https://polygonscan.com/address/' },
];

function loadAbi() {
  const a = JSON.parse(fs.readFileSync(path.join(__dirname, '..', 'artifacts', 'contracts', 'VaultfireForumRegistry.sol', 'VaultfireForumRegistry.json'), 'utf8'));
  return a.abi;
}

function withTimeout(p, ms, l) { return Promise.race([p, new Promise((_, r) => setTimeout(() => r(new Error(`timeout ${l}`)), ms))]); }

async function checkOne(d, abi) {
  try {
    const provider = new ethers.JsonRpcProvider(d.rpc, d.chainId, { staticNetwork: true });
    const code = await withTimeout(provider.getCode(d.address), 10000, 'getCode');
    if (code === '0x') return console.log(`[${d.chain.padEnd(10)}] FAIL: no contract at address`);
    const codeSize = (code.length - 2) / 2;
    const c = new ethers.Contract(d.address, abi, provider);
    const count = await withTimeout(c.categoryCount(), 10000, 'categoryCount');
    const cats = await withTimeout(c.listCategories(), 10000, 'listCategories');
    const isReg = await withTimeout(c.isRegistered('general'), 10000, 'isRegistered');
    console.log(`[${d.chain.padEnd(10)}] OK  code=${codeSize}b  count=${count}  categories=${cats.length}  general_registered=${isReg}  ${d.explorer}${d.address}`);
  } catch (e) {
    console.log(`[${d.chain.padEnd(10)}] FAIL: ${e.message}`);
  }
}

(async () => {
  const abi = loadAbi();
  console.log(`Triple-checking ${DEPLOYMENTS.length} chains with ABI loaded (${abi.length} entries)\n`);
  await Promise.all(DEPLOYMENTS.map(d => checkOne(d, abi)));
})();
