package cn.com.poc.thirdparty.resource.demand.ai.function.calculator;

import cn.com.poc.agent_application.entity.KnowledgeContentResult;
import cn.com.poc.agent_application.entity.Variable;
import cn.com.poc.common.utils.JsonUtils;
import cn.com.poc.thirdparty.resource.demand.ai.entity.dbchain.DBChainResult;
import cn.com.poc.thirdparty.resource.demand.ai.function.AbstractFunctionResult;
import cn.com.poc.thirdparty.resource.demand.ai.function.AbstractLargeModelFunction;
import cn.com.poc.thirdparty.resource.demand.ai.function.entity.FunctionLLMConfig;
import cn.com.poc.thirdparty.resource.demand.ai.function.entity.Parameters;
import cn.com.poc.thirdparty.resource.demand.ai.function.entity.Properties;
import cn.hutool.core.collection.ListUtil;
import com.alibaba.fastjson.JSONObject;
import com.googlecode.aviator.AviatorEvaluator;
import org.springframework.stereotype.Component;

import java.util.List;

/**
 * @author alex.yao
 * @date 2025/3/21
 */
@Component
public class CalculatorFunction extends AbstractLargeModelFunction {
    private final String DESC = "该方法是计算算术表达式，如 12/(7-1.0)";

    private final FunctionLLMConfig functionLLMConfig = new FunctionLLMConfig.FunctionLLMConfigBuilder()
            .name("calculator")
            .description(DESC)
            .parameters(new Parameters("object")
                    .addProperties("arithmetic_expression", new Properties("string", "算术表达式,需要精确的算术表达式如6的平方或6的2次方为 6*6，9的5次方为9*9*9*9*9")))
            .build();

    @Override
    public AbstractFunctionResult<String> doFunction(String content, String identifier, List<DBChainResult> dbChainResults, List<KnowledgeContentResult> knowledgeContentResults) {

        JSONObject jsonObject = JSONObject.parseObject(content);
        String arithmeticExpression = jsonObject.getString("arithmetic_expression");
        String answer = AviatorEvaluator.compile(arithmeticExpression).execute().toString();
        AbstractFunctionResult<String> result = new AbstractFunctionResult<String>();
        result.setPromptContent(answer);
        result.setFunctionResult(answer);
        return result;
    }

    @Override
    public String getDesc() {
        return DESC;
    }

    @Override
    public List<String> getLLMConfig() {
        return ListUtil.toList(JsonUtils.serialize(functionLLMConfig));
    }

    @Override
    public List<String> getLLMConfig(List<Variable> variableStructure) {
        return this.getLLMConfig();
    }
}
