/**
 * Copyright (c) 2025-2026, Michael Yang 杨福海 (fuhai999@gmail.com).
 * <p>
 * Licensed under the GNU Lesser General Public License (LGPL) ,Version 3.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 * <p>
 * http://www.gnu.org/licenses/lgpl-3.0.txt
 * <p>
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */
package com.easyagents.flow.core.parser.impl;

import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.easyagents.flow.core.chain.Parameter;
import com.easyagents.flow.core.node.LoopNode;
import com.easyagents.flow.core.parser.BaseNodeParser;

import java.util.List;

/**
 * 解析显式循环节点的双输入与旧版单输入配置。
 */
public class LoopNodeParser extends BaseNodeParser<LoopNode> {

    /**
     * {@inheritDoc}
     */
    @Override
    public LoopNode doParse(JSONObject root, JSONObject data, JSONObject chainJSONObject) {
        LoopNode loopNode = new LoopNode();

        JSONObject loopInputs = data.getJSONObject("loopInputs");
        if (loopInputs != null) {
            loopNode.setLoopCount(
                    parseParameter(loopInputs.getJSONObject("count")));
            loopNode.setLoopItems(
                    parseParameter(loopInputs.getJSONObject("items")));
            return loopNode;
        }

        // 新结构不存在时继续兼容旧版 loopVars[0]。
        List<Parameter> loopVars = getParameters(data, "loopVars");
        if (!loopVars.isEmpty()) {
            loopNode.setLoopVar(loopVars.get(0));
        }

        return loopNode;
    }

    /**
     * 将单个参数对象复用基础参数解析逻辑转换为运行时参数。
     *
     * @param parameterObject 参数 JSON
     * @return 参数对象；输入为空时返回 {@code null}
     */
    private Parameter parseParameter(JSONObject parameterObject) {
        if (parameterObject == null || parameterObject.isEmpty()) {
            return null;
        }
        JSONArray parameters = new JSONArray();
        parameters.add(parameterObject);
        List<Parameter> parsed = getParameters(parameters);
        return parsed.isEmpty() ? null : parsed.get(0);
    }
}
