/**
 * Live test: invoke readGroupId() against all 4 deployed registries.
 * Each call should return null (no groups registered yet) and not throw.
 */
const { Interface, JsonRpcProvider } = require('ethers');

const FORUM_REGISTRY = {
  base:      '0xB6Ac5aFfF7e5934fc19b16007F26b1866B976240',
  avalanche: '0x80f64F6dcdB7aceAfA6762Cd33b14abfF32BcA27',
  arbitrum:  '0x87404357B9D978E4754c542f54E6724E0cda846e',
  polygon:   '0x80f64F6dcdB7aceAfA6762Cd33b14abfF32BcA27',
};
const RPC = {
  base:      'https://mainnet.base.org',
  avalanche: 'https://api.avax.network/ext/bc/C/rpc',
  arbitrum:  'https://arb1.arbitrum.io/rpc',
  polygon:   'https://polygon-bor-rpc.publicnode.com',
};
const CHAIN_ID = { base: 8453, avalanche: 43114, arbitrum: 42161, polygon: 137 };

// Replicate the exact selector + encoder + decoder from forum-xmtp.ts
const SELECTOR = '0xabef281e';
function encodeStringArg(s) {
  const offset = '0000000000000000000000000000000000000000000000000000000000000020';
  const bytes = new TextEncoder().encode(s);
  const len = bytes.length.toString(16).padStart(64, '0');
  let hex = ''; for (const b of bytes) hex += b.toString(16).padStart(2, '0');
  const padded = (hex + '0'.repeat(64)).slice(0, Math.ceil(hex.length / 64) * 64);
  return offset + len + padded;
}
function decode(result) {
  if (!result || result === '0x') return null;
  const hex = result.slice(2);
  if (hex.length < 64 * 4) return null;
  const bytesOffset = parseInt(hex.slice(0, 64), 16) * 2;
  if (bytesOffset + 64 > hex.length) return null;
  const bytesLen = parseInt(hex.slice(bytesOffset, bytesOffset + 64), 16);
  if (bytesLen === 0) return null;
  return '0x' + hex.slice(bytesOffset + 64, bytesOffset + 64 + bytesLen * 2);
}

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

async function check(chain) {
  const provider = new JsonRpcProvider(RPC[chain], CHAIN_ID[chain], { staticNetwork: true });
  for (const cat of ['general', 'technical', 'governance', 'tasks', 'announcements']) {
    const data = SELECTOR + encodeStringArg(cat);
    try {
      const result = await timeout(provider.call({ to: FORUM_REGISTRY[chain], data }), 15000, `${chain}/${cat}`);
      const decoded = decode(result);
      console.log(`[${chain.padEnd(10)}] ${cat.padEnd(14)} -> ${decoded === null ? 'null' : decoded.slice(0, 24) + '...'}`);
    } catch (e) {
      console.log(`[${chain.padEnd(10)}] ${cat.padEnd(14)} -> ERROR ${e.message}`);
    }
  }
}

(async () => {
  for (const chain of ['base', 'avalanche', 'arbitrum', 'polygon']) await check(chain);
})();
