import { describe, it, expect, vi } from 'vitest';
import { formatPrompt, parseCommand } from './minimal.js';
import type { ModelConfig } from '../../config/schema.js';
import { MinimalTui } from './minimal.js';

describe('formatPrompt', () => {
  it('formats default prompt', () => {
    const prompt = formatPrompt('default');
    expect(prompt).toContain('flynn>');
  });

  it('formats thinking prompt', () => {
    const prompt = formatPrompt('thinking');
    expect(prompt).toContain('flynn...');
  });
});

describe('parseCommand (re-exported)', () => {
  it('parses /quit command', () => {
    const result = parseCommand('/quit');
    expect(result).toEqual({ type: 'quit' });
  });

  it('parses /model command', () => {
    const result = parseCommand('/model local');
    expect(result).toEqual({ type: 'model', name: 'local' });
  });

  it('parses regular message', () => {
    const result = parseCommand('Hello, Flynn!');
    expect(result).toEqual({ type: 'message', content: 'Hello, Flynn!' });
  });

  it('returns null for empty input', () => {
    const result = parseCommand('');
    expect(result).toBeNull();
  });
});

describe('MinimalTui backend command', () => {
  it('switches local backend when provider is configured', async () => {
    const mockSession = {
      id: 'test',
      getHistory: () => [],
      addMessage: vi.fn(),
      clear: vi.fn(),
      replaceHistory: vi.fn(),
    };

    const mockRouter = {
      getTier: () => 'default' as const,
      getAvailableTiers: () => ['default', 'local'],
      setTier: vi.fn(() => true),
      getLocalProviderName: () => 'ollama',
      setLocalClient: vi.fn(),
      chat: vi.fn(),
      getClient: vi.fn(),
    };

    const localProviders: Record<string, ModelConfig> = {
      llamacpp: {
        provider: 'llamacpp',
        model: '',
        endpoint: 'http://localhost:8080',
      },
    };

    const tui = new MinimalTui({
      session: mockSession as any,
      modelClient: mockRouter as any,
      modelRouter: mockRouter as any,
      systemPrompt: 'test',
      localProviders,
    });

    // Access private method for testing
    await (tui as any).handleBackendCommand('llamacpp');

    expect(mockRouter.setLocalClient).toHaveBeenCalled();
  });

  it('syncs agent tier when /model command switches tier', () => {
    const mockSession = {
      id: 'test',
      getHistory: () => [],
      addMessage: vi.fn(),
      clear: vi.fn(),
      replaceHistory: vi.fn(),
    };

    const mockRouter = {
      getTier: () => 'default' as const,
      getAvailableTiers: () => ['default', 'local'],
      setTier: vi.fn(() => true),
      getLocalProviderName: () => 'ollama',
      setLocalClient: vi.fn(),
      chat: vi.fn(),
      getClient: vi.fn(),
    };

    const mockAgent = {
      setModelTier: vi.fn(),
      getModelTier: vi.fn(() => 'default'),
      process: vi.fn(),
    };

    const tui = new MinimalTui({
      session: mockSession as any,
      modelClient: mockRouter as any,
      modelRouter: mockRouter as any,
      agent: mockAgent as any,
      systemPrompt: 'test',
    });

    // Call private handleModelCommand to switch to local
    (tui as any).handleModelCommand('local');

    expect(mockRouter.setTier).toHaveBeenCalledWith('local');
    expect(mockAgent.setModelTier).toHaveBeenCalledWith('local');
  });

  it('reuses configured provider credentials for /model <tier> <provider/model>', () => {
    const prevOpenRouterKey = process.env.OPENROUTER_API_KEY;
    delete process.env.OPENROUTER_API_KEY;

    try {
      const mockSession = {
        id: 'test',
        getHistory: () => [],
        addMessage: vi.fn(),
        clear: vi.fn(),
        replaceHistory: vi.fn(),
      };

      const mockRouter = {
        getTier: () => 'default' as const,
        getAvailableTiers: () => ['default', 'local'],
        setTier: vi.fn(() => true),
        getLocalProviderName: () => 'ollama',
        setLocalClient: vi.fn(),
        setClient: vi.fn(),
        setTierStrict: vi.fn(),
        chat: vi.fn(),
        getClient: vi.fn(),
      };

      const tui = new MinimalTui({
        session: mockSession as any,
        modelClient: mockRouter as any,
        modelRouter: mockRouter as any,
        systemPrompt: 'test',
        modelProviderConfigs: {
          openrouter: {
            provider: 'openrouter',
            model: 'seed-model',
            api_key: 'test-key',
            endpoint: 'https://openrouter.ai/api/v1',
          },
        },
      });

      (tui as any).handleModelCommand('default', 'openrouter/deepseek/deepseek-chat');

      expect(mockRouter.setClient).toHaveBeenCalledOnce();
      expect(mockRouter.setTierStrict).toHaveBeenCalledWith('default', true);
    } finally {
      if (prevOpenRouterKey) {
        process.env.OPENROUTER_API_KEY = prevOpenRouterKey;
      } else {
        delete process.env.OPENROUTER_API_KEY;
      }
    }
  });
});
