package com.infoepoch.pms.agent.aiMode;

import com.infoepoch.pms.agent.properties.AiLocalProperties;
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.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 AiLocalConfiguration {

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

    @Bean("localChatModel")
    ChatModel localChatModel(@Qualifier("localOpenAiApi") OpenAiApi localOpenAiApi,
                             AiLocalProperties properties) {
        return OpenAiChatModel.builder()
                .openAiApi(localOpenAiApi)
                .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(AiLocalProperties properties) {
        return StringUtils.hasText(properties.getApiKey()) ? properties.getApiKey() : "EMPTY";
    }
}
