package com.sonic.cow.job;


import com.baomidou.mybatisplus.core.toolkit.CollectionUtils;
import com.byteplus.ark.runtime.model.completion.chat.ChatMessageRole;
import com.google.common.collect.Lists;
import com.sonic.bear.lib.client.UserNicknamePoolClient;
import com.sonic.common.client.JobmanClient;
import com.sonic.common.utils.LogUtils;
import com.sonic.cow.client.ResponseChatClient;
import com.sonic.cow.client.request.ContentRequest;
import com.sonic.cow.client.request.InputRequest;
import com.sonic.cow.client.response.ResponseChatResponse;
import com.sonic.cow.domain.entity.PromptConfig;
import com.sonic.cow.enums.PromptTypeEnum;
import com.sonic.cow.service.ContextSessionCacheService;
import com.sonic.cow.service.PromptConfigService;
import com.sonic.cow.service.impl.InputRequestBuildServiceImpl;
import com.sonic.cow.utils.RedisKeyUtils;
import com.sonic.pigeon.lib.client.ImMessageClient;
import com.sonic.pigeon.lib.input.SendAiTextMessageInput;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.data.redis.core.ZSetOperations;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.stereotype.Component;

import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Set;
import java.util.concurrent.TimeUnit;


/**
 * 超过24小时未聊天时，AI自动给用户发送一条消息
 * @author code
 */
@Slf4j
@Component
public class AutoSendAiMessageJobV2Handler {

    @Autowired
    private JobmanClient jobmanClient;
    @Autowired
    private StringRedisTemplate stringRedisTemplate;
    @Autowired
    private RedisKeyUtils redisKeyUtils;
    @Autowired
    private ResponseChatClient responseChatClient;
    @Autowired
    private ContextSessionCacheService contextSessionCacheService;
    @Autowired
    private ImMessageClient imMessageClient;
    @Autowired
    private PromptConfigService promptConfigService;
    @Autowired
    private UserNicknamePoolClient userNicknamePoolClient;


    /** 每5分钟行一次 */
    @Scheduled(cron = "0 */5 * * * *")
    public void autoSendAiMessageScanSchedule() {
        // 锁 1 分钟过期
        jobmanClient.run("autoSendAiMessageScanJob", TimeUnit.MINUTES.toSeconds(1), this::autoSendAiMessageScanJob);
    }

    protected JobmanClient.JobResult autoSendAiMessageScanJob(JobmanClient.JobContext jobContext) {
        try {
            LogUtils.setTraceId();
            log.info("===> autoSendAiMessageScanJob start !!!");
            long startTime = System.currentTimeMillis() / 1000 - 3 * 24 * 60 * 60;
            long endTime = System.currentTimeMillis() / 1000 - 24 * 60 * 60;
            Set<ZSetOperations.TypedTuple<String>> redisResults = stringRedisTemplate.opsForZSet()
                    .rangeByScoreWithScores(redisKeyUtils.notifyUserZSetKey(), startTime, endTime);
            List<String> allList = Lists.newArrayList();
            for (ZSetOperations.TypedTuple<String> tuple : redisResults) {
                //获取 value
                allList.add(tuple.getValue());
            }
            //没有数据则不继续执行
            if(CollectionUtils.isEmpty(allList)) {
                return JobmanClient.JobResult.success(0);
            }
            log.info("===> autoSendAiMessageScanJob list : {}", allList);
            //数据库查询模板数据
            PromptConfig systemPromptConfig = promptConfigService.getPromptTemplate(PromptTypeEnum.AUTO_SEND_CHAT_SYSTEM_PROMPT_TEMPLATE.name());
            for (String ftUserId : allList) {
                String[] split = ftUserId.split("-");
                Long fromUserId = Long.parseLong(split[0]);
                Long toUserId = Long.parseLong(split[1]);
                //获取上下文缓存 这个缓存一定是存在的
                String responseId = contextSessionCacheService.getByRedis(fromUserId, toUserId);
                //批量查询昵称
                Map<Long, String> nicknameMap = userNicknamePoolClient.batchGetNickname(Lists.newArrayList(fromUserId, toUserId));
                log.debug("===> nicknameMap : {}", nicknameMap);
                Map<String, Object> param = new HashMap<>(2);
                param.put("userNickname", nicknameMap.get(fromUserId));
                param.put("aiNickname", nicknameMap.get(toUserId));
                //处理系统提示词
                String systemPromptConfigContent = InputRequestBuildServiceImpl.processTemplate(systemPromptConfig.getPromptTemplate(), param);

                //构造系统提示词
                List<InputRequest> inputRequests = Lists.newArrayList(InputRequest.builder()
                        .role(ChatMessageRole.SYSTEM)
                        .content(Lists.newArrayList(ContentRequest.builder()
                                .type("input_text")
                                .text(systemPromptConfigContent)
                                .build())).build());
                //执行聊天 不将添加缓存
                ResponseChatResponse chatResponse = responseChatClient.responseStructuredChat(responseId, null, inputRequests, null, false);
                log.info("===> chatResponse : {}", chatResponse);
                if(chatResponse == null) {
                    //删除数据
                    stringRedisTemplate.opsForZSet().remove(redisKeyUtils.notifyUserZSetKey(), ftUserId);
                    continue;
                }
                log.info("===> AiChatHandler chat time : {} ms", System.currentTimeMillis() - startTime);
                // 发送消息给用户
                SendAiTextMessageInput sendAiTextMessageInput = new SendAiTextMessageInput();
                sendAiTextMessageInput.setFromUserId(toUserId);
                sendAiTextMessageInput.setToUserId(fromUserId);
                sendAiTextMessageInput.setContent(chatResponse.getMessage());
                imMessageClient.sendAiToUserTextMessage(sendAiTextMessageInput);
                //删除数据
                stringRedisTemplate.opsForZSet().remove(redisKeyUtils.notifyUserZSetKey(), ftUserId);
            }

            int count = allList.size();
            log.info("===> autoSendAiMessageScanJob count : {} end !!!", count);
            return JobmanClient.JobResult.success(count);
        } finally {
            LogUtils.removeTraceId();
        }
    }
}