function _define_property(obj, key, value) {
    if (key in obj) {
        Object.defineProperty(obj, key, {
            value: value,
            enumerable: true,
            configurable: true,
            writable: true
        });
    } else {
        obj[key] = value;
    }
    return obj;
}
import { logger } from "../../utils";
import { transformRoutes } from "./utils/transform";
import { transformRoutesToReactRoutes } from "./utils/adapters/react-router/transform";
import { createBrowserRouter, createHashRouter, createMemoryRouter } from "react-router-dom";
import { RouterConfigValidator } from "./validation";
import { getRouterLifecycleManager } from "./lifecycle";
import { getRouterMiddlewareManager } from "./middleware";
import { RouterError, RouterErrorCode } from "./errors";
import { getRouteCache } from "./performance/RouteCache";
import { getRoutePreloader } from "./performance/RoutePreloader";
import { getRouterPluginManager, PluginLifecycleStage } from "./plugin";
import { getRouterMonitoring } from "./monitoring";
import { getAdapterManager } from "./adapter";
import { createReactRouterAdapter } from "./adapter/react-router";
export class RouterManager {
    /**
     * 获取单例实例
     */ static getInstance() {
        if (!RouterManager.instance) {
            RouterManager.instance = new RouterManager();
        }
        return RouterManager.instance;
    }
    /**
     * 初始化路由管理器
     * 
     * @param config - 路由配置
     * @param _appInstance - 应用实例（保留用于兼容性，当前未使用）
     */ async initialize(config) {
        // 如果路由被禁用，直接返回
        if (config.enabled === false || config.enabled === 'disabled') {
            logger.info('路由系统已禁用');
            return;
        }
        // 配置验证（如果启用）
        if (config.enableValidation !== false) {
            try {
                RouterConfigValidator.validate(config);
                logger.debug('路由配置验证通过');
            } catch (error) {
                logger.error('路由配置验证失败', error);
                // 开发环境下抛出错误，生产环境下记录警告但继续执行
                if (process.env.NODE_ENV === 'development') {
                    throw error;
                }
            }
        }
        // 执行插件钩子：路由初始化前
        await this.pluginManager.executeHooks(PluginLifecycleStage.BEFORE_INIT, {
            config
        });
        // 注册生命周期钩子
        if (config.hooks) {
            const lifecycleManager = getRouterLifecycleManager();
            lifecycleManager.register(config.hooks);
            logger.debug('路由生命周期钩子已注册');
        }
        // 转换数据（使用缓存）
        if (!config.routes) {
            throw new RouterError('路由配置不能为空', RouterErrorCode.ROUTER_CONFIG_ERROR);
        }
        let result;
        const cacheKey = config.routes;
        const cachedResult = this.cache.get(cacheKey);
        if (cachedResult) {
            logger.debug('使用缓存的路由转换结果');
            result = cachedResult;
        } else {
            // 执行插件钩子：路由转换前
            await this.pluginManager.executeHooks(PluginLifecycleStage.BEFORE_TRANSFORM, {
                config
            });
            result = await transformRoutes(config.routes, config.transformOptions);
            // 执行插件钩子：路由转换后
            await this.pluginManager.executeHooks(PluginLifecycleStage.AFTER_TRANSFORM, {
                config,
                routes: result.routes
            });
            // 缓存转换结果
            this.cache.set(cacheKey, result);
        }
        const reactRoutes = await transformRoutesToReactRoutes(result.routes, result, config.defaultRouteErrorComponent, config.defaultRouteLoadingComponent);
        // 注册路由到预加载器
        if (result.routes) {
            this.preloader.registerRoutes(result.routes);
            // 开始预加载
            this.preloader.startPreload();
        }
        let routerInstance = null;
        if (config.mode === 'browser') {
            routerInstance = createBrowserRouter(reactRoutes, config.options);
        } else if (config.mode === 'hash') {
            routerInstance = createHashRouter(reactRoutes, config.options);
        } else if (config.mode === 'memory') {
            routerInstance = createMemoryRouter(reactRoutes, config.options);
        }
        if (!routerInstance) {
            throw new RouterError('路由模式不支持', RouterErrorCode.ROUTER_CONFIG_ERROR, undefined, undefined, {
                mode: config.mode
            });
        }
        // 只能在 initialize 方法中赋值
        this.router = routerInstance;
        this.initialized = true;
        // 执行插件钩子：路由初始化后
        await this.pluginManager.executeHooks(PluginLifecycleStage.AFTER_INIT, {
            config,
            routes: result.routes
        });
        // 记录监控：路由初始化完成
        this.monitoring.trackRouteAccess({
            path: window.location.pathname,
            meta: {
                name: 'router-init'
            }
        }, undefined, true);
        logger.info('路由管理器初始化完成');
    }
    /**
     * 获取路由实例
     * 
     * @returns 路由实例，如果未初始化则返回 null
     */ getRouter() {
        return this.router;
    }
    /**
     * 检查是否已初始化
     * 
     * @returns 如果已初始化返回 true，否则返回 false
     */ isInitialized() {
        return this.initialized;
    }
    /**
     * 销毁路由管理器
     */ destroy() {
        // 执行插件钩子：销毁
        this.pluginManager.executeHooks(PluginLifecycleStage.DESTROY, {
            config: {}
        });
        // 停止预加载
        this.preloader.stopPreload();
        this.router = null;
        this.initialized = false;
        // 清空生命周期钩子和中间件
        const lifecycleManager = getRouterLifecycleManager();
        lifecycleManager.clear();
        const middlewareManager = getRouterMiddlewareManager();
        middlewareManager.clear();
        logger.info('路由管理器已销毁');
    }
    /**
     * 获取路由缓存实例
     */ getCache() {
        return this.cache;
    }
    /**
     * 获取路由预加载器实例
     */ getPreloader() {
        return this.preloader;
    }
    /**
     * 获取路由插件管理器实例
     */ getPluginManager() {
        return this.pluginManager;
    }
    /**
     * 获取路由监控服务实例
     */ getMonitoring() {
        return this.monitoring;
    }
    constructor(){
        /**
     * 路由实例
     * 只能在 initialize 方法中赋值
     */ _define_property(this, "router", null);
        /**
     * 是否已初始化
     */ _define_property(this, "initialized", false);
        /**
     * 路由缓存实例
     */ _define_property(this, "cache", getRouteCache());
        /**
     * 路由预加载器实例
     */ _define_property(this, "preloader", getRoutePreloader());
        /**
     * 路由插件管理器实例
     */ _define_property(this, "pluginManager", getRouterPluginManager());
        /**
     * 路由监控服务实例
     */ _define_property(this, "monitoring", getRouterMonitoring());
        /**
     * 路由适配器管理器实例
     */ _define_property(this, "adapterManager", getAdapterManager());
        // 私有构造函数
        // 注册默认的 React Router 适配器
        this.adapterManager.register({
            name: 'react-router',
            factory: createReactRouterAdapter(),
            priority: 10
        });
    }
}
_define_property(RouterManager, "instance", null);
/**
 * 获取路由管理器
 */ export function getRouterManager() {
    return RouterManager.getInstance();
}

//# sourceMappingURL=RouterManager.js.map