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

import cn.hutool.core.bean.BeanUtil;
import com.alibaba.fastjson2.JSONObject;
import com.cmvr.common.utils.spring.SpringUtils;
import com.cmvr.test.flow.builder.FlowGraph;
import com.cmvr.test.flow.builder.FlowNodeWrapper;
import com.cmvr.test.flow.context.TaskThreadRegistry;
import com.cmvr.test.flow.runtime.engine.FlowItemExecutor;
import com.cmvr.test.flow.runtime.message.TaskNodeExecuteMessage;
import com.cmvr.test.flow.runtime.message.TaskNodeExecuteResult;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Component;

import java.util.ArrayList;
import java.util.List;
import java.util.concurrent.CountDownLatch;

@Slf4j
@Component("LOOP")
@RequiredArgsConstructor
public class FlowLoopNodeHandler implements FlowNodeTypeHandler {

    private final TaskThreadRegistry taskThreadRegistry;

    @Override
    public TaskNodeExecuteResult handle(TaskNodeExecuteMessage message) {
        String instId = message.getInstId();
        FlowGraph graph = message.getGraph();
        JSONObject inputParams = message.getInputParams();
        // 当前从第几次循环开始
        int loopStartNum = Math.max(message.getLoopNum(), 1);
        // 父级迭代路径
        List<Integer> parentIterations = message.getIterations();

        String nodeId = message.getNodeId();
        FlowNodeWrapper nodeWrapper = graph.getNode(nodeId);
        int loopCount = inputParams.getIntValue("loopNum"); // 获取循环次数
        Object loopArray = inputParams.get("loopArray"); // 获取循环次数

        // 如果没有设置循环次数或者循环次数为 0，则跳过处理
        if (loopCount <= 0) {
            log.warn("循环节点 {} 没有有效的 loopCount 参数，跳过处理", nodeId);
            return TaskNodeExecuteResult.success(inputParams);
        }
        FlowGraph subGraph = nodeWrapper.getSubGraph();
        subGraph.setSub(true);

        // 循环执行子图
        for (int i = loopStartNum; i <= loopCount; i++) {
            // 如果子图设置了跳出标志，则结束循环
            if (subGraph.isBreakLoop()) {
                log.info("检测到子图设置跳出标志，提前结束循环：instId={}, nodeId={}", instId, nodeId);
                break;
            }
            CountDownLatch latch = new CountDownLatch(1);

            taskThreadRegistry.registerLatch(instId, nodeId, latch);
            FlowItemExecutor flowItemExecutor = SpringUtils.getBean(FlowItemExecutor.class);

            // 构造新的迭代路径
            List<Integer> newIterations = new ArrayList<>(parentIterations);
            newIterations.add(i);

            // 克隆 message，并明确设置 loopNum
            TaskNodeExecuteMessage subMessage = new TaskNodeExecuteMessage();
            BeanUtil.copyProperties(message, subMessage);
            subMessage.setLoopNum(i);                  // 当前 loop 第 i 次
            subMessage.setIterations(newIterations);   // 完整路径
            subMessage.setLoopArray(loopArray);

            flowItemExecutor.executeSubGraph(subGraph, subMessage, latch::countDown, newIterations);

            try {
                latch.await(); // 等待子图执行完毕后再进行下一轮
            } catch (InterruptedException e) {
                log.error("循环第 {} 次等待中断", i, e);
                Thread.currentThread().interrupt(); // 保留中断标志
                break;
            } finally {
                taskThreadRegistry.releaseLatch(instId, nodeId);
            }
        }

        // 返回执行结果
        return TaskNodeExecuteResult.success(inputParams);
    }
}
