package tech.easyflow.ai.node;

import com.easyagents.flow.core.chain.Chain;
import com.easyagents.flow.core.chain.runtime.ChainExecutor;
import com.easyagents.flow.core.node.BaseNode;
import tech.easyflow.ai.entity.Workflow;
import tech.easyflow.ai.service.WorkflowService;
import tech.easyflow.common.util.SpringContextUtil;

import java.util.Map;

/**
 * 在独立子工作流执行通道中同步执行子工作流。
 */
public class WorkflowNode extends BaseNode {
    private static final long serialVersionUID = 1L;


    private String workflowId;

    public WorkflowNode() {
    }

    public WorkflowNode(String workflowId) {
        this.workflowId = workflowId;
    }

    /**
     * 执行子流程并返回其业务结果。
     *
     * @param chain 父工作流
     * @return 子流程完成结果，或保持当前节点运行的控制结果
     */
    @Override
    public Map<String, Object> execute(Chain chain) {
        Map<String, Object> params =
                chain.getExecutionState()
                        .resolveParameters(this);
        WorkflowService service =
                SpringContextUtil.getBean(WorkflowService.class);
        Workflow workflow = service.getById(workflowId);
        if (workflow == null) {
            throw new RuntimeException("工作流不存在：" + workflowId);
        }
        ChainExecutor executor =
                SpringContextUtil.getBean(ChainExecutor.class);
        return executor.executeChild(
                workflowId, params, chain, this.id);
    }

    public String getWorkflowId() {
        return workflowId;
    }

    public void setWorkflowId(String workflowId) {
        this.workflowId = workflowId;
    }
}
