package com.cmvr.test.flow.runtime.interceptor;

import com.alibaba.fastjson2.JSONObject;
import com.cmvr.test.flow.builder.FlowGraph;
import com.cmvr.test.flow.builder.FlowNodeWrapper;
import com.cmvr.test.flow.runtime.engine.support.FlowNodeParamPreparer;
import com.cmvr.test.flow.runtime.event.FlowExecutionEventPublisher;
import com.cmvr.test.flow.runtime.message.TaskNodeExecuteMessage;
import com.cmvr.test.flow.runtime.message.TaskNodeExecuteResult;
import lombok.extern.slf4j.Slf4j;
import org.springframework.core.annotation.Order;
import org.springframework.stereotype.Component;

import java.util.function.Function;

/**
 * 节点输入参数准备拦截器
 * 在执行 OperatorService 前，利用 FlowNodeParamPreparer 生成 inputParams
 */
@Slf4j
@Component
@Order(2)
public class FlowInputPrepareInterceptor extends AbstractFlowMsgPreInterceptor {

    private final FlowNodeParamPreparer paramPreparer;

    public FlowInputPrepareInterceptor(FlowExecutionEventPublisher eventPublisher, FlowNodeParamPreparer paramPreparer) {
        super(eventPublisher);
        this.paramPreparer = paramPreparer;
    }


    @Override
    public TaskNodeExecuteResult doIntercept(TaskNodeExecuteMessage message,
                                           Function<TaskNodeExecuteMessage, TaskNodeExecuteResult> next) {
        FlowGraph graph = message.getGraph();
        FlowNodeWrapper node = graph.getNode(message.getNodeId());

        // 调用已有的 prepare 方法
        JSONObject inputParams = paramPreparer.prepare(graph, node, message);

        message.setInputParams(inputParams);
        log.debug("[InputPrepare] 节点 {} 准备输入参数: {}", message.getNodeId(), inputParams);

        // 执行下一个拦截器 / OperatorService
        return next.apply(message);
    }
}
