package cn.com.poc.common.utils;

import cn.com.gsst.dify_client.DifyClientFactory;
import cn.com.gsst.dify_client.DifyWorkflowClient;
import cn.com.gsst.dify_client.enums.FileTransferMethod;
import cn.com.gsst.dify_client.enums.FileType;
import cn.com.gsst.dify_client.enums.ResponseMode;
import cn.com.gsst.dify_client.model.file.FileInfo;
import cn.com.gsst.dify_client.model.workflow.WorkflowRunRequest;
import cn.com.gsst.dify_client.model.workflow.WorkflowRunResponse;
import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.util.ArrayList;
import java.util.LinkedHashMap;
import java.util.List;
import java.util.Map;

/**
 * MD表格/表单转 json
 *
 * @author alex.yao
 * @date 2025/10/30
 */
public class MD2Json {

    private static String DIFY_BASE_URL = "https://dify.gsstcloud.com/v1";

    private static Logger logger = LoggerFactory.getLogger(MD2Json.class);

    public static String md2json(String md) {
        Map<String, Object> inputs = new LinkedHashMap<>();
        inputs.put("document", md);

        List<FileInfo> files = new ArrayList<>();
        files.add(FileInfo.builder()
                .type(FileType.DOCUMENT)
                .transferMethod(FileTransferMethod.REMOTE_URL)
                .build());

        try {
            DifyWorkflowClient workflowClient = DifyClientFactory.createWorkflowClient(DIFY_BASE_URL, "app-pYQciBixUQCmSpVTMDCMD0Uj");
            WorkflowRunRequest workflowRunRequest = new WorkflowRunRequest();
            workflowRunRequest.setResponseMode(ResponseMode.BLOCKING);
            workflowRunRequest.setInputs(inputs);
            workflowRunRequest.setUser("ModelLink");

            WorkflowRunResponse workflowRunResponse = workflowClient.runWorkflow(workflowRunRequest);
            Map<String, Object> outputs = workflowRunResponse.getData().getOutputs();
            if (outputs.containsKey("text")) {
                Object text = outputs.get("text");
                JSONObject jsonObject = JSON.parseObject(text.toString());
                if (jsonObject.containsKey("paper") && !jsonObject.getBoolean("paper")) {
                    logger.info("------------ md to json could not paper -------------");
                    return StringUtils.EMPTY;
                }
                return jsonObject.toJSONString();
            }
            logger.error("------------- md to json error , text is null -------------");
            return StringUtils.EMPTY;
        } catch (Exception e) {
            logger.error("------------- md to json error -------------", e);
            return StringUtils.EMPTY;
        }
    }

}
