package com.ruoyi.interfaces.workflow;

import com.ruoyi.interfaces.domain.MdModelStepExecution;
import lombok.Data;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * 工作流执行结果
 */
@Data
public class ExecutionResult {

    // 执行状态枚举
    public enum ExecutionStatus {
        RUNNING,      // 执行中
        SUCCESS,      // 成功
        FAILED,       // 失败
        TIMEOUT,      // 超时
        PARTIAL_SUCCESS // 部分成功
    }

    // Getter & Setter 方法
    private String executionId;          // 执行ID
    private ExecutionStatus status;      // 整体执行状态
    private String workflowId;           // 工作流ID
    private Map<String, Object> input;   // 输入数据
    private Map<String, Object> output;  // 最终输出数据
    private Map<String, Object> context; // 执行上下文(全部数据快照)
    private List<MdModelStepExecution> stepExecutions = new ArrayList<>(); // 步骤执行记录
    private String errorMessage;         // 错误信息（如整体失败）
    private long startTime;              // 开始时间(毫秒时间戳)
    private long endTime;                // 结束时间(毫秒时间戳)

    public ExecutionResult(String workflowId, Map<String, Object> input) {
        this.workflowId = workflowId;
        this.input = input;
        this.status = ExecutionStatus.RUNNING;
        this.context = new HashMap<>();
        this.startTime = System.currentTimeMillis();
    }

    // 添加步骤执行记录
    public void addStepExecution(MdModelStepExecution stepExecution) {
        stepExecutions.add(stepExecution);
    }

    // 标记执行成功
    public void markSuccess(Map<String, Object> output) {
        this.status = ExecutionStatus.SUCCESS;
        this.output = output;
        this.endTime = System.currentTimeMillis();
    }

    // 标记执行失败
    public void markFailed(String errorMessage) {
        this.status = ExecutionStatus.FAILED;
        this.errorMessage = errorMessage;
        this.endTime = System.currentTimeMillis();
    }

    // 标记部分成功（有条件的分支成功）
    public void markPartialSuccess(Map<String, Object> output, String reason) {
        this.status = ExecutionStatus.PARTIAL_SUCCESS;
        this.output = output;
        this.errorMessage = reason;
        this.endTime = System.currentTimeMillis();
    }

    // 计算总耗时（毫秒）
    public long getTotalDuration() {
        if (endTime > startTime) {
            return endTime - startTime;
        }
        return System.currentTimeMillis() - startTime;
    }

    // 获取某个步骤的执行记录
    public MdModelStepExecution getStepExecution(String stepName) {
        return stepExecutions.stream()
                .filter(se -> stepName.equals(se.getStepName()))
                .findFirst()
                .orElse(null);
    }

}

