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

import cn.dev33.satoken.exception.SaTokenException;
import com.seer.teach.common.ResultBean;
import com.seer.teach.common.enums.ResultCodeEnum;
import com.seer.teach.common.exception.FileUploadException;
import com.seer.teach.common.service.CommonFileService;
import com.seer.teach.common.utils.CommonUtils;
import com.seer.teach.openapi.llm.resp.CorrectDTO;
import com.seer.teach.openapi.llm.req.LlmAiCorrectReq;
import com.seer.teach.openapi.entity.SnCodesEntity;
import com.seer.teach.openapi.service.LlmSseService;
import com.seer.teach.openapi.uitl.OpenApiUtils;
import com.seer.teach.openapi.uitl.StpOpenApiUtils;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Service;
import org.springframework.web.multipart.MultipartFile;
import reactor.core.publisher.Flux;

/**
 *
 * <p>
 *
 * </p >
 *
 * @author Captain
 * @since 2025-11-03 13:46
 */
@Slf4j
@Service
@RequiredArgsConstructor
public class BusinessServiceImpl implements com.seer.teach.openapi.service.BusinessService {

    private final LlmSseService llmSseService;

    private final CommonFileService commonFileService;

    private final com.seer.teach.openapi.service.SnCodesService snCodesService;

    /**
     * AI批改接口实现
     *
     * @param file 待批改的图片文件
     * @return 返回AI批改结果的响应流，包含批改数据或错误信息
     */
    @Override
    public Flux<ResultBean<CorrectDTO>> aiCorrect(String file) {
        try {
            MultipartFile multipartFile = OpenApiUtils.base64ToMultipart(file);
            // 验证上传文件类型是否合法
            CommonUtils.isIllegalImageType(multipartFile);
            int snId = StpOpenApiUtils.getLoginIdAsInt();
            SnCodesEntity snCode = snCodesService.getById(snId);

            // 上传AI批改图片并获取访问URL
            String url = commonFileService.uploadAiCorrectImage(snId, multipartFile);

            // 生成会话ID用于AI批改请求跟踪
            Integer sessionId = OpenApiUtils.generateSessionId(url, snId, snCode.getSnCode());

            // 构造AI批改请求对象
            LlmAiCorrectReq llmReq = LlmAiCorrectReq.requestObject(sessionId, snCode.getSnCode(), url);

            // 调用AI批改服务并返回结果流
            return llmSseService.aiCorrect(llmReq);
        } catch (FileUploadException e) {
            return Flux.just(ResultBean.error(ResultCodeEnum.FILE_FORMAT_ERROR));
        } catch (SaTokenException e) {
            e.printStackTrace();
            log.info("e :{} {}", e.getMessage(), e.getCode());
            return Flux.just(ResultBean.error(ResultCodeEnum.AI_CORRECT_ERROR));
        }
    }

}
