/**
 * LibRegistry - 全局库注册表
 * 管理所有共享库的实例
 */

class LibRegistry {
  constructor() {
    this.libs = new Map();
  }
  
  /**
   * 注册库
   */
  register(lib) {
    if (this.libs.has(lib.name)) {
      console.warn(`[LibRegistry] Library ${lib.name} already registered, replacing...`);
    }
    this.libs.set(lib.name, lib);
  }
  
  /**
   * 获取库实例
   */
  get(name) {
    return this.libs.get(name);
  }
  
  /**
   * 检查库是否已注册
   */
  has(name) {
    return this.libs.has(name);
  }
  
  /**
   * 获取所有库
   */
  getAll() {
    return Array.from(this.libs.values());
  }
  
  /**
   * 获取所有库的信息
   */
  getAllInfo() {
    return this.getAll().map(lib => lib.getInfo());
  }
  
  /**
   * 初始化所有库
   */
  async initializeAll() {
    const libs = this.getAll();
    for (const lib of libs) {
      if (!lib.initialized) {
        await lib.initialize();
      }
    }
  }
  
  /**
   * 清理所有库
   */
  async cleanupAll() {
    const libs = this.getAll();
    for (const lib of libs) {
      if (lib.initialized) {
        await lib.cleanup();
      }
    }
  }
}

// 创建全局单例
if (!global.__libRegistry) {
  global.__libRegistry = new LibRegistry();
}

module.exports = global.__libRegistry;
