package com.webchat.controller.client;


import com.webchat.common.bean.APIResponseBean;
import com.webchat.common.bean.APIResponseBeanUtil;
import com.webchat.common.exception.BusinessException;
import com.webchat.common.helper.SessionHelper;
import com.webchat.common.helper.SseEmitterHelper;
import com.webchat.common.util.ThreadPoolExecutorUtil;
import com.webchat.config.annotation.ValidateLogin;
import com.webchat.domain.vo.llm.LLMChatRequestDTO;
import com.webchat.service.ai.RAGBotService;
import io.swagger.annotations.Api;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.util.Assert;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.servlet.mvc.method.annotation.SseEmitter;

import javax.servlet.http.HttpServletRequest;

@Api(tags = "【AI大模型】RAG搜索增强问答助手服务")
@RestController
@RequestMapping("/api/rag/bot")
public class RAGBotController {


    @Autowired
    private RAGBotService ragBotService;

    /**
     * 获取SSE链接对象
     *
     * @param request
     * @return
     */
    @ValidateLogin
    @GetMapping(path = "/stream", produces = "text/event-stream")
    public SseEmitter stream(HttpServletRequest request) {
        String biz = request.getParameter("biz");
        String userId = SessionHelper.getCurrentUserId();
        if (StringUtils.isBlank(userId)) {
            throw new BusinessException("对话Stream流长链接获取异常，用户未登录！");
        }
        return SseEmitterHelper.get(biz, userId);
    }


    @ValidateLogin
    @PostMapping("/chat/send")
    public APIResponseBean chat(@RequestBody LLMChatRequestDTO llmChatRequestDTO) {
        Assert.isTrue(llmChatRequestDTO != null, "参数为空");
        Assert.isTrue(StringUtils.isNotBlank(llmChatRequestDTO.getMessage()), "输入内容为空");
        Assert.isTrue(StringUtils.isNotBlank(llmChatRequestDTO.getMessage().trim()), "输入内容为空");
        String userId = SessionHelper.getCurrentUserId();
        ThreadPoolExecutorUtil.execute(() -> ragBotService.chat(userId, llmChatRequestDTO));
        return APIResponseBeanUtil.success(true);
    }
}
