package com.lideeyunji.tool.framework.ai.properties;


import com.lideeyunji.tool.framework.ai.config.DeepSeekConfig;
import com.lideeyunji.tool.framework.ai.config.KimiConfig;
import com.lideeyunji.tool.framework.ai.service.factor.AiService;
import okhttp3.OkHttpClient;
import org.springframework.boot.context.properties.EnableConfigurationProperties;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;

import javax.annotation.PostConstruct;
import java.util.concurrent.TimeUnit;


@Configuration
@EnableConfigurationProperties({
        DeepSeekConfigProperties.class,
        KimiConfigProperties.class})

public class AiConfigAutoConfiguration {


    private final DeepSeekConfigProperties deepSeekConfigProperties;
    private final KimiConfigProperties kimiConfigProperties;


    private com.lideeyunji.tool.framework.ai.service.Configuration configuration = new com.lideeyunji.tool.framework.ai.service.Configuration();

    public AiConfigAutoConfiguration(DeepSeekConfigProperties deepSeekConfigProperties, KimiConfigProperties kimiConfigProperties) {
        this.deepSeekConfigProperties = deepSeekConfigProperties;
        this.kimiConfigProperties = kimiConfigProperties;
    }

    @Bean
    public AiService aiService() {
        return new AiService(configuration);
    }


    @PostConstruct
    private void init() {
        initOkHttp();
        initDeepSeekConfig();
        initMoonshotConfig();
    }



    private void initOkHttp() {
        // 开启 Http 客户端
        OkHttpClient.Builder okHttpBuilder = new OkHttpClient
                .Builder()
                .connectTimeout(300, TimeUnit.SECONDS)
                .writeTimeout(300,TimeUnit.SECONDS)
                .readTimeout(300, TimeUnit.SECONDS);
        OkHttpClient okHttpClient = okHttpBuilder.build();

        configuration.setOkHttpClient(okHttpClient);
    }


    /**
     * 初始化DeepSeek 配置信息
     */
    private void initDeepSeekConfig(){
        DeepSeekConfig deepSeekConfig = new DeepSeekConfig();
        deepSeekConfig.setApiHost(deepSeekConfigProperties.getApiHost());
        deepSeekConfig.setApiKey(deepSeekConfigProperties.getApiKey());
        deepSeekConfig.setModel(deepSeekConfigProperties.getModel());
        deepSeekConfig.setChatCompletionUrl(deepSeekConfigProperties.getChatCompletionUrl());

        configuration.setDeepSeekConfig(deepSeekConfig);
    }

    /**
     * 初始化Moonshot 配置信息
     */
    private void initMoonshotConfig() {
        KimiConfig kimiConfig = new KimiConfig();
        kimiConfig.setApiHost(kimiConfigProperties.getApiHost());
        kimiConfig.setApiKey(kimiConfigProperties.getApiKey());
        kimiConfig.setModel(kimiConfigProperties.getModel());
        kimiConfig.setChatCompletionUrl(kimiConfigProperties.getChatCompletionUrl());

        configuration.setKimiConfig(kimiConfig);
    }

}
