package com.yanzhu.module.ai.framework.ai.config;

import cn.hutool.core.util.StrUtil;
import cn.hutool.extra.spring.SpringUtil;
import com.yanzhu.module.ai.framework.ai.core.model.AiModelFactory;
import com.yanzhu.module.ai.framework.ai.core.model.AiModelFactoryImpl;
import com.yanzhu.module.ai.framework.ai.core.model.baichuan.BaiChuanChatModel;
import com.yanzhu.module.ai.framework.ai.core.model.doubao.DouBaoChatModel;
import com.yanzhu.module.ai.framework.ai.core.model.gemini.GeminiChatModel;
import com.yanzhu.module.ai.framework.ai.core.model.grok.GrokChatModel;
import com.yanzhu.module.ai.framework.ai.core.model.hunyuan.HunYuanChatModel;
import com.yanzhu.module.ai.framework.ai.core.model.midjourney.api.MidjourneyApi;
import com.yanzhu.module.ai.framework.ai.core.model.siliconflow.SiliconFlowApiConstants;
import com.yanzhu.module.ai.framework.ai.core.model.siliconflow.SiliconFlowChatModel;
import com.yanzhu.module.ai.framework.ai.core.model.suno.api.SunoApi;
import com.yanzhu.module.ai.framework.ai.core.model.xinghuo.XingHuoChatModel;
import com.yanzhu.module.ai.framework.ai.core.model.grok.GrokChatModel;
import com.yanzhu.module.ai.framework.ai.core.webserch.AiWebSearchClient;
import com.yanzhu.module.ai.framework.ai.core.webserch.bocha.AiBoChaWebSearchClient;
import com.yanzhu.module.ai.tool.method.PersonService;
import lombok.extern.slf4j.Slf4j;
import dev.langchain4j.model.chat.ChatLanguageModel;

import dev.langchain4j.model.embedding.EmbeddingModel;
import dev.langchain4j.rag.content.retriever.ContentRetriever;
import dev.langchain4j.rag.content.retriever.EmbeddingStoreContentRetriever;
import dev.langchain4j.store.embedding.EmbeddingStore;
import dev.langchain4j.store.embedding.inmemory.InMemoryEmbeddingStore;
import dev.langchain4j.service.AiServices;
import org.springframework.boot.autoconfigure.condition.ConditionalOnMissingBean;
import org.springframework.boot.autoconfigure.condition.ConditionalOnProperty;
import org.springframework.boot.context.properties.EnableConfigurationProperties;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;

import java.util.List;
import java.util.Optional;

/**
 * 研筑 AI 自动配置
 *
 * @author fansili
 */
@Configuration
@EnableConfigurationProperties({ YudaoAiProperties.class })
@Slf4j
public class AiAutoConfiguration {

    @Bean
    public AiModelFactory aiModelFactory() {
        return new AiModelFactoryImpl();
    }


    // ========== 各种 AI Client 创建 ==========

    @Bean
    @ConditionalOnProperty(value = "yanzhu.ai.gemini.enable", havingValue = "true")
    public GeminiChatModel geminiChatModel(YudaoAiProperties yanzhuAiProperties) {
        YudaoAiProperties.Gemini properties = yanzhuAiProperties.getGemini();
        return buildGeminiChatClient(properties);
    }

    public GeminiChatModel buildGeminiChatClient(YudaoAiProperties.Gemini properties) {
        if (StrUtil.isEmpty(properties.getModel())) {
            properties.setModel(GeminiChatModel.MODEL_DEFAULT);
        }
        // 创建基础的OpenAI兼容模型
        dev.langchain4j.model.openai.OpenAiChatModel openAiChatModel = dev.langchain4j.model.openai.OpenAiChatModel.builder()
                .baseUrl(GeminiChatModel.BASE_URL)
                .modelName(properties.getModel())
                .temperature(properties.getTemperature())
                .maxTokens(properties.getMaxTokens())
                .topP(properties.getTopP())
                .apiKey(properties.getApiKey())
                .build();
        return new GeminiChatModel(openAiChatModel);
    }

    @Bean
    @ConditionalOnProperty(value = "yanzhu.ai.doubao.enable", havingValue = "true")
    public DouBaoChatModel douBaoChatClient(YudaoAiProperties yanzhuAiProperties) {
        YudaoAiProperties.DouBao properties = yanzhuAiProperties.getDoubao();
        return buildDouBaoChatClient(properties);
    }

