/**
 * Built-in CCIP / Trustless bridge route payload when BRIDGE_LIST_JSON_URL is unset.
 * Aligns with MetaMask Snap expectations and docs/07-ccip/CCIP_BRIDGE_MAINNET_CONNECTION.md.
 */

import { getActivePublicPools, getActiveTransportPairs, getGruTransportMetadata } from '../../config/gru-transport';

export interface BridgeRoutesPayload {
  routes: {
    weth9: Record<string, string>;
    weth10: Record<string, string>;
    trustless?: Record<string, string>;
  };
  chain138Bridges: {
    weth9: string;
    weth10: string;
    trustless?: string;
  };
  tokenMappingApi: {
    basePath: string;
    pairs: string;
    resolve: string;
    note: string;
  };
  gruTransport?: {
    system: unknown;
    summary?: Record<string, number>;
    activeTransportPairs: unknown[];
    activePublicPools: unknown[];
  };
}

const DEFAULT_WETH9_138 = '0xcacfd227A040002e49e2e01626363071324f820a';
const DEFAULT_WETH10_138 = '0xe0E93247376aa097dB308B92e6Ba36bA015535D0';
const DEFAULT_LOCKBOX_138 = '0xFce6f50B312B3D936Ea9693C5C9531CF92a3324c';

/** Destination-side WETH9 receivers (relay-backed where noted in CCIP docs). */
const WETH9_DESTINATIONS: Record<string, string> = {
  'Ethereum Mainnet (1)': '0xF9A32F37099c582D28b4dE7Fca6eaC1e5259f939',
  'BNB Chain (56)': '0x886C6A4ABC064dbf74E7caEc460b7eeC31F1b78C',
  'Avalanche C-Chain (43114)': '0x3f8C409C6072a2B6a4Ff17071927bA70F80c725F',
};

function envAddr(key: string, fallback: string): string {
  const v = process.env[key];
  return typeof v === 'string' && v.startsWith('0x') ? v : fallback;
}

export function buildDefaultBridgeRoutes(): BridgeRoutesPayload {
  const inboxEth = process.env.INBOX_ETH?.trim();
  const trustlessRoutes: Record<string, string> = {};
  if (inboxEth?.startsWith('0x')) {
    trustlessRoutes['Ethereum Mainnet (1)'] = inboxEth;
  }

  const gruTransportMetadata = getGruTransportMetadata();

  return {
    routes: {
      weth9: { ...WETH9_DESTINATIONS },
      weth10: { ...WETH9_DESTINATIONS },
      ...(Object.keys(trustlessRoutes).length > 0 ? { trustless: trustlessRoutes } : {}),
    },
    chain138Bridges: {
      weth9: envAddr('CCIPWETH9_BRIDGE_CHAIN138', DEFAULT_WETH9_138),
      weth10: envAddr('CCIPWETH10_BRIDGE_CHAIN138', DEFAULT_WETH10_138),
      trustless: envAddr('LOCKBOX_138', DEFAULT_LOCKBOX_138),
    },
    tokenMappingApi: {
      basePath: '/api/v1/token-mapping',
      pairs: '/api/v1/token-mapping/pairs',
      resolve: '/api/v1/token-mapping/resolve',
      note: 'Resolve bridged token addresses between chains; requires monorepo config/token-mapping-multichain.json on server.',
    },
    gruTransport: gruTransportMetadata
      ? {
          system: gruTransportMetadata.system,
          summary: gruTransportMetadata.counts,
          activeTransportPairs: getActiveTransportPairs(),
          activePublicPools: getActivePublicPools(),
        }
      : undefined,
  };
}
