/** GRU transport placeholders (e.g. 0xcaaa…008a) — not deployed ERC-20 contracts. */
export function isDeterministicPlaceholderAddress(address: string): boolean {
  const normalized = address.toLowerCase()
  return /^0x[a-f0-9]{4}0{24,}[a-f0-9]{1,8}$/.test(normalized)
}

export function isWalletWatchEligibleAddress(address?: string | null): boolean {
  if (!address) return false
  return !isDeterministicPlaceholderAddress(address)
}

export type WalletWatchTokenLike = {
  chainId?: number
  address?: string
  symbol?: string
  extensions?: Record<string, unknown>
}

function walletWatchTokenRank(token: WalletWatchTokenLike): number {
  let rank = 0
  const extensions = token.extensions || {}
  const status = String(extensions.deploymentStatus || '').toLowerCase()
  const version = String(extensions.deploymentVersion || '').toLowerCase()
  if (status === 'staged') rank += 100
  if (version === 'v2') rank += 50
  return rank
}

/** MetaMask stores one custom token row per symbol — keep the live contract address. */
export function dedupeWalletWatchTokens<T extends WalletWatchTokenLike>(tokens: T[]): T[] {
  const bySymbol = new Map<string, T>()
  for (const token of tokens) {
    if (!isWalletWatchEligibleAddress(token.address)) continue
    const key = String(token.symbol || '').trim().toLowerCase()
    if (!key) continue
    const existing = bySymbol.get(key)
    if (!existing || walletWatchTokenRank(token) < walletWatchTokenRank(existing)) {
      bySymbol.set(key, token)
    }
  }
  return Array.from(bySymbol.values())
}

/** Gas-family roadmap symbols that use deterministic placeholder bindings on Chain 138. */
export const CHAIN138_PLACEHOLDER_GAS_SYMBOLS = [
  'cAVAX',
  'cBNB',
  'cCELO',
  'cCRO',
  'cETH',
  'cETHL2',
  'cPOL',
  'cWEMIX',
  'cXDAI',
] as const
