/**
 * @license
 * Copyright 2025 Vybestack LLC
 * SPDX-License-Identifier: Apache-2.0
 */
import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest';
const { aliasEntries } = vi.hoisted(() => ({
    aliasEntries: [],
}));
const { StubSettingsService: StubSettingsServiceClass, StubConfig: StubConfigClass, StubProvider: StubProviderClass, } = vi.hoisted(() => {
    class StubSettingsService {
        providers = {};
        global = {};
        set(key, value) {
            this.global[key] = value;
        }
        get(key) {
            return this.global[key];
        }
        getAllGlobalSettings() {
            return { ...this.global };
        }
        setProviderSetting(provider, key, value) {
            if (!this.providers[provider]) {
                this.providers[provider] = {};
            }
            if (value === undefined) {
                delete this.providers[provider][key];
            }
            else {
                this.providers[provider][key] = value;
            }
        }
        getProviderSettings(provider) {
            return this.providers[provider] || {};
        }
        switchProvider = vi.fn(async (provider) => {
            this.set('activeProvider', provider);
        });
    }
    class StubConfig {
        model = undefined;
        provider = 'openai';
        ephemeral = {};
        providerManager;
        settingsService;
        lastRefreshedAuthType;
        constructor(settingsService) {
            this.settingsService = settingsService;
        }
        getSettingsService() {
            return this.settingsService;
        }
        setEphemeralSetting(key, value) {
            if (value === undefined) {
                delete this.ephemeral[key];
            }
            else {
                this.ephemeral[key] = value;
            }
        }
        getEphemeralSetting(key) {
            return this.ephemeral[key];
        }
        getEphemeralSettings() {
            return { ...this.ephemeral };
        }
        getModel() {
            return this.model;
        }
        setModel(model) {
            this.model = model;
        }
        setProvider(provider) {
            this.provider = provider;
        }
        getProvider() {
            return this.provider;
        }
        setProviderManager(manager) {
            this.providerManager = manager;
        }
        getProviderManager() {
            return this.providerManager;
        }
        getContentGeneratorConfig() {
            return { authType: this.lastRefreshedAuthType };
        }
        async refreshAuth(authType) {
            this.lastRefreshedAuthType = authType;
        }
    }
    class StubProvider {
        name;
        defaultModel = 'gpt-4o';
        providerConfig = {};
        constructor(name) {
            this.name = name;
        }
        getDefaultModel() {
            return this.defaultModel;
        }
    }
    return { StubSettingsService, StubConfig, StubProvider };
});
const StubSettingsService = StubSettingsServiceClass;
const StubConfig = StubConfigClass;
const StubProvider = StubProviderClass;
const providers = {
    openai: new StubProvider('openai'),
    qwenvercel: new StubProvider('qwenvercel'),
};
let activeProviderName = 'openai';
const mockProviderManager = {
    listProviders: vi.fn(() => Object.keys(providers)),
    getActiveProviderName: vi.fn(() => activeProviderName),
    getActiveProvider: vi.fn(() => providers[activeProviderName]),
    setActiveProvider: vi.fn(async (name) => {
        activeProviderName = name;
    }),
    getProviderByName: (name) => providers[name],
    getAvailableModels: vi.fn(async () => [{ id: 'model-a' }, { id: 'model-b' }]),
    setConfig: vi.fn(),
    prepareStatelessProviderInvocation: vi.fn(),
};
let stubSettingsService;
let stubConfig;
vi.mock('../providers/providerAliases.js', () => ({
    loadProviderAliasEntries: () => aliasEntries,
}));
vi.mock('@vybestack/llxprt-code-core', async (importOriginal) => {
    const actual = await importOriginal();
    let activeContext = null;
    return {
        ...actual,
        SettingsService: StubSettingsServiceClass,
        Config: StubConfigClass,
        createProviderRuntimeContext: (context) => {
            activeContext = context;
            return context;
        },
        getActiveProviderRuntimeContext: () => {
            if (!activeContext) {
                throw new Error('MissingProviderRuntimeError(provider-runtime): runtime registration missing');
            }
            return activeContext;
        },
        setActiveProviderRuntimeContext: (context) => {
            activeContext = context;
        },
    };
});
const { switchActiveProvider, setCliRuntimeContext, registerCliProviderInfrastructure, } = await import('./runtimeSettings.js');
const mockOAuthManager = {
    isOAuthEnabled: vi.fn(() => false),
    toggleOAuthEnabled: vi.fn(),
    authenticate: vi.fn(),
    setMessageBus: vi.fn(),
    setConfigGetter: vi.fn(),
};
describe('Provider alias defaults (model + ephemerals)', () => {
    beforeEach(() => {
        stubSettingsService = new StubSettingsService();
        stubConfig = new StubConfig(stubSettingsService);
        activeProviderName = 'openai';
        // Set up runtime context and provider infrastructure
        setCliRuntimeContext(stubSettingsService, stubConfig, {
            runtimeId: 'test-runtime',
        });
        registerCliProviderInfrastructure(mockProviderManager, mockOAuthManager);
        aliasEntries.length = 0;
        aliasEntries.push({
            alias: 'qwenvercel',
            source: 'builtin',
            filePath: '/fake/qwenvercel.config',
            config: {
                baseProvider: 'openaivercel',
                baseUrl: 'https://portal.qwen.ai/v1',
                defaultModel: 'qwen3-coder-plus',
                ephemeralSettings: {
                    'context-limit': 200000,
                    max_tokens: 50000,
                },
            },
        });
        // Ensure provider instance default doesn't match alias default
        providers.qwenvercel.defaultModel = 'gpt-4o';
        providers.qwenvercel.providerConfig.baseUrl = 'https://portal.qwen.ai/v1';
        vi.clearAllMocks();
    });
    afterEach(() => {
        vi.clearAllMocks();
    });
    it('applies alias defaultModel + alias ephemeralSettings on switch', async () => {
        await switchActiveProvider('qwenvercel');
        expect(stubConfig.getModel()).toBe('qwen3-coder-plus');
        expect(stubConfig.getEphemeralSetting('context-limit')).toBe(200000);
        expect(stubConfig.getEphemeralSetting('max_tokens')).toBe(50000);
        expect(stubSettingsService.getProviderSettings('qwenvercel').model).toBe('qwen3-coder-plus');
    });
    it('does not override preserved ephemerals', async () => {
        stubConfig.setEphemeralSetting('max_tokens', 8192);
        await switchActiveProvider('qwenvercel', {
            preserveEphemerals: ['max_tokens'],
        });
        expect(stubConfig.getEphemeralSetting('max_tokens')).toBe(8192);
    });
    it('does not allow alias ephemerals to set auth-like keys', async () => {
        const entry = aliasEntries[0];
        entry.config = entry.config ?? {};
        entry.config.ephemeralSettings = {
            'api-key': 'should-not-apply',
            max_tokens: 50000,
        };
        await switchActiveProvider('qwenvercel');
        expect(stubConfig.getEphemeralSetting('api-key')).toBeUndefined();
        expect(stubConfig.getEphemeralSetting('max_tokens')).toBe(50000);
    });
    it('ignores non-scalar alias ephemeral values', async () => {
        const entry = aliasEntries[0];
        entry.config = entry.config ?? {};
        entry.config.ephemeralSettings = {
            'context-limit': [200000],
            max_tokens: 50000,
        };
        await switchActiveProvider('qwenvercel');
        expect(stubConfig.getEphemeralSetting('context-limit')).toBeUndefined();
        expect(stubConfig.getEphemeralSetting('max_tokens')).toBe(50000);
    });
});
//# sourceMappingURL=provider-alias-defaults.test.js.map