package com.yanzhu.module.ai.framework.ai.core.model;

import cn.hutool.core.lang.Singleton;
import cn.hutool.core.lang.func.Func0;
import cn.hutool.core.util.StrUtil;
import com.yanzhu.module.ai.enums.model.AiPlatformEnum;
import com.yanzhu.module.ai.framework.ai.config.YudaoAiProperties;
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.hunyuan.HunYuanChatModel;
import com.yanzhu.module.ai.framework.ai.core.model.midjourney.api.MidjourneyApi;
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 dev.langchain4j.model.chat.ChatLanguageModel;
import dev.langchain4j.model.embedding.EmbeddingModel;
import dev.langchain4j.model.image.ImageModel;
import dev.langchain4j.store.embedding.EmbeddingStore;
import dev.langchain4j.store.embedding.inmemory.InMemoryEmbeddingStore;

import java.util.Map;

/**
 * AI Model 模型工厂的实现类（简化版，兼容JDK 1.8）
 *
 * @author 研筑科技
 */
public class AiModelFactoryImpl implements AiModelFactory {

    @Override
    public ChatLanguageModel getOrCreateChatModel(AiPlatformEnum platform, String apiKey, String url) {
        String cacheKey = buildClientCacheKey(ChatLanguageModel.class, platform, apiKey, url);
        return Singleton.get(cacheKey, (Func0<ChatLanguageModel>) () -> {
            switch (platform) {
                case TONG_YI:
                    return buildTongYiChatModel(apiKey);
                case YI_YAN:
                    return buildYiYanChatModel(apiKey);
                case DOU_BAO:
                    return buildDouBaoChatModel(apiKey);
                case HUN_YUAN:
                    return buildHunYuanChatModel(apiKey, url);
                case SILICON_FLOW:
                    return buildSiliconFlowChatModel(apiKey);
                case ZHI_PU:
                    return buildZhiPuChatModel(apiKey, url);
                case XING_HUO:
                    return buildXingHuoChatModel(apiKey);
                case BAI_CHUAN:
                    return buildBaiChuanChatModel(apiKey);
                case OPENAI:
                    return buildOpenAiChatModel(apiKey, url);
                case GEMINI:
                    return buildGeminiChatModel(apiKey);
                default:
                    throw new IllegalArgumentException(StrUtil.format("未知平台({})", platform));
            }
        });
    }

    @Override
    public ChatLanguageModel getDefaultChatModel(AiPlatformEnum platform) {
        throw new UnsupportedOperationException("暂不支持默认模型获取");
    }

    @Override
    public ImageModel getDefaultImageModel(AiPlatformEnum platform) {
        throw new UnsupportedOperationException("暂不支持默认图像模型获取");
    }

    @Override
    public ImageModel getOrCreateImageModel(AiPlatformEnum platform, String apiKey, String url) {
        switch (platform) {
            case TONG_YI:
                return buildTongYiImagesModel(apiKey);
            default:
                throw new IllegalArgumentException(StrUtil.format("未知平台({})", platform));
        }
    }

    @Override
    public MidjourneyApi getOrCreateMidjourneyApi(String apiKey, String url) {
        String cacheKey = buildClientCacheKey(MidjourneyApi.class, AiPlatformEnum.MIDJOURNEY.getPlatform(), apiKey, url);
        return Singleton.get(cacheKey, (Func0<MidjourneyApi>) () -> {
            YudaoAiProperties.Midjourney properties = new YudaoAiProperties.Midjourney()
                    .setBaseUrl(url).setApiKey(apiKey);
            return new MidjourneyApi(url, apiKey, properties.getNotifyUrl());
        });
    }

    @Override
    public SunoApi getOrCreateSunoApi(String apiKey, String url) {
        String cacheKey = buildClientCacheKey(SunoApi.class, AiPlatformEnum.SUNO.getPlatform(), apiKey, url);
        return Singleton.get(cacheKey, (Func0<SunoApi>) () -> new SunoApi(url));
    }

    @Override
    public EmbeddingModel getOrCreateEmbeddingModel(AiPlatformEnum platform, String apiKey, String url, String model) {
        String cacheKey = buildClientCacheKey(EmbeddingModel.class, platform, apiKey, url, model);
        return Singleton.get(cacheKey, (Func0<EmbeddingModel>) () -> {
            switch (platform) {
                case TONG_YI:
                    return buildTongYiEmbeddingModel(apiKey, model);
                default:
                    throw new IllegalArgumentException(StrUtil.format("未知平台({})", platform));
            }
        });
    }

