package com.sonic.cow.service.impl;

import com.alibaba.fastjson.JSONObject;
import com.google.common.collect.Lists;
import com.sonic.cow.service.ChatMemoryService;
import com.sonic.cow.utils.RedisKeyUtils;
import com.byteplus.ark.runtime.model.completion.chat.ChatMessage;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.stereotype.Service;

import java.util.List;
import java.util.concurrent.TimeUnit;

import static com.sonic.cow.utils.Constant.MAX_HISTORY_MESSAGE;
import static com.sonic.cow.utils.Constant.TTL_HISTORY_MESSAGE_DAY;

@Slf4j
@Service
public class ChatMemoryServiceImpl implements ChatMemoryService {

    @Autowired
    private RedisKeyUtils redisKeyUtils;
    @Autowired
    private StringRedisTemplate stringRedisTemplate;


    @Override
    public List<ChatMessage> getHistory(Long userId, Long aiId) {
        List<String> historyList = stringRedisTemplate.opsForList().range(redisKeyUtils.chatMemoryCacheKey(userId, aiId), 0, MAX_HISTORY_MESSAGE);
        //对象转换
        List<ChatMessage> messages = Lists.newArrayList();
        for (String historyMessage : historyList) {
            ChatMessage message = JSONObject.parseObject(historyMessage, ChatMessage.class);
            messages.add(message);
        }
        return messages;
    }

    @Override
    public void saveHistory(Long userId, Long aiId, List<ChatMessage> chatMessages) {
        String redisKey = redisKeyUtils.chatMemoryCacheKey(userId, aiId);
        for (ChatMessage message : chatMessages) {
            stringRedisTemplate.opsForList().leftPush(redisKey, JSONObject.toJSONString(message));
        }
        // 保留最近100条
        stringRedisTemplate.opsForList().trim(redisKey, 0, MAX_HISTORY_MESSAGE);
        // 设置360天过期
        stringRedisTemplate.expire(redisKey, TTL_HISTORY_MESSAGE_DAY, TimeUnit.DAYS);
    }

}
