/**
 * 应用启动主函数
 * 重构后的启动逻辑，集成所有新功能
 */ import { logger } from "../../utils";
import { ErrorCode, InitializationError } from "../../utils/errors";
import { initTraceIdGenerator, generateTraceId, setCurrentTraceId } from "../../utils/traceId";
import { shouldShowSplashScreen } from "../splash";
import { initialization, initializationErrorState } from "../initialization/index";
import { middlewareManager } from "../middleware";
import { initializeServices } from "./initializeServices";
import { getAppInstanceManager } from "./AppInstance";
import { getEnvironmentDetector } from "./environment";
import { getRouterManager } from "../router/RouterManager";
import { FrameworkEventManager } from "../event/frameworkEvents";
/**
 * 启动应用
 * 
 * @param options - 启动配置选项
 * @param instanceId - 应用实例ID（可选，用于多实例场景）
 * @returns 应用实例
 */ export async function startApp(options = {}, instanceId) {
    const startTime = performance.now();
    const envDetector = getEnvironmentDetector();
    const instanceManager = getAppInstanceManager();
    // 初始化追踪 ID 生成器
    initTraceIdGenerator('app');
    const traceId = generateTraceId();
    setCurrentTraceId(traceId);
    // 框架事件管理器（在服务初始化后创建）
    let frameworkEventManager = null;
    try {
        // 1. 环境检测和容器获取
        const container = options.container || envDetector.safeGetElement('#root');
        if (!container) {
            throw new InitializationError('未找到挂载容器', undefined, {
                container: options.container
            }, ErrorCode.CONTAINER_NOT_FOUND);
        }
        logger.info('框架启动中...');
        // 2. 创建应用实例
        const appInstance = instanceManager.createInstance(instanceId, options);
        const finalInstanceId = appInstance.id;
        // 3. 初始化服务（并行）
        const servicesInitStart = performance.now();
        const services = await initializeServices({
            ...options,
            eventBus: {
                ...options.eventBus,
                instanceId: finalInstanceId
            }
        });
        const servicesInitDuration = performance.now() - servicesInitStart;
        // 创建框架事件管理器
        frameworkEventManager = new FrameworkEventManager(services.eventBus);
        // 触发应用启动事件（使用真实的事件总线）
        frameworkEventManager.emitAppStart(finalInstanceId);
        // 触发实例创建事件
        frameworkEventManager.emitInstanceCreated(finalInstanceId);
        // 4. 初始化应用实例
        appInstance.initialize(container, services);
        // 5. 初始化路由管理器
        const routerManager = getRouterManager();
        if (options.router) {
            await routerManager.initialize(options.router);
        }
        // 6. 性能追踪
        const performanceTracker = appInstance.getPerformanceTracker();
        if (performanceTracker) {
            performanceTracker.recordServiceInit(servicesInitDuration);
        }
        // 6. 是否显示启动页
        const shouldShowSplash = shouldShowSplashScreen(options.showSplashScreen);
        const renderer = appInstance.getRenderer();
        // 8. 渲染应用函数
        const renderApp = async (context)=>{
            const renderStart = performance.now();
            // 触发渲染开始事件
            if (frameworkEventManager) {
                frameworkEventManager.emitAppRenderStart(finalInstanceId);
            }
            await renderer.renderApp(options, services, context);
            const renderDuration = performance.now() - renderStart;
            // 触发渲染完成事件
            if (frameworkEventManager) {
                frameworkEventManager.emitAppRenderComplete(finalInstanceId, renderDuration);
            }
            // 优化：在应用渲染完成后，延迟初始化非关键服务
            // 使用 requestIdleCallback 在浏览器空闲时初始化，不影响用户体验
            if (services.initializeNonCriticalServices) {
                services.initializeNonCriticalServices().catch((error)=>{
                    logger.warn('非关键服务初始化失败（不影响应用运行）:', error);
                });
            }
            if (performanceTracker) {
                performanceTracker.recordFirstRender(renderDuration);
                const totalDuration = performance.now() - startTime;
                performanceTracker.recordTotalStartup(totalDuration);
                performanceTracker.report();
            }
            // 触发应用启动完成事件
            if (frameworkEventManager) {
                frameworkEventManager.emitAppStarted(finalInstanceId, performance.now() - startTime);
            }
            // 开发模式下显示开发工具
            if (process.env.NODE_ENV === 'development' && typeof window !== 'undefined') {
                // 延迟显示开发工具，避免影响首次渲染
                setTimeout(()=>{
                    const devToolsContainer = document.createElement('div');
                    devToolsContainer.id = '__framework_dev_tools__';
                    document.body.appendChild(devToolsContainer);
                // 这里需要动态导入React来渲染开发工具
                // 为了简化，暂时注释掉，后续可以完善
                // import('react-dom/client').then(({ createRoot }) => {
                //   const root = createRoot(devToolsContainer);
                //   root.render(<DevToolsTrigger appInstance={appInstance} />);
                // });
                }, 1000);
            }
        };
        if (shouldShowSplash) {
            // 场景1: 显示启动页，初始化在启动页中完成
            const onSplashComplete = (context)=>{
                logger.info('启动页初始化完成');
                // 触发初始化完成事件
                if (frameworkEventManager) {
                    const initDuration = context.duration || 0;
                    frameworkEventManager.emitAppInitComplete(finalInstanceId, context, initDuration);
                }
                if (options.onSplashComplete) {
                    Promise.resolve(options.onSplashComplete(()=>{
                        logger.info('框架加载完成');
                        renderApp(context);
                    }, context)).catch((error)=>{
                        logger.error('onSplashComplete 回调执行失败:', error);
                        initializationErrorState.setError(error);
                        renderApp(context);
                    });
                } else {
                    logger.info('框架加载完成');
                    renderApp(context);
                }
            };
            // 触发初始化开始事件
            if (frameworkEventManager) {
                frameworkEventManager.emitAppInitStart(finalInstanceId);
            }
            // 渲染启动页
            renderer.renderSplashScreen(options, services, onSplashComplete);
        } else {
            // 场景2: 不显示启动页，直接执行初始化
            logger.info('开始执行初始化（无启动页）');
            // 触发初始化开始事件
            if (frameworkEventManager) {
                frameworkEventManager.emitAppInitStart(finalInstanceId);
            }
            try {
                const initStart = performance.now();
                // 使用中间件包装初始化函数
                const initContext = await middlewareManager.execute(options, async ()=>{
                    return await initialization(options, (progress, step)=>{
                        logger.debug(`初始化进度: ${progress}%${step ? ` - ${step}` : ''}`);
                    });
                });
                const initDuration = performance.now() - initStart;
                // 触发初始化完成事件
                if (frameworkEventManager) {
                    frameworkEventManager.emitAppInitComplete(finalInstanceId, initContext, initDuration);
                }
                if (performanceTracker) {
                    performanceTracker.recordInitialization(initDuration);
                }
                logger.info('初始化完成（无启动页）', initContext);
                logger.info('框架加载完成');
                renderApp(initContext);
            } catch (error) {
                logger.error('初始化失败:', error);
                // 触发初始化错误事件
                if (frameworkEventManager) {
                    frameworkEventManager.emitAppInitError(finalInstanceId, error instanceof Error ? error : new Error(String(error)));
                }
                initializationErrorState.setError(error);
                renderApp();
            }
        }
        return instanceManager;
    } catch (error) {
        logger.error('框架启动失败:', error);
        // 触发错误事件
        if (frameworkEventManager) {
            const errorInstanceId = instanceId || instanceManager.getInstance()?.id;
            if (errorInstanceId) {
                frameworkEventManager.emitErrorOccurred(error instanceof Error ? error : new Error(String(error)), {
                    phase: 'startup'
                });
            }
        }
        // 如果容器存在，尝试渲染错误页面
        const container = options.container || envDetector.safeGetElement('#root');
        if (container) {
            const errorInstance = instanceManager.getInstance();
            if (errorInstance && errorInstance.isInitialized()) {
                const renderer = errorInstance.getRenderer();
                const services = errorInstance.getServices();
                initializationErrorState.setError(error);
                renderer.renderError(options, services);
            }
        }
        throw error;
    }
}

//# sourceMappingURL=startApp.js.map