import { describe, it, expect, vi, beforeEach, afterEach } from 'vitest';
import { resolveModelEndpoint } from '../arena-model-call.js';

// Mock the llama-providers module so resolveModelEndpoint resolves against
// our test registry instead of the startup-time cached config.
const mockProviders = {
  defaultProvider: 'sam-desktop',
  providers: [
    {
      id: 'sam-desktop',
      label: 'Sam Desktop',
      baseUrl: 'http://100.101.41.16:8080',
      kind: 'llama-swap',
    },
    {
      id: 'embedding',
      label: 'Embedding Box',
      baseUrl: 'http://100.101.41.17:8080',
      kind: 'llama-swap',
    },
  ],
};

vi.mock('../llama-providers.js', () => ({
  getLlamaProviders: () => mockProviders,
  parseModelRef: (ref: string) => {
    const slashIdx = ref.indexOf('/');
    if (slashIdx <= 0) {
      return { providerId: mockProviders.defaultProvider, wireModelId: ref, isLegacyBareId: true };
    }
    return {
      providerId: ref.slice(0, slashIdx),
      wireModelId: ref.slice(slashIdx + 1),
      isLegacyBareId: false,
    };
  },
}));

// ─── resolveModelEndpoint ───────────────────────────────────────────────────

describe('resolveModelEndpoint', () => {
  it('resolves a composite provider/model id to the correct baseUrl', () => {
    const result = resolveModelEndpoint('sam-desktop/qwen3.6-35b-a3b-mxfp4');
    expect(result.baseUrl).toBe('http://100.101.41.16:8080');
    expect(result.wireModelId).toBe('qwen3.6-35b-a3b-mxfp4');
  });

  it('routes duplicate wire names to different baseUrls by provider', () => {
    // Same wire model on two providers
    const r1 = resolveModelEndpoint('sam-desktop/qwen3.6-35b-a3b-mxfp4');
    const r2 = resolveModelEndpoint('embedding/qwen3.6-35b-a3b-mxfp4');
    expect(r1.baseUrl).toBe('http://100.101.41.16:8080');
    expect(r1.wireModelId).toBe('qwen3.6-35b-a3b-mxfp4');
    expect(r2.baseUrl).toBe('http://100.101.41.17:8080');
    expect(r2.wireModelId).toBe('qwen3.6-35b-a3b-mxfp4');
  });

  it('resolves bare legacy ids to the default provider', () => {
    const result = resolveModelEndpoint('qwen3.6-35b-a3b-mxfp4');
    expect(result.baseUrl).toBe('http://100.101.41.16:8080');
    expect(result.wireModelId).toBe('qwen3.6-35b-a3b-mxfp4');
  });

  it('throws for an unknown provider prefix', () => {
    expect(() => resolveModelEndpoint('nonexistent/model')).toThrow('unknown provider: nonexistent');
  });

  it('handles models with slashes in the wire id', () => {
    const result = resolveModelEndpoint('sam-desktop/models/qwen3.6-35b');
    expect(result.baseUrl).toBe('http://100.101.41.16:8080');
    expect(result.wireModelId).toBe('models/qwen3.6-35b');
  });
});
