package com.infoepoch.pms.agent.aiMode;

import com.infoepoch.pms.agent.properties.AiZhiYuProperties;
import org.springframework.ai.chat.model.ChatModel;
import org.springframework.ai.openai.OpenAiChatModel;
import org.springframework.ai.openai.OpenAiChatOptions;
import org.springframework.ai.openai.api.OpenAiApi;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.context.annotation.Primary;
import org.springframework.http.client.BufferingClientHttpRequestFactory;
import org.springframework.http.client.ClientHttpRequestFactory;
import org.springframework.http.client.SimpleClientHttpRequestFactory;
import org.springframework.util.StringUtils;
import org.springframework.web.client.RestClient;

@Configuration
public class AiZhiYuConfiguration {

    @Bean("ZhiYuOpenAiApi")
    OpenAiApi ZhiYuOpenAiApi(AiZhiYuProperties properties) {
        return OpenAiApi.builder()
                .baseUrl(properties.getBaseUrl())
                .apiKey(resolveApiKey(properties))
                .restClientBuilder(buildCompatibleRestClient())
                .build();
    }

    @Primary
    @Bean("ZhiYuChatModel")
    ChatModel ZhiYuChatModel(@Qualifier("ZhiYuOpenAiApi") OpenAiApi zhiYuOpenAiApi,
                              AiZhiYuProperties properties) {
        return OpenAiChatModel.builder()
                .openAiApi(zhiYuOpenAiApi)
                .defaultOptions(OpenAiChatOptions.builder()
                        .model(properties.getModel())
                        .temperature(properties.getTemperature())
                        .maxTokens(properties.getMaxTokens())
                        .build())
                .build();
    }

    private RestClient.Builder buildCompatibleRestClient() {
        ClientHttpRequestFactory requestFactory =
                new BufferingClientHttpRequestFactory(new SimpleClientHttpRequestFactory());
        return RestClient.builder().requestFactory(requestFactory);
    }

    private String resolveApiKey(AiZhiYuProperties properties) {
        return StringUtils.hasText(properties.getApiKey()) ? properties.getApiKey() : "EMPTY";
    }
}
