package com.njzscloud.supervisory.doubao.config;

import com.volcengine.ark.runtime.service.ArkService;
import lombok.RequiredArgsConstructor;
import okhttp3.ConnectionPool;
import okhttp3.Dispatcher;
import org.springframework.boot.autoconfigure.condition.ConditionalOnMissingBean;
import org.springframework.boot.context.properties.EnableConfigurationProperties;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.util.StringUtils;

import java.util.concurrent.TimeUnit;

/**
 * 火山引擎豆包配置类
 */
@Configuration
@RequiredArgsConstructor
@EnableConfigurationProperties(DouBaoProperties.class)
public class DouBaoConfiguration {

    private final DouBaoProperties properties;

    @Bean(destroyMethod = "shutdownExecutor")
    @ConditionalOnMissingBean
    public ArkService arkService() {
        String apiKey = properties.getApiKey();
        if (!StringUtils.hasText(apiKey)) {
            throw new IllegalStateException("豆包API Key未配置，请设置环境变量 ARK_API_KEY 或在配置文件中设置 doubao.api-key");
        }
        
        ConnectionPool connectionPool = new ConnectionPool(
                properties.getConnectionPoolSize(), 
                properties.getConnectionKeepAliveSeconds(), 
                TimeUnit.SECONDS
        );
        Dispatcher dispatcher = new Dispatcher();
        
        return ArkService.builder()
                .dispatcher(dispatcher)
                .connectionPool(connectionPool)
                .baseUrl(properties.getBaseUrl())
                .apiKey(apiKey)
                .build();
    }
}

