package org.dromara.ai.mcp;

import org.springframework.stereotype.Component;

import java.util.HashMap;
import java.util.Map;
import java.util.concurrent.ConcurrentHashMap;
import java.util.function.Supplier;

/**
 * MCP工具注册表
 * 管理所有MCP工具的注册、版本控制和动态加载
 *
 * @author pengles
 */
@Component
public class McpToolRegistry {
    private final Map<String, McpTool> tools = new ConcurrentHashMap<>();
    private final Map<String, String> versions = new ConcurrentHashMap<>();
    private final Map<String, Supplier<McpTool>> factories = new ConcurrentHashMap<>();

    public void register(McpTool tool) {
        tools.put(tool.name(), tool);
        versions.put(tool.name(), "1.0.0");
    }

    public McpTool get(String name) {
        return tools.get(name);
    }

    public Map<String, McpTool> all() {
        return new HashMap<>(tools);
    }

    public void unregister(String name) {
        tools.remove(name);
        versions.remove(name);
        factories.remove(name);
    }

    public void registerFactory(String name, String version, Supplier<McpTool> factory) {
        factories.put(name, factory);
        versions.put(name, version);
        tools.put(name, factory.get());
    }

    public void reload(String name) {
        Supplier<McpTool> f = factories.get(name);
        if (f != null) {
            tools.put(name, f.get());
        }
    }

    public Map<String, Object> metadata(String name) {
        McpTool t = tools.get(name);
        String v = versions.get(name);
        if (t == null) return Map.of();
        return Map.of("name", t.name(), "version", v);
    }
}
