import type { CuratedPoolRegistryEntry, CuratedPoolRegistryReport } from './pool-registry-report';
import { getLiveDodoPools } from './live-dodo-fallback';

interface LivePoolSnapshot {
  totalLiquidityUsd: number;
  reserve0: string;
  reserve1: string;
  reserve0Usd: number;
  reserve1Usd: number;
  liquidityAsOf: string;
  liquiditySource: 'on-chain-dodo-probe';
}

export async function enrichCuratedPoolRegistryWithLiveLiquidity(
  report: CuratedPoolRegistryReport,
): Promise<CuratedPoolRegistryReport> {
  const chainIds = [...new Set(report.pools.map((pool) => pool.chainId))];
  const liveByAddress = new Map<string, LivePoolSnapshot>();

  await Promise.all(
    chainIds.map(async (chainId) => {
      if (chainId !== 138) return;
      const livePools = await getLiveDodoPools(chainId);
      for (const pool of livePools) {
        const address = pool.poolAddress.toLowerCase();
        const tvl = Number(pool.totalLiquidityUsd ?? 0);
        if (tvl <= 0) continue;
        liveByAddress.set(address, {
          totalLiquidityUsd: tvl,
          reserve0: pool.reserve0,
          reserve1: pool.reserve1,
          reserve0Usd: Number(pool.reserve0Usd ?? 0),
          reserve1Usd: Number(pool.reserve1Usd ?? 0),
          liquidityAsOf: pool.lastUpdated instanceof Date ? pool.lastUpdated.toISOString() : new Date().toISOString(),
          liquiditySource: 'on-chain-dodo-probe',
        });
      }
    }),
  );

  if (liveByAddress.size === 0) {
    return report;
  }

  const pools: CuratedPoolRegistryEntry[] = report.pools.map((pool) => {
    const live = liveByAddress.get(pool.poolAddress.toLowerCase());
    if (!live) {
      return pool;
    }
    return {
      ...pool,
      totalLiquidityUsd:
        pool.totalLiquidityUsd != null && pool.totalLiquidityUsd >= live.totalLiquidityUsd
          ? pool.totalLiquidityUsd
          : live.totalLiquidityUsd,
      reserve0: live.reserve0,
      reserve1: live.reserve1,
      reserve0Usd: live.reserve0Usd,
      reserve1Usd: live.reserve1Usd,
      liquiditySource: live.liquiditySource,
      liquidityAsOf: live.liquidityAsOf,
    };
  });

  return { ...report, pools };
}
