Skip to content

:hedgehog: PostHog is the leading platform for building self-driving products. Our developer tools – AI observability, analytics, session replay, flags, experiments, error tracking, logs, and more – capture all the context agents need to diagnose problems, uncover opportunities, and ship fixes. Steer it all from Slack, web, desktop, or the MCP.

127 KB
Raw Blame
import { logger } from '~/common/utils/logger'
import { PluginEvent } from '~/plugin-scaffold'

import { CostModelSource } from './costs/cost-model-matching'
import type { ModelCost, ModelCostRow } from './costs/providers/types'
import { aiCostTotalOutcomeCounter } from './metrics'
import { normalizeTraceProperties, processAiEvent } from './process-ai-event'

jest.mock('~/common/utils/logger', () => ({
    logger: {
        warn: jest.fn(),
    },
}))

const mockWarn = logger.warn as jest.Mock

type MockModelRow = { model: string; cost: ModelCost }

const costsByModel: Record<string, MockModelRow> = {
    testing_model: { model: 'testing_model', cost: { prompt_token: 0.1, completion_token: 0.1 } },
    'openai/gpt-4': { model: 'openai/gpt-4', cost: { prompt_token: 0.2, completion_token: 0.2 } },
    'openai/gpt-4-0125-preview': {
        model: 'openai/gpt-4-0125-preview',
        cost: { prompt_token: 0.3, completion_token: 0.3 },
    },
    'mistralai/mistral-7b-instruct-v0.1': {
        model: 'mistralai/mistral-7b-instruct-v0.1',
        cost: { prompt_token: 0.4, completion_token: 0.4 },
    },
    'openai/gpt-4o-mini': { model: 'openai/gpt-4o-mini', cost: { prompt_token: 0.5, completion_token: 0.5 } },
    'openai/openai-primary': { model: 'openai/openai-primary', cost: { prompt_token: 0.7, completion_token: 0.7 } },
    'anthropic/anthropic-primary': {
        model: 'anthropic/anthropic-primary',
        cost: { prompt_token: 0.8, completion_token: 0.8 },
    },
    'claude-2': { model: 'claude-2', cost: { prompt_token: 0.6, completion_token: 0.6 } },
    'anthropic/claude-sonnet-4': {
        model: 'anthropic/claude-sonnet-4',
        cost: {
            prompt_token: 0.000003,
            completion_token: 0.000015,
            cache_read_token: 3e-7,
            cache_write_token: 0.00000375,
        },
    },
    'google/gemini-2.5-pro-preview': {
        model: 'google/gemini-2.5-pro-preview',
        cost: {
            prompt_token: 0.00000125,
            completion_token: 0.00001,
            cache_read_token: 3.1e-7,
            cache_write_token: 3.75e-7,
        },
    },
    'gemini-2.5-pro-preview:large': {
        model: 'gemini-2.5-pro-preview:large',
        cost: { prompt_token: 0.0000025, completion_token: 0.000015, cache_read_token: 0.000000625 },
    },
    'google/gemini-2.5-flash': {
        model: 'google/gemini-2.5-flash',
        cost: { prompt_token: 3e-7, completion_token: 0.0000025, cache_read_token: 7.5e-8 },
    },
    'google/gemini-2.0-flash-001': {
        model: 'google/gemini-2.0-flash-001',
        cost: { prompt_token: 1e-7, completion_token: 4e-7, cache_read_token: 2.5e-8 },
    },
    'openai/o1-mini': {
        model: 'openai/o1-mini',
        cost: { prompt_token: 0.0000011, completion_token: 0.0000044 },
    },
    'openai/gpt-4.1': { model: 'openai/gpt-4.1', cost: { prompt_token: 0.9, completion_token: 0.9 } },
    'backup-model': { model: 'backup-model', cost: { prompt_token: 0.5, completion_token: 0.5 } },
    'fallback-model': { model: 'fallback-model', cost: { prompt_token: 0.6, completion_token: 0.6 } },
    'perplexity/sonar-pro': {
        model: 'perplexity/sonar-pro',
        cost: { prompt_token: 0.000001, completion_token: 0.000001, request: 0.005, web_search: 0.005 },
    },
    'model-with-request-only': {
        model: 'model-with-request-only',
        cost: { prompt_token: 0.0000015, completion_token: 0.000006, request: 0.002 },
    },
    'openai/gpt-4o-audio-preview': {
        model: 'openai/gpt-4o-audio-preview',
        cost: {
            prompt_token: 0.0000025,
            completion_token: 0.00001,
            audio: 0.00004,
            audio_output: 0.00008,
        },
    },
    'openai/gpt-audio-mini': {
        model: 'openai/gpt-audio-mini',
        cost: {
            prompt_token: 0.00000015,
            completion_token: 0.0000006,
            cache_read_token: 0.000000075,
            audio: 0.000001,
            input_audio_cache: 0.0000001,
        },
    },
    'google/gemini-2.5-flash-image': {
        model: 'google/gemini-2.5-flash-image',
        cost: {
            prompt_token: 3e-7,
            completion_token: 0.0000025,
            image: 3e-7,
            image_output: 0.00003,
        },
    },
    'google/gemini-3.1-flash-lite': {
        model: 'google/gemini-3.1-flash-lite',
        cost: {
            prompt_token: 2.5e-7,
            completion_token: 0.0000015,
            image: 2.5e-7,
            cache_read_token: 2.5e-8,
        },
    },
    'google/gemini-3-flash-preview': {
        model: 'google/gemini-3-flash-preview',
        cost: {
            prompt_token: 5e-7,
            completion_token: 3e-6,
            audio: 0.0000015,
            input_audio_cache: 1.5e-7,
        },
    },
}

jest.mock('./costs/providers', () => {
    const excludedFromOpenRouter = new Set(['claude-2', 'backup-model', 'fallback-model'])

    const providerOverrides: Record<string, string> = {
        'openai/gpt-4': 'openai',
        'openai/gpt-4-0125-preview': 'openai',
        'openai/gpt-4o-mini': 'openai',
        'openai/gpt-4.1': 'openai',
        'openai/openai-primary': 'openai',
        'anthropic/anthropic-primary': 'anthropic',
        'anthropic/claude-sonnet-4': 'anthropic',
        'google/gemini-2.5-pro-preview': 'google-ai-studio',
        'gemini-2.5-pro-preview:large': 'google-ai-studio',
        'google/gemini-2.5-flash': 'google-ai-studio',
        'google/gemini-2.0-flash-001': 'google-ai-studio',
        'openai/o1-mini': 'openai',
        'mistralai/mistral-7b-instruct-v0.1': 'mistralai',
        'perplexity/sonar-pro': 'perplexity',
        'model-with-request-only': 'custom',
        'openai/gpt-4o-audio-preview': 'openai',
        'openai/gpt-audio-mini': 'openai',
        'google/gemini-2.5-flash-image': 'google-ai-studio',
        'google/gemini-3.1-flash-lite': 'google-ai-studio',
        'google/gemini-3-flash-preview': 'google-ai-studio',
    }

    let cachedMocks:
        | {
              openRouterCostsByModel: Record<string, ModelCostRow>
              manualCostsByModel: Record<string, ModelCostRow>
          }
        | undefined

    const buildMocks = () => {
        if (cachedMocks) {
            return cachedMocks
        }

        const openRouterCostsByModel: Record<string, ModelCostRow> = {}

        for (const [model, row] of Object.entries(costsByModel)) {
            if (excludedFromOpenRouter.has(model)) {
                continue
            }

            const normalizedKey = model.toLowerCase()
            const providerKey = providerOverrides[model]

            const costRecord = providerKey ? { default: row.cost, [providerKey]: row.cost } : { default: row.cost }

            openRouterCostsByModel[normalizedKey] = {
                model: row.model,
                cost: costRecord,
            }
        }

        const manualCostsByModel: Record<string, ModelCostRow> = {}

        for (const model of excludedFromOpenRouter) {
            const row = costsByModel[model]
            manualCostsByModel[model] = {
                model: row.model,
                cost: { default: row.cost },
            }
        }

        cachedMocks = {
            openRouterCostsByModel,
            manualCostsByModel,
        }

        return cachedMocks
    }

    return {
        get openRouterCostsByModel() {
            return buildMocks().openRouterCostsByModel
        },
        get manualCostsByModel() {
            return buildMocks().manualCostsByModel
        },
    }
})

