import { describe, it, expect } from 'vitest';
import { createInterface } from 'readline/promises';
import { EventEmitter } from 'events';
import { createPrompter } from './prompts.js';
import { ConfigBuilder } from './config.js';
import { setupProviders } from './providers.js';

function mockReadline(inputs: string[]) {
  let questionIdx = 0;
  const emitter = new EventEmitter();

  return {
    async question(query: string) {
      const answer = inputs[questionIdx++];
      return answer ?? '';
    },

    close() {
      // no-op
    },

    [Symbol.asyncIterator]() {
      return this;
    },

    async next() {
      return { done: true };
    },
  } as any;
}

describe('setupProviders', () => {
  it('configures anthropic as default provider', async () => {
    const rl = mockReadline(['1', 'sk-ant-test123', '', 'n']);
    const p = createPrompter(rl);
    const builder = new ConfigBuilder();
    await setupProviders(p, builder);
    const config = builder.build();
    expect(config.models.default.provider).toBe('anthropic');
    expect(config.models.default.api_key).toBe('sk-ant-test123');
    expect(config.models.default.model).toBe('claude-sonnet-4-20250514');
  });

  it('configures ollama as default provider', async () => {
    const rl = mockReadline(['3', '', '', 'n']);
    const p = createPrompter(rl);
    const builder = new ConfigBuilder();
    await setupProviders(p, builder);
    const config = builder.build();
    expect(config.models.default.provider).toBe('ollama');
    expect(config.models.default.endpoint).toBe('http://localhost:11434');
  });

  it('configures anthropic with fast tier', async () => {
    const rl = mockReadline(['1', 'sk-ant-test123', '', 'y', '']);
    const p = createPrompter(rl);
    const builder = new ConfigBuilder();
    await setupProviders(p, builder);
    const config = builder.build();
    expect(config.models.default.provider).toBe('anthropic');
    expect(config.models.fast).toBeDefined();
    expect(config.models.fast.provider).toBe('anthropic');
  });

  it('configures vercel gateway as default provider (second tier)', async () => {
    // Pick "More providers..." then pick "Vercel AI Gateway".
    // Prompts: api key, endpoint, model, then confirm fast tier.
    const rl = mockReadline(['4', '3', 'sk-vercel-test123', '', '', 'n']);
    const p = createPrompter(rl);
    const builder = new ConfigBuilder();
    await setupProviders(p, builder);
    const config = builder.build();
    expect(config.models.default.provider).toBe('vercel');
    expect(config.models.default.api_key).toBe('sk-vercel-test123');
    expect(config.models.default.endpoint).toBe('https://ai-gateway.vercel.sh/v1');
    expect(config.models.default.model).toBe('openai/gpt-4.1');
  });
});