    @Override
    public EmbeddingStore getOrCreateVectorStore(Class<? extends EmbeddingStore> type,
                                           EmbeddingModel embeddingModel,
                                           Map<String, Class<?>> metadataFields) {
        String cacheKey = buildClientCacheKey(EmbeddingStore.class, embeddingModel, type);
        return Singleton.get(cacheKey, (Func0<EmbeddingStore>) () -> {
            if (type == InMemoryEmbeddingStore.class) {
                return new InMemoryEmbeddingStore<>();
            }
            throw new IllegalArgumentException(StrUtil.format("未知类型({})", type));
        });
    }

    private static String buildClientCacheKey(Class<?> clazz, Object... params) {
        StringBuilder sb = new StringBuilder(clazz.getName());
        for (Object param : params) {
            sb.append("_").append(param);
        }
        return sb.toString();
    }

    // ========== 各种创建 LangChain4J 客户端的方法 ==========

    private ChatLanguageModel buildTongYiChatModel(String key) {
        // 通义千问兼容 OpenAI API 格式
        return dev.langchain4j.model.openai.OpenAiChatModel.builder()
                .baseUrl("https://dashscope.aliyuncs.com/compatible-mode/v1")
                .apiKey(key)
                .modelName("qwen-max")
                .build();
    }

    private ImageModel buildTongYiImagesModel(String key) {
        // 通义万相兼容 OpenAI API 格式
        return dev.langchain4j.model.openai.OpenAiImageModel.builder()
                .baseUrl("https://dashscope.aliyuncs.com/compatible-mode/v1")
                .apiKey(key)
                .modelName("wanx-image-generation")
                .build();
    }

    private ChatLanguageModel buildYiYanChatModel(String key) {
        // 暂时返回null，实际应根据配置创建对应的模型
        return null;
    }

    private ChatLanguageModel buildDouBaoChatModel(String apiKey) {
        return dev.langchain4j.model.openai.OpenAiChatModel.builder()
                .baseUrl("https://ark.cn-beijing.volces.com/api")
                .apiKey(apiKey)
                .modelName("doubao-1-5-lite-32k-250115")
                .build();
    }

    private ChatLanguageModel buildHunYuanChatModel(String apiKey, String url) {
        return dev.langchain4j.model.openai.OpenAiChatModel.builder()
                .baseUrl(url)
                .apiKey(apiKey)
                .modelName("hunyuan-turbo")
                .build();
    }

    private ChatLanguageModel buildSiliconFlowChatModel(String apiKey) {
        return dev.langchain4j.model.openai.OpenAiChatModel.builder()
                .baseUrl("https://api.siliconflow.cn")
                .apiKey(apiKey)
                .modelName("Qwen/Qwen2.5-72B-Instruct")
                .build();
    }

    private ChatLanguageModel buildZhiPuChatModel(String apiKey, String url) {
        return dev.langchain4j.model.openai.OpenAiChatModel.builder()
                .baseUrl(url)
                .apiKey(apiKey)
                .modelName("glm-4")
                .build();
    }

    private ChatLanguageModel buildXingHuoChatModel(String apiKey) {
        return dev.langchain4j.model.openai.OpenAiChatModel.builder()
                .baseUrl("https://spark-api-open.xf-yun.com")
                .apiKey(apiKey)
                .modelName("4.0Ultra")
                .build();
    }

    private ChatLanguageModel buildBaiChuanChatModel(String apiKey) {
        return dev.langchain4j.model.openai.OpenAiChatModel.builder()
                .baseUrl("https://api.baichuan-ai.com")
                .apiKey(apiKey)
                .modelName("Baichuan4-Turbo")
                .build();
    }

    private ChatLanguageModel buildOpenAiChatModel(String apiKey, String url) {
        return dev.langchain4j.model.openai.OpenAiChatModel.builder()
                .baseUrl(url)
                .apiKey(apiKey)
                .build();
    }

    private ChatLanguageModel buildGeminiChatModel(String apiKey) {
        return dev.langchain4j.model.openai.OpenAiChatModel.builder()
                .baseUrl("https://generativelanguage.googleapis.com/v1beta/openai/")
                .apiKey(apiKey)
                .modelName("gemini-2.5-flash")
                .build();
    }

    private EmbeddingModel buildTongYiEmbeddingModel(String apiKey, String model) {
        // 通义千问嵌入模型兼容 OpenAI API 格式
        return dev.langchain4j.model.openai.OpenAiEmbeddingModel.builder()
                .baseUrl("https://dashscope.aliyuncs.com/compatible-mode/v1")
                .apiKey(apiKey)
                .modelName(model != null ? model : "text-embedding-v2")
                .build();
    }
}