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> {

    /**
     * 将 TinyFlow 条件节点配置解析为运行时节点。
     *
     * @param root 节点根配置
     * @param data 节点业务配置
     * @param tinyflow 工作流配置
     * @return 条件判断运行时节点
     * @throws RuntimeException 分支或规则配置无效
     */
    @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("条件判断节点必须配置默认分支");
        }
        validateBranches(branches);

        return node;
    }

    /**
     * 返回条件节点类型名称。
     *
     * @return 条件节点类型名称
     */
    public String getNodeName() {
        return "conditionNode";
    }

    /**
     * 校验可视化分支内的全部条件规则。
     *
     * @param branches 条件分支
     * @throws RuntimeException 任一规则配置无效
     */
    private void validateBranches(List<ConditionNode.ConditionBranch> branches) {
        for (int branchIndex = 0; branchIndex < branches.size(); branchIndex++) {
            ConditionNode.ConditionBranch branch = branches.get(branchIndex);
            if (branch == null
                    || "expression".equalsIgnoreCase(
                    StringUtil.getFirstWithText(branch.getMode(), "visual"))) {
                continue;
            }
            List<ConditionNode.ConditionRule> rules = branch.getRules();
            if (rules == null || rules.isEmpty()) {
                continue;
            }
            for (int ruleIndex = 0; ruleIndex < rules.size(); ruleIndex++) {
                String error = ConditionRuleSupport.validateRule(rules.get(ruleIndex));
                if (error != null) {
                    String branchName = StringUtil.getFirstWithText(
                            branch.getLabel(),
                            branch.getId(),
                            "第 " + (branchIndex + 1) + " 个分支");
                    throw new RuntimeException(
                            "条件分支[" + branchName + "]第 " + (ruleIndex + 1)
                                    + " 条规则配置无效: " + error);
                }
            }
        }
    }
}
