import { describe, it, expect } from 'vitest'
import { computeCacheHitRate, formatCacheHitRate } from '../cost-tracker.js'

describe('computeCacheHitRate', () => {
  it('returns 0 when there is no activity', () => {
    expect(computeCacheHitRate({ input: 0, cacheRead: 0, cacheCreation: 0 })).toBe(0)
  })

  it('returns 0 when nothing is served from cache', () => {
    expect(computeCacheHitRate({ input: 1000, cacheRead: 0, cacheCreation: 0 })).toBe(0)
  })

  it('returns 1 when every prompt token is served from cache', () => {
    expect(computeCacheHitRate({ input: 0, cacheRead: 5000, cacheCreation: 0 })).toBe(1)
  })

  it('counts fresh input and cache writes in the denominator', () => {
    const rate = computeCacheHitRate({
      input: 100,
      cacheRead: 900,
      cacheCreation: 0,
    })
    expect(rate).toBeCloseTo(0.9)
  })

  it('treats cache creation as a miss (denominator only)', () => {
    const rate = computeCacheHitRate({
      input: 0,
      cacheRead: 800,
      cacheCreation: 200,
    })
    expect(rate).toBeCloseTo(0.8)
  })

  it('bounds output to [0, 1]', () => {
    expect(computeCacheHitRate({ input: -1, cacheRead: -1, cacheCreation: -1 })).toBe(0)
  })
})

describe('formatCacheHitRate', () => {
  it('formats as percentage with token volume', () => {
    const s = formatCacheHitRate({
      input: 100,
      cacheRead: 900,
      cacheCreation: 0,
    })
    expect(s).toContain('90%')
    expect(s).toMatch(/cache hit/i)
  })

  it('returns a neutral string when there has been no activity', () => {
    const s = formatCacheHitRate({ input: 0, cacheRead: 0, cacheCreation: 0 })
    expect(s).toMatch(/no (api|prompt) (activity|tokens)/i)
  })
})
