/**
 * 配置管理模块
 *
 * 提供统一的配置读取、设置和管理功能
 */
/**
 * 配置管理器类
 */
export class ConfigManager {
    static instance;
    config = null;
    constructor() {
        // 不在构造函数中建立任何默认配置，必须由外部显式调用 setConfig
        // 注入配置，避免 llmswitch-core 内部产生隐式默认行为。
    }
    /**
     * 获取单例实例
     */
    static getInstance() {
        if (!ConfigManager.instance) {
            ConfigManager.instance = new ConfigManager();
        }
        return ConfigManager.instance;
    }
    /**
     * 设置配置
     *
     * @param config 要设置的配置
     * @param options 选项
     */
    static setConfig(config, options = {}) {
        const manager = ConfigManager.getInstance();
        try {
            // 合并配置
            const base = manager.config ?? {};
            manager.config = options.merge === false
                ? { ...base, ...config }
                : manager.deepMerge(base, config);
            // 验证配置
            if (options.validate !== false) {
                manager.validateConfig(manager.config);
            }
            console.log(`Config updated successfully (source: ${options.source || 'manual'})`);
        }
        catch (error) {
            console.error('Failed to set config:', error);
            throw new Error(`Failed to set config: ${error instanceof Error ? error.message : 'Unknown error'}`);
        }
    }
    /**
     * 获取配置
     *
     * @param path 指定配置路径（可选）
     * @returns 配置对象
     */
    static async getConfig(path) {
        const manager = ConfigManager.getInstance();
        // 为保持签名兼容，保留 path 参数但忽略它；
        // 真正的配置加载应由上层完成后通过 setConfig 注入。
        if (!manager.config) {
            throw new Error('Conversion config has not been initialized. Use ConfigManager.setConfig() before getConfig().');
        }
        return manager.config;
    }
    /**
     * 重新加载配置
     */
    static async reloadConfig() {
        // 不再尝试从磁盘重载配置，仅简单委托给 getConfig，
        // 由外部在调用前决定是否需要更新内存中的配置快照。
        return ConfigManager.getConfig();
    }
    /**
     * 验证配置
     */
    validateConfig(config) {
        if (!config) {
            throw new Error('Config cannot be null');
        }
        // 验证虚拟路由器配置
        if (config.virtualrouter) {
            if (!config.virtualrouter.outputProtocol) {
                throw new Error('virtualrouter.outputProtocol is required');
            }
            if (!config.virtualrouter.providers) {
                throw new Error('virtualrouter.providers is required');
            }
            // 验证每个 provider 配置
            for (const [name, provider] of Object.entries(config.virtualrouter.providers)) {
                if (!provider.id) {
                    throw new Error(`Provider ${name} missing id`);
                }
                if (typeof provider.type !== 'string') {
                    throw new Error(`Provider ${name} type must be a string`);
                }
            }
        }
    }
    /**
     * 深度合并对象（仅在内存中操作，不做任何持久化）
     */
    deepMerge(target, source) {
        if (!source)
            return target;
        const result = { ...target };
        for (const key in source) {
            if (source[key] && typeof source[key] === 'object' && !Array.isArray(source[key])) {
                result[key] = this.deepMerge(result[key] || {}, source[key]);
            }
            else {
                result[key] = source[key];
            }
        }
        return result;
    }
    /**
     * 获取配置摘要
     */
    static getConfigSummary() {
        const manager = ConfigManager.getInstance();
        const config = manager.config || {};
        const providers = config.virtualrouter?.providers || {};
        const enabled = Object.entries(providers)
            .filter(([_, provider]) => provider.enabled)
            .map(([name, _]) => name);
        return {
            totalProviders: Object.keys(providers).length,
            enabledProviders: enabled,
            outputProtocol: config.virtualrouter?.outputProtocol || 'unknown',
            inputProtocol: config.virtualrouter?.inputProtocol || 'unknown',
            routingDefaults: config.virtualrouter?.routing?.default || [],
            hasConversionConfig: !!config.conversion
        };
    }
    /**
     * 获取 provider 配置
     */
    static getProviderConfig(providerName) {
        const manager = ConfigManager.getInstance();
        return manager.config?.virtualrouter?.providers?.[providerName] || null;
    }
    /**
     * 检查 provider 是否可用
     */
    static isProviderEnabled(providerName) {
        const provider = ConfigManager.getProviderConfig(providerName);
        return provider?.enabled || false;
    }
    /**
     * 设置 provider 启用状态
     */
    static setProviderEnabled(providerName, enabled) {
        const manager = ConfigManager.getInstance();
        if (!manager.config || !manager.config.virtualrouter?.providers?.[providerName]) {
            return;
        }
        manager.config.virtualrouter.providers[providerName].enabled = enabled;
    }
    /**
    /**
     * 获取输出协议
     */
    static getOutputProtocol() {
        const manager = ConfigManager.getInstance();
        return manager.config?.virtualrouter?.outputProtocol || 'openai';
    }
    /**
     * 设置输出协议
     */
    static setOutputProtocol(protocol) {
        const manager = ConfigManager.getInstance();
        if (!manager.config) {
            manager.config = {};
        }
        if (!manager.config.virtualrouter) {
            manager.config.virtualrouter = {};
        }
        manager.config.virtualrouter.outputProtocol = protocol;
        console.log(`Output protocol changed to: ${protocol}`);
    }
    /**
     * 获取输入协议
     */
    static getInputProtocol() {
        const manager = ConfigManager.getInstance();
        return manager.config?.virtualrouter?.inputProtocol || 'openai';
    }
    /**
     * 设置输入协议
     */
    static setInputProtocol(protocol) {
        const manager = ConfigManager.getInstance();
        if (!manager.config) {
            manager.config = {};
        }
        if (!manager.config.virtualrouter) {
            manager.config.virtualrouter = {};
        }
        manager.config.virtualrouter.inputProtocol = protocol;
        console.log(`Input protocol changed to: ${protocol}`);
    }
    /**
   * 获取路由配置
     */
    static getRoutingConfig() {
        const manager = ConfigManager.getInstance();
        return manager.config?.virtualrouter?.routing || {};
    }
    /**
   * 设置路由配置
     */
    static setRoutingConfig(routing) {
        const manager = ConfigManager.getInstance();
        if (!manager.config) {
            manager.config = {};
        }
        if (!manager.config.virtualrouter) {
            manager.config.virtualrouter = {};
        }
        manager.config.virtualrouter.routing = routing;
        console.log('Routing config updated');
    }
    /**
   * 获取 V3 转换配置
     */
    static getConversionConfig() {
        const manager = ConfigManager.getInstance();
        return manager.config?.conversion || {};
    }
    /**
    * 设置 V3 转换配置
     */
    static setConversionConfig(conversion) {
        const manager = ConfigManager.getInstance();
        if (!manager.config) {
            manager.config = {};
        }
        if (!manager.config.conversion) {
            manager.config.conversion = {};
        }
        manager.config.conversion = manager.deepMerge(manager.config.conversion, conversion);
        console.log('Conversion config updated');
    }
}
/**
 * 便捷函数：设置配置
 */
