package com.infoepoch.pms.agent.platform.model.adapter.out.ai;

import com.infoepoch.pms.agent.platform.model.domain.AiModelConfig;
import com.infoepoch.pms.agent.platform.model.domain.ProviderType;
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.stereotype.Component;
import org.springframework.util.LinkedMultiValueMap;
import org.springframework.util.MultiValueMap;
import org.springframework.util.StringUtils;

import java.util.Map;

/**
 * OpenAI 及 OpenAI 兼容接口的 ChatModel 构建器。
 */
@Component
public class OpenAiChatModelBuilder implements ProviderChatModelBuilder {

    /**
     * 判断是否支持指定供应商类型。
     *
     * @param providerType 供应商类型
     * @return true 表示支持
     */
    @Override
    public boolean supports(String providerType) {
        return ProviderType.OPENAI.getCode().equalsIgnoreCase(providerType);
    }

    /**
     * 构建 OpenAI ChatModel。
     *
     * @param config 模型配置
     * @return ChatModel
     */
    @Override
    public ChatModel build(AiModelConfig config) {
        String apiKey = config.getProvider().getApiKey();
        String baseUrl = config.getProvider().getBaseUrl();

        OpenAiApi.Builder apiBuilder = OpenAiApi.builder()
                .apiKey(apiKey);
        if (StringUtils.hasText(baseUrl)) {
            apiBuilder.baseUrl(baseUrl);
        }
        MultiValueMap<String, String> headers = buildCustomHeaders(config.getProvider().getCustomHeaders());
        if (!headers.isEmpty()) {
            apiBuilder.headers(headers);
        }
        OpenAiApi api = apiBuilder.build();

        OpenAiChatOptions.Builder optionsBuilder = OpenAiChatOptions.builder()
                .model(config.getModelName());

        if (config.getTemperature() != null) {
            optionsBuilder.temperature(config.getTemperature().doubleValue());
        }
        if (config.getMaxTokens() != null) {
            optionsBuilder.maxTokens(config.getMaxTokens());
        }

        return OpenAiChatModel.builder()
                .openAiApi(api)
                .defaultOptions(optionsBuilder.build())
                .build();
    }

    /**
     * 将供应商自定义请求头转换为 Spring AI 所需的 MultiValueMap。
     *
     * @param customHeaders 自定义请求头
     * @return 转换后的请求头集合
     */
    private MultiValueMap<String, String> buildCustomHeaders(Map<String, String> customHeaders) {
        LinkedMultiValueMap<String, String> headers = new LinkedMultiValueMap<>();
        if (customHeaders == null || customHeaders.isEmpty()) {
            return headers;
        }
        customHeaders.forEach(headers::add);
        return headers;
    }
}
