import type { TokenListToken } from '@/services/api/config'

export const WETH9_CANONICAL_ADDRESS = '0xC02aaA39b223FE8D0A0e5C4F27eAD9083C756Cc2'

export const TOKEN_DISPLAY_OVERRIDES: Record<string, { name?: string; symbol?: string; decimals?: number }> = {
  [WETH9_CANONICAL_ADDRESS.toLowerCase()]: {
    name: 'Wrapped Ether (WETH9)',
    symbol: 'WETH9',
    decimals: 18,
  },
}

export function buildCanonicalAddressSet(tokens: TokenListToken[]): Set<string> {
  const addresses = new Set<string>()
  for (const token of tokens) {
    if (typeof token.address === 'string' && token.address.trim().length > 0) {
      addresses.add(token.address.toLowerCase())
    }
  }
  return addresses
}

export function isCanonicalTokenAddress(address: string, canonicalSet: Set<string>): boolean {
  return canonicalSet.has(address.toLowerCase())
}

export function applyTokenDisplayOverrides<T extends { address: string; name?: string; symbol?: string; decimals?: number }>(
  token: T,
): T {
  const override = TOKEN_DISPLAY_OVERRIDES[token.address.toLowerCase()]
  if (!override) {
    return token
  }

  return {
    ...token,
    name: override.name || token.name,
    symbol: override.symbol || token.symbol,
    decimals: override.decimals ?? token.decimals,
  }
}

export function sortIndexedTokensCanonicalFirst<T extends { address: string; symbol?: string; name?: string }>(
  tokens: T[],
  canonicalSet: Set<string>,
): T[] {
  return [...tokens].sort((left, right) => {
    const leftCanonical = isCanonicalTokenAddress(left.address, canonicalSet)
    const rightCanonical = isCanonicalTokenAddress(right.address, canonicalSet)
    if (leftCanonical !== rightCanonical) {
      return leftCanonical ? -1 : 1
    }

    const leftLabel = left.symbol || left.name || left.address
    const rightLabel = right.symbol || right.name || right.address
    return leftLabel.localeCompare(rightLabel, undefined, { sensitivity: 'base' })
  })
}