describe('processAiEvent()', () => {
    let event: PluginEvent

    beforeEach(() => {
        jest.clearAllMocks()
        event = {
            distinct_id: 'test_id',
            team_id: 1,
            uuid: 'test-uuid',
            timestamp: '2024-01-01T00:00:00.000Z',
            event: '$ai_generation',
            properties: {
                $ai_model: 'gpt-4',
                $ai_provider: 'openai',
                $ai_input_tokens: 100,
                $ai_output_tokens: 50,
            },
            ip: '127.0.0.1',
            site_url: 'https://test.com',
            now: '2024-01-01T00:00:00.000Z',
        } as PluginEvent
    })

    describe('event matching', () => {
        it.each(['$ai_generation', '$ai_embedding', '$ai_evaluation'])(
            'processes cost calculation for %s events',
            (eventType) => {
                event.event = eventType
                const result = processAiEvent(event)
                // With gpt-4 model and openai provider from primaryCostsList: 0.2 per token
                expect(result.properties!.$ai_input_cost_usd).toBe(20) // 100 * 0.2
                expect(result.properties!.$ai_output_cost_usd).toBe(10) // 50 * 0.2
                expect(result.properties!.$ai_total_cost_usd).toBe(30)
            }
        )

        it('does not process cost for other AI events', () => {
            event.event = '$ai_span'
            const result = processAiEvent(event)
            expect(result.properties!.$ai_total_cost_usd).toBeUndefined()
        })

        it('does not match non-AI events', () => {
            event.event = '$other_event'
            const result = processAiEvent(event)
            expect(result).toEqual(event)
        })
    })

    describe('OTel ingestion', () => {
        it('extracts Pydantic AI tool calls from output message parts', () => {
            event.properties = {
                $ai_ingestion_source: 'otel',
                'logfire.json_schema': '{}',
                'gen_ai.response.model': 'testing_model',
                'gen_ai.provider.name': 'openai',
                'gen_ai.usage.input_tokens': 100,
                'gen_ai.usage.output_tokens': 50,
                'gen_ai.output.messages': JSON.stringify([
                    {
                        role: 'assistant',
                        parts: [
                            { type: 'text', content: 'Let me check.' },
                            {
                                type: 'tool_call',
                                id: 'call_weather',
                                name: 'get_weather',
                                arguments: '{"city":"NYC"}',
                            },
                            {
                                type: 'tool_call',
                                id: 'call_docs',
                                name: 'search_docs',
                                arguments: '{"query":"weather"}',
                            },
                        ],
                    },
                ]),
            }

            const result = processAiEvent(event)

            expect(result.properties!.$ai_output_choices).toEqual([
                {
                    role: 'assistant',
                    parts: [
                        { type: 'text', content: 'Let me check.' },
                        {
                            type: 'tool_call',
                            id: 'call_weather',
                            name: 'get_weather',
                            arguments: '{"city":"NYC"}',
                        },
                        {
                            type: 'tool_call',
                            id: 'call_docs',
                            name: 'search_docs',
                            arguments: '{"query":"weather"}',
                        },
                    ],
                },
            ])
            expect(result.properties!.$ai_tools_called).toBe('get_weather,search_docs')
            expect(result.properties!.$ai_tool_call_count).toBe(2)
        })

        // The middleware writes $ai_cost_passthrough and processCost reads it. Both
        // halves have their own tests, so only a test through the whole pipeline
        // catches the two sides drifting apart.
        it('keeps the Vercel AI Gateway reported cost end to end', () => {
            event.properties = {
                $ai_ingestion_source: 'otel',
                'ai.operationId': 'ai.generateText.doGenerate',
                'gen_ai.provider.name': 'gateway',
                'gen_ai.response.model': 'openai/gpt-4o-mini',
                'gen_ai.usage.input_tokens': 100,
                'gen_ai.usage.output_tokens': 50,
                'ai.response.providerMetadata': JSON.stringify({ gateway: { cost: '0.001234' } }),
            }

            const result = processAiEvent(event)

            expect(result.properties!.$ai_total_cost_usd).toBe(0.001234)
            expect(result.properties!.$ai_cost_model_source).toBe(CostModelSource.Passthrough)
            expect(result.properties!.$ai_input_cost_usd).toBeUndefined()
            expect(result.properties!.$ai_output_cost_usd).toBeUndefined()
        })

        it('uses total output tokens for non-Gemini AI SDK v7 reasoning models', () => {
            event.properties = {
                $ai_ingestion_source: 'otel',
                'ai.operationId': 'ai.streamText.doStream',
                'gen_ai.provider.name': 'openai',
                'gen_ai.response.model': 'o1-mini',
                'gen_ai.usage.input_tokens': 0,
                'gen_ai.usage.output_tokens': 250,
                'ai.usage.outputTokenDetails.textTokens': 50,
                'ai.usage.outputTokenDetails.reasoningTokens': 200,
            }

            const result = processAiEvent(event)

            expect(result.properties!.$ai_reasoning_tokens).toBe(200)
            expect(result.properties!.$ai_text_output_tokens).toBeUndefined()
            expect(result.properties!.$ai_output_cost_usd).toBeCloseTo(0.0011, 6)
            expect(result.properties!.$ai_total_cost_usd).toBeCloseTo(0.0011, 6)
        })

        it('splits Gemini AI SDK v7 text and reasoning tokens before cost calculation', () => {
            event.properties = {
                $ai_ingestion_source: 'otel',
                'ai.operationId': 'ai.streamText.doStream',
                'gen_ai.provider.name': 'google',
                'gen_ai.response.model': 'gemini-2.5-flash',
                'gen_ai.usage.input_tokens': 0,
                'gen_ai.usage.output_tokens': 250,
                'ai.usage.outputTokenDetails.textTokens': 50,
                'ai.usage.outputTokenDetails.reasoningTokens': 200,
            }

            const result = processAiEvent(event)

            expect(result.properties!.$ai_text_output_tokens).toBe(50)
            expect(result.properties!.$ai_reasoning_tokens).toBe(200)
            expect(result.properties!.$ai_output_cost_usd).toBeCloseTo(0.000625, 6)
            expect(result.properties!.$ai_total_cost_usd).toBeCloseTo(0.000625, 6)
        })
    })

    describe('model matching', () => {
        it('matches exact model names', () => {
            const result = processAiEvent(event)
            expect(result.properties!.$ai_total_cost_usd).toBeDefined()
            expect(result.properties!.$ai_input_cost_usd).toBeDefined()
            expect(result.properties!.$ai_output_cost_usd).toBeDefined()
        })

        it('matches model variants', () => {
            event.properties!.$ai_model = 'gpt-4-turbo-0125-preview'
            const result = processAiEvent(event)
            expect(result.properties!.$ai_total_cost_usd).toBeDefined()
            expect(result.properties!.$ai_input_cost_usd).toBeDefined()
            expect(result.properties!.$ai_output_cost_usd).toBeDefined()
        })

        it('handles unknown models', () => {
            event.properties!.$ai_model = 'unknown-model'
            const result = processAiEvent(event)
            expect(result.properties!.$ai_total_cost_usd).toBeUndefined()
            expect(result.properties!.$ai_input_cost_usd).toBeUndefined()
            expect(result.properties!.$ai_output_cost_usd).toBeUndefined()
        })
    })

    describe('modality cost calculation', () => {
        it('rolls audio token costs into input/output for audio-capable models', () => {
            event.properties!.$ai_model = 'gpt-4o-audio-preview'
            event.properties!.$ai_input_tokens = 1000 // 800 text + 200 audio
            event.properties!.$ai_output_tokens = 1000 // 200 text + 800 audio
            event.properties!.$ai_audio_input_tokens = 200
            event.properties!.$ai_audio_output_tokens = 800

            const result = processAiEvent(event)

            // Input: text (800 × 0.0000025) + audio (200 × 0.00004) = 0.002 + 0.008 = 0.01
            // Output: text (200 × 0.00001) + audio (800 × 0.00008) = 0.002 + 0.064 = 0.066
            // Total: input + output = 0.076 (request and web search are 0)
            expect(result.properties!.$ai_input_cost_usd).toBeCloseTo(0.01, 5)
            expect(result.properties!.$ai_output_cost_usd).toBeCloseTo(0.066, 5)
            expect(result.properties!.$ai_total_cost_usd).toBeCloseTo(0.076, 5)
            // We do not expose a separate modality breakdown property
            expect(result.properties!.$ai_audio_cost_usd).toBeUndefined()
        })

        it('rolls image token costs into input/output for image-capable models', () => {
            event.properties!.$ai_model = 'gemini-2.5-flash-image'
            event.properties!.$ai_provider = 'google'
            event.properties!.$ai_input_tokens = 600 // 200 text + 400 image
            event.properties!.$ai_output_tokens = 1300 // 10 text + 1290 image
            event.properties!.$ai_image_input_tokens = 400
            event.properties!.$ai_image_output_tokens = 1290

            const result = processAiEvent(event)

            // Input: text (200 × 3e-7) + image (400 × 3e-7) = 6e-5 + 0.00012 = 0.00018
            // Output: text (10 × 0.0000025) + image (1290 × 0.00003) = 0.000025 + 0.0387 = 0.038725
            expect(result.properties!.$ai_input_cost_usd).toBeCloseTo(0.00018, 6)
            expect(result.properties!.$ai_output_cost_usd).toBeCloseTo(0.038725, 6)
            expect(result.properties!.$ai_image_cost_usd).toBeUndefined()
        })

        it('bills cached audio at the audio-cache rate end-to-end', () => {
            event.properties!.$ai_model = 'gpt-audio-mini'
            event.properties!.$ai_input_tokens = 1000 // 500 text uncached + 250 text cached + 50 audio cached + 150 audio uncached
            event.properties!.$ai_output_tokens = 100
            event.properties!.$ai_cache_read_input_tokens = 300 // 250 text + 50 audio
            event.properties!.$ai_audio_input_tokens = 200 // 150 uncached + 50 cached
            event.properties!.$ai_cache_read_audio_tokens = 50

            const result = processAiEvent(event)

            // Cached text: 250 × 0.000000075 = 0.00001875
            // Uncached text: 550 × 0.00000015 = 0.0000825
            // Uncached audio: 150 × 0.000001 = 0.00015
            // Cached audio: 50 × 0.0000001 = 0.000005
            // Input total: 0.00025625
            // Output: 100 × 0.0000006 = 0.00006
            // Grand total: 0.00031625
            expect(result.properties!.$ai_input_cost_usd).toBeCloseTo(0.00025625, 8)
            expect(result.properties!.$ai_output_cost_usd).toBeCloseTo(0.00006, 8)
            expect(result.properties!.$ai_total_cost_usd).toBeCloseTo(0.00031625, 8)
        })

        it('extracts Gemini audio input tokens from snake_case $ai_usage and bills at audio rate', () => {
            // Simulates a Gemini transcription event coming from posthog-python:
            // the SDK forwards usage_metadata via to_dict() / vars() which
            // produces snake_case keys (prompt_tokens_details with token_count
            // entries) rather than the camelCase form Vercel uses. Ingestion
            // must extract from this shape and bill the audio portion at the
            // audio rate even though $ai_audio_input_tokens is not pre-set.
            event.properties!.$ai_model = 'gemini-3-flash-preview'
            event.properties!.$ai_provider = 'gemini'
            event.properties!.$ai_input_tokens = 1000 // 750 audio + 250 text
            event.properties!.$ai_output_tokens = 100
            event.properties!.$ai_usage = {
                prompt_token_count: 1000,
                candidates_token_count: 100,
                prompt_tokens_details: [
                    { modality: 'AUDIO', token_count: 750 },
                    { modality: 'TEXT', token_count: 250 },
                ],
            }

            const result = processAiEvent(event)

            // After extraction, the audio token property should be populated.
            expect(result.properties!.$ai_audio_input_tokens).toBe(750)
            expect(result.properties!.$ai_text_input_tokens).toBe(250)
            // $ai_usage is always stripped after extraction.
            expect(result.properties!.$ai_usage).toBeUndefined()

            // Input billing: text (250 × 5e-7) + audio (750 × 0.0000015)
            //              = 0.000125 + 0.001125 = 0.00125
            // Output: 100 × 3e-6 = 0.0003
            // Total: 0.00155
            expect(result.properties!.$ai_input_cost_usd).toBeCloseTo(0.00125, 7)
            expect(result.properties!.$ai_output_cost_usd).toBeCloseTo(0.0003, 7)
            expect(result.properties!.$ai_total_cost_usd).toBeCloseTo(0.00155, 7)
        })

        it('bills Gemini Interactions cached audio at the audio cache rate', () => {
            event.properties!.$ai_model = 'gemini-3-flash-preview'
            event.properties!.$ai_provider = 'gemini'
            event.properties!.$ai_input_tokens = 1000
            event.properties!.$ai_output_tokens = 100
            event.properties!.$ai_cache_read_input_tokens = 50
            event.properties!.$ai_usage = {
                input_tokens_by_modality: [
                    { modality: 'audio', tokens: 750 },
                    { modality: 'text', tokens: 250 },
                ],
                output_tokens_by_modality: [{ modality: 'text', tokens: 100 }],
                cached_tokens_by_modality: [{ modality: 'audio', tokens: 50 }],
            }

            const result = processAiEvent(event)

            expect(result.properties).toMatchObject({
                $ai_audio_input_tokens: 750,
                $ai_text_input_tokens: 250,
                $ai_text_output_tokens: 100,
                $ai_cache_read_audio_tokens: 50,
            })
            expect(result.properties!.$ai_usage).toBeUndefined()
            expect(result.properties!.$ai_input_cost_usd).toBeCloseTo(0.0011825, 8)
            expect(result.properties!.$ai_output_cost_usd).toBeCloseTo(0.0003, 8)
            expect(result.properties!.$ai_total_cost_usd).toBeCloseTo(0.0014825, 8)
        })

        it('bills Gemini Interactions image output at the image rate', () => {
            event.properties!.$ai_model = 'gemini-2.5-flash-image'
            event.properties!.$ai_provider = 'google'
            event.properties!.$ai_input_tokens = 600
            event.properties!.$ai_output_tokens = 1300
            event.properties!.$ai_usage = {
                input_tokens_by_modality: [
                    { modality: 'text', tokens: 200 },
                    { modality: 'image', tokens: 400 },
                ],
                output_tokens_by_modality: [
                    { modality: 'text', tokens: 10 },
                    { modality: 'image', tokens: 1290 },
                ],
            }

            const result = processAiEvent(event)

            expect(result.properties).toMatchObject({
                $ai_text_input_tokens: 200,
                $ai_image_input_tokens: 400,
                $ai_text_output_tokens: 10,
                $ai_image_output_tokens: 1290,
            })
            expect(result.properties!.$ai_usage).toBeUndefined()
            expect(result.properties!.$ai_input_cost_usd).toBeCloseTo(0.00018, 7)
            expect(result.properties!.$ai_output_cost_usd).toBeCloseTo(0.038725, 7)
            expect(result.properties!.$ai_total_cost_usd).toBeCloseTo(0.038905, 7)
        })

        it('bills Gemini Interactions cached image input once at the cache-read rate', () => {
            event.properties!.$ai_model = 'gemini-3.1-flash-lite'
            event.properties!.$ai_provider = 'google'
            event.properties!.$ai_input_tokens = 100
            event.properties!.$ai_output_tokens = 0
            event.properties!.$ai_cache_read_input_tokens = 100
            event.properties!.$ai_usage = {
                input_tokens_by_modality: [{ modality: 'image', tokens: 100 }],
                cached_tokens_by_modality: [{ modality: 'image', tokens: 100 }],
            }

            const result = processAiEvent(event)

            expect(result.properties).toMatchObject({
                $ai_image_input_tokens: 100,
                $ai_cache_read_image_tokens: 100,
            })
            expect(result.properties!.$ai_usage).toBeUndefined()
            expect(result.properties!.$ai_input_cost_usd).toBeCloseTo(0.0000025, 12)
            expect(result.properties!.$ai_total_cost_usd).toBeCloseTo(0.0000025, 12)
        })

        it('ignores invalid object-form Gemini text tokens before costing image output', () => {
            event.properties!.$ai_model = 'gemini-2.5-flash-image'
            event.properties!.$ai_provider = 'google'
            event.properties!.$ai_input_tokens = 600
            event.properties!.$ai_output_tokens = 1300
            event.properties!.$ai_usage = {
                candidatesTokensDetails: { textTokens: -5, imageTokens: 1290 },
            }

            const result = processAiEvent(event)

            expect(result.properties!.$ai_text_output_tokens).toBeUndefined()
            expect(result.properties!.$ai_image_output_tokens).toBe(1290)
            expect(result.properties!.$ai_output_cost_usd).toBeCloseTo(0.038725, 6)
        })

        it('does not bill a negative Interactions text token count', () => {
            event.properties!.$ai_model = 'gemini-3-flash-preview'
            event.properties!.$ai_provider = 'gemini'
            event.properties!.$ai_input_tokens = 0
            event.properties!.$ai_output_tokens = 10
            event.properties!.$ai_usage = {
                output_tokens_by_modality: [{ modality: 'text', tokens: -5 }],
            }

            const result = processAiEvent(event)

            expect(result.properties!.$ai_text_output_tokens).toBeUndefined()
            expect(result.properties!.$ai_output_cost_usd).toBeCloseTo(0.00003, 8)
            expect(result.properties!.$ai_total_cost_usd).toBeCloseTo(0.00003, 8)
            expect(result.properties!.$ai_usage).toBeUndefined()
        })
    })

    describe('cost calculation', () => {
        it('calculates correct cost for prompt and completion tokens', () => {
            const result = processAiEvent(event)
            expect(result.properties!.$ai_total_cost_usd).toBeGreaterThan(0)
        })

        // Absent and zero token counts describe different calls, so they must not
        // price the same. Zero is a usage report of nothing; absent is no report.
        it.each([
            { counts: 'absent', tokens: {}, expected: undefined },
            { counts: 'zero', tokens: { $ai_input_tokens: 0, $ai_output_tokens: 0 }, expected: 0 },
        ])('records $expected cost when token counts are $counts', ({ tokens, expected }) => {
            delete event.properties!.$ai_input_tokens
            delete event.properties!.$ai_output_tokens
            Object.assign(event.properties!, tokens)

            const result = processAiEvent(event)

            expect(result.properties!.$ai_total_cost_usd).toBe(expected)
            expect(result.properties!.$ai_input_cost_usd).toBe(expected)
            expect(result.properties!.$ai_output_cost_usd).toBe(expected)
        })

        // The properties are named here rather than read from the token count
        // lists, so narrowing either list to the plain input/output counts fails
        // these. Iterating the lists themselves would only drop the case. Neither
        // catches the opposite drift: a calculator that starts reading a token
        // property nobody added to its list.
        it.each(['$ai_cache_read_input_tokens', '$ai_audio_input_tokens', '$ai_reasoning_tokens'])(
            'treats %s on its own as a usage report',
            (property) => {
                delete event.properties!.$ai_input_tokens
                delete event.properties!.$ai_output_tokens
                event.properties![property] = 100

                const result = processAiEvent(event)

                expect(result.properties!.$ai_total_cost_usd).toBeDefined()
            }
        )

        it.each(['image', 'audio'] as const)(
            'keeps orphan cached %s usage unknown without inventing parent counts',
            async (modality) => {
                aiCostTotalOutcomeCounter.reset()
                delete event.properties!.$ai_input_tokens
                delete event.properties!.$ai_output_tokens
                event.properties![`$ai_cache_read_${modality}_tokens`] = '100'

                const result = processAiEvent(event)

                expect(result.properties!.$ai_input_cost_usd).toBeUndefined()
                expect(result.properties!.$ai_total_cost_usd).toBeUndefined()
                expect(result.properties!.$ai_output_cost_usd).toBeUndefined()
                expect(result.properties![`$ai_${modality}_input_tokens`]).toBeUndefined()
                expect(result.properties!.$ai_cache_read_input_tokens).toBeUndefined()
                expect((await aiCostTotalOutcomeCounter.get()).values).toEqual([
                    { labels: { outcome: 'unknown' }, value: 1 },
                ])
            }
        )

        it.each(['image', 'audio'] as const)('preserves explicit zero cached %s usage', async (modality) => {
            aiCostTotalOutcomeCounter.reset()
            delete event.properties!.$ai_input_tokens
            delete event.properties!.$ai_output_tokens
            event.properties![`$ai_cache_read_${modality}_tokens`] = '0'

            const result = processAiEvent(event)

            expect(result.properties!.$ai_input_cost_usd).toBe(0)
            expect(result.properties!.$ai_total_cost_usd).toBe(0)
            expect(result.properties!.$ai_output_cost_usd).toBeUndefined()
            expect((await aiCostTotalOutcomeCounter.get()).values).toEqual([{ labels: { outcome: 'zero' }, value: 1 }])
        })

        it.each(['image', 'audio'] as const)(
            'ignores unusable parent counts when cached %s usage is the only valid report',
            (modality) => {
                event.properties!.$ai_input_tokens = 'invalid'
                event.properties![`$ai_${modality}_input_tokens`] = NaN
                event.properties!.$ai_cache_read_input_tokens = Infinity
                event.properties![`$ai_cache_read_${modality}_tokens`] = 100
                delete event.properties!.$ai_output_tokens

                const result = processAiEvent(event)

                expect(result.properties!.$ai_input_cost_usd).toBeUndefined()
                expect(result.properties!.$ai_total_cost_usd).toBeUndefined()
            }
        )

        it.each([
            { properties: { $ai_input_tokens: 100 }, costProperty: '$ai_input_cost_usd', expected: 20 },
            { properties: { $ai_output_tokens: 50 }, costProperty: '$ai_output_cost_usd', expected: 10 },
            { properties: { $ai_input_cost_usd: 3 }, costProperty: '$ai_input_cost_usd', expected: 3 },
            {
                properties: { $ai_model: 'model-with-request-only', $ai_provider: 'custom' },
                costProperty: '$ai_request_cost_usd',
                expected: 0.002,
            },
            {
                properties: { $ai_model: 'perplexity/sonar-pro', $ai_provider: 'perplexity', $ai_web_search_count: 3 },
                costProperty: '$ai_web_search_cost_usd',
                expected: 0.015,
            },
        ])('preserves known $costProperty alongside orphan cached images', ({ properties, costProperty, expected }) => {
            delete event.properties!.$ai_input_tokens
            delete event.properties!.$ai_output_tokens
            Object.assign(event.properties!, properties, { $ai_cache_read_image_tokens: 100 })

            const result = processAiEvent(event)

            expect(result.properties![costProperty]).toBeCloseTo(expected)
            expect(result.properties!.$ai_total_cost_usd).toBeGreaterThan(0)
            if (costProperty !== '$ai_input_cost_usd') {
                expect(result.properties!.$ai_input_cost_usd).toBeUndefined()
            }
        })

        // Each side is a rate times its own counts, so one reported side must
        // not fabricate a $0 for the other. Interrupted streams commonly report
        // input only: Anthropic sends input tokens on message_start and the
        // output count in the final delta.
        it.each([
            {
                reported: 'input',
                tokens: { $ai_input_tokens: 100 },
                pricedProperty: '$ai_input_cost_usd',
                absentProperty: '$ai_output_cost_usd',
            },
            {
                reported: 'output',
                tokens: { $ai_output_tokens: 50 },
                pricedProperty: '$ai_output_cost_usd',
                absentProperty: '$ai_input_cost_usd',
            },
        ])(
            'prices only the $reported side when only it reported usage',
            ({ tokens, pricedProperty, absentProperty }) => {
                delete event.properties!.$ai_input_tokens
                delete event.properties!.$ai_output_tokens
                Object.assign(event.properties!, tokens)

                const result = processAiEvent(event)

                expect(result.properties![pricedProperty]).toBeGreaterThan(0)
                expect(result.properties![absentProperty]).toBeUndefined()
                expect(result.properties!.$ai_total_cost_usd).toBe(result.properties![pricedProperty])
            }
        )

        // Request and web search charges are computed without reading a token
        // count, so absent token counts must not discard a cost we do know.
        it.each([
            {
                charge: 'per-request',
                model: 'model-with-request-only',
                provider: 'custom',
                extra: {},
                costProperty: '$ai_request_cost_usd',
            },
            {
                charge: 'web search',
                model: 'perplexity/sonar-pro',
                provider: 'perplexity',
                extra: { $ai_web_search_count: 3 },
                costProperty: '$ai_web_search_cost_usd',
            },
        ])('prices a $charge charge when token counts are absent', ({ model, provider, extra, costProperty }) => {
            delete event.properties!.$ai_input_tokens
            delete event.properties!.$ai_output_tokens
            Object.assign(event.properties!, { $ai_model: model, $ai_provider: provider }, extra)

            const result = processAiEvent(event)

            expect(result.properties![costProperty]).toBeGreaterThan(0)
            expect(result.properties!.$ai_total_cost_usd).toBeGreaterThan(0)
            // Input and output are token costs, so without token counts they are
            // unknown. Writing them as 0 would show "Input $0.00" in the cost
            // breakdown for the same class of event this distinction exists for.
            expect(result.properties!.$ai_input_cost_usd).toBeUndefined()
            expect(result.properties!.$ai_output_cost_usd).toBeUndefined()
        })

        // A cost the client computed themselves is a cost we know, so absent
        // token counts must not discard it. One-sided costs never reach the
        // passthrough early return, which needs both input and output present.
        it.each([
            { component: 'input', property: '$ai_input_cost_usd', value: 0.5 },
            { component: 'per-request', property: '$ai_request_cost_usd', value: 0.25 },
        ])('keeps a client-supplied $component cost when token counts are absent', ({ property, value }) => {
            delete event.properties!.$ai_input_tokens
            delete event.properties!.$ai_output_tokens
            event.properties![property] = value

            const result = processAiEvent(event)

            expect(result.properties![property]).toBe(value)
            expect(result.properties!.$ai_total_cost_usd).toBe(value)
        })
    })

    describe('provider handling', () => {
        it('processes OpenAI events', () => {
            event.properties!.$ai_provider = 'openai'
            const result = processAiEvent(event)
            expect(result.properties!.$ai_total_cost_usd).toBeDefined()
            expect(result.properties!.$ai_input_cost_usd).toBeDefined()
            expect(result.properties!.$ai_output_cost_usd).toBeDefined()
        })

        it('processes Anthropic events', () => {
            event.properties!.$ai_provider = 'anthropic'
            event.properties!.$ai_model = 'claude-2'
            const result = processAiEvent(event)
            expect(result.properties!.$ai_total_cost_usd).toBeDefined()
            expect(result.properties!.$ai_input_cost_usd).toBeDefined()
            expect(result.properties!.$ai_output_cost_usd).toBeDefined()
        })
    })

    describe('model parameters', () => {
        it('dont extract core model parameters if not present', () => {
            const result = processAiEvent(event)
            expect(result.properties!.$ai_temperature).toBeUndefined()
            expect(result.properties!.$ai_max_tokens).toBeUndefined()
            expect(result.properties!.$ai_stream).toBeUndefined()
        })

        it('extracts core model parameters if present', () => {
            event.properties!.$ai_model_parameters = {
                temperature: 0.5,
                max_completion_tokens: 100,
                stream: false,
            }
            const result = processAiEvent(event)
            expect(result.properties!.$ai_temperature).toBe(0.5)
            expect(result.properties!.$ai_max_tokens).toBe(100)
            expect(result.properties!.$ai_stream).toBe(false)
        })

        it('extracts anthropic-specific parameters', () => {
            event.properties!.$ai_provider = 'anthropic'
            event.properties!.$ai_model_parameters = {
                temperature: 0.7,
                max_tokens: 200,
                stream: true,
                some_other_param: 'ignored',
            }
            const result = processAiEvent(event)
            expect(result.properties!.$ai_temperature).toBe(0.7)
            expect(result.properties!.$ai_max_tokens).toBe(200)
            expect(result.properties!.$ai_stream).toBe(true)
        })

        it('extracts parameters for unknown providers using openai defaults', () => {
            event.properties!.$ai_provider = 'custom-provider'
            event.properties!.$ai_model_parameters = {
                temperature: 0.8,
                max_completion_tokens: 300,
                stream: false,
            }
            const result = processAiEvent(event)
            expect(result.properties!.$ai_temperature).toBe(0.8)
            expect(result.properties!.$ai_max_tokens).toBe(300)
            expect(result.properties!.$ai_stream).toBe(false)
        })

        it('handles missing provider gracefully', () => {
            delete event.properties!.$ai_provider
            event.properties!.$ai_model_parameters = {
                temperature: 0.5,
            }
            const result = processAiEvent(event)
            // Extracts parameters even without provider
            expect(result.properties!.$ai_temperature).toBe(0.5)
        })

        it('handles empty model parameters object', () => {
            event.properties!.$ai_model_parameters = {}
            const result = processAiEvent(event)
            expect(result.properties!.$ai_temperature).toBeUndefined()
            expect(result.properties!.$ai_max_tokens).toBeUndefined()
            expect(result.properties!.$ai_stream).toBeUndefined()
        })

        it('preserves undefined parameter values', () => {
            event.properties!.$ai_model_parameters = {
                temperature: undefined,
                max_completion_tokens: undefined,
                stream: undefined,
            }
            const result = processAiEvent(event)
            expect(result.properties!.$ai_temperature).toBeUndefined()
            expect(result.properties!.$ai_max_tokens).toBeUndefined()
            expect(result.properties!.$ai_stream).toBeUndefined()
        })
    })

    describe('error handling', () => {
        it('handles missing required properties', () => {
            delete event.properties!.$ai_model
            const result = processAiEvent(event)
            expect(result.properties!.$ai_total_cost_usd).toBeUndefined()
            expect(result.properties!.$ai_input_cost_usd).toBeUndefined()
            expect(result.properties!.$ai_output_cost_usd).toBeUndefined()
        })

        it('handles null properties object', () => {
            event.properties = null as any
            const result = processAiEvent(event)
            expect(result.properties).toBeNull()
        })

        it('handles events without properties', () => {
            delete (event as any).properties
            const result = processAiEvent(event)
            expect(result.properties).toBeUndefined()
        })
    })

    describe('provider-specific cost filtering', () => {
        it('uses primary costs when provider matches', () => {
            event.properties!.$ai_provider = 'openai'
            event.properties!.$ai_model = 'openai-primary'
            const result = processAiEvent(event)

            // Should use openai/openai-primary from primaryCostsList (0.7 per token)
            expect(result.properties!.$ai_model_cost_used).toBe('openai/openai-primary')
            expect(result.properties!.$ai_cost_model_source).toBe(CostModelSource.OpenRouter)
            expect(result.properties!.$ai_cost_model_provider).toBe('openai')
            expect(result.properties!.$ai_input_cost_usd).toBeCloseTo(70, 2)
            expect(result.properties!.$ai_output_cost_usd).toBeCloseTo(35, 2)
        })

        it('falls back to manual costs when primary not found', () => {
            event.properties!.$ai_provider = 'custom'
            event.properties!.$ai_model = 'fallback-model'
            const result = processAiEvent(event)

            // Should use fallback-model from supplementaryCostsByModel
            expect(result.properties!.$ai_model_cost_used).toBe('fallback-model')
            expect(result.properties!.$ai_cost_model_source).toBe(CostModelSource.Manual)
            expect(result.properties!.$ai_cost_model_provider).toBe('default')
            expect(result.properties!.$ai_input_cost_usd).toBeCloseTo(60, 2)
            expect(result.properties!.$ai_output_cost_usd).toBeCloseTo(30, 2)
        })

        it('logs warning when no cost found', () => {
            event.properties!.$ai_provider = 'unknown'
            event.properties!.$ai_model = 'completely-unknown-model-xyz-123'

            processAiEvent(event)

            expect(mockWarn).toHaveBeenCalledWith(
                expect.stringContaining('No cost found for model: completely-unknown-model-xyz-123')
            )
        })
    })

    describe('model cost tracking', () => {
        it('sets $ai_model_cost_used to track which model was used for cost calculation', () => {
            event.properties!.$ai_model = 'gpt-4-turbo-0125-preview'
            const result = processAiEvent(event)

            // Based on the matching logic, with provider=openai, it would match openai/gpt-4 first from primaryCostsList
            expect(result.properties!.$ai_model_cost_used).toBe('openai/gpt-4')
            expect(result.properties!.$ai_cost_model_source).toBe(CostModelSource.OpenRouter)
            expect(result.properties!.$ai_cost_model_provider).toBe('openai')
        })

        it('tracks exact model match', () => {
            event.properties!.$ai_model = 'claude-2'
            const result = processAiEvent(event)

            expect(result.properties!.$ai_model_cost_used).toBe('claude-2')
            expect(result.properties!.$ai_cost_model_source).toBe(CostModelSource.Manual)
            expect(result.properties!.$ai_cost_model_provider).toBe('default')
        })

        it('does not set model_cost_used when no match found', () => {
            event.properties!.$ai_model = 'unknown-model-xyz'
            const result = processAiEvent(event)

            expect(result.properties!.$ai_model_cost_used).toBeUndefined()
            expect(result.properties!.$ai_cost_model_source).toBeUndefined()
            expect(result.properties!.$ai_cost_model_provider).toBeUndefined()
        })

        it('uses manual costs when model is only in supplementary', () => {
            event.properties!.$ai_model = 'backup-model'
            const result = processAiEvent(event)

            expect(result.properties!.$ai_model_cost_used).toBe('backup-model')
            expect(result.properties!.$ai_cost_model_source).toBe(CostModelSource.Manual)
            expect(result.properties!.$ai_cost_model_provider).toBe('default')
        })

        it('uses primary costs when anthropic provider matches anthropic-primary', () => {
            event.properties!.$ai_provider = 'anthropic'
            event.properties!.$ai_model = 'anthropic-primary'
            const result = processAiEvent(event)

            expect(result.properties!.$ai_model_cost_used).toBe('anthropic/anthropic-primary')
            expect(result.properties!.$ai_cost_model_source).toBe(CostModelSource.OpenRouter)
            expect(result.properties!.$ai_cost_model_provider).toBe('anthropic')
        })
    })

    describe('cost optimization bypass', () => {
        it('skips calculation when costs are pre-calculated', () => {
            event.properties!.$ai_input_cost_usd = 10.5
            event.properties!.$ai_output_cost_usd = 5.5
            const result = processAiEvent(event)

            // Should not recalculate, should keep existing values
            expect(result.properties!.$ai_input_cost_usd).toBe(10.5)
            expect(result.properties!.$ai_output_cost_usd).toBe(5.5)
            expect(result.properties!.$ai_total_cost_usd).toBe(16)
            // Should not set model_cost_used when bypassing
            expect(result.properties!.$ai_model_cost_used).toBeUndefined()
            expect(result.properties!.$ai_cost_model_provider).toBeUndefined()
            // Should mark as passthrough so we know costs were not calculated by the pipeline
            expect(result.properties!.$ai_cost_model_source).toBe(CostModelSource.Passthrough)
        })

        it('calculates total when input/output exist but total is missing', () => {
            event.properties!.$ai_input_cost_usd = 3.5
            event.properties!.$ai_output_cost_usd = 2.5
            delete event.properties!.$ai_total_cost_usd

            const result = processAiEvent(event)
            expect(result.properties!.$ai_total_cost_usd).toBe(6)
        })

        it('preserves existing total cost when all costs are present', () => {
            event.properties!.$ai_input_cost_usd = 3
            event.properties!.$ai_output_cost_usd = 2
            event.properties!.$ai_total_cost_usd = 10 // Intentionally different

            const result = processAiEvent(event)
            expect(result.properties!.$ai_total_cost_usd).toBe(10)
        })

        it('preserves user-provided web_search_cost when model-based calculation happens', () => {
            event.properties!.$ai_model = 'gpt-4'
            event.properties!.$ai_provider = 'openai'
            event.properties!.$ai_input_tokens = 100
            event.properties!.$ai_output_tokens = 50
            event.properties!.$ai_web_search_cost_usd = 0.035

            const result = processAiEvent(event)

            expect(result.properties!.$ai_web_search_cost_usd).toBe(0.035)
        })

        it('preserves user-provided total_cost when model-based calculation happens', () => {
            event.properties!.$ai_model = 'gpt-4'
            event.properties!.$ai_provider = 'openai'
            event.properties!.$ai_input_tokens = 100
            event.properties!.$ai_output_tokens = 50
            event.properties!.$ai_total_cost_usd = 0.5

            const result = processAiEvent(event)

            expect(result.properties!.$ai_total_cost_usd).toBe(0.5)
            // Without the passthrough flag, a supplied total does not skip the
            // estimate: the input/output split is still computed from the model.
            expect(result.properties!.$ai_input_cost_usd).toBe(20)
            expect(result.properties!.$ai_output_cost_usd).toBe(10)
            expect(result.properties!.$ai_cost_model_source).not.toBe(CostModelSource.Passthrough)
        })

        it('preserves user-provided request_cost when model-based calculation happens', () => {
            event.properties!.$ai_model = 'gpt-4'
            event.properties!.$ai_provider = 'openai'
            event.properties!.$ai_input_tokens = 100
            event.properties!.$ai_output_tokens = 50
            event.properties!.$ai_request_cost_usd = 0.02

            const result = processAiEvent(event)

            expect(result.properties!.$ai_request_cost_usd).toBe(0.02)
        })

        // A pre-calculated cost is only worth preserving if bigDecimal can add it up,
        // so an unusable one has to be recomputed instead of trusted. "0x10" earns its
        // place next to "abc": Number() reads it as 16, so a check that doesn't also
        // replace the value lets the original string reach bigDecimal.
        it.each([
            '$ai_input_cost_usd',
            '$ai_output_cost_usd',
            '$ai_request_cost_usd',
            '$ai_web_search_cost_usd',
            '$ai_total_cost_usd',
        ])('recomputes costs when the pre-calculated %s is unusable', (property) => {
            for (const value of ['abc', '0x10', '1_000', 'Infinity']) {
                const candidate = { ...event, properties: { ...event.properties, [property]: value } }
                candidate.properties.$ai_model = 'gpt-4'
                candidate.properties.$ai_provider = 'openai'
                candidate.properties.$ai_input_tokens = 100
                candidate.properties.$ai_output_tokens = 50

                const result = processAiEvent(candidate)

                expect(result.properties!.$ai_input_cost_usd).toBeCloseTo(20, 6)
                expect(result.properties!.$ai_output_cost_usd).toBeCloseTo(10, 6)
                expect(result.properties!.$ai_total_cost_usd).toBeCloseTo(30, 6)
            }
        })

        // Valid input and output costs short-circuit to a passthrough, where the total
        // is only recomputed when falsy, so an unusable one would otherwise be kept.
        it.each(['abc', '0x10'])('recomputes a passthrough total of %p', (total) => {
            event.properties!.$ai_input_cost_usd = 3
            event.properties!.$ai_output_cost_usd = 2
            event.properties!.$ai_total_cost_usd = total

            const result = processAiEvent(event)

            expect(result.properties!.$ai_total_cost_usd).toBe(5)
            expect(result.properties!.$ai_cost_model_source).toBe(CostModelSource.Passthrough)
        })

        it.each([true, 'true'])('passes the total through when $ai_cost_passthrough is %p', (flag) => {
            event.properties!.$ai_cost_passthrough = flag
            event.properties!.$ai_total_cost_usd = 0.000372

            const result = processAiEvent(event)

            expect(result.properties!.$ai_total_cost_usd).toBe(0.000372)
            expect(result.properties!.$ai_cost_model_source).toBe(CostModelSource.Passthrough)
            expect(result.properties!.$ai_input_cost_usd).toBeUndefined()
            expect(result.properties!.$ai_output_cost_usd).toBeUndefined()
        })

        it('ignores $ai_cost_passthrough when no usable total is present', () => {
            event.properties!.$ai_cost_passthrough = true

            const result = processAiEvent(event)

            expect(result.properties!.$ai_total_cost_usd).toBe(30)
            expect(result.properties!.$ai_cost_model_source).not.toBe(CostModelSource.Passthrough)
        })

        // "false" must read as off, not as a truthy string.
        it('treats a non-truthy $ai_cost_passthrough as off', () => {
            event.properties!.$ai_cost_passthrough = 'false'

            const result = processAiEvent(event)

            expect(result.properties!.$ai_input_cost_usd).toBe(20)
            expect(result.properties!.$ai_cost_model_source).not.toBe(CostModelSource.Passthrough)
        })

        // A usable cost has to come out as the parsed number, not the original string,
        // since these properties are read as floats downstream.
        it('parses pre-calculated costs supplied as numeric strings', () => {
            event.properties!.$ai_input_cost_usd = '3'
            event.properties!.$ai_output_cost_usd = ' 2.5 '

            const result = processAiEvent(event)

            expect(result.properties!.$ai_input_cost_usd).toBe(3)
            expect(result.properties!.$ai_output_cost_usd).toBe(2.5)
            expect(result.properties!.$ai_total_cost_usd).toBe(5.5)
        })
    })

    describe('custom token pricing', () => {
        it('uses custom pricing when provided', () => {
            event.properties!.$ai_input_token_price = 0.001
            event.properties!.$ai_output_token_price = 0.002
            event.properties!.$ai_input_tokens = 100
            event.properties!.$ai_output_tokens = 50

            const result = processAiEvent(event)

            expect(result.properties!.$ai_input_cost_usd).toBeCloseTo(0.1, 6)
            expect(result.properties!.$ai_output_cost_usd).toBeCloseTo(0.1, 6)
            expect(result.properties!.$ai_total_cost_usd).toBeCloseTo(0.2, 6)
            expect(result.properties!.$ai_model_cost_used).toBe('custom')
            expect(result.properties!.$ai_cost_model_source).toBe(CostModelSource.Custom)
            expect(result.properties!.$ai_cost_model_provider).toBe('custom')
        })

        it('uses custom pricing even when model is unknown', () => {
            event.properties!.$ai_model = 'completely-unknown-model'
            event.properties!.$ai_input_token_price = 0.0005
            event.properties!.$ai_output_token_price = 0.0015
            event.properties!.$ai_input_tokens = 200
            event.properties!.$ai_output_tokens = 100

            const result = processAiEvent(event)

            expect(result.properties!.$ai_input_cost_usd).toBeCloseTo(0.1, 6)
            expect(result.properties!.$ai_output_cost_usd).toBeCloseTo(0.15, 6)
            expect(result.properties!.$ai_total_cost_usd).toBeCloseTo(0.25, 6)
            expect(result.properties!.$ai_model_cost_used).toBe('custom')
            expect(result.properties!.$ai_cost_model_provider).toBe('custom')
        })

        it('custom pricing takes precedence over model matching', () => {
            event.properties!.$ai_model = 'gpt-4'
            event.properties!.$ai_provider = 'openai'
            event.properties!.$ai_input_token_price = 0.1
            event.properties!.$ai_output_token_price = 0.2
            event.properties!.$ai_input_tokens = 10
            event.properties!.$ai_output_tokens = 5

            const result = processAiEvent(event)

            expect(result.properties!.$ai_input_cost_usd).toBeCloseTo(1, 6)
            expect(result.properties!.$ai_output_cost_usd).toBeCloseTo(1, 6)
            expect(result.properties!.$ai_total_cost_usd).toBeCloseTo(2, 6)
            expect(result.properties!.$ai_model_cost_used).toBe('custom')
            expect(result.properties!.$ai_cost_model_provider).toBe('custom')
        })

        it('pre-calculated costs take precedence over custom pricing', () => {
            event.properties!.$ai_input_cost_usd = 5.5
            event.properties!.$ai_output_cost_usd = 3.5
            event.properties!.$ai_input_token_price = 0.001
            event.properties!.$ai_output_token_price = 0.002
            event.properties!.$ai_input_tokens = 100
            event.properties!.$ai_output_tokens = 50

            const result = processAiEvent(event)

            expect(result.properties!.$ai_input_cost_usd).toBe(5.5)
            expect(result.properties!.$ai_output_cost_usd).toBe(3.5)
            expect(result.properties!.$ai_total_cost_usd).toBe(9)
            expect(result.properties!.$ai_model_cost_used).toBeUndefined()
            expect(result.properties!.$ai_cost_model_provider).toBeUndefined()
            expect(result.properties!.$ai_cost_model_source).toBe(CostModelSource.Passthrough)
        })

        it('treats object cost values as unset and falls through to model calculation', () => {
            event.properties!.$ai_model = 'gpt-4'
            event.properties!.$ai_input_tokens = 100
            event.properties!.$ai_output_tokens = 50
            event.properties!.$ai_input_cost_usd = { value: 5.5 } as any
            event.properties!.$ai_output_cost_usd = { value: 3.5 } as any

            const result = processAiEvent(event)

            // Should fall through to model-based calculation, not crash or use 0
            expect(result.properties!.$ai_cost_model_source).toBe(CostModelSource.OpenRouter)
            expect(result.properties!.$ai_input_cost_usd).toBeGreaterThan(0)
            expect(result.properties!.$ai_output_cost_usd).toBeGreaterThan(0)
        })

        it.each([
            { provider: 'openai', model: 'gpt-4o', writeRate: 0.00125, expectedInputCost: 0.085 },
            { provider: 'google', model: 'gemini-2.5-flash', writeRate: 0.00125, expectedInputCost: 0.085 },
            { provider: 'google', model: 'gemini-2.5-flash', writeRate: 0, expectedInputCost: 0.06 },
        ])(
            'handles custom cache pricing for $provider at write rate $writeRate',
            ({ provider, model, writeRate, expectedInputCost }) => {
                event.properties!.$ai_provider = provider
                event.properties!.$ai_model = model
                event.properties!.$ai_input_token_price = 0.001
                event.properties!.$ai_output_token_price = 0.002
                event.properties!.$ai_cache_read_token_price = 0.0005
                event.properties!.$ai_cache_write_token_price = writeRate
                event.properties!.$ai_input_tokens = 100
                event.properties!.$ai_cache_read_input_tokens = 40
                event.properties!.$ai_cache_creation_input_tokens = 20
                event.properties!.$ai_output_tokens = 50

                const result = processAiEvent(event)

                expect(result.properties!.$ai_input_cost_usd).toBeCloseTo(expectedInputCost, 6)
                expect(result.properties!.$ai_output_cost_usd).toBeCloseTo(0.1, 6)
                expect(result.properties!.$ai_total_cost_usd).toBeCloseTo(expectedInputCost + 0.1, 6)
            }
        )

        it('handles custom pricing with cache tokens for Anthropic', () => {
            event.properties!.$ai_provider = 'anthropic'
            event.properties!.$ai_input_token_price = 0.000003
            event.properties!.$ai_output_token_price = 0.000015
            event.properties!.$ai_cache_read_token_price = 0.0000003
            event.properties!.$ai_cache_write_token_price = 0.00000375
            event.properties!.$ai_input_tokens = 1000
            event.properties!.$ai_cache_read_input_tokens = 500
            event.properties!.$ai_cache_creation_input_tokens = 200
            event.properties!.$ai_output_tokens = 100

            const result = processAiEvent(event)

            expect(result.properties!.$ai_input_cost_usd).toBeCloseTo(0.0039, 6)
            expect(result.properties!.$ai_output_cost_usd).toBeCloseTo(0.0015, 6)
            expect(result.properties!.$ai_total_cost_usd).toBeCloseTo(0.0054, 6)
        })

        it('extracts and prices Anthropic mixed-TTL cache writes with custom rates', () => {
            event.properties!.$ai_provider = 'anthropic'
            event.properties!.$ai_input_token_price = 0.000003
            event.properties!.$ai_output_token_price = 0.000015
            event.properties!.$ai_cache_write_token_price = 0.000004
            event.properties!.$ai_cache_write_1h_token_price = 0.000007
            event.properties!.$ai_input_tokens = 1000
            event.properties!.$ai_output_tokens = 100
            event.properties!.$ai_cache_creation_input_tokens = 300
            event.properties!.$ai_usage = {
                usage: {
                    inputTokens: {
                        total: 1300,
                        noCache: 1000,
                        cacheRead: 0,
                        cacheWrite: 300,
                    },
                    outputTokens: { total: 100, text: 100, reasoning: 0 },
                    raw: {
                        cache_creation_input_tokens: 300,
                        cache_creation: {
                            ephemeral_5m_input_tokens: 100,
                            ephemeral_1h_input_tokens: 200,
                        },
                    },
                },
                providerMetadata: {
                    anthropic: {
                        usage: {
                            cache_creation_input_tokens: 300,
                            cache_creation: {
                                ephemeral_5m_input_tokens: 100,
                                ephemeral_1h_input_tokens: 200,
                            },
                        },
                    },
                },
            }

            const result = processAiEvent(event)

            expect(result.properties!.$ai_cache_creation_5m_input_tokens).toBe(100)
            expect(result.properties!.$ai_cache_creation_1h_input_tokens).toBe(200)
            expect(result.properties!.$ai_usage).toBeUndefined()
            expect(result.properties!.$ai_input_cost_usd).toBeCloseTo(0.0048, 8)
            expect(result.properties!.$ai_total_cost_usd).toBeCloseTo(0.0063, 8)
        })

        it('extracts and prices Vercel Bedrock mixed-TTL cache writes', () => {
            event.properties!.$ai_model = 'anthropic/claude-sonnet-4'
            event.properties!.$ai_provider = 'bedrock'
            event.properties!.$ai_input_tokens = 1000
            event.properties!.$ai_output_tokens = 100
            event.properties!.$ai_cache_creation_input_tokens = 300
            const bedrockUsage = {
                cacheDetails: [
                    { ttl: 'T5M', inputTokens: 100 },
                    { ttl: 'T1H', inputTokens: 200 },
                ],
            }
            event.properties!.$ai_usage = {
                providerMetadata: {
                    amazonBedrock: { usage: bedrockUsage },
                },
            }

            const result = processAiEvent(event)

            expect(result.properties!.$ai_input_cost_usd).toBeCloseTo(0.004575, 8)
            expect(result.properties!.$ai_total_cost_usd).toBeCloseTo(0.006075, 8)
            expect(result.properties!.$ai_cache_creation_5m_input_tokens).toBe(100)
            expect(result.properties!.$ai_cache_creation_1h_input_tokens).toBe(200)
            expect(result.properties!.$ai_usage).toBeUndefined()
        })

        it('falls back to multipliers when cache prices not provided', () => {
            event.properties!.$ai_provider = 'openai'
            event.properties!.$ai_input_token_price = 0.001
            event.properties!.$ai_output_token_price = 0.002
            event.properties!.$ai_input_tokens = 100
            event.properties!.$ai_cache_read_input_tokens = 40
            event.properties!.$ai_output_tokens = 50

            const result = processAiEvent(event)

            expect(result.properties!.$ai_input_cost_usd).toBeCloseTo(0.08, 6)
            expect(result.properties!.$ai_output_cost_usd).toBeCloseTo(0.1, 6)
            expect(result.properties!.$ai_total_cost_usd).toBeCloseTo(0.18, 6)
        })

        it('handles zero custom prices', () => {
            event.properties!.$ai_input_token_price = 0
            event.properties!.$ai_output_token_price = 0
            event.properties!.$ai_input_tokens = 100
            event.properties!.$ai_output_tokens = 50

            const result = processAiEvent(event)

            expect(result.properties!.$ai_input_cost_usd).toBe(0)
            expect(result.properties!.$ai_output_cost_usd).toBe(0)
            expect(result.properties!.$ai_total_cost_usd).toBe(0)
            expect(result.properties!.$ai_model_cost_used).toBe('custom')
            expect(result.properties!.$ai_cost_model_provider).toBe('custom')
        })

        it('requires both input and output prices to use custom pricing', () => {
            event.properties!.$ai_input_token_price = 0.001
            event.properties!.$ai_input_tokens = 100
            event.properties!.$ai_output_tokens = 50

            const result = processAiEvent(event)

            expect(result.properties!.$ai_model_cost_used).toBe('openai/gpt-4')
            expect(result.properties!.$ai_cost_model_source).toBe(CostModelSource.OpenRouter)
            expect(result.properties!.$ai_cost_model_provider).toBe('openai')
        })

        // A price js-big-decimal can't parse has to count as unset, so the event bills
        // at model rates rather than throwing or silently billing at a rate of zero.
        it.each<{ description: string; inputPrice: unknown; outputPrice: unknown }>([
            { description: 'non-numeric string input price', inputPrice: '$0.001', outputPrice: 0.002 },
            { description: 'whitespace-only input price', inputPrice: ' ', outputPrice: 0.002 },
            { description: 'null input price', inputPrice: null, outputPrice: 0.002 },
            { description: 'object input price', inputPrice: { value: 0.001 }, outputPrice: 0.002 },
            { description: 'boolean input price', inputPrice: true, outputPrice: 0.002 },
            { description: 'non-numeric string output price', inputPrice: 0.001, outputPrice: '$0.002' },
            { description: 'NaN output price', inputPrice: 0.001, outputPrice: Number.NaN },
        ])('falls back to model pricing for $description', ({ inputPrice, outputPrice }) => {
            event.properties!.$ai_input_token_price = inputPrice
            event.properties!.$ai_output_token_price = outputPrice
            event.properties!.$ai_input_tokens = 100
            event.properties!.$ai_output_tokens = 50

            const result = processAiEvent(event)

            expect(result.properties!.$ai_model_cost_used).toBe('openai/gpt-4')
            expect(result.properties!.$ai_cost_model_source).toBe(CostModelSource.OpenRouter)
            expect(result.properties!.$ai_cost_model_provider).toBe('openai')
            expect(result.properties!.$ai_input_cost_usd).toBeCloseTo(20, 6)
            expect(result.properties!.$ai_output_cost_usd).toBeCloseTo(10, 6)
        })

        // Reasoning tokens make the output-cost path inspect the model as well.
        it.each<{ description: string; properties: Record<string, unknown> }>([
            { description: 'numeric model', properties: { $ai_model: 4 } },
            { description: 'boolean model', properties: { $ai_model: true } },
            { description: 'array model', properties: { $ai_model: ['gpt-4'] } },
            { description: 'object model', properties: { $ai_model: { name: 'gpt-4' } } },
            { description: 'numeric provider', properties: { $ai_provider: 1 } },
            {
                description: 'object framework',
                properties: { $ai_provider: 'anthropic', $ai_framework: { name: 'vercel' } },
            },
        ])('keeps custom pricing when the event carries a $description', ({ properties }) => {
            Object.assign(event.properties!, properties)
            event.properties!.$ai_input_token_price = 0.001
            event.properties!.$ai_output_token_price = 0.002
            event.properties!.$ai_input_tokens = 100
            event.properties!.$ai_output_tokens = 50
            event.properties!.$ai_reasoning_tokens = 10

            const result = processAiEvent(event)

            expect(result.properties!.$ai_input_cost_usd).toBeCloseTo(0.1, 6)
            expect(result.properties!.$ai_output_cost_usd).toBeCloseTo(0.1, 6)
            expect(result.properties!.$ai_total_cost_usd).toBeCloseTo(0.2, 6)
            expect(result.properties!.$ai_cost_model_source).toBe(CostModelSource.Custom)
        })

        // Several optional prices are invalid at once, so dropping the coercion on
        // any single one puts it back in front of js-big-decimal.
        it('ignores unusable optional prices and keeps custom pricing', () => {
            event.properties!.$ai_provider = 'openai'
            event.properties!.$ai_input_token_price = 0.001
            event.properties!.$ai_output_token_price = 0.002
            event.properties!.$ai_cache_read_token_price = '$0.10'
            event.properties!.$ai_request_price = Number.NaN
            event.properties!.$ai_web_search_price = ' '
            event.properties!.$ai_input_tokens = 100
            event.properties!.$ai_cache_read_input_tokens = 40
            event.properties!.$ai_output_tokens = 50
            event.properties!.$ai_request_count = 3
            event.properties!.$ai_web_search_count = 2

            const result = processAiEvent(event)

            expect(result.properties!.$ai_model_cost_used).toBe('custom')
            // Cache reads fall back to the 0.5 multiplier: 60 * 0.001 + 40 * 0.001 * 0.5.
            expect(result.properties!.$ai_input_cost_usd).toBeCloseTo(0.08, 6)
            expect(result.properties!.$ai_output_cost_usd).toBeCloseTo(0.1, 6)
            expect(result.properties!.$ai_request_cost_usd).toBe(0)
            expect(result.properties!.$ai_web_search_cost_usd).toBe(0)
            expect(result.properties!.$ai_total_cost_usd).toBeCloseTo(0.18, 6)
        })

        // Only the Anthropic TTL path consumes the 1-hour cache-write rate, and only
        // when both TTL counts are present.
        it('ignores unusable cache write prices on an Anthropic event', () => {
            event.properties!.$ai_model = 'claude-sonnet-4'
            event.properties!.$ai_provider = 'anthropic'
            event.properties!.$ai_input_token_price = 0.001
            event.properties!.$ai_output_token_price = 0.002
            event.properties!.$ai_cache_write_token_price = 'abc'
            event.properties!.$ai_cache_write_1h_token_price = { value: 0.1 }
            event.properties!.$ai_input_tokens = 1000
            event.properties!.$ai_cache_creation_5m_input_tokens = 100
            event.properties!.$ai_cache_creation_1h_input_tokens = 200
            event.properties!.$ai_output_tokens = 50

            const result = processAiEvent(event)

            expect(result.properties!.$ai_model_cost_used).toBe('custom')
            // Both writes fall back to prompt-rate multipliers, 1.25 for 5m and 2 for 1h:
            // 1000 * 0.001 + 100 * 0.00125 + 200 * 0.002.
            expect(result.properties!.$ai_input_cost_usd).toBeCloseTo(1.525, 6)
            expect(result.properties!.$ai_output_cost_usd).toBeCloseTo(0.1, 6)
        })

        it('treats a null cache read price as unset rather than free', () => {
            event.properties!.$ai_provider = 'openai'
            event.properties!.$ai_input_token_price = 0.001
            event.properties!.$ai_output_token_price = 0.002
            event.properties!.$ai_cache_read_token_price = null
            event.properties!.$ai_input_tokens = 100
            event.properties!.$ai_cache_read_input_tokens = 40
            event.properties!.$ai_output_tokens = 50

            const result = processAiEvent(event)

            expect(result.properties!.$ai_input_cost_usd).toBeCloseTo(0.08, 6)
        })

        // A request count defaults to 1 when absent, a web search count to nothing, so
        // an unusable value has to land on each default rather than on bigDecimal.
        it.each<{ property: string; costProperty: string; expected: number }>([
            { property: '$ai_request_count', costProperty: '$ai_request_cost_usd', expected: 0.01 },
            { property: '$ai_web_search_count', costProperty: '$ai_web_search_cost_usd', expected: 0 },
        ])('prices the event when $property is not a number', ({ property, costProperty, expected }) => {
            event.properties!.$ai_input_token_price = 0.001
            event.properties!.$ai_output_token_price = 0.002
            event.properties!.$ai_request_price = 0.01
            event.properties!.$ai_web_search_price = 0.02
            event.properties!.$ai_input_tokens = 100
            event.properties!.$ai_output_tokens = 50
            event.properties![property] = 'lots'

            const result = processAiEvent(event)

            expect(result.properties![costProperty]).toBeCloseTo(expected, 6)
        })

        it('accepts numeric-string custom prices', () => {
            event.properties!.$ai_input_token_price = '0.001'
            event.properties!.$ai_output_token_price = '0.002'
            event.properties!.$ai_input_tokens = 100
            event.properties!.$ai_output_tokens = 50

            const result = processAiEvent(event)

            expect(result.properties!.$ai_input_cost_usd).toBeCloseTo(0.1, 6)
            expect(result.properties!.$ai_output_cost_usd).toBeCloseTo(0.1, 6)
            expect(result.properties!.$ai_model_cost_used).toBe('custom')
        })

        it('works without provider when using custom pricing', () => {
            delete event.properties!.$ai_provider
            event.properties!.$ai_input_token_price = 0.001
            event.properties!.$ai_output_token_price = 0.002
            event.properties!.$ai_input_tokens = 100
            event.properties!.$ai_output_tokens = 50

            const result = processAiEvent(event)

            expect(result.properties!.$ai_input_cost_usd).toBeCloseTo(0.1, 6)
            expect(result.properties!.$ai_output_cost_usd).toBeCloseTo(0.1, 6)
            expect(result.properties!.$ai_total_cost_usd).toBeCloseTo(0.2, 6)
        })

        it('works without model when using custom pricing', () => {
            delete event.properties!.$ai_model
            event.properties!.$ai_input_token_price = 0.001
            event.properties!.$ai_output_token_price = 0.002
            event.properties!.$ai_input_tokens = 100
            event.properties!.$ai_output_tokens = 50

            const result = processAiEvent(event)

            expect(result.properties!.$ai_input_cost_usd).toBeCloseTo(0.1, 6)
            expect(result.properties!.$ai_output_cost_usd).toBeCloseTo(0.1, 6)
            expect(result.properties!.$ai_total_cost_usd).toBeCloseTo(0.2, 6)
        })

        it('handles reasoning tokens with custom pricing for gemini-2.5 models', () => {
            event.properties!.$ai_provider = 'google'
            event.properties!.$ai_model = 'gemini-2.5-flash'
            event.properties!.$ai_input_token_price = 0.0000003
            event.properties!.$ai_output_token_price = 0.0000025
            event.properties!.$ai_input_tokens = 100
            event.properties!.$ai_output_tokens = 50
            event.properties!.$ai_reasoning_tokens = 200

            const result = processAiEvent(event)

            expect(result.properties!.$ai_input_cost_usd).toBeCloseTo(0.00003, 6)
            expect(result.properties!.$ai_output_cost_usd).toBeCloseTo(0.000625, 6)
            expect(result.properties!.$ai_total_cost_usd).toBeCloseTo(0.000655, 6)
        })
    })

    describe('model name edge cases', () => {
        it('handles empty string model names', () => {
            event.properties!.$ai_model = ''
            const result = processAiEvent(event)
            expect(result.properties!.$ai_total_cost_usd).toBeUndefined()
        })

        it('handles case-insensitive model matching', () => {
            event.properties!.$ai_model = 'GPT-4' // Uppercase
            const result = processAiEvent(event)
            expect(result.properties!.$ai_model_cost_used).toBe('openai/gpt-4')
            expect(result.properties!.$ai_total_cost_usd).toBeDefined()
        })

        it('handles model names with special characters using substring matching', () => {
            // Test various special character scenarios in a single test
            const specialCases = [
                { model: 'gpt-4-日本語', expected: 'openai/gpt-4' },
                { model: 'gpt-4@latest#v2', expected: 'openai/gpt-4' },
                { model: 'openai/gpt-4', expected: 'openai/gpt-4' },
            ]

            for (const { model, expected } of specialCases) {
                event.properties!.$ai_model = model
                const result = processAiEvent(event)
                expect(result.properties!.$ai_model_cost_used).toBe(expected)
            }
        })
    })

    describe('edge cases in token handling', () => {
        it('handles very large token numbers', () => {
            event.properties!.$ai_input_tokens = 1e10
            event.properties!.$ai_output_tokens = 1e10

            const result = processAiEvent(event)

            expect(result.properties!.$ai_input_cost_usd).toBeGreaterThan(0)
            expect(result.properties!.$ai_output_cost_usd).toBeGreaterThan(0)
            expect(result.properties!.$ai_total_cost_usd).toBeGreaterThan(0)
        })

        it('handles scientific notation in token counts', () => {
            event.properties!.$ai_input_tokens = 1.5e3 // 1500
            event.properties!.$ai_output_tokens = 2e2 // 200

            const result = processAiEvent(event)

            expect(result.properties!.$ai_input_cost_usd).toBeCloseTo(300, 2) // 1500 * 0.2
            expect(result.properties!.$ai_output_cost_usd).toBeCloseTo(40, 2) // 200 * 0.2
        })
    })

    describe('model cost calculations', () => {
        it.each([
            { model: 'testing_model', inputCost: 10, outputCost: 5, totalCost: 15 },
            { model: 'gpt-4', inputCost: 20, outputCost: 10, totalCost: 30 },
            { model: 'gpt-4o-mini', inputCost: 50, outputCost: 25, totalCost: 75 },
            { model: 'claude-2', inputCost: 60, outputCost: 30, totalCost: 90 },
            { model: 'o1-mini', inputCost: 0.00011, outputCost: 0.00022, totalCost: 0.00033 },
        ])('calculates correct costs for $model', ({ model, inputCost, outputCost, totalCost }) => {
            event.properties!.$ai_model = model
            event.properties!.$ai_provider = undefined // Use default costs
            const result = processAiEvent(event)
            expect(result.properties!.$ai_input_cost_usd).toBeCloseTo(inputCost, 2)
            expect(result.properties!.$ai_output_cost_usd).toBeCloseTo(outputCost, 2)
            expect(result.properties!.$ai_total_cost_usd).toBeCloseTo(totalCost, 2)
        })
    })

    describe('openai cache handling', () => {
        it('handles cache read and write tokens with correct cost calculation', () => {
            event.properties!.$ai_provider = 'openai'
            event.properties!.$ai_model = 'testing_model'
            event.properties!.$ai_input_tokens = 100
            event.properties!.$ai_output_tokens = 50
            event.properties!.$ai_cache_read_input_tokens = 40

            const result = processAiEvent(event)

            // For testing_model: prompt_token = 0.1, completion_token = 0.1
            // Input cost: (40 * 0.1 * 0.5) + (60 * 0.1) = 2 + 6 = 8
            // Output cost: 50 * 0.1 = 5
            // Total cost: 8 + 5 = 13
            expect(result.properties!.$ai_input_cost_usd).toBeCloseTo(8, 2)
            expect(result.properties!.$ai_output_cost_usd).toBeCloseTo(5, 2)
            expect(result.properties!.$ai_total_cost_usd).toBeCloseTo(13, 2)
        })

        it('handles zero cache tokens correctly', () => {
            event.properties!.$ai_provider = 'openai'
            event.properties!.$ai_model = 'testing_model'
            event.properties!.$ai_input_tokens = 100
            event.properties!.$ai_output_tokens = 50
            event.properties!.$ai_cache_read_input_tokens = 0

            const result = processAiEvent(event)

            // Input cost: 100 * 0.1 = 10
            // Output cost: 50 * 0.1 = 5
            // Total cost: 10 + 5 = 15
            expect(result.properties!.$ai_input_cost_usd).toBeCloseTo(10, 2)
            expect(result.properties!.$ai_output_cost_usd).toBeCloseTo(5, 2)
            expect(result.properties!.$ai_total_cost_usd).toBeCloseTo(15, 2)
        })
    })

    describe('cache costs with defined values', () => {
        it('uses actual cache costs when defined in model', () => {
            event.properties!.$ai_provider = 'anthropic'
            event.properties!.$ai_model = 'claude-sonnet-4' // Has defined cache costs
            event.properties!.$ai_input_tokens = 1000
            event.properties!.$ai_output_tokens = 100
            event.properties!.$ai_cache_read_input_tokens = 500
            event.properties!.$ai_cache_creation_input_tokens = 200

            const result = processAiEvent(event)

            // claude-sonnet-4: prompt=0.000003, cache_read=3e-7, cache_write=0.00000375
            // Write: 200 * 0.00000375 = 0.00075
            // Read: 500 * 3e-7 = 0.00015
            // Regular: 1000 * 0.000003 = 0.003
            // Total input: 0.00075 + 0.00015 + 0.003 = 0.0039
            expect(result.properties!.$ai_input_cost_usd).toBeCloseTo(0.0039, 6)

            // Output: 100 * 0.000015 = 0.0015
            expect(result.properties!.$ai_output_cost_usd).toBeCloseTo(0.0015, 6)
        })

        it('falls back to multipliers when cache costs not defined', () => {
            event.properties!.$ai_provider = 'anthropic'
            event.properties!.$ai_model = 'testing_model' // No defined cache costs
            event.properties!.$ai_input_tokens = 100
            event.properties!.$ai_cache_read_input_tokens = 50
            event.properties!.$ai_cache_creation_input_tokens = 20

            const result = processAiEvent(event)

            // testing_model: prompt=0.1, no cache costs defined
            // Write: 20 * 0.1 * 1.25 = 2.5
            // Read: 50 * 0.1 * 0.1 = 0.5
            // Regular: 100 * 0.1 = 10
            // Total input: 2.5 + 0.5 + 10 = 13
            expect(result.properties!.$ai_input_cost_usd).toBeCloseTo(13, 2)
        })
    })

    describe('anthropic cache handling', () => {
        it('handles cache read and write tokens with correct cost calculation', () => {
            event.properties!.$ai_provider = 'anthropic'
            event.properties!.$ai_model = 'testing_model'
            event.properties!.$ai_input_tokens = 100
            event.properties!.$ai_output_tokens = 50
            event.properties!.$ai_cache_read_input_tokens = 1000
            event.properties!.$ai_cache_creation_input_tokens = 20

            const result = processAiEvent(event)

            // For testing_model: prompt_token = 0.1, completion_token = 0.1
            // Write cost: 20 * 0.1 * 1.25 = 2.5
            // Read cost: 1000 * 0.1 * 0.1 = 10
            // Uncached cost: 100 * 0.1 = 10
            // Input cost: 2.5 + 10 + 10 = 22.5
            // Output cost: 50 * 0.1 = 5
            // Total cost: 22.5 + 5 = 27.5
            expect(result.properties!.$ai_input_cost_usd).toBeCloseTo(22.5, 2)
            expect(result.properties!.$ai_output_cost_usd).toBeCloseTo(5, 2)
            expect(result.properties!.$ai_total_cost_usd).toBeCloseTo(27.5, 2)
        })

        it('handles zero cache tokens correctly', () => {
            event.properties!.$ai_provider = 'anthropic'
            event.properties!.$ai_model = 'testing_model'
            event.properties!.$ai_input_tokens = 100
            event.properties!.$ai_output_tokens = 50
            event.properties!.$ai_cache_read_input_tokens = 0
            event.properties!.$ai_cache_creation_input_tokens = 0

            const result = processAiEvent(event)

            // Input cost: 100 * 0.1 = 10
            // Output cost: 50 * 0.1 = 5
            // Total cost: 10 + 5 = 15
            expect(result.properties!.$ai_input_cost_usd).toBeCloseTo(10, 2)
            expect(result.properties!.$ai_output_cost_usd).toBeCloseTo(5, 2)
            expect(result.properties!.$ai_total_cost_usd).toBeCloseTo(15, 2)
        })
    })

    describe('gateway provider handling', () => {
        it('handles Anthropic models through gateway provider with cache tokens', () => {
            // Simulate the exact user scenario
            event.properties!.$ai_provider = 'gateway'
            event.properties!.$ai_model = 'anthropic/claude-sonnet-4'
            event.properties!.$ai_input_tokens = 3815
            event.properties!.$ai_output_tokens = 460
            event.properties!.$ai_cache_creation_input_tokens = 84329

            const result = processAiEvent(event)

            // Should use anthropic/claude-sonnet-4 costs from OpenRouter
            expect(result.properties!.$ai_model_cost_used).toBe('anthropic/claude-sonnet-4')
            expect(result.properties!.$ai_cost_model_provider).toBe('default')

            // Cache creation: 84329 * 0.000003 * 1.25 = 0.31623375
            // Regular input: 3815 * 0.000003 = 0.011445
            // Total input: 0.31623375 + 0.011445 = 0.32767875
            expect(result.properties!.$ai_input_cost_usd).toBeCloseTo(0.327679, 5)

            // Output: 460 * 0.000015 = 0.0069
            expect(result.properties!.$ai_output_cost_usd).toBeCloseTo(0.0069, 4)

            // Total: 0.327679 + 0.0069 = 0.334579
            expect(result.properties!.$ai_total_cost_usd).toBeCloseTo(0.334579, 5)
        })

        it('uses inclusive token accounting for Anthropic models via Vercel gateway', () => {
            event.properties!.$ai_provider = 'gateway'
            event.properties!.$ai_framework = 'vercel'
            event.properties!.$ai_model = 'anthropic/claude-sonnet-4.5'
            event.properties!.$ai_input_tokens = 14013
            event.properties!.$ai_output_tokens = 165
            event.properties!.$ai_cache_read_input_tokens = 13306
            event.properties!.$ai_cache_creation_input_tokens = 701

            const result = processAiEvent(event)

            expect(result.properties!.$ai_model_cost_used).toBe('anthropic/claude-sonnet-4')
            expect(result.properties!.$ai_cost_model_provider).toBe('default')

            // Input:
            // Read: 13306 * 3e-7 = 0.0039918
            // Write: 701 * 0.00000375 = 0.00262875
            // Uncached: (14013 - 13306 - 701) * 0.000003 = 0.000018
            // Total input: 0.00663855
            expect(result.properties!.$ai_input_cost_usd).toBeCloseTo(0.00663855, 8)

            // Output: 165 * 0.000015 = 0.002475
            expect(result.properties!.$ai_output_cost_usd).toBeCloseTo(0.002475, 6)

            // Total: 0.00663855 + 0.002475 = 0.00911355
            expect(result.properties!.$ai_total_cost_usd).toBeCloseTo(0.00911355, 8)
        })

        it('handles OpenAI models through gateway provider', () => {
            event.properties!.$ai_provider = 'gateway'
            event.properties!.$ai_model = 'openai/gpt-4'
            event.properties!.$ai_input_tokens = 100
            event.properties!.$ai_output_tokens = 50
            event.properties!.$ai_cache_read_input_tokens = 40

            const result = processAiEvent(event)

            expect(result.properties!.$ai_model_cost_used).toBe('openai/gpt-4')
            expect(result.properties!.$ai_cost_model_provider).toBe('default')
            // Should calculate OpenAI cache costs correctly
            expect(result.properties!.$ai_input_cost_usd).toBeCloseTo(16, 2) // (40*0.2*0.5) + (60*0.2) = 4 + 12 = 16
            expect(result.properties!.$ai_output_cost_usd).toBeCloseTo(10, 2) // 50 * 0.2 = 10
        })

        it('matches provider when provider name appears anywhere in model string', () => {
            event.properties!.$ai_provider = 'gateway'
            event.properties!.$ai_model = 'some-prefix-anthropic-claude-sonnet-4'
            event.properties!.$ai_input_tokens = 3815
            event.properties!.$ai_output_tokens = 460
            event.properties!.$ai_cache_creation_input_tokens = 84329

            const result = processAiEvent(event)

            expect(result.properties!.$ai_model_cost_used).toBe('anthropic/claude-sonnet-4')
            expect(result.properties!.$ai_cost_model_provider).toBe('default')

            // Cache creation: 84329 * 0.000003 * 1.25 = 0.31623375
            // Regular input: 3815 * 0.000003 = 0.011445
            // Total input: 0.31623375 + 0.011445 = 0.32767875
            expect(result.properties!.$ai_input_cost_usd).toBeCloseTo(0.327679, 5)

            // Output: 460 * 0.000015 = 0.0069
            expect(result.properties!.$ai_output_cost_usd).toBeCloseTo(0.0069, 4)

            // Total: 0.327679 + 0.0069 = 0.334579
            expect(result.properties!.$ai_total_cost_usd).toBeCloseTo(0.334579, 5)
        })
    })

    describe('gemini 2.5 pro preview', () => {
        it('handles missing model property in getNewModelName', () => {
            const eventWithoutModel = {
                ...event,
                properties: {
                    ...event.properties,
                    $ai_model: undefined,
                    $ai_input_tokens: 250000,
                },
            }

            const result = processAiEvent(eventWithoutModel)
            expect(result.properties!.$ai_total_cost_usd).toBeUndefined()
        })

        it('handles the separate price for lage prompts', () => {
            const event1 = {
                ...event,
                properties: {
                    ...event.properties,
                    $ai_model: 'gemini-2.5-pro-preview',
                    $ai_input_tokens: 200001,
                },
            }

            const event2 = {
                ...event,
                properties: {
                    ...event.properties,
                    $ai_model: 'gemini-2.5-pro-preview',
                    $ai_input_tokens: 199999,
                },
            }

            const result1 = processAiEvent(event1)
            const result2 = processAiEvent(event2)

            expect(result1.properties!.$ai_total_cost_usd).toBeDefined()
            expect(result1.properties!.$ai_input_cost_usd).toBeDefined()
            expect(result1.properties!.$ai_output_cost_usd).toBeDefined()
            expect(result2.properties!.$ai_input_cost_usd).toBeDefined()
            expect(result2.properties!.$ai_output_cost_usd).toBeDefined()
            expect(result1.properties!.$ai_input_cost_usd).toBeGreaterThan(result2.properties!.$ai_input_cost_usd)
            expect(result1.properties!.$ai_output_cost_usd).toBeGreaterThan(result2.properties!.$ai_output_cost_usd)
            expect(result1.properties!.$ai_total_cost_usd).toBeGreaterThan(result2.properties!.$ai_total_cost_usd)
        })
    })

    describe('advanced model matching logic specific tests', () => {
        const inputTokens = 100
        const outputTokens = 50

        beforeEach(() => {
            event.properties = {
                ...event.properties,
                $ai_provider: 'openai',
                $ai_input_tokens: inputTokens,
                $ai_output_tokens: outputTokens,
                $ai_model: undefined,
                $ai_input_cost_usd: undefined,
                $ai_output_cost_usd: undefined,
                $ai_total_cost_usd: undefined,
            }
        })

        it('correctly matches a more specific input model to its known base (Rule 2)', () => {
            event.properties!.$ai_model = 'testing_model-suffix-123'
            const result = processAiEvent(event)

            const expectedInputCost = inputTokens * 0.1 // 100 * 0.1
            const expectedOutputCost = outputTokens * 0.1 // 50 * 0.1
            expect(result.properties!.$ai_input_cost_usd).toBe(expectedInputCost)
            expect(result.properties!.$ai_output_cost_usd).toBe(expectedOutputCost)
            expect(result.properties!.$ai_total_cost_usd).toBe(expectedInputCost + expectedOutputCost)
        })

        it('matches the most specific provider model when available (Rule 2 refinement)', () => {
            event.properties!.$ai_model = 'gpt-4-0125-preview-custom-suffix'
            const result = processAiEvent(event)

            // With provider=openai, it matches the specific gpt-4-0125-preview pricing from OpenRouter
            const modelCost = costsByModel['openai/gpt-4-0125-preview'].cost // p:0.3, c:0.3
            const expectedInputCost = inputTokens * modelCost.prompt_token // 100 * 0.3
            const expectedOutputCost = outputTokens * modelCost.completion_token // 50 * 0.3

            expect(result.properties!.$ai_input_cost_usd).toBe(expectedInputCost)
            expect(result.properties!.$ai_output_cost_usd).toBe(expectedOutputCost)
            expect(result.properties!.$ai_total_cost_usd).toBe(expectedInputCost + expectedOutputCost)
        })

        it('matches a general input model to a more specific known model (Rule 3, first found)', () => {
            event.properties!.$ai_model = 'mistral-7b-instruct'
            const result = processAiEvent(event)

            const modelCost = costsByModel['mistralai/mistral-7b-instruct-v0.1'].cost // p:0.4, c:0.4
            const expectedInputCost = inputTokens * modelCost.prompt_token // 100 * 0.4
            const expectedOutputCost = outputTokens * modelCost.completion_token // 50 * 0.4

            expect(result.properties!.$ai_input_cost_usd).toBe(expectedInputCost)
            expect(result.properties!.$ai_output_cost_usd).toBe(expectedOutputCost)
            expect(result.properties!.$ai_total_cost_usd).toBe(expectedInputCost + expectedOutputCost)
        })

        it('correctly prioritizes Rule 2 (input specific) over Rule 3 (input general) for ambiguous cases like "gpt-4o"', () => {
            event.properties!.$ai_model = 'gpt-4o'
            const result = processAiEvent(event)

            const gpt4Cost = costsByModel['openai/gpt-4'].cost // p:0.2, c:0.2
            const expectedInputCost = inputTokens * gpt4Cost.prompt_token // 100 * 0.2
            const expectedOutputCost = outputTokens * gpt4Cost.completion_token // 50 * 0.2

            expect(result.properties!.$ai_input_cost_usd).toBe(expectedInputCost)
            expect(result.properties!.$ai_output_cost_usd).toBe(expectedOutputCost)
            expect(result.properties!.$ai_total_cost_usd).toBe(expectedInputCost + expectedOutputCost)
        })

        it('uses provider-specific gpt-4.1 pricing when available', () => {
            event.properties!.$ai_model = 'gpt-4.1-preview-0502'
            const result = processAiEvent(event)

            // OpenRouter contains openai/gpt-4.1 pricing, which should be preferred for provider-specific matches
            const modelCost = costsByModel['openai/gpt-4.1'].cost // p:0.9, c:0.9
            const expectedInputCost = inputTokens * modelCost.prompt_token // 100 * 0.9
            const expectedOutputCost = outputTokens * modelCost.completion_token // 50 * 0.9

            expect(result.properties!.$ai_model_cost_used).toBe('openai/gpt-4.1')
            expect(result.properties!.$ai_cost_model_provider).toBe('openai')
            expect(result.properties!.$ai_input_cost_usd).toBe(expectedInputCost)
            expect(result.properties!.$ai_output_cost_usd).toBe(expectedOutputCost)
            expect(result.properties!.$ai_total_cost_usd).toBe(expectedInputCost + expectedOutputCost)
        })

        it('returns undefined costs if no matching rule applies after all checks', () => {
            event.properties!.$ai_model = 'completely_unknown_model_structure_123_xyz_very_unique'
            const result = processAiEvent(event)
            expect(result.properties!.$ai_input_cost_usd).toBeUndefined()
            expect(result.properties!.$ai_output_cost_usd).toBeUndefined()
            expect(result.properties!.$ai_total_cost_usd).toBeUndefined()
        })
    })

    describe('reasoning token handling', () => {
        it('includes reasoning tokens for gemini-2.5-*', () => {
            event.properties!.$ai_provider = 'google'
            event.properties!.$ai_model = 'gemini-2.5-flash'
            event.properties!.$ai_input_tokens = 100
            event.properties!.$ai_output_tokens = 50
            event.properties!.$ai_reasoning_tokens = 200

            const result = processAiEvent(event)

            // For gemini-2.5-flash: prompt_token = 3e-7, completion_token = 0.0000025
            // Input cost: 100 * 3e-7 = 0.00003
            // Output cost: (50 + 200) * 0.0000025 = 250 * 0.0000025 = 0.000625
            // Total cost: 0.00003 + 0.000625 = 0.000655
            expect(result.properties!.$ai_input_cost_usd).toBeCloseTo(0.00003, 6)
            expect(result.properties!.$ai_output_cost_usd).toBeCloseTo(0.000625, 6)
            expect(result.properties!.$ai_total_cost_usd).toBeCloseTo(0.000655, 6)
        })

        it('handles undefined reasoning tokens for gemini-2.5-*', () => {
            event.properties!.$ai_provider = 'google'
            event.properties!.$ai_model = 'gemini-2.5-flash'
            event.properties!.$ai_input_tokens = 100
            event.properties!.$ai_output_tokens = 50
            // $ai_reasoning_tokens is intentionally undefined

            const result = processAiEvent(event)

            // For gemini-2.5-flash: prompt_token = 3e-7, completion_token = 0.0000025
            // Input cost: 100 * 3e-7 = 0.00003
            // Output cost: (50 + 0) * 0.0000025 = 50 * 0.0000025 = 0.000125 (undefined reasoning tokens treated as 0)
            // Total cost: 0.00003 + 0.000125 = 0.000155
            expect(result.properties!.$ai_input_cost_usd).toBeCloseTo(0.00003, 6)
            expect(result.properties!.$ai_output_cost_usd).toBeCloseTo(0.000125, 6)
            expect(result.properties!.$ai_total_cost_usd).toBeCloseTo(0.000155, 6)
        })

        it('does not include reasoning tokens for gemini-2.0-*', () => {
            event.properties!.$ai_provider = 'google'
            event.properties!.$ai_model = 'gemini-2.0-flash'
            event.properties!.$ai_input_tokens = 100
            event.properties!.$ai_output_tokens = 50
            event.properties!.$ai_reasoning_tokens = 200

            const result = processAiEvent(event)

            // Model will match gemini-2.0-flash-001: prompt_token = 1e-7, completion_token = 4e-7
            // Input cost: 100 * 1e-7 = 0.00001
            // Output cost: 50 * 4e-7 = 0.00002 (reasoning tokens ignored)
            // Total cost: 0.00001 + 0.00002 = 0.00003
            expect(result.properties!.$ai_input_cost_usd).toBeCloseTo(0.00001, 7)
            expect(result.properties!.$ai_output_cost_usd).toBeCloseTo(0.00002, 7)
            expect(result.properties!.$ai_total_cost_usd).toBeCloseTo(0.00003, 7)
        })

        it('does not include reasoning tokens for non gemini models', () => {
            event.properties!.$ai_provider = 'openai'
            event.properties!.$ai_model = 'o1-mini'
            event.properties!.$ai_input_tokens = 100
            event.properties!.$ai_output_tokens = 50
            event.properties!.$ai_reasoning_tokens = 200

            const result = processAiEvent(event)

            // For o1-mini: prompt_token = 0.0000011, completion_token = 0.0000044
            // Input cost: 100 * 0.0000011 = 0.00011
            // Output cost: 50 * 0.0000044 = 0.00022 (reasoning tokens ignored)
            // Total cost: 0.00011 + 0.00022 = 0.00033
            expect(result.properties!.$ai_input_cost_usd).toBeCloseTo(0.00011, 5)
            expect(result.properties!.$ai_output_cost_usd).toBeCloseTo(0.00022, 5)
            expect(result.properties!.$ai_total_cost_usd).toBeCloseTo(0.00033, 5)
        })
    })

    describe('gemini cache handling', () => {
        it.each([
            { provider: 'gemini', cacheWriteTokens: 0 },
            { provider: 'gemini', cacheWriteTokens: 300 },
            { provider: 'vertex', cacheWriteTokens: 300 },
            { provider: 'openrouter', cacheWriteTokens: 300 },
        ])('prices cache reads and $cacheWriteTokens writes for $provider', ({ provider, cacheWriteTokens }) => {
            event.properties!.$ai_provider = provider
            event.properties!.$ai_model = 'gemini-2.5-pro-preview'
            event.properties!.$ai_input_tokens = 1000
            event.properties!.$ai_cache_read_input_tokens = 400
            event.properties!.$ai_cache_creation_input_tokens = cacheWriteTokens
            event.properties!.$ai_output_tokens = 50

            const result = processAiEvent(event)

            // Regular tokens: 1000 - 400 = 600
            // Input cost: (600 * 0.00000125) + (400 * 3.1e-7) = 0.00075 + 0.000124 = 0.000874
            // Output cost: 50 * 0.00001 = 0.0005
            // Total cost: 0.000874 + 0.0005 = 0.001374
            expect(result.properties!.$ai_input_cost_usd).toBeCloseTo(0.000874, 6)
            expect(result.properties!.$ai_output_cost_usd).toBeCloseTo(0.0005, 6)
            expect(result.properties!.$ai_total_cost_usd).toBeCloseTo(0.001374, 6)
        })

        it('handles cache read tokens for gemini-2.5-pro-preview:large', () => {
            event.properties!.$ai_provider = 'gemini'
            event.properties!.$ai_model = 'gemini-2.5-pro-preview'
            event.properties!.$ai_input_tokens = 250000 // > 200k triggers large model
            event.properties!.$ai_cache_read_input_tokens = 100000
            event.properties!.$ai_output_tokens = 500

            const result = processAiEvent(event)

            // Model should be switched to gemini-2.5-pro-preview:large
            expect(result.properties!.$ai_model_cost_used).toBe('gemini-2.5-pro-preview:large')

            // Regular tokens: 250000 - 100000 = 150000
            // Input cost: (150000 * 0.0000025) + (100000 * 0.000000625) = 0.375 + 0.0625 = 0.4375
            // Output cost: 500 * 0.000015 = 0.0075
            // Total cost: 0.4375 + 0.0075 = 0.445
            expect(result.properties!.$ai_input_cost_usd).toBeCloseTo(0.4375, 6)
            expect(result.properties!.$ai_output_cost_usd).toBeCloseTo(0.0075, 6)
            expect(result.properties!.$ai_total_cost_usd).toBeCloseTo(0.445, 6)
        })

        it('handles cache read tokens for gemini-2.0-flash', () => {
            event.properties!.$ai_provider = 'gemini'
            event.properties!.$ai_model = 'gemini-2.0-flash'
            event.properties!.$ai_input_tokens = 1000
            event.properties!.$ai_cache_read_input_tokens = 400
            event.properties!.$ai_output_tokens = 50

            const result = processAiEvent(event)

            // Model will match gemini-2.0-flash-001 from generated-providers.json
            // Regular tokens: 1000 - 400 = 600
            // Input cost: (600 * 1e-7) + (400 * 2.5e-8) = 0.00006 + 0.00001 = 0.00007
            // Output cost: 50 * 4e-7 = 0.00002
            // Total cost: 0.00007 + 0.00002 = 0.00009
            expect(result.properties!.$ai_input_cost_usd).toBeCloseTo(0.00007, 7)
            expect(result.properties!.$ai_output_cost_usd).toBeCloseTo(0.00002, 7)
            expect(result.properties!.$ai_total_cost_usd).toBeCloseTo(0.00009, 7)
        })

        it('handles zero cache tokens correctly for gemini', () => {
            event.properties!.$ai_provider = 'gemini'
            event.properties!.$ai_model = 'gemini-2.5-pro-preview'
            event.properties!.$ai_input_tokens = 100
            event.properties!.$ai_cache_read_input_tokens = 0
            event.properties!.$ai_output_tokens = 50

            const result = processAiEvent(event)

            // Input cost: 100 * 0.00000125 = 0.000125
            // Output cost: 50 * 0.00001 = 0.0005
            // Total cost: 0.000125 + 0.0005 = 0.000625
            expect(result.properties!.$ai_input_cost_usd).toBeCloseTo(0.000125, 6)
            expect(result.properties!.$ai_output_cost_usd).toBeCloseTo(0.0005, 6)
            expect(result.properties!.$ai_total_cost_usd).toBeCloseTo(0.000625, 6)
        })

        it('handles combined cache and reasoning tokens for gemini-2.5-pro-preview', () => {
            event.properties!.$ai_provider = 'gemini'
            event.properties!.$ai_model = 'gemini-2.5-pro-preview'
            event.properties!.$ai_input_tokens = 1000
            event.properties!.$ai_cache_read_input_tokens = 400
            event.properties!.$ai_output_tokens = 50
            event.properties!.$ai_reasoning_tokens = 200

            const result = processAiEvent(event)

            // Regular tokens: 1000 - 400 = 600
            // Input cost: (600 * 0.00000125) + (400 * 3.1e-7) = 0.00075 + 0.000124 = 0.000874
            // Output cost: (50 + 200) * 0.00001 = 250 * 0.00001 = 0.0025
            // Total cost: 0.000874 + 0.0025 = 0.003374
            expect(result.properties!.$ai_input_cost_usd).toBeCloseTo(0.000874, 6)
            expect(result.properties!.$ai_output_cost_usd).toBeCloseTo(0.0025, 6)
            expect(result.properties!.$ai_total_cost_usd).toBeCloseTo(0.003374, 6)
        })

        it('handles gemini-2.5-flash with cache from generated providers', () => {
            event.properties!.$ai_provider = 'gemini'
            event.properties!.$ai_model = 'gemini-2.5-flash'
            event.properties!.$ai_input_tokens = 1000
            event.properties!.$ai_cache_read_input_tokens = 400
            event.properties!.$ai_output_tokens = 50
            event.properties!.$ai_reasoning_tokens = 100

            const result = processAiEvent(event)

            // Regular tokens: 1000 - 400 = 600
            // Input cost: (600 * 3e-7) + (400 * 7.5e-8) = 0.00018 + 0.00003 = 0.00021
            // Output cost: (50 + 100) * 0.0000025 = 150 * 0.0000025 = 0.000375
            // Total cost: 0.00021 + 0.000375 = 0.000585
            expect(result.properties!.$ai_input_cost_usd).toBeCloseTo(0.00021, 6)
            expect(result.properties!.$ai_output_cost_usd).toBeCloseTo(0.000375, 6)
            expect(result.properties!.$ai_total_cost_usd).toBeCloseTo(0.000585, 6)
        })
    })

    describe('request cost handling', () => {
        it('calculates request cost with model-based pricing and default count', () => {
            event.properties!.$ai_provider = 'perplexity'
            event.properties!.$ai_model = 'sonar-pro'
            event.properties!.$ai_input_tokens = 100
            event.properties!.$ai_output_tokens = 50

            const result = processAiEvent(event)

            // Token costs: (100 * 0.000001) + (50 * 0.000001) = 0.0001 + 0.00005 = 0.00015
            // Request cost: 1 * 0.005 = 0.005 (defaults to 1 when model has request cost)
            // Total: 0.00015 + 0.005 = 0.00515
            expect(result.properties!.$ai_input_cost_usd).toBeCloseTo(0.0001, 6)
            expect(result.properties!.$ai_output_cost_usd).toBeCloseTo(0.00005, 6)
            expect(result.properties!.$ai_request_cost_usd).toBeCloseTo(0.005, 6)
            expect(result.properties!.$ai_total_cost_usd).toBeCloseTo(0.00515, 6)
        })

        it('calculates request cost with explicit request count', () => {
            event.properties!.$ai_provider = 'perplexity'
            event.properties!.$ai_model = 'sonar-pro'
            event.properties!.$ai_input_tokens = 100
            event.properties!.$ai_output_tokens = 50
            event.properties!.$ai_request_count = 3

            const result = processAiEvent(event)

            // Token costs: 0.00015
            // Request cost: 3 * 0.005 = 0.015
            // Total: 0.00015 + 0.015 = 0.01515
            expect(result.properties!.$ai_request_cost_usd).toBeCloseTo(0.015, 6)
            expect(result.properties!.$ai_total_cost_usd).toBeCloseTo(0.01515, 6)
        })

        it('calculates request cost with zero count', () => {
            event.properties!.$ai_provider = 'perplexity'
            event.properties!.$ai_model = 'sonar-pro'
            event.properties!.$ai_input_tokens = 100
            event.properties!.$ai_output_tokens = 50
            event.properties!.$ai_request_count = 0

            const result = processAiEvent(event)

            // Request cost: 0 * 0.005 = 0
            expect(result.properties!.$ai_request_cost_usd).toBe(0)
            expect(result.properties!.$ai_total_cost_usd).toBeCloseTo(0.00015, 6)
        })

        it('does not calculate request cost for models without request pricing', () => {
            event.properties!.$ai_model = 'gpt-4'
            event.properties!.$ai_provider = 'openai'
            event.properties!.$ai_input_tokens = 100
            event.properties!.$ai_output_tokens = 50
            event.properties!.$ai_request_count = 5

            const result = processAiEvent(event)

            // gpt-4 does not have request pricing
            expect(result.properties!.$ai_request_cost_usd).toBe(0)
            expect(result.properties!.$ai_total_cost_usd).toBe(30) // Only token costs
        })

        it('uses custom request pricing when provided', () => {
            event.properties!.$ai_input_token_price = 0.000001
            event.properties!.$ai_output_token_price = 0.000001
            event.properties!.$ai_request_price = 0.01
            event.properties!.$ai_input_tokens = 100
            event.properties!.$ai_output_tokens = 50
            event.properties!.$ai_request_count = 2

            const result = processAiEvent(event)

            // Token costs: (100 * 0.000001) + (50 * 0.000001) = 0.00015
            // Request cost: 2 * 0.01 = 0.02
            // Total: 0.00015 + 0.02 = 0.02015
            expect(result.properties!.$ai_input_cost_usd).toBeCloseTo(0.0001, 6)
            expect(result.properties!.$ai_output_cost_usd).toBeCloseTo(0.00005, 6)
            expect(result.properties!.$ai_request_cost_usd).toBeCloseTo(0.02, 6)
            expect(result.properties!.$ai_total_cost_usd).toBeCloseTo(0.02015, 6)
            expect(result.properties!.$ai_model_cost_used).toBe('custom')
        })

        it('handles pre-calculated request cost', () => {
            event.properties!.$ai_input_cost_usd = 0.01
            event.properties!.$ai_output_cost_usd = 0.02
            event.properties!.$ai_request_cost_usd = 0.005

            const result = processAiEvent(event)

            // Should use pre-calculated costs
            expect(result.properties!.$ai_input_cost_usd).toBe(0.01)
            expect(result.properties!.$ai_output_cost_usd).toBe(0.02)
            expect(result.properties!.$ai_request_cost_usd).toBe(0.005)
            expect(result.properties!.$ai_total_cost_usd).toBe(0.035)
        })

        it('includes request cost in total when using custom pricing without count', () => {
            event.properties!.$ai_input_token_price = 0.000001
            event.properties!.$ai_output_token_price = 0.000001
            event.properties!.$ai_request_price = 0.003
            event.properties!.$ai_input_tokens = 100
            event.properties!.$ai_output_tokens = 50

            const result = processAiEvent(event)

            // Custom pricing defaults request count to 1 if request price is provided
            expect(result.properties!.$ai_request_cost_usd).toBeCloseTo(0.003, 6)
            expect(result.properties!.$ai_total_cost_usd).toBeCloseTo(0.00315, 6)
        })
    })

    describe('web search cost handling', () => {
        it('calculates web search cost with model-based pricing and explicit count', () => {
            event.properties!.$ai_provider = 'perplexity'
            event.properties!.$ai_model = 'sonar-pro'
            event.properties!.$ai_input_tokens = 100
            event.properties!.$ai_output_tokens = 50
            event.properties!.$ai_web_search_count = 2

            const result = processAiEvent(event)

            // Token costs: 0.00015
            // Request cost: 1 * 0.005 = 0.005 (defaults to 1)
            // Web search cost: 2 * 0.005 = 0.01
            // Total: 0.00015 + 0.005 + 0.01 = 0.01515
            expect(result.properties!.$ai_web_search_cost_usd).toBeCloseTo(0.01, 6)
            expect(result.properties!.$ai_total_cost_usd).toBeCloseTo(0.01515, 6)
        })

        it('does not calculate web search cost without explicit count', () => {
            event.properties!.$ai_provider = 'perplexity'
            event.properties!.$ai_model = 'sonar-pro'
            event.properties!.$ai_input_tokens = 100
            event.properties!.$ai_output_tokens = 50

            const result = processAiEvent(event)

            // No web search count provided, should be 0
            expect(result.properties!.$ai_web_search_cost_usd).toBe(0)
        })

        it('calculates web search cost with zero count', () => {
            event.properties!.$ai_provider = 'perplexity'
            event.properties!.$ai_model = 'sonar-pro'
            event.properties!.$ai_input_tokens = 100
            event.properties!.$ai_output_tokens = 50
            event.properties!.$ai_web_search_count = 0

            const result = processAiEvent(event)

            // Web search cost: 0 * 0.005 = 0
            expect(result.properties!.$ai_web_search_cost_usd).toBe(0)
        })

        it('does not calculate web search cost for models without web search pricing', () => {
            event.properties!.$ai_model = 'gpt-4'
            event.properties!.$ai_provider = 'openai'
            event.properties!.$ai_input_tokens = 100
            event.properties!.$ai_output_tokens = 50
            event.properties!.$ai_web_search_count = 3

            const result = processAiEvent(event)

            // gpt-4 does not have web search pricing
            expect(result.properties!.$ai_web_search_cost_usd).toBe(0)
        })

        it('uses custom web search pricing when provided', () => {
            event.properties!.$ai_input_token_price = 0.000001
            event.properties!.$ai_output_token_price = 0.000001
            event.properties!.$ai_web_search_price = 0.008
            event.properties!.$ai_input_tokens = 100
            event.properties!.$ai_output_tokens = 50
            event.properties!.$ai_web_search_count = 3

            const result = processAiEvent(event)

            // Token costs: 0.00015
            // Web search cost: 3 * 0.008 = 0.024
            // Total: 0.00015 + 0.024 = 0.02415
            expect(result.properties!.$ai_web_search_cost_usd).toBeCloseTo(0.024, 6)
            expect(result.properties!.$ai_total_cost_usd).toBeCloseTo(0.02415, 6)
            expect(result.properties!.$ai_model_cost_used).toBe('custom')
        })

        it('does not calculate custom web search cost without count', () => {
            event.properties!.$ai_input_token_price = 0.000001
            event.properties!.$ai_output_token_price = 0.000001
            event.properties!.$ai_web_search_price = 0.008
            event.properties!.$ai_input_tokens = 100
            event.properties!.$ai_output_tokens = 50

            const result = processAiEvent(event)

            // No web search count, should not calculate
            expect(result.properties!.$ai_web_search_cost_usd).toBe(0)
            expect(result.properties!.$ai_total_cost_usd).toBeCloseTo(0.00015, 6)
        })

        it('handles pre-calculated web search cost', () => {
            event.properties!.$ai_input_cost_usd = 0.01
            event.properties!.$ai_output_cost_usd = 0.02
            event.properties!.$ai_web_search_cost_usd = 0.015

            const result = processAiEvent(event)

            // Should use pre-calculated costs
            expect(result.properties!.$ai_web_search_cost_usd).toBe(0.015)
            expect(result.properties!.$ai_total_cost_usd).toBe(0.045)
        })
    })

    describe('combined request and web search costs', () => {
        it('calculates all cost components together', () => {
            event.properties!.$ai_provider = 'perplexity'
            event.properties!.$ai_model = 'sonar-pro'
            event.properties!.$ai_input_tokens = 1000
            event.properties!.$ai_output_tokens = 500
            event.properties!.$ai_request_count = 2
            event.properties!.$ai_web_search_count = 3

            const result = processAiEvent(event)

            // Token costs: (1000 * 0.000001) + (500 * 0.000001) = 0.0015
            // Request cost: 2 * 0.005 = 0.01
            // Web search cost: 3 * 0.005 = 0.015
            // Total: 0.0015 + 0.01 + 0.015 = 0.0265
            expect(result.properties!.$ai_input_cost_usd).toBeCloseTo(0.001, 6)
            expect(result.properties!.$ai_output_cost_usd).toBeCloseTo(0.0005, 6)
            expect(result.properties!.$ai_request_cost_usd).toBeCloseTo(0.01, 6)
            expect(result.properties!.$ai_web_search_cost_usd).toBeCloseTo(0.015, 6)
            expect(result.properties!.$ai_total_cost_usd).toBeCloseTo(0.0265, 6)
        })

        it('calculates all cost components with custom pricing', () => {
            event.properties!.$ai_input_token_price = 0.000002
            event.properties!.$ai_output_token_price = 0.000003
            event.properties!.$ai_request_price = 0.007
            event.properties!.$ai_web_search_price = 0.01
            event.properties!.$ai_input_tokens = 500
            event.properties!.$ai_output_tokens = 200
            event.properties!.$ai_request_count = 1
            event.properties!.$ai_web_search_count = 2

            const result = processAiEvent(event)

            // Token costs: (500 * 0.000002) + (200 * 0.000003) = 0.001 + 0.0006 = 0.0016
            // Request cost: 1 * 0.007 = 0.007
            // Web search cost: 2 * 0.01 = 0.02
            // Total: 0.0016 + 0.007 + 0.02 = 0.0286
            expect(result.properties!.$ai_input_cost_usd).toBeCloseTo(0.001, 6)
            expect(result.properties!.$ai_output_cost_usd).toBeCloseTo(0.0006, 6)
            expect(result.properties!.$ai_request_cost_usd).toBeCloseTo(0.007, 6)
            expect(result.properties!.$ai_web_search_cost_usd).toBeCloseTo(0.02, 6)
            expect(result.properties!.$ai_total_cost_usd).toBeCloseTo(0.0286, 6)
        })

        it('handles all pre-calculated costs together', () => {
            event.properties!.$ai_input_cost_usd = 0.1
            event.properties!.$ai_output_cost_usd = 0.2
            event.properties!.$ai_request_cost_usd = 0.05
            event.properties!.$ai_web_search_cost_usd = 0.03

            const result = processAiEvent(event)

            expect(result.properties!.$ai_total_cost_usd).toBe(0.38)
        })

        it('includes request cost but not web search when only request count provided', () => {
            event.properties!.$ai_provider = 'perplexity'
            event.properties!.$ai_model = 'sonar-pro'
            event.properties!.$ai_input_tokens = 100
            event.properties!.$ai_output_tokens = 50
            event.properties!.$ai_request_count = 1

            const result = processAiEvent(event)

            // Token + request, no web search
            expect(result.properties!.$ai_request_cost_usd).toBeCloseTo(0.005, 6)
            expect(result.properties!.$ai_web_search_cost_usd).toBe(0)
            expect(result.properties!.$ai_total_cost_usd).toBeCloseTo(0.00515, 6)
        })
    })
})

