package com.ruoyi.aicall.controller;

import com.alibaba.fastjson.JSONObject;
import com.ruoyi.aicall.domain.CcInboundLlmAccount;
import com.ruoyi.aicall.domain.CcLlmAgentAccount;
import com.ruoyi.aicall.llm.ILlmCapability;
import com.ruoyi.aicall.llm.model.AccountBaseEntity;
import com.ruoyi.aicall.model.ChatRequest;
import com.ruoyi.aicall.service.ICcInboundLlmAccountService;
import com.ruoyi.aicall.service.ICcLlmAgentAccountService;
import com.ruoyi.cc.utils.LlmAccountParser;
import com.ruoyi.common.utils.StringUtils;
import com.ruoyi.common.utils.uuid.UuidGenerator;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.collections.CollectionUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.MediaType;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.servlet.mvc.method.annotation.SseEmitter;

import javax.servlet.http.HttpServletRequest;
import java.time.LocalTime;
import java.util.ArrayList;
import java.util.List;
import java.util.concurrent.CompletableFuture;

@Slf4j
@RestController
@RequestMapping("/api/ai")
public class AIChatController {

    @Autowired
    private ICcLlmAgentAccountService llmAgentAccountService;
    @Autowired
    private ICcInboundLlmAccountService inboundLlmAccountService;

    /**
     * 模拟 ChatGPT 流式响应
     */
    @PostMapping(value = "/chat/stream", produces = MediaType.TEXT_EVENT_STREAM_VALUE)
    @ResponseBody
    public SseEmitter chatStream(@RequestBody ChatRequest chatRequest, HttpServletRequest httpRequest) {
        SseEmitter emitter = new SseEmitter(0L); // 0表示永不超时
        String requestId = chatRequest.getRequestId();

//        // 异步执行，避免阻塞
//        CompletableFuture.runAsync(() -> {
//            try {
//                for (int i = 0; i < 5; i++) {
//                    // 发送数据
//                    emitter.send(SseEmitter.event()
//                            .id(String.valueOf(i))
//                            .name("message")
//                            .data("数据块 #" + i + " - " + LocalTime.now()));
//
//                    Thread.sleep(1000); // 模拟耗时操作
//                }
//                emitter.complete(); // 完成
//            } catch (Exception e) {
//                emitter.completeWithError(e);
//            }
//        });

        // 异步执行，避免阻塞
        CompletableFuture.runAsync(() -> {
            try {
                List<CcInboundLlmAccount> ccInboundLlmAccountList = inboundLlmAccountService.selectCcInboundLlmAccountByCallee(chatRequest.getInboundCallee());
                if (CollectionUtils.isEmpty(ccInboundLlmAccountList)) {
                    // 发送数据
                    JSONObject rsponseData = new JSONObject();
                    rsponseData.put("requestId", requestId);
                    rsponseData.put("code", "500");
                    rsponseData.put("content", "客服号码不正确");
                    rsponseData.put("msgType", "message");
                    log.info(JSONObject.toJSONString(rsponseData));
                    emitter.send(SseEmitter.event()
                            .name("message")
                            .data(JSONObject.toJSONString(rsponseData)));
                    emitter.complete(); // 完成
                    return ;
                } else {
                    CcLlmAgentAccount ccLlmAgentAccount = llmAgentAccountService.selectCcLlmAgentAccountById(ccInboundLlmAccountList.get(0).getLlmAccountId());
                    if (null == ccLlmAgentAccount) {
                        // 发送数据
                        JSONObject rsponseData = new JSONObject();
                        rsponseData.put("requestId", requestId);
                        rsponseData.put("code", "500");
                        rsponseData.put("content", "客服号码不正确");
                        rsponseData.put("msgType", "message");
                        log.info(JSONObject.toJSONString(rsponseData));
                        emitter.send(SseEmitter.event()
                                .name("message")
                                .data(JSONObject.toJSONString(rsponseData)));
                        emitter.complete(); // 完成
                        return ;
                    } else {
                        ILlmCapability llmAccount;
                        String provider = ccLlmAgentAccount.getProviderClassName();
                        AccountBaseEntity account =  LlmAccountParser.parse(ccLlmAgentAccount);
                        llmAccount = (ILlmCapability) (Class.forName("com.ruoyi.aicall.llm.impl." + provider).newInstance());
                        llmAccount.setAccount(account);
                        String question = chatRequest.getQuestion();
                        // 首句
                        if (CollectionUtils.isEmpty(chatRequest.getMessages())) {
                            chatRequest.setMessages(new ArrayList<>());
                            // 没有历史记录，直接返回首句
                            String openingRemarks = account.openingRemarks;
                            JSONObject rsponseData = new JSONObject();
                            rsponseData.put("requestId", requestId);
                            rsponseData.put("code", "200");
                            rsponseData.put("content", openingRemarks);
                            JSONObject userMessage = new JSONObject();
                            userMessage.put("role",  "assistant");
                            userMessage.put("content",  openingRemarks);
                            userMessage.put("content_type", "text");
                            chatRequest.getMessages().add(userMessage);
                            rsponseData.put("messages", chatRequest.getMessages());
                            rsponseData.put("msgType", "message");
                            log.info(JSONObject.toJSONString(rsponseData));
                            emitter.send(SseEmitter.event()
                                    .name("message")
                                    .data(JSONObject.toJSONString(rsponseData)));
                            emitter.complete(); // 完成
                            return ;
                        } else {
                            // 客户未说话
                            if (StringUtils.isEmpty(question)) {
                                String noVoiceTips = account.customerNoVoiceTips;
                                // 没有历史记录，直接返回首句
                                JSONObject rsponseData = new JSONObject();
                                rsponseData.put("requestId", requestId);
                                rsponseData.put("code", "200");
                                rsponseData.put("content", noVoiceTips);
                                JSONObject userMessage = new JSONObject();
                                userMessage.put("role",  "assistant");
                                userMessage.put("content",  noVoiceTips);
                                userMessage.put("content_type", "text");
                                chatRequest.getMessages().add(userMessage);
                                rsponseData.put("messages", chatRequest.getMessages());
                                rsponseData.put("msgType", "message");
                                log.info(JSONObject.toJSONString(rsponseData));
                                emitter.send(SseEmitter.event()
                                        .name("message")
                                        .data(JSONObject.toJSONString(rsponseData)));
                                emitter.complete(); // 完成
                                return ;
                            } else {
                                // 调用大模型获取应答话术
                                llmAccount.getStreamingChatContent(emitter, chatRequest);
                                emitter.complete(); // 完成
                                return;
                            }
                        }
                    }
                }
            } catch (Exception e) {
                emitter.completeWithError(e);
            }
        });

        return emitter;
    }
}
