import { type CanonicalTokenSpec } from '../config/canonical-tokens';

/** CoinGecko IDs used only as USD valuation proxies for ISO-4217 c* eMoney (not issuer identity). */
/** USD valuation proxies for CoinGecko / MetaMask submissions — not issuer identity. */
const ISO4217_COINGECKO_PROXY: Record<string, string> = {
  USD: 'usd-coin',
  EUR: 'euro-coin',
  XAU: 'pax-gold',
  ETH: 'ethereum',
  BTC: 'bitcoin',
  LINK: 'chainlink',
};

const USD_TREASURY_SYMBOLS = new Set(['CUSDT', 'CEURT', 'CGBPT', 'CXAUT']);

export function resolveIso4217AssetClassSuffix(symbol: string): 'C' | 'T' | undefined {
  const upper = symbol.trim().toUpperCase();
  if (upper.length < 2) return undefined;
  const suffix = upper.at(-1);
  if (suffix === 'C' || suffix === 'T') return suffix;
  return undefined;
}

export function resolveCoingeckoPriceProxyId(spec: Pick<CanonicalTokenSpec, 'symbol' | 'currencyCode'>): string | undefined {
  const currency = String(spec.currencyCode || '').trim().toUpperCase();
  if (currency && ISO4217_COINGECKO_PROXY[currency]) {
    const upper = spec.symbol.trim().toUpperCase();
    if (currency === 'USD' && USD_TREASURY_SYMBOLS.has(upper)) {
      return 'tether';
    }
    return ISO4217_COINGECKO_PROXY[currency];
  }

  if (spec.symbol.trim().toUpperCase() === 'LINK') return ISO4217_COINGECKO_PROXY.LINK;
  if (spec.symbol.trim().toUpperCase().includes('BTC')) return ISO4217_COINGECKO_PROXY.BTC;
  if (spec.symbol.trim().toUpperCase().includes('ETH')) return ISO4217_COINGECKO_PROXY.ETH;

  return undefined;
}

export function buildIso4217TokenListExtensions(
  spec: Pick<CanonicalTokenSpec, 'symbol' | 'currencyCode' | 'type' | 'name'>,
): Record<string, unknown> {
  const currencyCode = String(spec.currencyCode || '').trim().toUpperCase() || undefined;
  const assetClass = resolveIso4217AssetClassSuffix(spec.symbol);
  const coingeckoPriceProxyId = resolveCoingeckoPriceProxyId(spec);

  return {
    gruLayer: spec.type === 'w' ? 'cW' : 'c',
    iso4217: currencyCode,
    gruAssetClass: assetClass,
    gruAssetClassLabel:
      assetClass === 'C'
        ? 'Cash (Tokenized M1)'
        : assetClass === 'T'
          ? 'Treasury (Tokenized GILT or equivalent security)'
          : undefined,
    coingeckoPriceProxyId,
    pricingNote:
      'Native GRU Compliant eMoney — CoinGecko proxy is for USD display only, not third-party issuer identity.',
  };
}
