/**
 * BaseLib - 所有共享库的基类
 * 提供统一的接口、日志、配置管理
 */

const logger = require('../../logger');

class BaseLib {
  /**
   * @param {Object} config - 库配置
   * @param {string} config.name - 库名称
   * @param {string} config.version - 版本号
   * @param {Object} config.options - 可选配置
   */
  constructor(config = {}) {
    // 验证必需配置
    if (!config.name) {
      throw new Error('Lib must have a name');
    }
    
    this.name = config.name;
    this.version = config.version || '1.0.0';
    this.options = config.options || {};
    this.initialized = false;
    
    // 注册到全局注册表
    if (global.__libRegistry) {
      global.__libRegistry.register(this);
    }
  }
  
  /**
   * 初始化库（子类可重写）
   */
  async initialize() {
    if (this.initialized) {
      return;
    }
    
    this.log('info', `Initializing ${this.name} v${this.version}...`);
    
    // 子类实现具体初始化逻辑
    await this.onInitialize();
    
    this.initialized = true;
    this.log('info', `${this.name} initialized successfully`);
  }
  
  /**
   * 子类重写此方法实现初始化逻辑
   */
  async onInitialize() {
    // 子类实现
  }
  
  /**
   * 清理资源（子类可重写）
   */
  async cleanup() {
    this.log('info', `Cleaning up ${this.name}...`);
    await this.onCleanup();
    this.initialized = false;
  }
  
  /**
   * 子类重写此方法实现清理逻辑
   */
  async onCleanup() {
    // 子类实现
  }
  
  /**
   * 统一的日志方法
   */
  log(level, message) {
    const prefix = `[${this.name}]`;
    logger[level](prefix, message);
  }
  
  /**
   * 验证配置
   */
  validateConfig(required = []) {
    for (const key of required) {
      if (!this.options[key]) {
        throw new Error(`${this.name}: Missing required config: ${key}`);
      }
    }
  }
  
  /**
   * 获取配置项
   */
  getConfig(key, defaultValue = null) {
    return this.options[key] !== undefined ? this.options[key] : defaultValue;
  }
  
  /**
   * 设置配置项
   */
  setConfig(key, value) {
    this.options[key] = value;
  }
  
  /**
   * 获取库信息
   */
  getInfo() {
    return {
      name: this.name,
      version: this.version,
      initialized: this.initialized,
      options: this.options
    };
  }
}

module.exports = BaseLib;
