"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
const Brain_1 = require("./orchestrator/Brain");
function stubModelManager(brain, primary, fallbacks) {
    brain.modelManager = {
        getModelConfig: () => ({ primary, fallbacks })
    };
}
async function testPrimaryFailsSecondaryWins() {
    const brain = new Brain_1.Brain();
    stubModelManager(brain, { raw: 'openai-api/gpt-test', provider: 'openai-api', name: 'gpt-test' }, [{ raw: 'gemini-api/gemini-test', provider: 'gemini-api', name: 'gemini-test' }]);
    let primaryCalled = 0;
    let secondaryCalled = 0;
    brain.thinkWithOpenAIAPI = async () => {
        primaryCalled++;
        const err = new Error('forced primary failure');
        err.status = 401;
        err.error = { message: 'Incorrect API key provided' };
        throw err;
    };
    brain.thinkWithGeminiAPI = async () => {
        secondaryCalled++;
        return 'response-from-fallback';
    };
    const out = await brain.think('sys', 'usr');
    if (primaryCalled !== 1)
        throw new Error(`PRIMARY_NOT_CALLED_ONCE: ${primaryCalled}`);
    if (secondaryCalled !== 1)
        throw new Error(`SECONDARY_NOT_CALLED_ONCE: ${secondaryCalled}`);
    if (!out.includes('response-from-fallback'))
        throw new Error(`FALLBACK_RESPONSE_NOT_RETURNED: ${out.slice(0, 150)}`);
}
async function testAllFailReturnsCriticalError() {
    const brain = new Brain_1.Brain();
    stubModelManager(brain, { raw: 'openai-api/x', provider: 'openai-api', name: 'x' }, [
        { raw: 'gemini-api/y', provider: 'gemini-api', name: 'y' },
        { raw: 'anthropic/z', provider: 'anthropic', name: 'z' }
    ]);
    const calls = [];
    brain.thinkWithOpenAIAPI = async () => { calls.push('openai-api'); throw new Error('openai-down'); };
    brain.thinkWithGeminiAPI = async () => { calls.push('gemini-api'); throw new Error('gemini-down'); };
    brain.thinkWithAnthropic = async () => { calls.push('anthropic'); throw new Error('anthropic-down'); };
    const out = await brain.think('sys', 'usr');
    if (calls.length !== 3)
        throw new Error(`EXPECTED_3_CALLS_GOT_${calls.length}: ${calls.join(',')}`);
    if (!out.includes('CRITICAL ERROR'))
        throw new Error(`MISSING_CRITICAL_ERROR: ${out.slice(0, 200)}`);
    if (!out.includes('openai-api/x') || !out.includes('gemini-api/y') || !out.includes('anthropic/z')) {
        throw new Error(`CRITICAL_ERROR_MISSING_PROVIDER_FAILURES: ${out}`);
    }
}
async function testOpenAIBaseURLApplied() {
    process.env.OPENAI_API_KEY = 'sk-fake-for-construction-only';
    process.env.OPENAI_BASE_URL = 'https://api.together.xyz/v1';
    try {
        const brain = new Brain_1.Brain();
        const openaiClient = brain.openai;
        if (!openaiClient)
            throw new Error('OPENAI_CLIENT_NOT_CONSTRUCTED');
        const inferredBase = openaiClient.baseURL || openaiClient._options?.baseURL;
        if (typeof inferredBase === 'string' && !inferredBase.includes('together.xyz')) {
            throw new Error(`BASE_URL_NOT_APPLIED: got ${inferredBase}`);
        }
    }
    finally {
        delete process.env.OPENAI_API_KEY;
        delete process.env.OPENAI_BASE_URL;
    }
}
async function testOpenAIBaseURLDefaultUnset() {
    process.env.OPENAI_API_KEY = 'sk-fake-default-base';
    delete process.env.OPENAI_BASE_URL;
    try {
        const brain = new Brain_1.Brain();
        const openaiClient = brain.openai;
        if (!openaiClient)
            throw new Error('OPENAI_CLIENT_NOT_CONSTRUCTED');
    }
    finally {
        delete process.env.OPENAI_API_KEY;
    }
}
async function main() {
    await testPrimaryFailsSecondaryWins();
    await testAllFailReturnsCriticalError();
    await testOpenAIBaseURLApplied();
    await testOpenAIBaseURLDefaultUnset();
    console.log('TEST_BRAIN_FALLBACK_CHAIN_OK');
}
main().catch((err) => {
    console.error('TEST_BRAIN_FALLBACK_CHAIN_FAIL:', err?.message || err);
    process.exit(1);
});
