/**
 * GET /api/abis
 *
 * Index of all available contract ABIs — machine-readable, agent-consumable.
 * Partners use this as the discovery endpoint to wire Vaultfire into any
 * viem/ethers/wagmi stack in minutes.
 *
 * Returns:
 *   - List of every ABI available, with addresses per chain
 *   - Direct URLs to fetch each ABI as JSON
 *   - Contract categories for easy navigation
 *
 * Pair with:
 *   GET /api/abis/[name]                  → full ABI JSON
 *   GET /api/abis/[name]?chain=base       → chain-specific ABI variant
 *   GET /api/contracts                    → addresses only (no ABI)
 */

import { NextResponse } from 'next/server';
import { ABI_MAP } from '../../lib/abis/abi-map';
import {
  BASE_CONTRACTS,
  AVALANCHE_CONTRACTS,
  ARBITRUM_CONTRACTS,
  POLYGON_CONTRACTS,
} from '../../lib/contracts';

const CORS = {
  'Access-Control-Allow-Origin': '*',
  'Access-Control-Allow-Methods': 'GET, OPTIONS',
  'Access-Control-Allow-Headers': 'Content-Type',
};

export async function OPTIONS() {
  return new NextResponse(null, { status: 204, headers: CORS });
}

export async function GET(request: Request) {
  const base = new URL(request.url).origin;

  // Build address lookup per (name, chain)
  const addresses: Record<string, Record<string, string>> = {};
  const register = (chain: string, contracts: typeof BASE_CONTRACTS) => {
    for (const c of contracts) {
      if (!addresses[c.name]) addresses[c.name] = {};
      addresses[c.name][chain] = c.address;
    }
  };
  register('base', BASE_CONTRACTS);
  register('avalanche', AVALANCHE_CONTRACTS);
  register('arbitrum', ARBITRUM_CONTRACTS);
  register('polygon', POLYGON_CONTRACTS);

  // Unique ABI names from ABI_MAP (excluding chain-suffixed overrides)
  const allKeys = Object.keys(ABI_MAP);
  const baseNames = Array.from(new Set(
    allKeys
      .map(k => k.replace(/_(base|avalanche|arbitrum|polygon)$/, ''))
      .filter(Boolean)
  )).sort();

  const abis = baseNames.map(name => {
    // Chain-specific override names
    const chainOverrides = allKeys
      .filter(k => k.startsWith(`${name}_`))
      .map(k => k.replace(`${name}_`, ''));

    return {
      name,
      url: `${base}/api/abis/${name}`,
      addresses: addresses[name] || {},
      chainSpecificVariants: chainOverrides.length > 0 ? chainOverrides : undefined,
      functionCount: ABI_MAP[name]?.filter((x: any) => x?.type === 'function').length || 0,
      eventCount: ABI_MAP[name]?.filter((x: any) => x?.type === 'event').length || 0,
    };
  });

  return NextResponse.json({
    description: 'Vaultfire contract ABI registry — drop-in for viem/ethers/wagmi.',
    version: '1.0.0',
    chains: ['base', 'avalanche', 'arbitrum', 'polygon'],
    totalABIs: abis.length,
    totalContracts:
      BASE_CONTRACTS.length +
      AVALANCHE_CONTRACTS.length +
      ARBITRUM_CONTRACTS.length +
      POLYGON_CONTRACTS.length,
    fetchPattern: {
      single: `${base}/api/abis/{name}`,
      chainSpecific: `${base}/api/abis/{name}?chain={base|avalanche|arbitrum|polygon}`,
      addressesOnly: `${base}/api/contracts`,
    },
    quickStart: {
      viem: `import { createPublicClient, http } from 'viem'; import { base } from 'viem/chains'; const abi = await fetch('${base}/api/abis/ERC8004IdentityRegistry').then(r => r.json()); const client = createPublicClient({ chain: base, transport: http() }); const count = await client.readContract({ address: '0xa7BD20bf5De63df949cA5Be2F20835978eCba81A', abi: abi.abi, functionName: 'getTotalAgents' });`,
    },
    abis,
  }, {
    headers: {
      ...CORS,
      'Cache-Control': 'public, max-age=3600', // ABIs change rarely
    },
  });
}
