package cn.iocoder.yudao.module.llm.service.http;

import cn.iocoder.yudao.framework.common.util.http.HttpUtils;
import cn.iocoder.yudao.framework.common.util.object.BeanUtils;
import cn.iocoder.yudao.module.llm.framework.backend.config.LLMBackendProperties;
import cn.iocoder.yudao.module.llm.service.http.vo.*;
import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.fasterxml.jackson.core.type.TypeReference;
import com.fasterxml.jackson.databind.ObjectMapper;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.io.BufferedReader;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

@Slf4j
@Service
public class ModelService {

    public final static String DEFAULT_MODEL_ID = "Qwen2.5-0.5B-Instruct";
    public final static String PRIVATE_MODEL_ID = "llama3.1";

    @Resource
    private LLMBackendProperties llmBackendProperties;
    @Resource
    private TrainHttpService trainHttpService;

    /**
     * 获取模型列表
     */
    public ModelListRespVO modelList(){
        String result = HttpUtils.get(llmBackendProperties.getModelCompletions(), null);
        if (StringUtils.isBlank(result)) {
            return null;
        }
        try {
            ModelList modelList = JSON.parseObject(result, ModelList.class);
            if (StringUtils.isBlank(modelList.getDetail())) {
                // 没有detail，就是没有错误
                ModelListRespVO respVO = new ModelListRespVO();
                respVO.setData(BeanUtils.toBean(modelList.getData(), ModelListRespVO.ModelData.class));
                return respVO;
            }
            return null;
        } catch (Exception e) {
            return null;
        }
    }

    /**
     * 对话聊天
     * @param req
     * @return
     */
    public ModelCompletionsRespVO modelCompletions(ModelCompletionsReqVO req) {
        if (StringUtils.isBlank(req.getModel())) {
            req.setModel(DEFAULT_MODEL_ID);
        }
        log.info("url: {}", llmBackendProperties.getModelCompletions());
        log.info("request: {}", req);
        String result = HttpUtils.post(llmBackendProperties.getModelCompletions(), null, JSON.toJSONString(req));
        log.info("response: {}", result);
        if (StringUtils.isBlank(result)) {
            return null;
        }
        try {
            ChatCompletion chatCompletion = JSON.parseObject(result, ChatCompletion.class);
            if (StringUtils.isBlank(chatCompletion.getDetail())) {
                // 没有detail，就是没有错误
                ModelCompletionsRespVO respVO = new ModelCompletionsRespVO();
                respVO.setSystem("助手");
                respVO.setQuestion(req.getMessages().get(req.getMessages().size() - 1).getContent());
                respVO.setAnswer(chatCompletion.getChoices().get(0).getMessage().getContent());
                return respVO;
            }
            return null;
        } catch (Exception e) {
            return null;
        }
    }

    /**
     * 获取模型下载列表
     */
    public List<String> getFileList(String fileName){
        String url = llmBackendProperties.getModelFileList() + fileName;
        String res = HttpUtils.get(url, null);
        log.info(" getFileList:{}", res);
        try {
            return JSONArray.parseArray(res, String.class);
        } catch (Exception e) {
            log.info("error getFileList:{}", e.getMessage());
        }
        return null;
    }

    public ModelCompletionsRespVO modelPrivateCompletions(Map<String, String> headers,ModelCompletionsReqVO req) {
       trainHttpService.login(headers);
        if (StringUtils.isBlank(req.getModel())) {
            req.setModel(PRIVATE_MODEL_ID);
        }
        log.info("url: {}", llmBackendProperties.getAigcModelCompletions());
        log.info("request: {}", req);
/*        String result = HttpUtils.postStream(llmBackendProperties.getAigcModelCompletions(), headers, JSON.toJSONString(req));
        log.info("response: {}", result);
        if (StringUtils.isBlank(result)) {
            return null;
        }*/
        try {
            StringBuilder fullContent = new StringBuilder();
            try (InputStream inputStream = HttpUtils.postStream(llmBackendProperties.getAigcModelCompletions(), headers, JSON.toJSONString(req));
                 BufferedReader reader = new BufferedReader(new InputStreamReader(inputStream))) {
                String line;
                while ((line = reader.readLine()) != null) {
                    JSONObject jsonObject = JSON.parseObject(line);
                    if (jsonObject.getBoolean("success")) {
                        AigcRespChatVO aigcRespVO = jsonObject.toJavaObject(AigcRespChatVO.class);
                        if (aigcRespVO.getData().size() != 0) {
                            AigcChatCompletion chatCompletion = aigcRespVO.getData().get(aigcRespVO.getData().size() - 1);
                            fullContent.append(chatCompletion.getContent());
                        }
                    }
                }
            }
            ModelCompletionsRespVO respVO = new ModelCompletionsRespVO();
            respVO.setSystem("助手");
            respVO.setQuestion(req.getMessages().get(req.getMessages().size() - 1).getContent());
            respVO.setAnswer(fullContent.toString());
            return respVO;
        } catch (Exception e) {
            e.printStackTrace();
            return null;
        }
    }

    public TextToImageRespVo textToImage(TextToImageReqVo req) {
        log.info("url: {}", llmBackendProperties.getTextToImage());
        log.info("request: {}", req);
        String result = HttpUtils.post(llmBackendProperties.getTextToImage(),new HashMap<>(), JSON.toJSONString(req));
        log.info("response: {}", result);
        if (StringUtils.isBlank(result)) {
            return null;
        }
        try {
            return JSON.parseObject(result, TextToImageRespVo.class);
        }catch (Exception e){
            log.error("text to image error : {}",e.getMessage());
        }
        return null;
    }
}
