package com.seer.teach.teacher.service.impl;

import cn.dev33.satoken.stp.StpUtil;
import com.seer.teach.common.enums.teacher.LessonStateEvent;
import com.seer.teach.common.utils.CommonUtils;
import com.seer.teach.iot.api.UserDeviceServiceApi;
import com.seer.teach.teacher.common.req.ChatReq;
import com.seer.teach.teacher.common.utils.TeacherUtils;
import com.seer.teach.teacher.common.utils.UserQuestionTextCache;
import com.seer.teach.teacher.service.AiChatService;
import com.seer.teach.teacher.service.LlmRequestService;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Service;
import org.springframework.web.multipart.MultipartFile;

/**
 * AI聊天服务实现类，负责处理用户的语音提问并根据不同的状态或匹配结果进行相应的处理。
 * 包括语音识别、指令匹配、发送设备指令、与大模型对话等功能。
 */
@Slf4j
@Service
@RequiredArgsConstructor
public class AiChatServiceImpl implements AiChatService {

    private final LessonStateMachineService lessonStateMachineService;

    private final UserQuestionTextCache userQuestionTextCache;

    private final UserDeviceServiceApi userDeviceServiceApi;

    private final LlmRequestService llmRequestService;

    @Override
    public void chat(ChatReq params) {
        MultipartFile file = TeacherUtils.base64ToMultipart(params.getFileBase64());
        CommonUtils.isIllegalImageType(file);
        Integer userId = StpUtil.getLoginIdAsInt();
        String questionText = llmRequestService.requestLlmForStt(file, userId);
        userQuestionTextCache.put(userId, questionText);
        log.info("用户{}提问，问题为{}", userId, questionText);
        if (lessonStateMachineService.hasLessonContext(userId)) {
            lessonStateMachineService.updateAudioSort(userId, params.getSort());
            lessonStateMachineService.sendEvent(userId, LessonStateEvent.USER_ASK);
        }
    }

}
