import { describe, it, expect } from 'bun:test'

describe('openaiCompatAdapter', () => {
  describe('SSE event parsing', () => {
    it('parses data lines as JSON', () => {
      const line = 'data: {"id":"chatcmpl-1","choices":[{"delta":{"content":"Hi"}}]}'
      const match = line.match(/^data: (.+)$/)
      expect(match).not.toBeNull()
      const parsed = JSON.parse(match![1])
      expect(parsed.choices[0].delta.content).toBe('Hi')
    })

    it('handles [DONE] sentinel', () => {
      const line = 'data: [DONE]'
      const match = line.match(/^data: (.+)$/)
      expect(match).not.toBeNull()
      expect(match![1]).toBe('[DONE]')
    })

    it('ignores non-data lines', () => {
      const line = 'event: ping'
      expect(line.match(/^data: /)).toBeNull()
    })
  })

  describe('stop reason mapping', () => {
    const stopReasonMap: Record<string, string> = {
      stop: 'end_turn',
      tool_calls: 'tool_use',
      length: 'max_tokens',
    }

    it('maps known finish reasons', () => {
      expect(stopReasonMap['stop']).toBe('end_turn')
      expect(stopReasonMap['tool_calls']).toBe('tool_use')
      expect(stopReasonMap['length']).toBe('max_tokens')
    })

    it('falls back to end_turn for unknown reasons', () => {
      expect(stopReasonMap['unknown'] ?? 'end_turn').toBe('end_turn')
    })
  })

  describe('cached token tracking', () => {
    it('subtracts cached tokens from input_tokens', () => {
      const promptTokens = 100
      const cachedTokens = 60
      const inputTokens = promptTokens - cachedTokens
      expect(inputTokens).toBe(40)
    })

    it('handles zero cached tokens', () => {
      const promptTokens = 100
      const cachedTokens = 0
      expect(promptTokens - cachedTokens).toBe(100)
    })
  })

  describe('tool call conversion', () => {
    it('parses function arguments as JSON', () => {
      const args = '{"path":"/test.txt","offset":10}'
      const parsed = JSON.parse(args)
      expect(parsed).toEqual({ path: '/test.txt', offset: 10 })
    })

    it('handles malformed arguments gracefully', () => {
      const args = 'not-json'
      expect(() => JSON.parse(args)).toThrow()
    })
  })
})
