import { logger } from '../utils/logger';
import { refreshReserveCapacityCache } from './gru-reserve-capacity';

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

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

  const intervalMs = Math.max(
    15_000,
    parseInt(process.env.GRU_RESERVE_CAPACITY_INTERVAL_MS || '30000', 10) || 30_000,
  );
  const minimumSet = process.env.GRU_RESERVE_CAPACITY_MINIMUM_SET?.trim() || 'reserveCapacityLive';

  const tick = async () => {
    try {
      const snap = await refreshReserveCapacityCache(minimumSet);
      logger.info('GRU reserve capacity refreshed', {
        quorumPassed: snap.proofQuorum.passed,
        passCount: snap.proofQuorum.passCount,
        issuanceBlocked: snap.capacity.issuanceBlocked,
      });
    } catch (error) {
      logger.warn('GRU reserve capacity refresh failed', {
        error: error instanceof Error ? error.message : String(error),
      });
    }
  };

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

  logger.info('GRU reserve capacity live scheduler enabled', { intervalMs, minimumSet });
}

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