import { describe, expect, test } from "bun:test"
import * as State from "@/saeeol/cost-tracker/state"
import { formatCost, formatTotalCost } from "@/saeeol/cost-tracker/format"

describe("CostTracker State", () => {
  test("starts at zero", () => {
    State.reset()
    expect(State.getTotalCost()).toBe(0)
    expect(State.getAPIDuration()).toBe(0)
    expect(State.getLines()).toEqual({ added: 0, removed: 0 })
  })

  test("accumulates cost per model", () => {
    State.reset()
    const usage = {
      input_tokens: 100,
      output_tokens: 50,
      cache_read_input_tokens: 10,
      cache_creation_input_tokens: 5,
    }
    State.addSessionCost(0.01, usage, "gpt-4")
    expect(State.getTotalCost()).toBe(0.01)

    const m = State.getModelUsage()["gpt-4"]
    expect(m.inputTokens).toBe(100)
    expect(m.outputTokens).toBe(50)
    expect(m.costUSD).toBe(0.01)
  })

  test("accumulates across multiple calls", () => {
    State.reset()
    State.addSessionCost(0.02, { input_tokens: 100, output_tokens: 50 }, "model-a")
    State.addSessionCost(0.03, { input_tokens: 200, output_tokens: 100 }, "model-b")
    expect(State.getTotalCost()).toBeCloseTo(0.05)
    expect(Object.keys(State.getModelUsage()).length).toBe(2)
  })

  test("tracks lines changed", () => {
    State.reset()
    State.addLines(10, 3)
    State.addLines(5, 1)
    expect(State.getLines()).toEqual({ added: 15, removed: 4 })
  })
})

describe("formatCost", () => {
  test("formats small costs with 4 decimals", () => {
    expect(formatCost(0.0123)).toBe("$0.0123")
  })

  test("formats large costs with 2 decimals", () => {
    expect(formatCost(1.234)).toBe("$1.23")
  })
})

describe("formatTotalCost", () => {
  test("formats complete report", () => {
    State.reset()
    State.addSessionCost(0.05, { input_tokens: 1000, output_tokens: 500 }, "test-model")
    const report = formatTotalCost()
    expect(report).toContain("$0.05")
    expect(report).toContain("test-model")
  })
})
