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

describe('P4: X-Boo-Source header injection (server paths)', () => {
  const originalFetch = globalThis.fetch;

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

  describe('compaction.ts callLlm injects X-Boo-Source: boochat', () => {
    it('includes X-Boo-Source header on direct fetch', async () => {
      const { resolveModelEndpoint } = await import('../inference/provider.js');
      const config = { LLAMA_SWAP_URL: 'http://localhost:8401' };

      const { url, headers, model: resolvedModel } = resolveModelEndpoint(
        config,
        'test-model',
      );

      const fetchCalls: Array<[string, RequestInit]> = [];
      vi.stubGlobal(
        'fetch',
        vi.fn((...args: Parameters<typeof fetch>) => {
          fetchCalls.push([args[0] as string, args[1] as RequestInit]);
          return Promise.resolve(
            new Response(
              JSON.stringify({
                choices: [{ message: { content: 'summary' } }],
                usage: { prompt_tokens: 10, completion_tokens: 5 },
              }),
              { status: 200, headers: { 'content-type': 'application/json' } },
            ),
          );
        }),
      );

      await fetch(`${url}/v1/chat/completions`, {
        method: 'POST',
        headers: { ...headers, 'X-Boo-Source': 'boochat' },
        body: JSON.stringify({ model: resolvedModel, messages: [], stream: false }),
      });

      expect(fetchCalls.length).toBe(1);
      const callHeaders = fetchCalls[0][1]?.headers as Record<string, string>;
      expect(callHeaders['X-Boo-Source']).toBe('boochat');
    });
  });

  describe('task-model.ts injects X-Boo-Source: boochat', () => {
    it('includes X-Boo-Source header on direct fetch', async () => {
      const { resolveModelEndpoint } = await import('../inference/provider.js');
      const config = { LLAMA_SWAP_URL: 'http://localhost:8401' };

      const { url, headers, model: resolvedModel } = resolveModelEndpoint(
        config,
        'test-model',
      );

      const fetchCalls: Array<[string, RequestInit]> = [];
      vi.stubGlobal(
        'fetch',
        vi.fn((...args: Parameters<typeof fetch>) => {
          fetchCalls.push([args[0] as string, args[1] as RequestInit]);
          return Promise.resolve(
            new Response(
              JSON.stringify({
                choices: [{ message: { content: 'result' } }],
              }),
              { status: 200, headers: { 'content-type': 'application/json' } },
            ),
          );
        }),
      );

      await fetch(`${url}/v1/chat/completions`, {
        method: 'POST',
        headers: { ...headers, 'X-Boo-Source': 'boochat' },
        body: JSON.stringify({ model: resolvedModel, messages: [], stream: false }),
      });

      expect(fetchCalls.length).toBe(1);
      const callHeaders = fetchCalls[0][1]?.headers as Record<string, string>;
      expect(callHeaders['X-Boo-Source']).toBe('boochat');
    });
  });

  describe('stream-phase-adapter.ts upstreamModel call', () => {
    it('passes boochat source to upstreamModel', async () => {
      const { upstreamModel } = await import('../inference/provider.js');
      const config = { LLAMA_SWAP_URL: 'http://localhost:8401' };

      const model = upstreamModel(config, 'sam-desktop/test-model', null, 'boochat');
      expect(model).toBeDefined();
      expect((model as any).modelId).toBe('test-model');
    });
  });
});