    public DouBaoChatModel buildDouBaoChatClient(YudaoAiProperties.DouBao properties) {
        if (StrUtil.isEmpty(properties.getModel())) {
            properties.setModel(DouBaoChatModel.MODEL_DEFAULT);
        }
        // 创建基础的OpenAI兼容模型
        dev.langchain4j.model.openai.OpenAiChatModel openAiChatModel = dev.langchain4j.model.openai.OpenAiChatModel.builder()
                .baseUrl(DouBaoChatModel.BASE_URL)
                .modelName(properties.getModel())
                .temperature(properties.getTemperature())
                .maxTokens(properties.getMaxTokens())
                .topP(properties.getTopP())
                .apiKey(properties.getApiKey())
                .build();
        return new DouBaoChatModel(openAiChatModel);
    }

    @Bean
    @ConditionalOnProperty(value = "yanzhu.ai.siliconflow.enable", havingValue = "true")
    public SiliconFlowChatModel siliconFlowChatClient(YudaoAiProperties yanzhuAiProperties) {
        YudaoAiProperties.SiliconFlow properties = yanzhuAiProperties.getSiliconflow();
        return buildSiliconFlowChatClient(properties);
    }

    public SiliconFlowChatModel buildSiliconFlowChatClient(YudaoAiProperties.SiliconFlow properties) {
        if (StrUtil.isEmpty(properties.getModel())) {
            properties.setModel(SiliconFlowApiConstants.MODEL_DEFAULT);
        }
        // 创建基础的OpenAI兼容模型
        dev.langchain4j.model.openai.OpenAiChatModel openAiChatModel = dev.langchain4j.model.openai.OpenAiChatModel.builder()
                .baseUrl(SiliconFlowApiConstants.DEFAULT_BASE_URL)
                .modelName(properties.getModel())
                .temperature(properties.getTemperature())
                .maxTokens(properties.getMaxTokens())
                .topP(properties.getTopP())
                .apiKey(properties.getApiKey())
                .build();
        return new SiliconFlowChatModel(openAiChatModel);
    }

    @Bean
    @ConditionalOnProperty(value = "yanzhu.ai.hunyuan.enable", havingValue = "true")
    public HunYuanChatModel hunYuanChatClient(YudaoAiProperties yanzhuAiProperties) {
        YudaoAiProperties.HunYuan properties = yanzhuAiProperties.getHunyuan();
        return buildHunYuanChatClient(properties);
    }

    public HunYuanChatModel buildHunYuanChatClient(YudaoAiProperties.HunYuan properties) {
        if (StrUtil.isEmpty(properties.getModel())) {
            properties.setModel(HunYuanChatModel.MODEL_DEFAULT);
        }
        // 特殊：由于混元大模型不提供 deepseek，而是通过知识引擎，所以需要区分下 URL
        if (StrUtil.isEmpty(properties.getBaseUrl())) {
            properties.setBaseUrl(
                    StrUtil.startWithIgnoreCase(properties.getModel(), "deepseek") ? HunYuanChatModel.DEEP_SEEK_BASE_URL
                            : HunYuanChatModel.BASE_URL);
        }
        // 创建基础的OpenAI兼容模型
        dev.langchain4j.model.openai.OpenAiChatModel openAiChatModel = dev.langchain4j.model.openai.OpenAiChatModel.builder()
                .baseUrl(properties.getBaseUrl())
                .modelName(properties.getModel())
                .temperature(properties.getTemperature())
                .maxTokens(properties.getMaxTokens())
                .topP(properties.getTopP())
                .apiKey(properties.getApiKey())
                .build();
        return new HunYuanChatModel(openAiChatModel);
    }

    @Bean
    @ConditionalOnProperty(value = "yanzhu.ai.xinghuo.enable", havingValue = "true")
    public XingHuoChatModel xingHuoChatClient(YudaoAiProperties yanzhuAiProperties) {
        YudaoAiProperties.XingHuo properties = yanzhuAiProperties.getXinghuo();
        return buildXingHuoChatClient(properties);
    }

