package tech.easyflow.ai.node;

import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.easyagents.flow.core.parser.BaseNodeParser;
import com.easyagents.flow.core.util.StringUtil;

import java.util.Collections;
import java.util.List;

/**
 * 条件判断节点解析器。
 */
public class ConditionNodeParser extends BaseNodeParser<ConditionNode> {

    @Override
    protected ConditionNode doParse(JSONObject root, JSONObject data, JSONObject tinyflow) {
        ConditionNode node = new ConditionNode();
        node.setBranchMode(StringUtil.getFirstWithText(data.getString("branchMode"), "first_match"));
        node.setDefaultBranchId(data.getString("defaultBranchId"));
        node.setDefaultBranchLabel(data.getString("defaultBranchLabel"));

        JSONArray branchesJson = data.getJSONArray("branches");
        List<ConditionNode.ConditionBranch> branches = branchesJson == null
                ? Collections.emptyList()
                : branchesJson.toJavaList(ConditionNode.ConditionBranch.class);
        node.setBranches(branches);

        if (branches.isEmpty()) {
            throw new RuntimeException("条件判断节点至少需要一个分支");
        }
        if (StringUtil.noText(node.getDefaultBranchId())) {
            throw new RuntimeException("条件判断节点必须配置默认分支");
        }

        return node;
    }

    public String getNodeName() {
        return "conditionNode";
    }
}
