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

import com.alibaba.fastjson2.JSONObject;
import com.cmvr.test.flow.context.TaskContext;
import com.cmvr.test.flow.context.TaskInstHolder;
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;

/**
 * 节点输出统一存储拦截器
 * 在节点执行结束后，把输出参数存入 TaskContext，支持循环迭代路径
 */
@Slf4j
@Component
@Order(5)
public class FlowOutputStoreInterceptor extends AbstractFlowMsgPreInterceptor {

    private final TaskInstHolder taskInstHolder;
    public FlowOutputStoreInterceptor(FlowExecutionEventPublisher eventPublisher, TaskInstHolder taskInstHolder) {
        super(eventPublisher);
        this.taskInstHolder = taskInstHolder;
    }

    @Override
    public TaskNodeExecuteResult doIntercept(TaskNodeExecuteMessage message,
                                           Function<TaskNodeExecuteMessage, TaskNodeExecuteResult> next) {

        TaskNodeExecuteResult result = next.apply(message);

        if (result != null && result.isSuccess()) {
            TaskContext ctx = taskInstHolder.getContext(message.getInstId());
            if (ctx != null) {
                JSONObject outputParams = result.getOutputParams();
                ctx.setNodeOutput(message.getNodeId(), message.getIterations(), outputParams);
                log.debug("[OutputStore] 保存节点输出: instId={}, nodeId={}, iterations={}, output={}",
                        message.getInstId(), message.getNodeId(), message.getIterations(), outputParams);
            }
        }
        return result;
    }
}
