import registryDoc from '../../../config/web3-identity-registry.v1.json'

export interface Web3IdentityEntry {
  id: string
  address: string
  chainIds: number[]
  roles: string[]
  displayName: string
  ens?: { primary: string; chainId: number } | null
  identifiers?: Array<{ type: string; value: string; entityRef?: string; note?: string }>
  explorer?: { blockscoutLabel?: string | null; tagTypes?: string[] }
  eiLabel?: string | null
}

export interface Web3IdentityEntity {
  id: string
  displayName: string
  lei: string
  entityRef: string
  roles: string[]
}

export interface Web3IdentityRegistry {
  schemaVersion: string
  entries: Web3IdentityEntry[]
  entities?: Web3IdentityEntity[]
}

const registry = registryDoc as Web3IdentityRegistry

const byAddress = new Map<string, Web3IdentityEntry>()
const byEns = new Map<string, Web3IdentityEntry>()
const byId = new Map<string, Web3IdentityEntry>()
const byLei = new Map<string, Web3IdentityEntity>()

for (const entry of registry.entries) {
  const lower = entry.address.toLowerCase()
  if (lower === `0x${'0'.repeat(40)}`) continue
  byAddress.set(lower, entry)
  byId.set(entry.id, entry)
  const ensName = entry.ens?.primary?.toLowerCase()
  if (ensName) byEns.set(ensName, entry)
}

for (const entity of registry.entities ?? []) {
  byLei.set(entity.lei, entity)
}

export function getRegistryEntryByAddress(address: string): Web3IdentityEntry | undefined {
  return byAddress.get(address.toLowerCase())
}

export function getRegistryEntryByEns(name: string): Web3IdentityEntry | undefined {
  return byEns.get(name.trim().toLowerCase())
}

export function getRegistryEntryById(id: string): Web3IdentityEntry | undefined {
  return byId.get(id)
}

export function getEntityByLei(lei: string): Web3IdentityEntity | undefined {
  return byLei.get(lei.trim().toUpperCase())
}

/** Registry blockscoutLabel or displayName — not live ENS. */
export function getKnownDisplayName(address: string): string | undefined {
  const entry = getRegistryEntryByAddress(address)
  if (!entry) return undefined
  return entry.explorer?.blockscoutLabel || entry.displayName
}

export function resolveAddressFromRegistryEns(name: string): string | undefined {
  return getRegistryEntryByEns(name)?.address
}

export function searchRegistryByQuery(query: string): Web3IdentityEntry[] {
  const q = query.trim().toLowerCase()
  if (!q) return []
  return registry.entries.filter((entry) => {
    if (entry.address.toLowerCase() === q) return true
    if (entry.displayName.toLowerCase().includes(q)) return true
    if (entry.ens?.primary.toLowerCase() === q) return true
    if (entry.explorer?.blockscoutLabel?.toLowerCase().includes(q)) return true
    return entry.identifiers?.some(
      (id) => id.value?.toLowerCase() === q || id.value?.toLowerCase().includes(q),
    )
  })
}

export { registry as web3IdentityRegistry }
