package com.lideeyunji.tool.framework.ai.chat.deepseek;

import com.fasterxml.jackson.databind.ObjectMapper;
import com.lideeyunji.tool.framework.ai.config.DeepSeekConfig;
import com.lideeyunji.tool.framework.ai.convert.ParameterConvert;
import com.lideeyunji.tool.framework.ai.convert.ResultConvert;
import com.lideeyunji.tool.framework.ai.chat.ChatBaseRequest;
import com.lideeyunji.tool.framework.ai.chat.ChatBaseResponse;
import com.lideeyunji.tool.framework.ai.chat.deepseek.entity.DeepSeekChatRequest;
import com.lideeyunji.tool.framework.ai.chat.deepseek.entity.DeepSeekChatResponse;
import com.lideeyunji.tool.framework.ai.service.Configuration;
import com.lideeyunji.tool.framework.ai.service.IChatService;
import com.lideeyunji.tool.framework.yunji.utils.FuncBase;
import okhttp3.*;


public class DeepSeekChatService implements IChatService, ParameterConvert<DeepSeekChatRequest>, ResultConvert<DeepSeekChatResponse> {
    private final DeepSeekConfig deepSeekConfig;
    private final OkHttpClient okHttpClient;


    public DeepSeekChatService(Configuration configuration) {
        this.deepSeekConfig = configuration.getDeepSeekConfig();
        this.okHttpClient = configuration.getOkHttpClient();
    }


    @Override
    public DeepSeekChatRequest convertParam(ChatBaseRequest chatBaseRequest) {
        DeepSeekChatRequest deepSeekChatRequest = DeepSeekChatRequest.builder()
                .messages(chatBaseRequest.getMessages())
                .frequencyPenalty(chatBaseRequest.getFrequencyPenalty())
                .maxTokens(chatBaseRequest.getMaxTokens())
                .presencePenalty(chatBaseRequest.getPresencePenalty())
                .responseFormat(chatBaseRequest.getResponseFormat())
                .stop(chatBaseRequest.getStop())
                .temperature(chatBaseRequest.getTemperature() / 2)
                .topP(chatBaseRequest.getTopP())
                .functions(chatBaseRequest.getFunctions())
                .toolChoice(chatBaseRequest.getToolChoice())
                .build();
        return deepSeekChatRequest;
    }


    @Override
    public ChatBaseResponse convertResponse(DeepSeekChatResponse deepSeekChatResponse) {
        ChatBaseResponse chatBaseResponse = new ChatBaseResponse();
        chatBaseResponse.setId(deepSeekChatResponse.getId());
        chatBaseResponse.setObject(deepSeekChatResponse.getObject());
        chatBaseResponse.setCreated(deepSeekChatResponse.getCreated());
        chatBaseResponse.setModel(deepSeekChatResponse.getModel());
        chatBaseResponse.setSystemFingerprint(deepSeekChatResponse.getSystemFingerprint());
        chatBaseResponse.setChoices(deepSeekChatResponse.getChoices());
        return chatBaseResponse;
    }

    @Override
    public ChatBaseResponse chatCompletion(String baseUrl, String apiKey, ChatBaseRequest chatBaseRequest) throws Exception {
        baseUrl = FuncBase.isEmpty(baseUrl) ? deepSeekConfig.getApiHost() : baseUrl;
        apiKey = FuncBase.isEmpty(apiKey) ? deepSeekConfig.getApiKey() : apiKey;

        // 转换 请求参数
        DeepSeekChatRequest deepSeekChatRequest = this.convertParam(chatBaseRequest);
        deepSeekChatRequest.setModel(deepSeekConfig.getModel());

        // 构造请求
        ObjectMapper mapper = new ObjectMapper();
        String requestString = mapper.writeValueAsString(deepSeekChatRequest);


        Request request = new Request.Builder()
                .header("Authorization", "Bearer " + apiKey)
                .url(baseUrl + deepSeekConfig.getChatCompletionUrl())
                .post(RequestBody.create(MediaType.parse("application/json; charset=utf-8"), requestString))
                .build();

        Response execute = okHttpClient.newCall(request).execute();
        if (FuncBase.isEmpty(execute)) {
            return null;
        }
        if (FuncBase.isEmpty(execute.body())) {
            return null;
        }
        //转为统一格式
        String rsp = execute.body().string();
        DeepSeekChatResponse moonshotChatCompletionResponse = FuncBase.json2Bean(rsp, DeepSeekChatResponse.class);
        return this.convertResponse(moonshotChatCompletionResponse);
        
    }

    @Override
    public ChatBaseResponse chatCompletion(ChatBaseRequest chatBaseRequest) throws Exception {
        return this.chatCompletion(null, null, chatBaseRequest);
    }


}
