import { describe, expect, it } from 'vitest';
import { parseNativeV0, parseNativeV1, parseOpenAi, pickLoaded, inferHostStatus } from '../src/core/lmsModels';

describe('follow-the-loaded-model — the load button is the control surface', () => {
  it('native v1: loaded_instances decides (shape captured from a live LM Studio)', () => {
    const models = parseNativeV1({
      models: [
        { type: 'llm', key: 'qwen/qwen3.6-35b-a3b', loaded_instances: [] },
        { type: 'llm', key: 'google/gemma-4-e2b', loaded_instances: [{ id: 'i1' }] },
        { type: 'embedding', key: 'text-embedding-nomic', loaded_instances: [{ id: 'i2' }] },
      ],
    })!;
    expect(pickLoaded(models)).toBe('google/gemma-4-e2b');
  });

  it('native v0: state field decides', () => {
    const models = parseNativeV0({
      data: [
        { id: 'qwen/qwen3.6-35b-a3b', type: 'vlm', state: 'not-loaded' },
        { id: 'nvidia/nemotron-3-nano-4b', type: 'llm', state: 'loaded' },
      ],
    })!;
    expect(pickLoaded(models)).toBe('nvidia/nemotron-3-nano-4b');
  });

  it('nothing loaded → null (never guess, never JIT-load a 22 GB model)', () => {
    const models = parseNativeV1({
      models: [{ type: 'llm', key: 'a', loaded_instances: [] }, { type: 'llm', key: 'b', loaded_instances: [] }],
    })!;
    expect(pickLoaded(models)).toBeNull();
  });

  it('embedding models are never picked even when loaded', () => {
    const models = parseNativeV1({
      models: [{ type: 'embedding', key: 'text-embedding-x', loaded_instances: [{}] }],
    })!;
    expect(pickLoaded(models)).toBeNull();
  });

  it('plain OpenAI shape has no load state — parser reports order only', () => {
    const models = parseOpenAi({ data: [{ id: 'gpt-x' }, { id: 'gpt-y' }] })!;
    expect(models.map(m => m.id)).toEqual(['gpt-x', 'gpt-y']);
    expect(models.every(m => !m.loaded)).toBe(true);
  });

  it('v0 parser refuses OpenAI-shaped data (no state field) so fallback chain works', () => {
    expect(parseNativeV0({ data: [{ id: 'gpt-x' }] })).toBeNull();
  });

  it('SET 22 — ready status is idle; generating is busy', () => {
    expect(inferHostStatus([
      { id: 'm', loaded: true, status: 'ready' },
    ])).toBe('idle');
    expect(inferHostStatus([
      { id: 'm', loaded: true, status: 'busy' },
    ])).toBe('busy');
  });
});