export function setConfig(config, options) {
    ConfigManager.setConfig(config, options);
}
/**
 * 便捷函数：获取配置
 */
export async function getConfig(path) {
    return ConfigManager.getConfig(path);
}
/**
 * 便捷函数：重新加载配置
 */
export async function reloadConfig() {
    return ConfigManager.reloadConfig();
}
/**
 * 便捷函数：获取配置摘要
 */
export function getConfigSummary() {
    return ConfigManager.getConfigSummary();
}
/**
 * 便捷函数：获取 Provider 配置
 */
export function getProviderConfig(providerName) {
    return ConfigManager.getProviderConfig(providerName);
}
/**
 * 便捷函数：检查 Provider 状态
 */
export function isProviderEnabled(providerName) {
    return ConfigManager.isProviderEnabled(providerName);
}
/**
 * 便捷函数：设置 Provider 状态
 */
export function setProviderEnabled(providerName, enabled) {
    ConfigManager.setProviderEnabled(providerName, enabled);
}
/**
 * 便捷函数：获取输出协议
 */
export function getOutputProtocol() {
    return ConfigManager.getOutputProtocol();
}
/**
 * 便捷函数：设置输出协议
 */
export function setOutputProtocol(protocol) {
    ConfigManager.setOutputProtocol(protocol);
}
/**
 * 便捷函数：获取输入协议
 */
export function getInputProtocol() {
    return ConfigManager.getInputProtocol();
}
/**
 * 便捷函数：设置输入协议
 */
export function setInputProtocol(protocol) {
    ConfigManager.setInputProtocol(protocol);
}
