package com.webchat.service.ai;

import com.webchat.common.enums.PromptTemplateEnum;
import com.webchat.common.enums.SseEmitterBizEnum;
import com.webchat.common.helper.SseEmitterHelper;
import com.webchat.domain.vo.llm.ChatCompletionMessage;
import com.webchat.domain.vo.llm.ChatMessageRole;
import com.webchat.domain.vo.request.mess.ChatMessageRequestVO;
import com.webchat.domain.vo.response.UserBaseResponseInfoVO;
import com.webchat.service.FreeMarkEngineService;
import com.webchat.service.UserService;
import freemarker.template.TemplateException;
import lombok.extern.slf4j.Slf4j;
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.Arrays;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * @author 程序员王七七 https://www.coderutil.com 网站作者
 * @date 2024/10/29 13:42
 */
@Slf4j
@Service
public class GPTChatService {

    @Autowired
    private UserService userService;

    @Autowired
    private FreeMarkEngineService freeMarkEngineService;

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

    /**
     * 没有设定角色时，使用默认角色
     */
    private static final String DEFAULT_GPT_ROLE = "你是一个智能助手，帮我解决一切问题。";
    private static final String DEFAULT_ROLE = "暂无签名";


    public void chat(ChatMessageRequestVO chatMessage) {
        // 使用工厂模式，取对应的LLM服务，来完成对话
        AbstractLLMChatService abstractLLMChatService = LLMServiceFactory.getLLMService(model);
        // 获取用户发送消息内容
        String message = chatMessage.getMessage();
        // 取消息发送人、接收人信息
        String sendUserId = chatMessage.getSenderId();
        String receiverId = chatMessage.getReceiverId();
        UserBaseResponseInfoVO receiver = userService.getUserInfoByUserId(receiverId);
        String gptRoleSetting = receiver.getSignature();
        if (StringUtils.isBlank(gptRoleSetting) || DEFAULT_ROLE.equals(gptRoleSetting)) {
            gptRoleSetting = DEFAULT_GPT_ROLE;
        }
        Map<String, Object> vars = new HashMap<>();
        vars.put("roleSetting", gptRoleSetting);
        vars.put("content", message);
        String prompt;
        try {
            prompt = freeMarkEngineService.getContentByTemplate(PromptTemplateEnum.ROBOT_CHAT.getPath(), vars);
        } catch (Exception e) {
            log.error("GPTChatService.chat create prompt error. sendUserId:{}, receiverId:{}, msg:{}",
                    sendUserId, receiverId, message, e);
            return;
        }

        // 获取发送人对应的SseEmitter
        SseEmitter sseEmitter = SseEmitterHelper.get(SseEmitterBizEnum.ROBOT_CHAT.name(), sendUserId);

        final List<ChatCompletionMessage> messageList = Arrays.asList(
                new ChatCompletionMessage(ChatMessageRole.SYSTEM.value(), gptRoleSetting),
                new ChatCompletionMessage(ChatMessageRole.USER.value(), prompt));
        try {
            abstractLLMChatService.chat(sseEmitter, messageList);
        } catch (Exception e) {
            log.error("GPTChatService.chat error. sendUserId:{}, receiverId:{}, msg:{}",
                    sendUserId, receiverId, message, e);
        }
    }
}
