const ActionRegistry = require('./action-registry');
const ConfigValidator = require('./config-validator');
const PerformanceTracker = require('./performance-tracker');

// 导入内置动作
const NavigateAction = require('../actions/navigate-action');
const FillFormAction = require('../actions/fill-form-action');
const ClickAction = require('../actions/click-action');
const WaitAction = require('../actions/wait-action');
const CustomAction = require('../actions/custom-action');
const RetryBlockAction = require('../actions/retry-block-action');
const ExtractAction = require('../actions/extract-action');
const VerifyAction = require('../actions/verify-action');
const ScrollAction = require('../actions/scroll-action');

/**
 * 工作流引擎 - 执行配置驱动的自动化流程
 */
class WorkflowEngine {
  constructor(context, config) {
    this.context = context;
    this.config = config;
    this.actionRegistry = new ActionRegistry();
    this.currentStep = 0;
    
    // 性能追踪
    this.performanceTracker = new PerformanceTracker();
    
    // 验证配置
    if (context.validateConfig !== false) {
      const validator = new ConfigValidator();
      const result = validator.validate(config);
      if (!result.valid) {
        this.log('warn', '配置验证警告:');
        result.errors.forEach(err => this.log('warn', `  - ${err}`));
      }
    }
    
    // 注册内置动作
    this.registerBuiltinActions();
  }
  
  /**
   * 注册内置动作
   */
  registerBuiltinActions() {
    this.actionRegistry.register('navigate', NavigateAction);
    this.actionRegistry.register('fillForm', FillFormAction);
    this.actionRegistry.register('click', ClickAction);
    this.actionRegistry.register('wait', WaitAction);
    this.actionRegistry.register('custom', CustomAction);
    this.actionRegistry.register('retryBlock', RetryBlockAction);
    this.actionRegistry.register('extract', ExtractAction);
    this.actionRegistry.register('verify', VerifyAction);
    this.actionRegistry.register('scroll', ScrollAction);
  }
  
  /**
   * 执行工作流
   * @returns {Promise<Object>} - 执行结果
   */
  async execute() {
    // 检查是否使用配置
    if (this.context.adapter && this.context.adapter.useConfig === false) {
      // 完全自定义模式
      this.log('info', '使用完全自定义模式');
      return await this.context.adapter.execute();
    }
    
    // 配置驱动模式
    const workflow = this.config.workflow;
    
    if (!workflow || workflow.length === 0) {
      throw new Error('工作流配置为空');
    }
    
    this.log('info', `开始执行工作流，共 ${workflow.length} 个步骤`);
    
    return await this.executeActions(workflow);
  }
  
  /**
   * 执行动作列表
   * @param {Array} actions - 动作配置数组
   * @returns {Promise<Object>}
   */
  async executeActions(actions) {
    const results = [];
    
    for (let i = 0; i < actions.length; i++) {
      const actionConfig = actions[i];
      this.currentStep = i + 1;
      
      const stepName = actionConfig.name || `步骤 ${this.currentStep}`;
      this.log('info', `[${this.currentStep}/${actions.length}] ${stepName}`);
      
      // 开始性能追踪
      this.performanceTracker.startStep(stepName, i);
      
      try {
        const result = await this.executeAction(actionConfig);
        
        // 记录成功
        const metric = this.performanceTracker.endStep(true);
        this.log('debug', `✓ 完成 (${metric.duration}ms)`);
        
        results.push({ step: i, success: true, result });
        
      } catch (error) {
        // 记录失败
        this.performanceTracker.endStep(false, error);
        this.log('error', `步骤失败: ${error.message}`);
        
        // 检查是否是可选步骤
        if (actionConfig.optional) {
          this.log('warn', '可选步骤失败，继续执行');
          results.push({ step: i, success: false, error: error.message, optional: true });
          continue;
        }
        
        // 检查重试配置
        if (actionConfig.retry) {
          const success = await this.retryAction(actionConfig);
          if (success) {
            results.push({ step: i, success: true, retried: true });
            continue;
          }
        }
        
        // 不可恢复的错误
        throw error;
      }
    }
    
    this.log('info', '工作流执行完成');
    
    // 输出性能报告
    if (this.context.performanceReport !== false) {
      this.log('info', this.performanceTracker.generateReport());
    }
    
    return { 
      success: true, 
      results,
      performance: this.performanceTracker.exportJSON()
    };
  }
  
  /**
   * 执行单个动作
   * @param {Object} config - 动作配置
   * @returns {Promise<any>}
   */
  async executeAction(config) {
    const ActionClass = this.actionRegistry.get(config.action);
    
    if (!ActionClass) {
      throw new Error(`未知动作类型: ${config.action}`);
    }
    
    const action = new ActionClass(this.context, config);
    return await action.execute();
  }
  
  /**
   * 重试动作
   * @param {Object} config - 动作配置
   * @returns {Promise<boolean>}
   */
  async retryAction(config) {
    const maxAttempts = config.retry.maxAttempts || 3;
    const delay = config.retry.delay || 2000;
    
    for (let attempt = 1; attempt <= maxAttempts; attempt++) {
      this.log('warn', `重试第 ${attempt}/${maxAttempts} 次...`);
      
      try {
        await new Promise(resolve => setTimeout(resolve, delay));
        await this.executeAction(config);
        this.log('info', '重试成功');
        return true;
      } catch (error) {
        this.log('error', `重试失败: ${error.message}`);
      }
    }
    
    return false;
  }
  
  /**
   * 记录日志
   */
  log(level, message) {
    if (this.context.logger && this.context.logger[level]) {
      this.context.logger[level](this.context.siteName || 'WorkflowEngine', message);
    } else {
      console.log(`[${level.toUpperCase()}] ${message}`);
    }
  }
}

module.exports = WorkflowEngine;
