package cn.com.poc.meeting.analysis;

import cn.com.poc.agent_application.entity.BizAgentApplicationGcConfigEntity;
import cn.com.poc.common.segmentation.SegmentationBuilder;
import cn.com.poc.common.segmentation.contents.SegmentationEnum;
import cn.com.poc.common.segmentation.domain.SegmentationConfig;
import cn.com.poc.common.segmentation.domain.SegmentationResult;
import cn.com.poc.common.utils.JsonUtils;
import cn.com.poc.common.utils.StringUtils;
import cn.com.poc.thirdparty.resource.demand.ai.entity.dialogue.Message;
import cn.com.poc.thirdparty.resource.demand.ai.entity.largemodel.LargeModelDemandResult;
import cn.com.poc.thirdparty.resource.demand.ai.entity.largemodel.LargeModelResponse;
import cn.com.yict.framemax.core.exception.BusinessException;
import com.fasterxml.jackson.core.type.TypeReference;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.util.ArrayList;
import java.util.Collections;
import java.util.List;


/**
 * 会议助手-推荐问生成处理器
 */
public class FeaturedQuestionAnalyzer extends MeetingContentAnalysisAbstract<List<String>> {

    private final Logger logger = LoggerFactory.getLogger(FeaturedQuestionAnalyzer.class);

    private final String FIRST_GENERATE_GC_CONFIG_CODE = "MEETING_FEATURED_QUESTION_FIRST";

    private final String MULTI_GENERATE_GC_CONFIG_CODE = "MEETING_FEATURED_QUESTION_MULTI";

    @Override
    public List<String> run(String content) {

        BizAgentApplicationGcConfigEntity firstGcConfigEntity = bizAgentApplicationGcConfigService.getByConfigCode(FIRST_GENERATE_GC_CONFIG_CODE);
        BizAgentApplicationGcConfigEntity multiGcConfigEntity = bizAgentApplicationGcConfigService.getByConfigCode(MULTI_GENERATE_GC_CONFIG_CODE);
        if (firstGcConfigEntity == null || multiGcConfigEntity == null) {
            throw new BusinessException("无法找到生成推荐问配置");
        }
        // 配置prompt参数
        String firstPrompt = firstGcConfigEntity.getConfigSystem();
        String firstModel = firstGcConfigEntity.getLargeModel();
        String multiPrompt = multiGcConfigEntity.getConfigSystem();
        String multiModel = multiGcConfigEntity.getLargeModel();

        // 内容分片
        SegmentationConfig segmentationConfig = new SegmentationConfig();
        segmentationConfig.setPunctuations(new ArrayList<>());
        segmentationConfig.setChunkSize(25000);
        segmentationConfig.setScrapSize(25000);
        segmentationConfig.setRepetitionRate(5);
        segmentationConfig.setRelationInfo(new ArrayList<>());
        List<SegmentationResult> segmentationResultList = new SegmentationBuilder()
                .segmentationType(SegmentationEnum.NUMBER_Of_WORDS.name())
                .content(content)
                .build().scrap(segmentationConfig);

        // 生成推荐问
        String generateContent = "";
        try {
            for (int i = 0; i < segmentationResultList.size(); i++) {
                if (i == 0) {
                    generateContent = firstGenerate(segmentationResultList.get(i).getChunkContent(), firstPrompt, firstModel);
                } else {
                    generateContent = multiGenerate(segmentationResultList.get(i).getChunkContent(), generateContent, multiPrompt, multiModel);
                }
                double progress = ((double) (i + 1) / segmentationResultList.size()) * 100D;
                logger.info("-------------推荐问生成进度 {} %--------------", progress);
            }
        } catch (Exception e) {
            logger.error("推荐问生成失败", e);
            return Collections.emptyList();
        }

        if (StringUtils.isBlank(generateContent)) {
            return Collections.emptyList();
        }

        // 转换格式 json to list
        int start = generateContent.lastIndexOf("[");
        int end = generateContent.lastIndexOf("]");
        return JsonUtils.deSerialize(generateContent.substring(start, end + 1), new TypeReference<List<String>>() {
        }.getType());
    }


    private String firstGenerate(String content, String prompt, String model) {
        LargeModelResponse largeResponse = new LargeModelResponse();
        largeResponse.setModel(model);
        Message[] messages = new Message[1];

        Message message1 = new Message();
        message1.setContent(prompt.replace("{content}", content));
        message1.setRole("user");
        messages[0] = message1;
        largeResponse.setMessages(messages);
        largeResponse.setStream(false);
        largeResponse.setUser("MEETING_FEATURED_QUESTION");
        LargeModelDemandResult chatResult = llmService.chat(largeResponse);
        return chatResult.getMessage();
    }

    private String multiGenerate(String content, String summaries, String prompt, String model) {
        LargeModelResponse largeResponse = new LargeModelResponse();
        largeResponse.setModel(model);
        Message[] messages = new Message[1];
        Message message1 = new Message();
        message1.setContent(prompt.replace("{content}", content).
                replace("{summaries}", summaries));
        message1.setRole("user");
        messages[0] = message1;
        largeResponse.setMessages(messages);
        largeResponse.setStream(false);
        largeResponse.setUser("MEETING_FEATURED_QUESTION");
        LargeModelDemandResult chatResult = llmService.chat(largeResponse);
        return chatResult.getMessage();
    }
}
