package com.yanzhu.module.ai.service.mindmap;

import cn.hutool.core.collection.CollUtil;
import cn.hutool.core.util.ObjUtil;
import cn.hutool.core.util.StrUtil;
import com.yanzhu.module.ai.enums.model.AiModelTypeEnum;
import com.yanzhu.module.ai.enums.model.AiPlatformEnum;
import com.yanzhu.module.ai.util.AiUtils;
import com.yanzhu.framework.common.pojo.CommonResult;
import com.yanzhu.framework.common.pojo.PageResult;
import com.yanzhu.framework.common.util.object.BeanUtils;
import com.yanzhu.framework.tenant.core.util.TenantUtils;
import com.yanzhu.module.ai.controller.admin.mindmap.vo.AiMindMapGenerateReqVO;
import com.yanzhu.module.ai.controller.admin.mindmap.vo.AiMindMapPageReqVO;
import com.yanzhu.module.ai.dal.dataobject.mindmap.AiMindMapDO;
import com.yanzhu.module.ai.dal.dataobject.model.AiChatRoleDO;
import com.yanzhu.module.ai.dal.dataobject.model.AiModelDO;
import com.yanzhu.module.ai.dal.mysql.mindmap.AiMindMapMapper;
import com.yanzhu.module.ai.enums.AiChatRoleEnum;
import com.yanzhu.module.ai.enums.ErrorCodeConstants;
import com.yanzhu.module.ai.service.model.AiChatRoleService;
import com.yanzhu.module.ai.service.model.AiModelService;
import javax.annotation.Resource;
import lombok.extern.slf4j.Slf4j;
import dev.langchain4j.data.message.AiMessage;
import dev.langchain4j.data.message.ChatMessage;
import dev.langchain4j.data.message.SystemMessage;
import dev.langchain4j.data.message.UserMessage;
import dev.langchain4j.model.chat.ChatLanguageModel;
import dev.langchain4j.model.output.Response;
import org.springframework.stereotype.Service;
import reactor.core.publisher.Flux;
import java.util.List;

import java.util.ArrayList;
import java.util.List;

import static com.yanzhu.framework.common.exception.util.ServiceExceptionUtil.exception;
import static com.yanzhu.framework.common.pojo.CommonResult.error;
import static com.yanzhu.framework.common.pojo.CommonResult.success;
import static com.yanzhu.module.ai.enums.ErrorCodeConstants.*;

/**
 * AI 思维导图 Service 实现类
 *
 * @author xiaoxin
 */
@Service
@Slf4j
public class AiMindMapServiceImpl implements AiMindMapService {

    @Resource
    private AiModelService modalService;
    @Resource
    private AiChatRoleService chatRoleService;

    @Resource
    private AiMindMapMapper mindMapMapper;

    @Override
    public Flux<CommonResult<String>> generateMindMap(AiMindMapGenerateReqVO generateReqVO, Long userId) {
        // 1. 获取导图模型。尝试获取思维导图助手角色，如果没有则使用默认模型
        AiChatRoleDO role = CollUtil.getFirst(
                chatRoleService.getChatRoleListByName(AiChatRoleEnum.AI_MIND_MAP_ROLE.getName()));
        // 1.1 获取导图执行模型
        AiModelDO model = getModel(role);
        // 1.2 获取角色设定消息
        String systemMessage = role != null && StrUtil.isNotBlank(role.getSystemMessage())
                ? role.getSystemMessage() : AiChatRoleEnum.AI_MIND_MAP_ROLE.getSystemMessage();
        // 1.3 校验平台
        AiPlatformEnum platform = AiPlatformEnum.validatePlatform(model.getPlatform());
        ChatLanguageModel chatModel = modalService.getChatModel(model.getId());

        // 2. 插入思维导图信息
        AiMindMapDO mindMapDO = BeanUtils.toBean(generateReqVO, AiMindMapDO.class, mindMap -> mindMap.setUserId(userId)
                .setPlatform(platform.getPlatform()).setModelId(model.getId()).setModel(model.getModel()));
        mindMapMapper.insert(mindMapDO);

        // 3.1 构建消息，并进行调用
        List<ChatMessage> messages = buildMessages(generateReqVO, systemMessage);
        // 暂时注释掉流式调用，因为langchain4j的ChatLanguageModel接口可能没有stream方法
        // 后续需要使用正确的方法调用
        // Flux<Response<AiMessage>> streamResponse = chatModel.stream(messages);

        // 3.2 暂时返回空的Flux
        return Flux.empty();

    }



    private static List<ChatMessage> buildMessages(AiMindMapGenerateReqVO generateReqVO, String systemMessage) {
        List<ChatMessage> chatMessages = new ArrayList<>();
        // 1. 角色设定
        if (StrUtil.isNotBlank(systemMessage)) {
            chatMessages.add(new SystemMessage(systemMessage));
        }
        // 2. 用户输入
        chatMessages.add(new UserMessage(generateReqVO.getPrompt()));
        return chatMessages;
    }

    private AiModelDO getModel(AiChatRoleDO role) {
        AiModelDO model = null;
        if (role != null && role.getModelId() != null) {
            model = modalService.getModel(role.getModelId());
        }
        if (model == null) {
            model = modalService.getRequiredDefaultModel(AiModelTypeEnum.CHAT.getType());
        }
        // 校验模型存在、且合法
        if (model == null) {
            throw exception(MODEL_NOT_EXISTS);
        }
        if (ObjUtil.notEqual(model.getType(), AiModelTypeEnum.CHAT.getType())) {
            throw exception(MODEL_USE_TYPE_ERROR);
        }
        return model;
    }

    @Override
    public void deleteMindMap(Long id) {
        // 校验存在
        validateMindMapExists(id);
        // 删除
        mindMapMapper.deleteById(id);
    }

    private void validateMindMapExists(Long id) {
        if (mindMapMapper.selectById(id) == null) {
            throw exception(MIND_MAP_NOT_EXISTS);
        }
    }

    @Override
    public PageResult<AiMindMapDO> getMindMapPage(AiMindMapPageReqVO pageReqVO) {
        return mindMapMapper.selectPage(pageReqVO);
    }

}
