import type { AIProviderRegistryStatusEntry, ChatMessage } from '@genesislcap/foundation-ai';
import { assert, createLogicSuite } from '@genesislcap/foundation-testing';
import { collectSessionModels } from './collect-session-models';

const assistantMsg = (overrides: Partial<ChatMessage> = {}): ChatMessage => ({
  role: 'assistant',
  content: '',
  ...overrides,
});

const statusEntry = (
  name: string,
  model: string,
  provider: AIProviderRegistryStatusEntry['status'] extends infer S
    ? S extends { provider: infer P }
      ? P
      : never
    : never,
): AIProviderRegistryStatusEntry => ({
  name,
  isDefault: false,
  status: { model, provider },
});

const suite = createLogicSuite('collectSessionModels');

suite('collects unique models from assistant messages', () => {
  const models = collectSessionModels(
    [
      assistantMsg({ model: 'claude-sonnet-4-6' }),
      assistantMsg({ model: 'claude-haiku-4-5-20251001' }),
      assistantMsg({ model: 'claude-sonnet-4-6', provider: 'anthropic' }),
      assistantMsg({ model: 'gemini-2.5-pro', providerName: 'high', provider: 'gemini' }),
    ],
    [],
  );
  assert.is(models.length, 3);
  assert.is(models[0]?.model, 'claude-sonnet-4-6');
  assert.is(models[0]?.provider, 'anthropic');
  assert.is(models[2]?.model, 'gemini-2.5-pro');
  assert.is(models[2]?.provider, 'gemini');
});

suite('resolves vendor from providerStatuses when messages lack provider', () => {
  const models = collectSessionModels(
    [assistantMsg({ model: 'gemini-3.1-flash-lite', providerName: 'low' })],
    [statusEntry('low', 'gemini-3.1-flash-lite', 'gemini')],
  );
  assert.is(models.length, 1);
  assert.is(models[0]?.provider, 'gemini');
});

suite('does not persist registry tier names as provider', () => {
  const models = collectSessionModels(
    [assistantMsg({ model: 'gemini-3.1-flash-lite', providerName: 'low' })],
    [],
  );
  assert.is(models[0]?.provider, undefined);
  assert.is('providerName' in (models[0] ?? {}), false);
});

suite('includes models from sub-agent traces', () => {
  const models = collectSessionModels(
    [
      assistantMsg({
        toolCalls: [
          {
            id: 'tc1',
            name: 'spawn',
            args: {},
            subAgentTrace: [assistantMsg({ model: 'claude-haiku-4-5-20251001' })],
          },
        ],
      }),
    ],
    [],
  );
  assert.is(models.length, 1);
  assert.is(models[0]?.model, 'claude-haiku-4-5-20251001');
});

suite.run();
