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

import com.alibaba.cloud.ai.dashscope.api.DashScopeApi;
import com.alibaba.cloud.ai.dashscope.chat.DashScopeChatModel;
import com.alibaba.cloud.ai.dashscope.chat.DashScopeChatOptions;
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.stereotype.Component;
import org.springframework.util.StringUtils;

/**
 * DashScope ChatModel 构建器。
 */
@Component
public class DashScopeChatModelBuilder implements ProviderChatModelBuilder {

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

    /**
     * 构建 DashScope ChatModel。
     *
     * @param config 模型配置
     * @return ChatModel
     */
    @Override
    public ChatModel build(AiModelConfig config) {
        String apiKey = config.getProvider().getApiKey();
        String baseUrl = config.getProvider().getBaseUrl();
        DashScopeApi.Builder apiBuilder = DashScopeApi.builder();
        if (StringUtils.hasText(baseUrl)) {
            apiBuilder.baseUrl(baseUrl);
        }
        if (StringUtils.hasText(apiKey)) {
            apiBuilder.apiKey(apiKey);
        }
        DashScopeApi api = apiBuilder.build();

        DashScopeChatOptions options = DashScopeChatOptions.builder()
                .model(config.getModelName())
                .build();

        if (config.getTemperature() != null) {
            options.setTemperature(config.getTemperature().doubleValue());
        }

        if (config.getMaxTokens() != null) {
            options.setMaxTokens(config.getMaxTokens());
        }
        if (config.getEnableThinking() != null) {
            options.setEnableThinking(config.getEnableThinking());
        }
        if (config.getMultiModel() != null) {
            options.setMultiModel(config.getMultiModel());
        }

        return DashScopeChatModel.builder()
                .dashScopeApi(api)
                .defaultOptions(options)
                .build();
    }
}
