import { describe, it, expect, vi, afterEach, beforeEach } from 'vitest';
import { loadLlmConfig, resetConfigCache } from '../../src/http/config.js';
import { existsSync, readFileSync } from 'node:fs';

vi.mock('node:fs', async () => {
  const actual = await vi.importActual<typeof import('node:fs')>('node:fs');
  return {
    ...actual,
    existsSync: vi.fn(),
    readFileSync: vi.fn(),
  };
});

beforeEach(() => {
  resetConfigCache();
});

afterEach(() => {
  vi.restoreAllMocks();
});

describe('loadLlmConfig', () => {
  it('returns undefined when config file does not exist', () => {
    vi.mocked(existsSync).mockReturnValue(false);
    expect(loadLlmConfig()).toBeUndefined();
  });

  it('returns undefined when config has no llm section', () => {
    vi.mocked(existsSync).mockReturnValue(true);
    vi.mocked(readFileSync).mockReturnValue(JSON.stringify({ mcplocalUrl: 'http://localhost:3200' }));
    expect(loadLlmConfig()).toBeUndefined();
  });

  it('returns undefined when provider is none', () => {
    vi.mocked(existsSync).mockReturnValue(true);
    vi.mocked(readFileSync).mockReturnValue(JSON.stringify({ llm: { provider: 'none' } }));
    expect(loadLlmConfig()).toBeUndefined();
  });

  it('returns LLM config when provider is configured', () => {
    vi.mocked(existsSync).mockReturnValue(true);
    vi.mocked(readFileSync).mockReturnValue(JSON.stringify({
      llm: { provider: 'anthropic', model: 'claude-haiku-3-5-20241022' },
    }));
    const result = loadLlmConfig();
    expect(result).toEqual({ provider: 'anthropic', model: 'claude-haiku-3-5-20241022' });
  });

  it('returns full LLM config with all fields', () => {
    vi.mocked(existsSync).mockReturnValue(true);
    vi.mocked(readFileSync).mockReturnValue(JSON.stringify({
      llm: { provider: 'vllm', model: 'my-model', url: 'http://gpu:8000' },
    }));
    const result = loadLlmConfig();
    expect(result).toEqual({ provider: 'vllm', model: 'my-model', url: 'http://gpu:8000' });
  });

  it('returns undefined on malformed JSON', () => {
    vi.mocked(existsSync).mockReturnValue(true);
    vi.mocked(readFileSync).mockReturnValue('NOT JSON!!!');
    expect(loadLlmConfig()).toBeUndefined();
  });

  it('returns undefined on read error', () => {
    vi.mocked(existsSync).mockReturnValue(true);
    vi.mocked(readFileSync).mockImplementation(() => { throw new Error('EACCES'); });
    expect(loadLlmConfig()).toBeUndefined();
  });
});
