import type { Context } from 'hono'
import { WarmCache } from '../cache/keep-warm.ts'
import {
  computeToolStats,
  type ToolsPeriod,
  type ToolsResult,
} from '../store/tools-queries.ts'

const VALID_PERIODS = new Set<ToolsPeriod>(['24h', '7d', '30d', 'lifetime'])

export const toolsCache = new WarmCache<ToolsPeriod, ToolsResult>('tools')
for (const period of VALID_PERIODS) {
  toolsCache.register(period, () => computeToolStats(period))
}

export async function handleTools(c: Context): Promise<Response> {
  const periodRaw = c.req.query('period') ?? '24h'
  if (!VALID_PERIODS.has(periodRaw as ToolsPeriod)) {
    return c.json({ error: `invalid period: ${periodRaw}` }, 400)
  }
  const period = periodRaw as ToolsPeriod
  if (c.req.query('nocache') === '1') toolsCache.invalidate(period)
  const result = await toolsCache.get(period)
  return c.json(result)
}
