import { logger, LogLevel } from "../../utils";
import { setupI18n } from "../../library";
import { storage } from "../../library";
import { NetworkError } from "../../utils/errors";
import { ConfigSecurity } from "../../utils/configSecurity";
import { pluginManager } from "../plugin";
/**
 * 配置缓存键
 */ const CONFIG_CACHE_KEY = '__framework_config_cache__';
/**
 * 加载配置（带超时、重试和缓存）
 */ async function loadConfigWithRetry(loadConfig, strategy, fallbackConfig) {
    const timeout = strategy.configTimeout ?? 5000;
    const retryCount = strategy.retryCount ?? 3;
    const retryDelay = strategy.retryDelay ?? 1000;
    const enableCache = strategy.enableCache ?? true;
    const cacheTTL = strategy.cacheTTL ?? 5 * 60 * 1000; // 5分钟
    const configVersion = strategy.configVersion;
    // 检查缓存
    if (enableCache && storage.localCache) {
        try {
            const cacheKey = `${CONFIG_CACHE_KEY}_${configVersion || 'default'}`;
            const cached = await storage.localCache.get(cacheKey);
            if (cached && (!configVersion || cached.version === configVersion)) {
                logger.debug('使用缓存的配置');
                return cached.data;
            }
        } catch (error) {
            logger.warn('读取配置缓存失败:', error);
        }
    }
    // 重试加载配置
    let lastError = null;
    for(let attempt = 0; attempt <= retryCount; attempt++){
        try {
            if (attempt > 0) {
                logger.debug(`配置加载重试 ${attempt}/${retryCount}`);
                // 指数退避
                await new Promise((resolve)=>setTimeout(resolve, retryDelay * Math.pow(2, attempt - 1)));
            }
            const configPromise = loadConfig();
            const timeoutPromise = new Promise((_, reject)=>setTimeout(()=>reject(new NetworkError('配置加载超时')), timeout));
            const config = await Promise.race([
                configPromise,
                timeoutPromise
            ]);
            // 保存到缓存
            if (enableCache && storage.localCache) {
                try {
                    const cacheKey = `${CONFIG_CACHE_KEY}_${configVersion || 'default'}`;
                    await storage.localCache.set(cacheKey, {
                        data: config,
                        version: configVersion
                    }, cacheTTL);
                } catch (error) {
                    logger.warn('保存配置缓存失败:', error);
                }
            }
            return config;
        } catch (error) {
            lastError = error instanceof Error ? error : new Error(String(error));
            logger.warn(`配置加载失败 (尝试 ${attempt + 1}/${retryCount + 1}):`, lastError);
        }
    }
    // 所有重试都失败，使用降级配置
    logger.warn('配置加载失败，使用降级配置:', lastError);
    return fallbackConfig || {};
}
/**
 * 初始化方法
 * 
 * 这是核心的初始化逻辑，可被启动页或直接调用
 * 
 * @param options - 初始化选项
 * @param onProgress - 进度回调函数（可选）
 * @returns Promise<InitializationContext>
 * 
 * @example
 * ```typescript
 * const context = await initialization({
 *   loggerLevel: LogLevel.INFO,
 *   lifecycle: {
 *     initialization: async () => {
 *       // 初始化逻辑
 *     },
 *   },
 * }, (progress, step) => {
 *   console.log(`进度: ${progress}%, 步骤: ${step}`);
 * });
 * ```
 */ export async function initialization(options, onProgress) {
    const startTime = Date.now();
    let config = {};
    try {
        // 0. 执行插件初始化前钩子
        await pluginManager.executeBeforeInit(options);
        // 1. 设置日志级别
        onProgress?.(5, '初始化日志系统...');
        logger.setLevel(options.loggerLevel ?? LogLevel.INFO);
        // 2. 加载关键配置
        if (options.configStrategy?.loadCriticalConfig) {
            onProgress?.(10, '加载关键配置...');
            try {
                config = await loadConfigWithRetry(options.configStrategy.loadCriticalConfig, options.configStrategy, options.configStrategy.fallbackConfig);
                // 验证配置安全性
                if (options.configSecurity) {
                    const securityResult = await ConfigSecurity.validateConfigSecurity(config, options.configSecurity);
                    if (!securityResult.valid) {
                        logger.warn('配置安全验证失败:', securityResult.errors);
                    // 根据安全策略决定是否继续
                    }
                }
                options.configStrategy.onConfigLoaded?.(config);
                onProgress?.(30, '关键配置加载完成');
            } catch (error) {
                logger.warn('关键配置加载失败，使用默认配置:', error);
                config = options.configStrategy.fallbackConfig || {};
                options.configStrategy.onConfigLoaded?.(config);
                onProgress?.(30, '使用默认配置');
            }
        } else {
            onProgress?.(30);
        }
        // 2.5. 渐进式加载非关键配置（在应用渲染后异步加载）
        if (options.configStrategy?.loadNonCriticalConfig) {
            // 智能延迟加载：根据网络状况动态调整延迟时间
            const getDelayTime = ()=>{
                if (typeof navigator === 'undefined' || !('connection' in navigator)) {
                    return 1000; // 默认延迟
                }
                const connection = navigator.connection;
                if (!connection) {
                    return 1000;
                }
                // 根据网络类型调整延迟
                const effectiveType = connection.effectiveType;
                switch(effectiveType){
                    case 'slow-2g':
                    case '2g':
                        return 3000; // 慢网络延迟更久
                    case '3g':
                        return 2000;
                    case '4g':
                    default:
                        return 500; // 快网络可以更快加载
                }
            };
            // 使用 requestIdleCallback 在空闲时加载
            if (typeof requestIdleCallback !== 'undefined') {
                requestIdleCallback(async ()=>{
                    try {
                        const nonCriticalConfig = await loadConfigWithRetry(options.configStrategy.loadNonCriticalConfig, options.configStrategy, {});
                        // 合并到主配置
                        config = {
                            ...config,
                            ...nonCriticalConfig
                        };
                        options.configStrategy?.onConfigLoaded?.(config);
                        logger.debug('非关键配置加载完成');
                    } catch (error) {
                        logger.warn('非关键配置加载失败:', error);
                    }
                }, {
                    timeout: getDelayTime()
                });
            } else {
                // 降级方案：智能延迟加载
                setTimeout(async ()=>{
                    try {
                        const nonCriticalConfig = await loadConfigWithRetry(options.configStrategy.loadNonCriticalConfig, options.configStrategy, {});
                        config = {
                            ...config,
                            ...nonCriticalConfig
                        };
                        options.configStrategy?.onConfigLoaded?.(config);
                        logger.debug('非关键配置加载完成');
                    } catch (error) {
                        logger.warn('非关键配置加载失败:', error);
                    }
                }, getDelayTime());
            }
        }
        // 3. 初始化之前回调
        if (options.lifecycle?.beforeInitialization) {
            onProgress?.(35, '执行初始化前回调...');
            await options.lifecycle.beforeInitialization();
        }
        // 4. 国际化设置
        onProgress?.(40, '设置国际化...');
        setupI18n(options.locale || undefined);
        // 5. 核心初始化
        if (options.lifecycle?.initialization) {
            onProgress?.(50, '初始化核心功能...');
            await options.lifecycle.initialization();
            onProgress?.(70, '核心功能初始化完成');
        } else {
            onProgress?.(70);
        }
        onProgress?.(80, '准备完成...');
        const duration = Date.now() - startTime;
        const context = {
            config,
            progress: 100,
            isReady: true,
            duration
        };
        // 执行插件初始化钩子
        await pluginManager.executeInit(options, context);
        // 执行插件初始化后钩子
        await pluginManager.executeAfterInit(options, context);
        // 6. 初始化之后回调（在 context 创建后执行，可以访问完整的初始化上下文）
        if (options.lifecycle?.afterInitialization) {
            onProgress?.(90, '执行初始化后回调...');
            await options.lifecycle.afterInitialization(context);
        }
        onProgress?.(100, '初始化完成');
        return context;
    } catch (error) {
        logger.error('初始化失败:', error);
        throw error;
    }
}

//# sourceMappingURL=initialization.js.map