package com.jeelowcode.framework.ai.platform.chat.kimi;


import com.jeelowcode.framework.ai.config.KimiConfig;
import com.jeelowcode.framework.ai.convert.ParameterConvert;
import com.jeelowcode.framework.ai.convert.ResultConvert;
import com.jeelowcode.framework.ai.platform.chat.ChatBaseRequest;
import com.jeelowcode.framework.ai.platform.chat.ChatBaseResponse;
import com.jeelowcode.framework.ai.platform.chat.kimi.entity.KimiChatRequest;
import com.jeelowcode.framework.ai.platform.chat.kimi.entity.KimiChatResponse;
import com.jeelowcode.framework.ai.service.Configuration;
import com.jeelowcode.framework.ai.service.IChatService;
import com.jeelowcode.framework.utils.utils.FuncBase;
import okhttp3.*;


public class KimiChatService implements IChatService, ParameterConvert<KimiChatRequest>, ResultConvert<KimiChatResponse> {
    private final KimiConfig kimiConfig;
    private final OkHttpClient okHttpClient;


    public KimiChatService(Configuration configuration) {
        this.kimiConfig = configuration.getKimiConfig();
        this.okHttpClient = configuration.getOkHttpClient();
    }

    @Override
    public KimiChatRequest convertParam(ChatBaseRequest chatBaseRequest) {
        KimiChatRequest kimiChatRequest = KimiChatRequest.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 kimiChatRequest;
    }

    /**
     * 回复内容参数转换
     */
    @Override
    public ChatBaseResponse convertResponse(KimiChatResponse kimiChatResponse) {
        ChatBaseResponse chatBaseResponse = new ChatBaseResponse();
        chatBaseResponse.setId(kimiChatResponse.getId());
        chatBaseResponse.setObject(kimiChatResponse.getObject());
        chatBaseResponse.setCreated(kimiChatResponse.getCreated());
        chatBaseResponse.setModel(kimiChatResponse.getModel());
        chatBaseResponse.setChoices(kimiChatResponse.getChoices());
        return chatBaseResponse;
    }

    /**
     * 同步请求
     */
    @Override
    public ChatBaseResponse chatCompletion(String baseUrl, String apiKey, ChatBaseRequest chatBaseRequest) throws Exception {
        baseUrl = FuncBase.isEmpty(baseUrl) ? kimiConfig.getApiHost() : baseUrl;
        apiKey = FuncBase.isEmpty(apiKey) ? kimiConfig.getApiKey() : apiKey;
        // 转换 请求参数
        KimiChatRequest kimiChatRequest = this.convertParam(chatBaseRequest);
        kimiChatRequest.setModel(kimiConfig.getModel());

        // 构造请求
        String requestString = FuncBase.json2Str(kimiChatRequest);
        RequestBody requestBody = RequestBody.create(MediaType.parse("application/json; charset=utf-8"), requestString);
        Request request = new Request.Builder()
                .header("Authorization", "Bearer " + apiKey)
                .url(baseUrl+ kimiConfig.getChatCompletionUrl())
                .post(requestBody)
                .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();
        KimiChatResponse kimiChatResponse = FuncBase.json2Bean(rsp, KimiChatResponse.class);
        return this.convertResponse(kimiChatResponse);
    }


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

}
