// Tests for the frontier_provider override in src/router.js.
// We isolate state by pointing HOME at a temp dir, so the module's
// path.join(os.homedir(), '.pre', 'router.json') lands inside the sandbox.

const path = require('path');
const realOs = jest.requireActual('os');
const fs = require('fs');

const mockHome = path.join(realOs.tmpdir(), `pre-test-router-${process.pid}`);
fs.mkdirSync(path.join(mockHome, '.pre'), { recursive: true });

// jest mocks os.homedir so both router.js (cached top-level require) and the
// lazy require inside getFrontierProvider see the sandbox directory.
jest.mock('os', () => {
  const actual = jest.requireActual('os');
  return { ...actual, homedir: () => mockHome };
});

// Stub calibration so router.js's `require('./calibration')` returns a no-op profile.
jest.mock('../src/calibration', () => ({
  loadProfile: () => ({ categories: {} }),
  confidence: () => null,
  categorize: () => [],
  CATEGORIES: {},
  recordToolOutcome: () => {},
}));

const router = require('../src/router');

const ROUTER_FILE = path.join(mockHome, '.pre', 'router.json');
const CONNECTIONS_FILE = path.join(mockHome, '.pre', 'connections.json');

function writeRouter(cfg) {
  fs.writeFileSync(ROUTER_FILE, JSON.stringify(cfg));
  // The module caches by mtime; bump it to force a reload.
  const now = Date.now() / 1000 + Math.random();
  fs.utimesSync(ROUTER_FILE, now, now);
}
function writeConnections(data) {
  fs.writeFileSync(CONNECTIONS_FILE, JSON.stringify(data));
}

afterAll(() => {
  try { fs.rmSync(mockHome, { recursive: true, force: true }); } catch {}
});

beforeEach(() => {
  router.resetConfig();
  try { fs.unlinkSync(CONNECTIONS_FILE); } catch {}
});

describe('router.getFrontierProvider', () => {
  test('returns null when frontier_enabled is false', () => {
    writeRouter({ enabled: true, frontier_enabled: false, frontier_provider: 'gemini' });
    writeConnections({ _provider: { gemini: { api_key: 'k', model: 'gemini-3.5-flash' } } });
    expect(router.getFrontierProvider()).toBeNull();
  });

  test('returns null when frontier_provider is "inherit"', () => {
    writeRouter({ enabled: true, frontier_enabled: true, frontier_provider: 'inherit' });
    writeConnections({ _provider: { gemini: { api_key: 'k', model: 'gemini-3.5-flash' } } });
    expect(router.getFrontierProvider()).toBeNull();
  });

  test('returns null when the requested provider has no saved config', () => {
    writeRouter({ enabled: true, frontier_enabled: true, frontier_provider: 'gemini' });
    writeConnections({ _provider: { openai: { base_url: 'https://api.openai.com/v1', api_key: 'k', model: 'gpt-4o' } } });
    expect(router.getFrontierProvider()).toBeNull();
  });

  test('returns a Gemini provider object with the default endpoint', () => {
    writeRouter({ enabled: true, frontier_enabled: true, frontier_provider: 'gemini' });
    writeConnections({
      _provider: {
        active: 'ollama',
        gemini: { api_key: 'AIzaTEST', model: 'gemini-3.5-flash' },
      },
    });
    const p = router.getFrontierProvider();
    expect(p).toEqual({
      type: 'gemini',
      base_url: 'https://generativelanguage.googleapis.com/v1beta',
      api_key: 'AIzaTEST',
      model: 'gemini-3.5-flash',
      max_tokens: 4096,
    });
  });

  test('honors an explicit base_url override (Vertex AI proxy)', () => {
    writeRouter({ enabled: true, frontier_enabled: true, frontier_provider: 'gemini' });
    writeConnections({
      _provider: {
        active: 'ollama',
        gemini: { base_url: 'https://vertex.example.com/v1/', api_key: 'k', model: 'gemini-3.5-pro' },
      },
    });
    const p = router.getFrontierProvider();
    expect(p.base_url).toBe('https://vertex.example.com/v1');
    expect(p.model).toBe('gemini-3.5-pro');
  });

  test('returns Anthropic provider with api_version when configured', () => {
    writeRouter({ enabled: true, frontier_enabled: true, frontier_provider: 'anthropic' });
    writeConnections({
      _provider: {
        active: 'ollama',
        anthropic: { base_url: 'https://api.anthropic.com/v1/messages', api_key: 'k', model: 'claude-sonnet-4-20250514' },
      },
    });
    const p = router.getFrontierProvider();
    expect(p.type).toBe('anthropic');
    expect(p.api_version).toBe('2023-06-01');
  });

  test('frontier override is independent of the active provider', () => {
    writeRouter({ enabled: true, frontier_enabled: true, frontier_provider: 'gemini' });
    writeConnections({
      _provider: {
        active: 'ollama', // user keeps Ollama as default
        gemini: { api_key: 'k', model: 'gemini-3.5-flash' },
        openai: { base_url: 'https://api.openai.com/v1', api_key: 'sk', model: 'gpt-4o' },
      },
    });
    const p = router.getFrontierProvider();
    expect(p.type).toBe('gemini');
  });
});
