package com.gzzm.lobster.llm;

import com.gzzm.lobster.common.LobsterException;
import com.gzzm.lobster.llm.adapter.OllamaAdapter;
import com.gzzm.lobster.llm.adapter.OpenAiCompatibleAdapter;

import java.util.concurrent.ConcurrentHashMap;

/**
 * LobsterAdapterFactory —— 按 ModelProfile 创建/缓存 adapter 实例 /
 * Factory that creates and caches adapter instances per model profile.
 */
public class LobsterAdapterFactory {

    private final ConcurrentHashMap<String, LobsterLlmAdapter> cache = new ConcurrentHashMap<>();

    public LobsterLlmAdapter get(ModelProfile profile) {
        if (profile == null) throw new LobsterException("llm.adapter", "null profile");
        LobsterLlmAdapter existing = cache.get(profile.getModelId());
        if (existing != null) return existing;
        LobsterLlmAdapter created = create(profile);
        LobsterLlmAdapter prev = cache.putIfAbsent(profile.getModelId(), created);
        return prev == null ? created : prev;
    }

    public void invalidate(String modelId) {
        cache.remove(modelId);
    }

    private LobsterLlmAdapter create(ModelProfile profile) {
        ModelProvider provider = profile.getProvider();
        if (provider == ModelProvider.ollama_compatible) {
            return new OllamaAdapter(profile);
        }
        // openai_compatible / vllm_compatible / anthropic_compatible / internal 暂共用 OpenAI 兼容适配器
        return new OpenAiCompatibleAdapter(profile);
    }
}
