/**
 * ISO-4217 compliant token symbol validation.
 * Validates 6-char native and 7-char bridged symbols; parses and resolves v0 legacy.
 * See docs/04-configuration/ISO4217_COMPLIANT_TOKEN_MATRIX.md
 */

import {
  V0_TO_V1_SYMBOL_MAP,
  isFinChainDesignator,
  isISO4217Supported,
  isAssetTypeChar,
  type V1SymbolIdentity,
} from '../config/iso4217-symbol-registry';

export type ParsedSymbolType = 'native' | 'bridged' | 'v0';

export interface ParsedSymbol {
  type: ParsedSymbolType;
  iso?: string;
  typeChar?: string;
  originChain?: string;
  v1Identity?: V1SymbolIdentity;
}

/**
 * Validates native (6-char) symbol: c + FinChain + ISO4217 + Type
 */
export function isValidNativeSymbol(s: string): boolean {
  if (typeof s !== 'string' || s.length !== 6) return false;
  if (s[0] !== 'c') return false;
  if (!isFinChainDesignator(s[1])) return false;
  const iso = s.slice(2, 5);
  if (!isISO4217Supported(iso)) return false;
  if (!isAssetTypeChar(s[5])) return false;
  return true;
}

/**
 * Validates bridged (7-char) symbol: c + W + OriginFinChain + ISO4217 + Type
 */
export function isValidBridgedSymbol(s: string): boolean {
  if (typeof s !== 'string' || s.length !== 7) return false;
  if (s[0] !== 'c') return false;
  if (s[1] !== 'W') return false;
  if (!isFinChainDesignator(s[2])) return false;
  const iso = s.slice(3, 6);
  if (!isISO4217Supported(iso)) return false;
  if (!isAssetTypeChar(s[6])) return false;
  return true;
}

/**
 * Parses a symbol and returns its type and components, or null if invalid/unknown.
 * v0 symbols (e.g. cUSDT, cUSDC) return type 'v0' with v1Identity from registry.
 */
export function parseSymbol(s: string): ParsedSymbol | null {
  if (typeof s !== 'string' || s.length === 0) return null;

  const v0Identity = V0_TO_V1_SYMBOL_MAP[s];
  if (v0Identity) {
    return {
      type: 'v0',
      iso: v0Identity.iso,
      typeChar: v0Identity.type,
      originChain: v0Identity.originChain,
      v1Identity: v0Identity,
    };
  }

  if (s.length === 6 && isValidNativeSymbol(s)) {
    return {
      type: 'native',
      iso: s.slice(2, 5),
      typeChar: s[5],
      originChain: s[1],
    };
  }

  if (s.length === 7 && isValidBridgedSymbol(s)) {
    return {
      type: 'bridged',
      iso: s.slice(3, 6),
      typeChar: s[6],
      originChain: s[2],
    };
  }

  return null;
}