describe('normalizeTraceProperties()', () => {
    it('logs warning for invalid trace property types', () => {
        const event: PluginEvent = {
            event: '$ai_span',
            properties: {
                $ai_trace_id: { invalid: 'object' },
                $ai_parent_id: ['invalid', 'array'],
            },
            ip: '',
            site_url: '',
            team_id: 0,
            now: '',
            distinct_id: '',
            uuid: '',
            timestamp: '',
        }

        jest.clearAllMocks()
        normalizeTraceProperties(event as any)

        expect(mockWarn).toHaveBeenCalledWith('Unexpected type for trace property $ai_trace_id: object')
        expect(mockWarn).toHaveBeenCalledWith('Unexpected type for trace property $ai_parent_id: object')
    })

    it('handles BigInt trace properties', () => {
        const bigIntValue = BigInt('12345678901234567890')
        const event: PluginEvent = {
            event: '$ai_span',
            properties: {
                $ai_trace_id: bigIntValue as any,
                $ai_parent_id: BigInt(123) as any,
            },
            ip: '',
            site_url: '',
            team_id: 0,
            now: '',
            distinct_id: '',
            uuid: '',
            timestamp: '',
        }
        const result = normalizeTraceProperties(event as any)
        expect(result.properties!.$ai_trace_id).toBe('12345678901234567890')
        expect(result.properties!.$ai_parent_id).toBe('123')
    })

    it('converts numeric trace_id to string', () => {
        const event: PluginEvent = {
            event: '$ai_span',
            properties: {
                $ai_trace_id: 12345,
                $ai_parent_id: 67890,
            },
            ip: '',
            site_url: '',
            team_id: 0,
            now: '',
            distinct_id: '',
            uuid: '',
            timestamp: '',
        }
        const result = normalizeTraceProperties(event as any)
        expect(result.properties!.$ai_trace_id).toBe('12345')
        expect(result.properties!.$ai_parent_id).toBe('67890')
    })

    it('preserves string trace_id', () => {
        const event: PluginEvent = {
            event: '$ai_span',
            properties: {
                $ai_trace_id: 'abc-123',
                $ai_parent_id: 'def-456',
            },
            ip: '',
            site_url: '',
            team_id: 0,
            now: '',
            distinct_id: '',
            uuid: '',
            timestamp: '',
        }
        const result = normalizeTraceProperties(event as any)
        expect(result.properties!.$ai_trace_id).toBe('abc-123')
        expect(result.properties!.$ai_parent_id).toBe('def-456')
    })

    it('handles null and undefined values', () => {
        const event: PluginEvent = {
            event: '$ai_span',
            properties: {
                $ai_trace_id: null,
                $ai_parent_id: undefined,
            },
            ip: '',
            site_url: '',
            team_id: 0,
            now: '',
            distinct_id: '',
            uuid: '',
            timestamp: '',
        }
        const result = normalizeTraceProperties(event as any)
        expect(result.properties!.$ai_trace_id).toBe(null)
        expect(result.properties!.$ai_parent_id).toBe(undefined)
    })

    it('normalizes span_id and generation_id', () => {
        const event: PluginEvent = {
            event: '$ai_generation',
            properties: {
                $ai_span_id: 111,
                $ai_generation_id: 222,
            },
            ip: '',
            site_url: '',
            team_id: 0,
            now: '',
            distinct_id: '',
            uuid: '',
            timestamp: '',
        }
        const result = normalizeTraceProperties(event as any)
        expect(result.properties!.$ai_span_id).toBe('111')
        expect(result.properties!.$ai_generation_id).toBe('222')
    })

    it('handles boolean trace IDs', () => {
        const event: PluginEvent = {
            event: '$ai_span',
            properties: {
                $ai_trace_id: true,
                $ai_parent_id: false,
            },
            ip: '',
            site_url: '',
            team_id: 0,
            now: '',
            distinct_id: '',
            uuid: '',
            timestamp: '',
        }
        const result = normalizeTraceProperties(event as any)
        expect(result.properties!.$ai_trace_id).toBe('true')
        expect(result.properties!.$ai_parent_id).toBe('false')
    })

    it('sets arrays to undefined', () => {
        const event: PluginEvent = {
            event: '$ai_span',
            properties: {
                $ai_trace_id: [1, 2, 3],
                $ai_parent_id: ['a', 'b', 'c'],
            },
            ip: '',
            site_url: '',
            team_id: 0,
            now: '',
            distinct_id: '',
            uuid: '',
            timestamp: '',
        }
        const result = normalizeTraceProperties(event as any)
        expect(result.properties!.$ai_trace_id).toBe(undefined)
        expect(result.properties!.$ai_parent_id).toBe(undefined)
    })

    it('sets objects to undefined', () => {
        const event: PluginEvent = {
            event: '$ai_span',
            properties: {
                $ai_trace_id: { id: 123, type: 'trace' },
                $ai_parent_id: { nested: { value: 456 } },
            },
            ip: '',
            site_url: '',
            team_id: 0,
            now: '',
            distinct_id: '',
            uuid: '',
            timestamp: '',
        }
        const result = normalizeTraceProperties(event as any)
        expect(result.properties!.$ai_trace_id).toBe(undefined)
        expect(result.properties!.$ai_parent_id).toBe(undefined)
    })

    it('handles mixed valid and invalid types', () => {
        const event: PluginEvent = {
            event: '$ai_span',
            properties: {
                $ai_trace_id: 123,
                $ai_parent_id: 'string-id',
                $ai_span_id: [1, 2],
                $ai_generation_id: { id: 'gen' },
            },
            ip: '',
            site_url: '',
            team_id: 0,
            now: '',
            distinct_id: '',
            uuid: '',
            timestamp: '',
        }
        const result = normalizeTraceProperties(event as any)
        expect(result.properties!.$ai_trace_id).toBe('123')
        expect(result.properties!.$ai_parent_id).toBe('string-id') // Already a string
        expect(result.properties!.$ai_span_id).toBe(undefined)
        expect(result.properties!.$ai_generation_id).toBe(undefined)
    })
})

