import { loadConfig } from './src/utils/config.js';
import { resolveProviderName } from './src/core/llm-provider.js';

let passed = 0;
let failed = 0;

function test(name, fn) {
  try {
    fn();
    console.log(`  ✓ ${name}`);
    passed++;
  } catch (e) {
    console.log(`  ✗ ${name}: ${e.message}`);
    failed++;
  }
}

function assertEqual(actual, expected, msg) {
  if (actual !== expected) {
    throw new Error(msg || `Expected ${JSON.stringify(expected)}, got ${JSON.stringify(actual)}`);
  }
}

console.log('\n── LLM Provider Selection ──');

test('loadConfig defaults to CLI even when an API key exists', () => {
  const original = process.env.ANTHROPIC_API_KEY;
  process.env.ANTHROPIC_API_KEY = 'test-key';
  try {
    const config = loadConfig([]);
    assertEqual(config.llmProvider, 'cli');
    assertEqual(config.apiKey, 'test-key');
  } finally {
    if (original === undefined) delete process.env.ANTHROPIC_API_KEY;
    else process.env.ANTHROPIC_API_KEY = original;
  }
});

test('explicit CLI selection stays on CLI when available', () => {
  assertEqual(resolveProviderName({ llmProvider: 'cli', cliAvailable: true, apiKey: 'test-key' }), 'cli');
});

test('CLI selection falls back to API key when CLI is unavailable', () => {
  assertEqual(resolveProviderName({ llmProvider: 'cli', cliAvailable: false, apiKey: 'test-key' }), 'api-key');
});

test('API Key selection stays on API key when configured', () => {
  assertEqual(resolveProviderName({ llmProvider: 'api-key', cliAvailable: true, apiKey: 'test-key' }), 'api-key');
});

console.log(`\n── Results ──\n\n  ${passed} passed, ${failed} failed\n`);
process.exit(failed > 0 ? 1 : 0);
