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

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.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.JSON;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import org.springframework.stereotype.Component;

import java.io.File;
import java.util.List;

@Component
public class DocumentReaderFunction extends AbstractLargeModelFunction {

    private final String DESC = "文档阅读器，读取PDF、docx、doc、txt、md格式文件";

    private final FunctionLLMConfig functionLLMConfig = new FunctionLLMConfig
            .FunctionLLMConfigBuilder()
            .name("document_reader")
            .description(DESC)
            .parameters(new Parameters("object")
                    .addProperties("file_urls", new Properties("array", "doc、docx、pdf、txt、md文件地址"))

            ).build();


    @Override
    public String doFunction(String content, String identifier) {
        if (StringUtils.isBlank(content)) {
            return StringUtils.EMPTY;
        }
        StringBuilder sb = new StringBuilder();
        JSONObject jsonObject = JSON.parseObject(content);
        if (jsonObject.containsKey("file_urls")) {
            JSONArray jsonArray = jsonObject.getJSONArray("file_urls");
            int size = jsonArray.size();
            if (size == 0) {
                return StringUtils.EMPTY;
            }
            for (int i = 0; i < size; i++) {
                String fileUrl = jsonArray.getString(i);
                File file = DocumentLoad.downloadURLDocument(fileUrl);
                sb.append(StringUtils.LF).append("## Document ").append((i + 1)).append(StringUtils.LF);
                sb.append(DocumentLoad.documentToText(file));
            }
            return sb.toString();
        }
        return StringUtils.EMPTY;
    }

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

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

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