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

import cn.com.poc.agent_application.entity.KnowledgeContentResult;
import cn.com.poc.agent_application.entity.Variable;
import cn.com.poc.common.utils.DocumentLoad;
import cn.com.poc.common.utils.JsonUtils;
import cn.com.poc.common.utils.StringUtils;
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 org.springframework.stereotype.Component;

import java.util.List;

@Component
public class HtmlReaderFunction extends AbstractLargeModelFunction {


    private final String DESC = "该方法用于加载和读取Html网页内容，并转换为markdown格式。";

    private final FunctionLLMConfig functionLLMConfig = new FunctionLLMConfig.FunctionLLMConfigBuilder()
            .name("html_reader")
            .description(DESC)
            .parameters(new Parameters("object")
                    .addProperties("url", new Properties("string", "网页地址")))
            .build();

    @Override
    public AbstractFunctionResult<String> doFunction(String content, String key, List<DBChainResult> dbChainResults, List<KnowledgeContentResult> knowledgeContentResults) {
        AbstractFunctionResult<String> result = new AbstractFunctionResult<>();
        if (StringUtils.isBlank(content)) {
            result.setFunctionResult("FAIL");
            result.setPromptContent("参数为空");
            return result;
        }
        JSONObject jsonObject = JSONObject.parseObject(content);
        String url = jsonObject.getString("url");
        if (StringUtils.isNotBlank(url)) {
            String res = DocumentLoad.loadHtml(url);
            result.setFunctionResult(res);
            result.setPromptContent(res);
            return result;
        }
        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();
    }

}
