package com.webchat.service.ai;

import com.webchat.common.bean.APIPageResponseBean;
import com.webchat.common.enums.PromptTemplateEnum;
import com.webchat.common.helper.SseEmitterHelper;
import com.webchat.common.util.JsonUtil;
import com.webchat.domain.vo.dto.ChatMessageSearchResultDTO;
import com.webchat.domain.vo.llm.ChatCompletionMessage;
import com.webchat.domain.vo.llm.ChatMessageRole;
import com.webchat.domain.vo.llm.LLMChatRequestDTO;
import com.webchat.domain.vo.response.publicaccount.ArticleBaseResponseVO;
import com.webchat.service.FreeMarkEngineService;
import com.webchat.service.elastic.WebChatElasticSearchService;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.collections.CollectionUtils;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;
import org.springframework.web.servlet.mvc.method.annotation.SseEmitter;

import java.io.IOException;
import java.util.*;

@Slf4j
@Service
public class RAGBotService {

    @Autowired
    private FreeMarkEngineService freeMarkEngineService;

    @Autowired
    private WebChatElasticSearchService webChatElasticSearchService;

    @Value("${llm.config.model}")
    private String model;

    public void chat(String userId, LLMChatRequestDTO requestDTO) {
        SseEmitter sseEmitter = SseEmitterHelper.get(requestDTO.getBiz(), userId);
        if (sseEmitter == null) {
            return;
        }
        ArticleBaseResponseVO article = queryDocumentsFormES(userId, requestDTO.getMessage());
        String document = "-";
        if (article != null) {
            try {
                String resourceUrl = "/article/" + article.getId();
                if (StringUtils.isNotBlank(resourceUrl)) {
                    sseEmitter.send("<a href=\""+resourceUrl+"\" target=\"_blank\"><button class='refDocument'>公众号资料源："+article.getTitle()+"</button><br/></a>");
                }
            } catch (IOException e) {}
            document = JsonUtil.toJsonString("内容标题：" + article.getTitle()+"\n 内容正文"+article.getContent());
        }
        Map<String, Object> vars = new HashMap<>();
        vars.put("input", requestDTO.getMessage());
        vars.put("document", document);
        try {
            String prompt = freeMarkEngineService.getContentByTemplate(PromptTemplateEnum.RAG.getPath(), vars);
            final List<ChatCompletionMessage> messageList = Arrays.asList(
                    new ChatCompletionMessage(ChatMessageRole.SYSTEM.value(), String.format("你是《webchat》的基于公众号文章的智能问答助理！")),
                    new ChatCompletionMessage(ChatMessageRole.USER.value(), prompt));
            LLMServiceFactory.getLLMService(model).chat(sseEmitter, messageList);
        } catch (Exception e) {
            log.error("知识社区RAG问答处理异常====> 参数={}", JsonUtil.toJsonString(requestDTO), e);
        }
    }

    private ArticleBaseResponseVO queryDocumentsFormES(String userId, String q) {
        APIPageResponseBean<ChatMessageSearchResultDTO> apiPageResponseBean = webChatElasticSearchService.query(null, userId, q, 1, 1);
        List<ChatMessageSearchResultDTO> dataList = apiPageResponseBean.getData();
        return CollectionUtils.isEmpty(dataList) ? null : dataList.get(0).getArticle();
    }
}
