/**
 * 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.node;

import com.easyagents.flow.core.chain.Chain;
import com.easyagents.flow.core.chain.ChainState;
import com.easyagents.flow.core.code.CodeRuntimeEngine;
import com.easyagents.flow.core.code.CodeRuntimeEngineManager;
import com.easyagents.flow.core.util.StringUtil;
import com.easyagents.flow.core.util.TextTemplate;

import java.util.Arrays;
import java.util.List;
import java.util.Map;

public class CodeNode extends BaseNode {
    private static final long serialVersionUID = 1L;

    /**
     * main 按节点参数顺序接收独立参数。
     */
    public static final String MAIN_ARGS_MODE_NAMED = "named";

    protected String engine;
    protected String code;
    /**
     * main 自动调用参数模式；空值沿用历史单对象参数。
     */
    protected String mainArgsMode;

    public String getEngine() {
        return engine;
    }

    public void setEngine(String engine) {
        this.engine = engine;
    }

    public String getCode() {
        return code;
    }

    public void setCode(String code) {
        this.code = code;
    }

    /**
     * 获取 main 自动调用参数模式。
     *
     * @return 参数模式；空值表示历史单对象参数模式
     */
    public String getMainArgsMode() {
        return mainArgsMode;
    }

    /**
     * 设置 main 自动调用参数模式。
     *
     * @param mainArgsMode 参数模式
     */
    public void setMainArgsMode(String mainArgsMode) {
        this.mainArgsMode = mainArgsMode;
    }

    @Override
    public Map<String, Object> execute(Chain chain) {
        if (StringUtil.noText(code)) {
            throw new IllegalArgumentException("code is empty");
        }

        ChainState chainState =
                chain.getExecutionState();
        Map<String, Object> parameterValues = chainState.resolveParameters(this);
        String newCode = TextTemplate.of(code).formatToString(chainState.buildTemplateRootMaps(parameterValues));

        CodeRuntimeEngine codeRuntimeEngine = CodeRuntimeEngineManager.getInstance().getCodeRuntimeEngine(this.engine);
        if (codeRuntimeEngine == null) {
            throw new IllegalArgumentException("code runtime engine not found: " + this.engine);
        }
        return codeRuntimeEngine.execute(
                newCode,
                this,
                chain,
                parameterValues);
    }

}
