import type { CostSpikeLimits } from '../../core/config.ts'
import type { AgentPacket, RiskTag } from '../../core/packet.ts'

type Threshold = { tag: string; usd: number; severity: 'info' | 'warn' | 'high' }

function thresholdsFrom(limits: CostSpikeLimits): Threshold[] {
  // Ascending by USD so the highest matching bound wins (scanned in reverse).
  const ts: Threshold[] = [
    { tag: `cost:over-${limits.info}`, usd: limits.info, severity: 'info' },
    { tag: `cost:over-${limits.warn}`, usd: limits.warn, severity: 'warn' },
    { tag: `cost:over-${limits.high}`, usd: limits.high, severity: 'high' },
  ]
  return ts.sort((a, b) => a.usd - b.usd)
}

// Module state, configured from ~/.thomas/config.json at daemon startup via
// configureCostSpike(). Defaults match the historical hard-coded bounds so
// the tagger works before (or without) any config.
let THRESHOLDS: Threshold[] = thresholdsFrom({ info: 1, warn: 5, high: 20 })

export function configureCostSpike(limits: CostSpikeLimits): void {
  THRESHOLDS = thresholdsFrom(limits)
}

export function costSpikeTagger(packet: AgentPacket): RiskTag[] {
  const usd = packet.cost?.usd ?? 0
  if (usd <= 0) return []

  // Emit only the highest matching threshold.
  for (let i = THRESHOLDS.length - 1; i >= 0; i--) {
    const t = THRESHOLDS[i]
    if (t && usd >= t.usd) {
      return [{ tag: t.tag, severity: t.severity, detail: { usd } }]
    }
  }
  return []
}
