import { logger } from '../utils/logger';
import { buildHoLiquiditySnapshot } from './omnl-ho-liquidity-snapshot';

let intervalHandle: ReturnType<typeof setInterval> | null = null;

export function startOmnlHoLiquidityScheduler(): void {
  const enabled =
    String(process.env.OMNL_HO_LIQUIDITY_LIVE || '1').toLowerCase() === '1' ||
    String(process.env.OMNL_HO_LIQUIDITY_LIVE || '').toLowerCase() === 'true';
  if (!enabled) {
    return;
  }

  const intervalMs = Math.max(
    60_000,
    parseInt(process.env.OMNL_HO_LIQUIDITY_INTERVAL_MS || '1800000', 10) || 1_800_000,
  );

  const tick = async () => {
    try {
      const snap = await buildHoLiquiditySnapshot({ forceRefresh: true });
      logger.info('HO nostro liquidity cache refreshed', {
        cashInBankUsd: snap.cashInBank.cashInBankUsd,
        coverageRatio: snap.reserveCoverage.coverageRatio,
        alerts: snap.alerts.length,
      });
    } catch (error) {
      logger.warn('HO nostro liquidity refresh failed', {
        error: error instanceof Error ? error.message : String(error),
      });
    }
  };

  void tick();
  intervalHandle = setInterval(() => {
    void tick();
  }, intervalMs);

  logger.info('HO nostro liquidity live scheduler enabled', { intervalMs });
}

export function stopOmnlHoLiquidityScheduler(): void {
  if (intervalHandle) {
    clearInterval(intervalHandle);
    intervalHandle = null;
  }
}
