/**
 * LibConfig - 库配置规范
 * 定义所有库的标准配置接口
 */

/**
 * 配置模式定义
 */
const CONFIG_SCHEMA = {
  // 基础配置
  base: {
    name: { type: 'string', required: true },
    version: { type: 'string', required: false, default: '1.0.0' },
    description: { type: 'string', required: false },
    author: { type: 'string', required: false }
  },
  
  // 运行时配置
  runtime: {
    logLevel: { type: 'string', required: false, default: 'info' },
    timeout: { type: 'number', required: false, default: 30000 },
    retries: { type: 'number', required: false, default: 3 }
  }
};

/**
 * 验证配置
 */
function validateLibConfig(config, schema = CONFIG_SCHEMA.base) {
  const errors = [];
  
  for (const [key, spec] of Object.entries(schema)) {
    // 检查必需字段
    if (spec.required && config[key] === undefined) {
      errors.push(`Missing required field: ${key}`);
    }
    
    // 检查类型
    if (config[key] !== undefined && typeof config[key] !== spec.type) {
      errors.push(`Invalid type for ${key}: expected ${spec.type}, got ${typeof config[key]}`);
    }
  }
  
  return {
    valid: errors.length === 0,
    errors
  };
}

/**
 * 应用默认配置
 */
function applyDefaults(config, schema = CONFIG_SCHEMA.base) {
  const result = { ...config };
  
  for (const [key, spec] of Object.entries(schema)) {
    if (result[key] === undefined && spec.default !== undefined) {
      result[key] = spec.default;
    }
  }
  
  return result;
}

/**
 * 创建库配置
 */
function createLibConfig(name, options = {}) {
  const baseConfig = {
    name,
    ...options
  };
  
  // 应用默认值
  const config = applyDefaults(baseConfig);
  
  // 验证配置
  const validation = validateLibConfig(config);
  if (!validation.valid) {
    throw new Error(`Invalid lib config: ${validation.errors.join(', ')}`);
  }
  
  return config;
}

module.exports = {
  CONFIG_SCHEMA,
  validateLibConfig,
  applyDefaults,
  createLibConfig
};
