import { readConfig } from '../../core/config.ts'
import { logger } from '../../core/logger.ts'
import { refreshPricingCatalog } from './fetch-catalog.ts'

const ONE_DAY_MS = 24 * 3_600_000

let timer: ReturnType<typeof setInterval> | null = null

/**
 * Opt-in daily pricing-catalog refresh. Disabled unless
 * config.autoRefreshPricing is true. When on, fetches models.dev's public
 * price list and writes the local overlay the cost resolver reads first —
 * so prices stay current without a Thomas upgrade. No user data leaves the
 * machine (see PRIVACY.md).
 */
export function startPricingRefreshLoop(): void {
  if (timer) return

  const tick = async (): Promise<void> => {
    try {
      const config = await readConfig()
      if (!config.autoRefreshPricing) return
      const { providers, models } = await refreshPricingCatalog()
      logger.info(`pricing: refreshed catalog — ${providers} providers / ${models} models`)
    } catch (err) {
      logger.debug(`pricing: scheduled refresh failed — ${(err as Error).message}`)
    }
  }

  // First refresh a few minutes after boot (jittered so installs don't all
  // hit models.dev at once), then daily.
  const firstDelay = 150_000 + Math.floor(Math.random() * 120_000)
  setTimeout(() => void tick(), firstDelay).unref()
  timer = setInterval(() => void tick(), ONE_DAY_MS)
  timer.unref()
  logger.info('pricing: daily catalog refresh enabled (opt-in)')
}

export function stopPricingRefreshLoop(): void {
  if (timer) {
    clearInterval(timer)
    timer = null
  }
}
