import { describe, it, expect, vi, beforeEach, afterEach } from 'vitest';

describe('P4: arena-model-call X-Boo-Source header', () => {
  const originalFetch = globalThis.fetch;

  beforeEach(() => {
    vi.stubGlobal(
      'fetch',
      vi.fn(() =>
        new Response(
          JSON.stringify({
            choices: [{ message: { content: 'analysis result' } }],
          }),
          { status: 200, headers: { 'content-type': 'application/json' } },
        ),
      ),
    );
  });

  afterEach(() => {
    vi.unstubAllGlobals();
  });

  it('sets X-Boo-Source: arena on model calls', async () => {
    const fetchMock = vi.fn(() =>
      new Response(
        JSON.stringify({
          choices: [{ message: { content: 'result' } }],
        }),
        { status: 200, headers: { 'content-type': 'application/json' } },
      ),
    );
    vi.stubGlobal('fetch', fetchMock);

    // Load providers fixture
    const { writeFileSync } = await import('node:fs');
    const { tmpdir } = await import('node:os');
    const { join } = await import('node:path');
    const providerFile = {
      defaultProvider: 'sam-desktop',
      providers: [
        { id: 'sam-desktop', label: 'Sam Desktop', baseUrl: 'http://test:8401', kind: 'llama-swap' },
      ],
    };
    const path = join(tmpdir(), `test-providers-${Date.now()}.json`);
    writeFileSync(path, JSON.stringify(providerFile), 'utf8');

    const { loadLlamaProviders } = await import('../llama-providers.js');
    loadLlamaProviders(path, 'http://localhost:8080');

    const { arenaModelCall } = await import('../arena-model-call.js');
    const result = await arenaModelCall({
      model: 'sam-desktop/test-model',
      system: 'You are a judge.',
      user: 'Evaluate this response.',
      temperature: 0,
    });

    expect(result).toBe('result');
    expect(fetchMock).toHaveBeenCalledTimes(1);
    const callHeaders = (fetchMock.mock.calls[0] as [string, RequestInit])[1]?.headers as Record<string, string>;
    expect(callHeaders['X-Boo-Source']).toBe('arena');
  });
});
