/**
 * Verify VaultfireForumRegistry on Sourcify (no API key required).
 * Sourcify is recognized by Basescan, Snowtrace, Arbiscan, Polygonscan.
 *
 * Usage:
 *   node scripts/verify-sourcify.js
 */
const fs = require('fs');
const path = require('path');

const DEPLOYMENTS = [
  { chain: 'Base',      chainId: 8453,  address: '0xB6Ac5aFfF7e5934fc19b16007F26b1866B976240' },
  { chain: 'Avalanche', chainId: 43114, address: '0x80f64F6dcdB7aceAfA6762Cd33b14abfF32BcA27' },
  { chain: 'Arbitrum',  chainId: 42161, address: '0x87404357B9D978E4754c542f54E6724E0cda846e' },
  { chain: 'Polygon',   chainId: 137,   address: '0x80f64F6dcdB7aceAfA6762Cd33b14abfF32BcA27' },
];

const SOURCE_PATH = 'contracts/VaultfireForumRegistry.sol';

function loadBuildInfo() {
  const dir = path.join(__dirname, '..', 'artifacts', 'build-info');
  const files = fs.readdirSync(dir).filter(f => f.endsWith('.json'));
  for (const f of files) {
    const bi = JSON.parse(fs.readFileSync(path.join(dir, f), 'utf8'));
    const c = bi.output?.contracts?.[SOURCE_PATH]?.VaultfireForumRegistry;
    if (c?.metadata) return { metadata: c.metadata, sources: bi.input.sources };
  }
  throw new Error('VaultfireForumRegistry build info not found');
}

async function verifyOne({ chain, chainId, address }, metadata, sources) {
  // Use multipart form-data upload to Sourcify's verification API
  const form = new FormData();
  form.append('address', address);
  form.append('chain', String(chainId));
  // metadata.json file
  form.append('files', new Blob([metadata], { type: 'application/json' }), 'metadata.json');
  // each source file
  for (const [filePath, src] of Object.entries(sources)) {
    const name = filePath.split('/').pop();
    form.append('files', new Blob([src.content], { type: 'text/plain' }), name);
  }
  const res = await fetch('https://sourcify.dev/server/verify', { method: 'POST', body: form });
  const text = await res.text();
  let parsed; try { parsed = JSON.parse(text); } catch { parsed = null; }
  const r = parsed?.result?.[0] || {};
  const summary = {
    runtimeMatch: r.runtimeMatch ?? null,
    creationMatch: r.creationMatch ?? null,
    status: r.status ?? null,
  };
  console.log(`[${chain.padEnd(10)} chainId=${String(chainId).padEnd(6)}] HTTP ${res.status}  ${JSON.stringify(summary)}`);
}

(async () => {
  const { metadata, sources } = loadBuildInfo();
  console.log(`Loaded metadata (${metadata.length} bytes), ${Object.keys(sources).length} source files\n`);
  for (const d of DEPLOYMENTS) {
    try { await verifyOne(d, metadata, sources); } catch (e) { console.log(`[${d.chain}] FAIL ${e.message}`); }
  }
})();