describe('processAiEvent() trace normalization', () => {
    it('normalizes trace properties for all AI event types', () => {
        const eventTypes = ['$ai_generation', '$ai_embedding', '$ai_span', '$ai_trace', '$ai_metric', '$ai_feedback']

        for (const eventType of eventTypes) {
            const event: PluginEvent = {
                event: eventType,
                properties: {
                    $ai_trace_id: 123,
                    $ai_parent_id: 456,
                    $ai_model: 'testing_model',
                    $ai_input_tokens: 100,
                    $ai_output_tokens: 50,
                },
                ip: '',
                site_url: '',
                team_id: 0,
                now: '',
                distinct_id: '',
                uuid: '',
                timestamp: '',
            }
            const result = processAiEvent(event)
            expect(result.properties!.$ai_trace_id).toBe('123')
            expect(result.properties!.$ai_parent_id).toBe('456')
        }
    })

    it('normalizes trace properties even for non-cost events', () => {
        const event: PluginEvent = {
            event: '$ai_metric',
            properties: {
                $ai_trace_id: 999,
                $ai_metric_name: 'test_metric',
                $ai_metric_value: 42,
            },
            ip: '',
            site_url: '',
            team_id: 0,
            now: '',
            distinct_id: '',
            uuid: '',
            timestamp: '',
        }
        const result = processAiEvent(event)
        expect(result.properties!.$ai_trace_id).toBe('999')
        // Should not have cost fields added
        expect(result.properties!.$ai_total_cost_usd).toBeUndefined()
    })

    it('normalizes trace properties on an unlisted $ai_* event without adding costs', () => {
        const event: PluginEvent = {
            event: '$ai_custom_step',
            properties: {
                $ai_trace_id: 123,
                $ai_parent_id: 456,
                $ai_model: 'gpt-4',
                $ai_input_tokens: 10,
            },
            ip: '',
            site_url: '',
            team_id: 0,
            now: '',
            distinct_id: '',
            uuid: '',
            timestamp: '',
        }
        const result = processAiEvent(event)
        expect(result.properties!.$ai_trace_id).toBe('123')
        expect(result.properties!.$ai_parent_id).toBe('456')
        expect(result.properties!.$ai_total_cost_usd).toBeUndefined()
    })

    it('does not normalize non-AI events', () => {
        const event: PluginEvent = {
            event: '$pageview',
            properties: {
                $ai_trace_id: 123,
                $ai_parent_id: 456,
            },
            ip: '',
            site_url: '',
            team_id: 0,
            now: '',
            distinct_id: '',
            uuid: '',
            timestamp: '',
        }
        const result = processAiEvent(event)
        // Should not be normalized since it's not an AI event
        expect(result.properties!.$ai_trace_id).toBe(123)
        expect(result.properties!.$ai_parent_id).toBe(456)
    })
})