import { getCanonicalTokenByAddress, getCanonicalTokensByChain, type CanonicalTokenSpec } from './canonical-tokens';

const CHAIN_138 = 138;

function normalizeAddress(value: string): string {
  return value.trim().toLowerCase();
}

/** Canonical Chain 138 issued c* base tokens (excludes staged V2 duplicates and cW* transport). */
export function getChain138IssuedCStarTokens(): CanonicalTokenSpec[] {
  return getCanonicalTokensByChain(CHAIN_138).filter((spec) => isChain138IssuedCStarTokenSpec(spec));
}

export function isChain138IssuedCStarTokenSpec(spec: CanonicalTokenSpec | undefined): boolean {
  if (!spec || spec.type !== 'base') return false;
  if (spec.deploymentStatus === 'staged') return false;
  const symbol = spec.symbol.trim();
  if (!symbol.startsWith('c') || symbol.startsWith('cW')) return false;
  const address = spec.addresses[CHAIN_138];
  return Boolean(address && String(address).trim() !== '');
}

export function isChain138IssuedCStarTokenAddress(address: string): boolean {
  const spec = getCanonicalTokenByAddress(CHAIN_138, normalizeAddress(address));
  return isChain138IssuedCStarTokenSpec(spec);
}
