package cn.teammodel.service.impl;

import cn.teammodel.common.ErrorCode;
import cn.teammodel.common.PK;
import cn.teammodel.config.exception.ServiceException;
import cn.teammodel.model.entity.ai.ChatSession;
import cn.teammodel.model.entity.ai.DeepSeekSession;
import cn.teammodel.model.entity.ai.DeepSeekSession.DeepSeekMessage;
import cn.teammodel.repository.DeepSeekRepository;
import cn.teammodel.service.DeepSeekSessionService;
import cn.teammodel.utils.RepositoryUtil;
import com.azure.cosmos.models.CosmosPatchOperations;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.ObjectUtils;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.time.Instant;
import java.util.Collections;
import java.util.Comparator;
import java.util.List;
import java.util.UUID;
import java.util.stream.Collectors;

@Service
@Slf4j
public class DeepSeekSessionServiceImpl implements DeepSeekSessionService {
    @Resource // 注入
    private DeepSeekRepository deepSeekRepository;

    /**
     * 创建初始会话
     * @param userId
     * @param name
     * @return
     */
    @Override
    public DeepSeekSession CreateDefaultSession(String userId, String name) {
        //初始化第一条欢迎语
        DeepSeekMessage message = DeepSeekMessage.of("你好"+name, "我是你的私人 DeepSeek AI 助手小豆,你可以问我任何包括但不仅限于教育的问题,我会尽力为您解答!");
        List<DeepSeekMessage> history = Collections.singletonList(message);
        DeepSeekSession session = new DeepSeekSession();
        session.setId(UUID.randomUUID().toString());
        session.setCode(PK.DEEPSEEK_SESSION);
        session.setTitle("新对话");
        session.setUserId(userId);
        session.setCreateTime(Instant.now().toEpochMilli());
        session.setUpdateTime(Instant.now().toEpochMilli());
        session.setHistory(history);
        return deepSeekRepository.save(session);
    }

    /**
     * 创建新会话
     * @param session
     * @return
     */
    @Override
    public  DeepSeekSession CreateSession(DeepSeekSession session) {
        return deepSeekRepository.save(session);
    }

    /**
     * 更新会话
     * @param upSession
     * @param userId
     * @return
     */
    @Override
    public DeepSeekSession updateSession (DeepSeekSession upSession, String userId)
    {
        String id = upSession.getId();
        String title = upSession.getTitle();
        DeepSeekSession session = RepositoryUtil.findOne(deepSeekRepository.findBySessionId(id), "");
        if (!session.getUserId().equals(userId)) {
            throw new ServiceException(ErrorCode.NO_AUTH_ERROR);
        }
        CosmosPatchOperations options = CosmosPatchOperations.create()
                .replace("/title", title);

        deepSeekRepository.save(id, PK.of(PK.CHAT_SESSION), DeepSeekSession.class, options);
        return session;
    }

    /**
     * 删除会话
     * @param id
     * @param userId
     */
    @Override
    public void deleteSession (String id, String userId)
    {
        DeepSeekSession session = RepositoryUtil.findOne(deepSeekRepository.findBySessionId(id), "");
        if (!session.getUserId().equals(userId)) {
            throw new ServiceException(ErrorCode.NO_AUTH_ERROR);
        }
        deepSeekRepository.deleteById(id, PK.of(PK.CHAT_SESSION));
    }


    /**
     * 获取用户会话列表
     * @param userId
     * @return
     */
    @Override
    public List<DeepSeekSession> UserSessionList(String userId) {
        List<DeepSeekSession> sessions = deepSeekRepository.findByUserId(userId);
        // 按更新时间排序
        if (ObjectUtils.isNotEmpty(sessions))
        {
            sessions = sessions.stream().sorted(Comparator.comparing(DeepSeekSession::getUpdateTime)).collect(Collectors.toList());
        }
        return sessions;
    }

    /**
     * 获取历史消息
     * @param sessionId
     * @param userId
     * @return
     */
    @Override
    public List<DeepSeekMessage> listHistory(String sessionId, String userId) {
        DeepSeekSession session = deepSeekRepository.findSessionByIdAndCode(sessionId, PK.DEEPSEEK_SESSION);
        if (!userId.equals(session.getUserId())) {
            throw new ServiceException(ErrorCode.NO_AUTH_ERROR);
        }
        return session.getHistory();
    }


}
