/**
 * 通用工作流引擎
 * 所有浏览器Provider共享，不依赖特定浏览器API
 */

import { IActionFactory, IActionContext } from '../core/interfaces/IAction';

export interface IWorkflowStep {
  action: string;
  name?: string;
  [key: string]: any;
}

export interface IWorkflowResult {
  success: boolean;
  steps: number;
  errors: any[];
  duration: number;
}

export class WorkflowEngine {
  private workflow: IWorkflowStep[];
  private context: IActionContext;
  private actionFactory: IActionFactory;
  private startTime: number = 0;

  constructor(
    workflow: IWorkflowStep[],
    context: IActionContext,
    actionFactory: IActionFactory
  ) {
    this.workflow = workflow;
    this.context = context;
    this.actionFactory = actionFactory;
  }

  async execute(): Promise<IWorkflowResult> {
    this.startTime = Date.now();
    const errors: any[] = [];
    let completedSteps = 0;

    console.log(`\n[WorkflowEngine] Starting workflow with ${this.workflow.length} steps\n`);

    for (let i = 0; i < this.workflow.length; i++) {
      const step = this.workflow[i];
      
      try {
        console.log(`[WorkflowEngine] [${i + 1}/${this.workflow.length}] ${step.name || step.action}`);
        
        await this.executeStep(step);
        completedSteps++;
        
      } catch (error: any) {
        errors.push({
          step: i + 1,
          name: step.name || step.action,
          error: error.message
        });

        // 如果步骤不是可选的，停止执行
        if (!step.optional) {
          console.error(`[WorkflowEngine] ❌ Fatal error at step ${i + 1}, stopping workflow`);
          break;
        }

        console.warn(`[WorkflowEngine] ⚠️  Step ${i + 1} failed but is optional, continuing...`);
      }
    }

    const duration = Date.now() - this.startTime;
    const success = errors.length === 0 || errors.every((e: any, i: number) => 
      this.workflow[i]?.optional
    );

    console.log(`\n[WorkflowEngine] Workflow completed: ${completedSteps}/${this.workflow.length} steps`);
    console.log(`[WorkflowEngine] Duration: ${(duration / 1000).toFixed(2)}s`);
    console.log(`[WorkflowEngine] Errors: ${errors.length}\n`);

    return {
      success,
      steps: completedSteps,
      errors,
      duration
    };
  }

  private async executeStep(step: IWorkflowStep): Promise<void> {
    // 从ActionFactory获取Action类
    const ActionClass = this.actionFactory.getAction(step.action);
    
    if (!ActionClass) {
      throw new Error(`Unknown action: ${step.action}`);
    }

    // 创建Action实例（参数顺序：context, config）
    const action = new ActionClass(this.context, step);

    // 执行（多态！不需要知道具体实现）
    const result = await action.execute();

    if (!result.success) {
      throw new Error(result.error?.message || 'Action failed');
    }
  }
}
