import type { CuratedPoolRegistryEntry } from '@/services/api/liquidityPositions'

export interface PoolSearchRow extends CuratedPoolRegistryEntry {
  pairLabel: string
  matchReason: 'exact pool address' | 'exact lp token' | 'pair symbol' | 'symbol prefix'
}

const addressPattern = /^0x[a-f0-9]{40}$/i

function pairLabel(pool: CuratedPoolRegistryEntry): string {
  return `${pool.baseSymbol} / ${pool.quoteSymbol}`
}

export function searchCuratedPools(query: string, pools: CuratedPoolRegistryEntry[] = []): PoolSearchRow[] {
  const trimmed = query.trim()
  if (!trimmed || pools.length === 0) return []

  const lower = trimmed.toLowerCase()
  const isAddress = addressPattern.test(trimmed)
  const matches: PoolSearchRow[] = []

  for (const pool of pools) {
    const label = pairLabel(pool)
    if (isAddress) {
      if (
        pool.poolAddress.toLowerCase() === lower ||
        pool.lpTokenAddress.toLowerCase() === lower ||
        pool.baseAddress.toLowerCase() === lower ||
        pool.quoteAddress.toLowerCase() === lower
      ) {
        matches.push({
          ...pool,
          pairLabel: label,
          matchReason:
            pool.poolAddress.toLowerCase() === lower
              ? 'exact pool address'
              : pool.lpTokenAddress.toLowerCase() === lower
                ? 'exact lp token'
                : 'pair symbol',
        })
      }
      continue
    }

    const symMatch =
      pool.baseSymbol.toLowerCase() === lower ||
      pool.quoteSymbol.toLowerCase() === lower ||
      label.toLowerCase().replace(/\s+/g, '') === lower.replace(/\s+/g, '') ||
      label.toLowerCase().includes(lower)

    if (symMatch) {
      matches.push({
        ...pool,
        pairLabel: label,
        matchReason:
          pool.baseSymbol.toLowerCase() === lower || pool.quoteSymbol.toLowerCase() === lower
            ? 'pair symbol'
            : 'symbol prefix',
      })
    }
  }

  const weight: Record<PoolSearchRow['matchReason'], number> = {
    'exact pool address': 100,
    'exact lp token': 90,
    'pair symbol': 70,
    'symbol prefix': 50,
  }

  return matches.sort((left, right) => {
    const reasonCmp = weight[right.matchReason] - weight[left.matchReason]
    if (reasonCmp !== 0) return reasonCmp
    return (right.totalLiquidityUsd ?? 0) - (left.totalLiquidityUsd ?? 0)
  })
}

export function findPoolByAddress(
  address: string,
  pools: CuratedPoolRegistryEntry[],
): CuratedPoolRegistryEntry | undefined {
  const lower = address.trim().toLowerCase()
  if (!addressPattern.test(lower)) return undefined
  return pools.find(
    (pool) =>
      pool.poolAddress.toLowerCase() === lower ||
      pool.lpTokenAddress.toLowerCase() === lower,
  )
}
