import { logger } from '../../utils/logger';
import { FeatureGovernanceService } from '../governance/FeatureGovernanceService';

export interface DomainModule {
  name: string;
  priority: number;
  init: () => Promise<void>;
  isAgi?: boolean; // 是否属于重型 AGI 模块
}

/**
 * [ARCH_LIGHT_01] 领域注册中心 (Domain Registry)
 * @description 核心逻辑：解耦 index.ts 中的服务初始化，支持按优先级、按领域、按 AGI 降级策略进行加载。
 */
export class DomainRegistry {
  private static modules: DomainModule[] = [];

  /**
   * 注册领域模块
   */
  static register(module: DomainModule) {
    this.modules.push(module);
  }

  /**
   * 执行全量初始化
   */
  static async bootstrap(tenantId?: string) {
    // 1. 按优先级排序 (低值优先)
    const sortedModules = [...this.modules].sort((a, b) => a.priority - b.priority);

    // 2. 检查 AGI 基础模式开关 (如果开启，则跳过重型 AGI 模块)
    const isAgiBaseMode = await FeatureGovernanceService.isEnabled('CORE_AGI_BASE_MODE', tenantId);
    
    logger.info(`[DomainRegistry] Bootstrapping ${sortedModules.length} modules... (AGI Base Mode: ${isAgiBaseMode})`);

    for (const module of sortedModules) {
      if (module.isAgi && isAgiBaseMode) {
        logger.warn(`[DomainRegistry] Skipping Heavy AGI module: ${module.name} (Base Mode Active)`);
        continue;
      }

      try {
        await module.init();
        logger.info(`[DomainRegistry] Module initialized: ${module.name}`);
      } catch (err: any) {
        logger.error(`[DomainRegistry] Module ${module.name} failed to initialize: ${err.message}`);
        // 核心模块失败应抛出异常，非核心模块可继续
        if (module.priority < 10) throw err;
      }
    }

    logger.info('✅ [DomainRegistry] Bootstrap completed successfully.');
  }

  /**
   * 预定义优先级常量
   */
  static Priority = {
    CORE_INFRA: 0,      // 核心基础设施 (DB, Cache, Governance)
    SECURITY: 5,        // 安全与身份 (Auth, DID, ZKP)
    RUNTIME: 10,        // 运行时引擎 (AsyncEngine, PluginMgr)
    BIZ_DOMAIN: 20,     // 业务领域 (Orders, Products, Trade)
    AGI_HEAVY: 50,      // 重型 AGI (Evolution, RCA, XAI)
    SUPPORT: 100        // 辅助支撑 (Logistics, Tax, Sync)
  };
}
