import { describe, it, beforeEach, afterEach } from 'node:test';
import assert from 'node:assert/strict';
import { getLLMCLICommands, getLLMConfig, getOpenCodeHttpsAgent } from '../config.js';

const ENV_KEYS = [
  'AI_ASSISTANT_CLI', 'MODEL', 'OPENCODE_MODEL',
];

let saved = {};
beforeEach(() => {
  saved = {};
  for (const k of ENV_KEYS) { saved[k] = process.env[k]; delete process.env[k]; }
});
afterEach(() => {
  for (const k of ENV_KEYS) {
    if (saved[k] === undefined) delete process.env[k];
    else process.env[k] = saved[k];
  }
});

describe('getLLMConfig', () => {
  it('exports the supported assistant CLI commands', () => {
    assert.deepEqual(getLLMCLICommands(), ['codex', 'claude', 'agy', 'antigravity', 'opencode']);
  });

  it('returns null provider when no env vars set', () => {
    const cfg = getLLMConfig({ commandExistsFn: () => false });
    assert.equal(cfg.provider, null);
    assert.deepEqual(cfg.apiKeys, []);
    assert.equal(cfg.command, null);
  });

  it('detects the first installed assistant CLI with defaults', () => {
    const cfg = getLLMConfig({ commandExistsFn: command => command === 'claude' });
    assert.equal(cfg.provider, 'claude');
    assert.deepEqual(cfg.apiKeys, ['claude']);
    assert.equal(cfg.baseURL, null);
    assert.equal(cfg.command, 'claude');
    assert.equal(cfg.model, 'sonnet');
  });

  it('uses MODEL for the selected assistant CLI', () => {
    process.env.MODEL = 'gpt-5-mini';
    const cfg = getLLMConfig({ commandExistsFn: command => command === 'codex' });
    assert.equal(cfg.provider, 'codex');
    assert.equal(cfg.command, 'codex');
    assert.equal(cfg.model, 'gpt-5-mini');
  });

  it('detects Antigravity through the agy command', () => {
    const cfg = getLLMConfig({ commandExistsFn: command => command === 'agy' });
    assert.equal(cfg.provider, 'antigravity');
    assert.equal(cfg.command, 'agy');
    assert.equal(cfg.model, 'gemini-2.5-flash');
  });

  it('can force a CLI with AI_ASSISTANT_CLI', () => {
    process.env.AI_ASSISTANT_CLI = 'opencode';
    process.env.OPENCODE_MODEL = 'google/gemini-2.5-pro';
    const cfg = getLLMConfig({ commandExistsFn: command => command === 'codex' || command === 'opencode' });
    assert.equal(cfg.provider, 'opencode');
    assert.equal(cfg.command, 'opencode');
    assert.equal(cfg.model, 'google/gemini-2.5-pro');
  });

  it('uses an insecure HTTPS agent for OpenCode', () => {
    const agent = getOpenCodeHttpsAgent();
    assert.equal(agent.options.rejectUnauthorized, false);
  });

  it('disables Node TLS certificate verification globally', () => {
    assert.equal(process.env.NODE_TLS_REJECT_UNAUTHORIZED, '0');
  });

});
