/*
 * Copyright (c) 2024 LangChat. TyCoding All Rights Reserved.
 *
 * Licensed under the GNU Affero General Public License, Version 3 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *     https://www.gnu.org/licenses/agpl-3.0.html
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */

package cn.iocoder.yudao.module.langchat.controller.admin.endpoint;

import cn.hutool.core.util.StrUtil;
import cn.iocoder.yudao.framework.common.pojo.CommonResult;
import cn.iocoder.yudao.framework.security.core.LoginUser;
import cn.iocoder.yudao.framework.security.core.util.SecurityFrameworkUtils;
import cn.iocoder.yudao.module.langchat.dal.dto.ChatReq;
import cn.iocoder.yudao.module.langchat.dal.dto.ChatRes;
import cn.iocoder.yudao.module.langchat.dal.dto.ImageR;
import cn.iocoder.yudao.module.langchat.dal.dto.PromptConst;
import cn.iocoder.yudao.module.langchat.entity.AigcApp;
import cn.iocoder.yudao.module.langchat.entity.AigcMessage;
import cn.iocoder.yudao.module.langchat.entity.AigcModel;
import cn.iocoder.yudao.module.langchat.enums.RoleEnum;
import cn.iocoder.yudao.module.langchat.properties.ChatProps;
import cn.iocoder.yudao.module.langchat.service.aigc.AigcAppService;
import cn.iocoder.yudao.module.langchat.service.aigc.AigcMessageService;
import cn.iocoder.yudao.module.langchat.service.aigc.AigcModelService;
import cn.iocoder.yudao.module.langchat.service.core.ChatService;
import cn.iocoder.yudao.module.langchat.service.core.impl.PersistentChatMemoryStore;
import cn.iocoder.yudao.module.langchat.utils.PromptUtil;
import cn.iocoder.yudao.module.langchat.utils.StreamEmitter;
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 lombok.AllArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.servlet.mvc.method.annotation.SseEmitter;

import java.util.ArrayList;
import java.util.List;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;

/**
 * @author tycoding
 * @since 2024/1/30
 */
@Slf4j
@RequestMapping("/aigc")
@RestController
@AllArgsConstructor
public class ChatEndpoint {

    private final ChatService chatService;
    private final AigcMessageService messageService;
    private final AigcModelService aigcModelService;
    private final AigcAppService appService;
    private final ChatProps chatProps;

    @PostMapping("/chat/completions")
    public SseEmitter chat(@RequestBody ChatReq req) {
        StreamEmitter emitter = new StreamEmitter();
        req.setEmitter(emitter);

        req.setUserId(String.valueOf(SecurityFrameworkUtils.getLoginUserId()));
        req.setUsername(SecurityFrameworkUtils.getLoginUserNickname());
        ExecutorService executor = Executors.newSingleThreadExecutor();
        req.setExecutor(executor);
        return emitter.streaming(executor, () -> {
            chatService.chat(req);
        });
    }

    @GetMapping("/app/info")
    public CommonResult<AigcApp> appInfo(@RequestParam String appId, String conversationId) {
        AigcApp app = appService.getById(appId);
        if (StrUtil.isBlank(conversationId)) {
            conversationId = app.getId();
        }

        if (StrUtil.isNotBlank(app.getPrompt())) {
            // initialize chat memory
            SystemMessage message = new SystemMessage(app.getPrompt());
            PersistentChatMemoryStore.init(conversationId, message);
        }

        return CommonResult.success(app);
    }

    @GetMapping("/chat/messages/{conversationId}")
    public CommonResult messages(@PathVariable String conversationId) {
        List<AigcMessage> list = messageService.getMessages(conversationId, String.valueOf(SecurityFrameworkUtils.getLoginUserId()));

        // initialize chat memory
        List<ChatMessage> chatMessages = new ArrayList<>();
        list.forEach(item -> {
            if (chatMessages.size() >= chatProps.getMemoryMaxMessage()) {
                return;
            }
            if (item.getRole().equals(RoleEnum.ASSISTANT.getName())) {
                chatMessages.add(new AiMessage(item.getMessage()));
            } else {
                chatMessages.add(new UserMessage(item.getMessage()));
            }
        });
        PersistentChatMemoryStore.init(conversationId, chatMessages);
        return CommonResult.success(list);
    }

    @DeleteMapping("/chat/messages/clean/{conversationId}")
    public CommonResult cleanMessage(@PathVariable String conversationId) {
        messageService.clearMessage(conversationId);

        // clean chat memory
        PersistentChatMemoryStore.clean(conversationId);
        return CommonResult.success(null);
    }

    @PostMapping("/chat/mindmap")
    public CommonResult mindmap(@RequestBody ChatReq req) {
        req.setPrompt(PromptUtil.build(req.getMessage(), PromptConst.MINDMAP));
        return CommonResult.success(new ChatRes(chatService.text(req)));
    }

    @PostMapping("/chat/image")
    public CommonResult image(@RequestBody ImageR req) {
        req.setPrompt(PromptUtil.build(req.getMessage(), PromptConst.IMAGE));
        return CommonResult.success(chatService.image(req));
    }

    @GetMapping("/chat/getImageModels")
    public CommonResult<List<AigcModel>> getImageModels() {
        List<AigcModel> list = aigcModelService.getImageModels();
        list.forEach(i -> {
            i.setApiKey(null);
            i.setSecretKey(null);
        });
        return CommonResult.success(list);
    }
}
