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

    protected String engine;
    protected String code;

    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;
    }

    @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);
    }

}