    public XingHuoChatModel buildXingHuoChatClient(YudaoAiProperties.XingHuo properties) {
        if (StrUtil.isEmpty(properties.getModel())) {
            properties.setModel(XingHuoChatModel.MODEL_DEFAULT);
        }
        String apiKey = properties.getAppKey() + ":" + properties.getSecretKey();
        String baseUrl = "x1".equals(properties.getModel()) ? XingHuoChatModel.BASE_URL_V2 : XingHuoChatModel.BASE_URL_V1;
        // 创建基础的OpenAI兼容模型
        dev.langchain4j.model.openai.OpenAiChatModel openAiChatModel = dev.langchain4j.model.openai.OpenAiChatModel.builder()
                .baseUrl(baseUrl)
                .modelName(properties.getModel())
                .temperature(properties.getTemperature())
                .maxTokens(properties.getMaxTokens())
                .topP(properties.getTopP())
                .apiKey(apiKey)
                .build();
        return new XingHuoChatModel(openAiChatModel);
    }

    @Bean
    @ConditionalOnProperty(value = "yanzhu.ai.baichuan.enable", havingValue = "true")
    public BaiChuanChatModel baiChuanChatClient(YudaoAiProperties yanzhuAiProperties) {
        YudaoAiProperties.BaiChuan properties = yanzhuAiProperties.getBaichuan();
        return buildBaiChuanChatClient(properties);
    }

    public BaiChuanChatModel buildBaiChuanChatClient(YudaoAiProperties.BaiChuan properties) {
        if (StrUtil.isEmpty(properties.getModel())) {
            properties.setModel(BaiChuanChatModel.MODEL_DEFAULT);
        }
        // 创建基础的OpenAI兼容模型
        dev.langchain4j.model.openai.OpenAiChatModel openAiChatModel = dev.langchain4j.model.openai.OpenAiChatModel.builder()
                .baseUrl(BaiChuanChatModel.BASE_URL)
                .modelName(properties.getModel())
                .temperature(properties.getTemperature())
                .maxTokens(properties.getMaxTokens())
                .topP(properties.getTopP())
                .apiKey(properties.getApiKey())
                .build();
        return new BaiChuanChatModel(openAiChatModel);
    }

    @Bean
    @ConditionalOnProperty(value = "yanzhu.ai.midjourney.enable", havingValue = "true")
    public MidjourneyApi midjourneyApi(YudaoAiProperties yanzhuAiProperties) {
        YudaoAiProperties.Midjourney config = yanzhuAiProperties.getMidjourney();
        return new MidjourneyApi(config.getBaseUrl(), config.getApiKey(), config.getNotifyUrl());
    }

    @Bean
    @ConditionalOnProperty(value = "yanzhu.ai.suno.enable", havingValue = "true")
    public SunoApi sunoApi(YudaoAiProperties yanzhuAiProperties) {
        return new SunoApi(yanzhuAiProperties.getSuno().getBaseUrl());
    }

    @Bean
    @ConditionalOnProperty(value = "yanzhu.ai.grok.enable", havingValue = "true")
    public GrokChatModel grokChatClient(YudaoAiProperties yanzhuAiProperties) {
        YudaoAiProperties.Grok properties = yanzhuAiProperties.getGrok();
        return buildGrokChatClient(properties);
    }

    public GrokChatModel buildGrokChatClient(YudaoAiProperties.Grok properties) {
        if (StrUtil.isEmpty(properties.getModel())) {
            properties.setModel(GrokChatModel.MODEL_DEFAULT);
        }
        // 创建基础的OpenAI兼容模型
        dev.langchain4j.model.openai.OpenAiChatModel openAiChatModel = dev.langchain4j.model.openai.OpenAiChatModel.builder()
                .baseUrl(Optional.ofNullable(properties.getBaseUrl())
                        .orElse(GrokChatModel.BASE_URL))
                .modelName(properties.getModel())
                .temperature(properties.getTemperature())
                .maxTokens(properties.getMaxTokens())
                .topP(properties.getTopP())
                .apiKey(properties.getApiKey())
                .build();
        return new GrokChatModel(openAiChatModel);
    }

    // ========== Web Search 相关 ==========

    @Bean
    @ConditionalOnProperty(value = "yanzhu.ai.web-search.enable", havingValue = "true")
    public AiWebSearchClient webSearchClient(YudaoAiProperties yanzhuAiProperties) {
        return new AiBoChaWebSearchClient(yanzhuAiProperties.getWebSearch().getApiKey());
    }

    // ========== MCP 相关 ==========



}