package com.sonic.cow.service.impl;

import com.baomidou.mybatisplus.core.toolkit.StringUtils;
import com.google.common.collect.Lists;
import com.sonic.cow.client.ContextChatClient;
import com.sonic.cow.service.ChatMemoryService;
import com.sonic.cow.service.ChatService;
import com.sonic.cow.service.ContextSessionCacheService;
import com.byteplus.ark.runtime.model.completion.chat.ChatMessage;
import com.byteplus.ark.runtime.model.completion.chat.ChatMessageRole;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.List;

import static com.sonic.cow.utils.Constant.TTL_CONTEXT_CACHING;

@Slf4j
@Service
public class ChatServiceImpl implements ChatService {

    @Autowired
    private ContextChatClient contextChatClient;
    @Autowired
    private ContextSessionCacheService contextSessionCacheService;
    @Autowired
    private ChatMemoryService chatMemoryService;

    @Override
    public String chat(Long userId, Long aiId, String message) {
        //STEP1：获取上下文id
        String contextId = contextSessionCacheService.getContextId(userId, aiId);
        if(StringUtils.isEmpty(contextId)) {
            List<ChatMessage> messages = Lists.newArrayList();
            //TODO 获取系统提示词并设置
            messages.add(ChatMessage.builder()
                    .role(ChatMessageRole.SYSTEM)
                    .content("不允许回复火星文、表情符这些内容")
                    .build());
            //获取对话历史数据
            List<ChatMessage> historyList = chatMemoryService.getHistory(userId, aiId);
            messages.addAll(historyList);
            //创建上下文ID的缓存
            contextId = contextChatClient.createContextCaching(messages, TTL_CONTEXT_CACHING);
        }
        //STEP2：执行聊天的操作
        String result = contextChatClient.contextChat(contextId, message);
        //STEP3：保存历史上下文
        List<ChatMessage> chatMessageList = Lists.newArrayList();
        chatMessageList.add(ChatMessage.builder()
                .role(ChatMessageRole.USER)
                .content(message)
                .build());
        chatMessageList.add(ChatMessage.builder()
                .role(ChatMessageRole.ASSISTANT)
                .content(result)
                .build());
        chatMemoryService.saveHistory(userId, aiId, chatMessageList);
        //TODO 发送IM消息给用户
        log.debug("===> ASSISTANT result Message : {}", result);
        return result;
    }
}
