package com.qingyun.service;

import cn.hutool.core.util.CharsetUtil;
import cn.hutool.http.HttpUtil;
import com.agentsflex.core.llm.response.AiMessageResponse;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.qingyun.service.agent.LlmStrategy;
import com.qingyun.service.agent.LlmStrategyFactory;
import com.qingyun.service.agent.TemplateManager;
import com.qingyun.service.domain.ContractReviewResult;
import com.qingyun.service.domain.ContractReviewTask;
import com.qingyun.service.mapper.ContractReviewTaskMapper;
import com.qingyun.service.utils.MarkdownUtils;
import org.apache.commons.lang3.StringUtils;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.test.context.SpringBootTest;
import org.springframework.test.context.junit4.SpringRunner;

import java.io.File;
import java.io.IOException;
import java.nio.file.Files;
import java.util.Base64;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

@SpringBootTest
@RunWith(SpringRunner.class)
public class TestAgentsFlex {

    @Autowired
    private ContractReviewTaskMapper contractReviewTaskMapper;

    @Test
    public void test() throws IOException {
        ContractReviewTask contractReviewTask = contractReviewTaskMapper.selectById(5);
        String reviewElement = contractReviewTask.getReviewElement();

        // 获取所有页面内容, 数组索引为页码，从0开始
        List<String> pagesContent = JSONArray.parseArray(contractReviewTask.getContractContentMd(), String.class);

        int totalPages = pagesContent.size();

        String reviewPromptTemp = TemplateManager.getTemplate("classpath:prompt/reviewElement.txt");
        String rulePromptTemp = TemplateManager.getTemplate("classpath:prompt/contractReview.txt");

        LlmStrategy strategy = LlmStrategyFactory.getStrategy(null);
        // 构建参数
        Map<String, String> reviewParams = new HashMap<>();
        reviewParams.put("rules", reviewElement);
        reviewParams.put("context", pagesContent.get(3));
        AiMessageResponse reviewResponse = null;
        if (StringUtils.isNotBlank(reviewElement)) {

            reviewResponse = strategy.chat(reviewPromptTemp, reviewParams);
            System.out.println("reviewResponse: " + reviewResponse);
            String content = reviewResponse.getMessage().getContent();
            List<String> strings = MarkdownUtils.extractJsonBlocks(content);
            if (strings != null && !strings.isEmpty()) {
                List<ContractReviewResult> resultList = JSONArray.parseArray(strings.get(0), ContractReviewResult.class);
                resultList.forEach(result -> System.out.println(JSONObject.toJSONString(result)));
            }
        }
    }

    @Test
    public void testParsing() throws IOException {
        String filePath = "localhost:8080/profile/upload/2025/07/15/12645cd2-2f6b-4e8d-808d-fb95c1fbc23b.pdf";

        File tempFile = File.createTempFile("contract_", ".pdf");
        long file = HttpUtil.downloadFile(filePath, tempFile);
        if (file <= 0) {
            throw new IOException("无法下载 PDF 文件");
        }

        byte[] pageBytes = Files.readAllBytes(tempFile.toPath());
        String base64 = Base64.getEncoder().encodeToString(pageBytes);

        // 删除临时文件
        Files.deleteIfExists(tempFile.toPath());

        // 构造请求体
        Map<String, Object> requestBody = new HashMap<>();
        requestBody.put("file", base64);
        String result = HttpUtil.post("http://10.78.113.249:8080/layout-parsing", requestBody);
        JSONObject jsonObject = JSONObject.parseObject(result);
    }
}
