/**
 * YAML 配置验证器
 */
class ConfigValidator {
  constructor() {
    // 定义每个 action 的必需字段
    this.actionSchemas = {
      navigate: {
        required: ['url'],
        optional: ['name', 'options', 'verifyUrl', 'verifyElements', 'waitAfter']
      },
      fillForm: {
        required: ['fields'],
        optional: ['name', 'humanLike']
      },
      click: {
        required: ['selector'],
        optional: ['name', 'verifyAfter', 'waitForPageChange', 'waitAfter', 'optional']
      },
      wait: {
        required: ['type'],
        optional: ['name', 'duration', 'find', 'timeout']
      },
      extract: {
        required: ['selector', 'contextKey'],
        optional: ['name', 'extractType', 'regex', 'saveTo', 'filter', 'multiple', 'required', 'attribute']
      },
      verify: {
        required: ['conditions'],
        optional: ['name', 'timeout', 'pollInterval', 'onSuccess', 'onFailure', 'onTimeout']
      },
      retryBlock: {
        required: ['steps'],
        optional: ['name', 'maxRetries', 'retryDelay', 'onRetryBefore', 'onRetryAfter']
      },
      custom: {
        required: ['handler'],
        optional: ['name', 'params', 'optional']
      }
    };
  }
  
  /**
   * 验证完整配置
   */
  validate(config) {
    const errors = [];
    
    // 验证基本结构
    if (!config.site) {
      errors.push('缺少 site 配置');
    }
    
    if (!config.workflow || !Array.isArray(config.workflow)) {
      errors.push('缺少 workflow 或 workflow 不是数组');
      return { valid: false, errors };
    }
    
    // 验证每个步骤
    config.workflow.forEach((step, index) => {
      const stepErrors = this.validateStep(step, index);
      errors.push(...stepErrors);
    });
    
    return {
      valid: errors.length === 0,
      errors
    };
  }
  
  /**
   * 验证单个步骤
   */
  validateStep(step, index) {
    const errors = [];
    const stepLabel = `步骤 ${index + 1} (${step.name || step.action})`;
    
    // 检查是否有 action
    if (!step.action) {
      errors.push(`${stepLabel}: 缺少 action 字段`);
      return errors;
    }
    
    // 检查 action 是否支持
    const schema = this.actionSchemas[step.action];
    if (!schema) {
      errors.push(`${stepLabel}: 未知的 action 类型 "${step.action}"`);
      return errors;
    }
    
    // 检查必需字段
    schema.required.forEach(field => {
      if (step[field] === undefined) {
        errors.push(`${stepLabel}: 缺少必需字段 "${field}"`);
      }
    });
    
    // 检查未知字段（警告）
    const allFields = [...schema.required, ...schema.optional, 'action'];
    Object.keys(step).forEach(field => {
      if (!allFields.includes(field)) {
        errors.push(`${stepLabel}: 警告 - 未知字段 "${field}"`);
      }
    });
    
    // 特定 action 的额外验证
    if (step.action === 'verify') {
      if (step.conditions) {
        if (!step.conditions.success && !step.conditions.failure) {
          errors.push(`${stepLabel}: conditions 必须包含 success 或 failure`);
        }
      }
    }
    
    if (step.action === 'retryBlock') {
      if (step.steps && Array.isArray(step.steps)) {
        step.steps.forEach((subStep, subIndex) => {
          const subErrors = this.validateStep(subStep, subIndex);
          errors.push(...subErrors.map(e => `${stepLabel} -> ${e}`));
        });
      }
    }
    
    return errors;
  }
  
  /**
   * 验证并打印结果
   */
  validateAndReport(config, logger = console) {
    const result = this.validate(config);
    
    if (result.valid) {
      logger.log('✓ 配置验证通过');
      return true;
    } else {
      logger.error('✗ 配置验证失败:');
      result.errors.forEach(error => {
        logger.error(`  - ${error}`);
      });
      return false;
    }
  }
}

module.exports = ConfigValidator;
