package com.webchat.service.ai;


import com.webchat.common.enums.AiFunctionEnum;
import com.webchat.common.enums.SseEmitterBizEnum;
import com.webchat.common.helper.SseEmitterHelper;
import com.webchat.common.util.JsonUtil;
import com.webchat.domain.vo.llm.FunctionCallResponse;
import com.webchat.domain.vo.llm.image.ImageGenerateResponse;
import com.webchat.domain.vo.llm.image.RequestGenerateBaseParam;
import com.webchat.domain.vo.llm.image.RequestGenerateParam;
import com.webchat.domain.vo.request.mess.ChatMessageRequestVO;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.collections.CollectionUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.List;

@Slf4j
@Service
public class AiAgentFlowService {

    @Autowired
    private GPTChatService gptChatService;
    @Autowired
    private AiFunctionCallService aiFunctionCallService;
    @Autowired
    private LibLibGenerateImageService libLibGenerateImageService;

    /**
     * 旗舰版文生图模版id
     */
    private static final String TEMPLATE_UUID = "5d7e67009b344550bc1aa6ccbfa1d7f4";


    public void doAgent(ChatMessageRequestVO chatMessage) {
        String senderId = chatMessage.getSenderId();
        // 1. 意图识别
        SseEmitterHelper.send(SseEmitterBizEnum.ROBOT_CHAT.name(), senderId, "意图识别中...");
        FunctionCallResponse functionCallResponse = null;
        try {
            functionCallResponse =
                    aiFunctionCallService.getFunction(chatMessage.getMessage());
            log.info("意图识别结果 =====> input: {}, response:{}",
                    chatMessage.getMessage(), JsonUtil.toJsonString(functionCallResponse));
            String functionInfo = "意图识别："+ AiFunctionEnum.getFunctionName(functionCallResponse.getFunction());
            SseEmitterHelper.send(SseEmitterBizEnum.ROBOT_CHAT.name(), senderId, functionInfo);
        } catch (Exception e) {
            log.error("意图识别异常 =====> input: {}", chatMessage.getMessage(), e);
            SseEmitterHelper.send(SseEmitterBizEnum.ROBOT_CHAT.name(), senderId, "意图识别失败，稍后重试～");
            return;
        }
        if (functionCallResponse == null) {
            SseEmitterHelper.send(SseEmitterBizEnum.ROBOT_CHAT.name(), senderId, "意图识别失败，稍后重试～");
            return;
        }
        // 2. 根据意图执行对应工作流
        if (AiFunctionEnum.CHAT.name().equals(functionCallResponse.getFunction())) {
            // 机器人对话
            gptChatService.chat(chatMessage);
        } else if (AiFunctionEnum.IMAGE.name().equals(functionCallResponse.getFunction())) {
            // 机器人对话
            RequestGenerateBaseParam baseParam = RequestGenerateBaseParam.of(chatMessage.getMessage());
            RequestGenerateParam param = RequestGenerateParam.of(TEMPLATE_UUID, baseParam);
            try {
                ImageGenerateResponse response = libLibGenerateImageService.generate(senderId, param);
                List<String> images = response.getImages();
                if (CollectionUtils.isEmpty(images)) {
                    SseEmitterHelper.send(SseEmitterBizEnum.ROBOT_CHAT.name(), senderId, "图片生成失败～");
                    return;
                }
                String imageMd = " ![%s](%s \"%s\")";
                StringBuilder stringBuilder = new StringBuilder();
                for (int i = 0; i < images.size(); i++) {
                    String imageName = "图片" + (i + 1);
                    stringBuilder.append(String.format(imageMd, imageName, images.get(i), imageName));
                    if (i == images.size() - 1) {
                        stringBuilder.append("\n");
                    }
                }
                SseEmitterHelper.send(SseEmitterBizEnum.ROBOT_CHAT.name(), senderId, stringBuilder.toString());
            } catch (Exception e) {
                log.error("文生图服务异常 =====> param: {}", JsonUtil.toJsonString(param), e);
                SseEmitterHelper.send(SseEmitterBizEnum.ROBOT_CHAT.name(), senderId, "意图识别失败，稍后重试～");

            }
        }
    }
}
