from enum import Enum
from typing import Any

from mcp.server.fastmcp import FastMCP
from openmcp.search_backend import SearchBackend


class ProviderType(Enum):
    SEARCH = "search"


PROVIDER_REGISTRY = {
    ProviderType.SEARCH: SearchBackend,
}


class Config:
    def __init__(self, max_results=5, provider_type=ProviderType.SEARCH, model=None):
        self.max_results = max_results
        self.provider_type = provider_type
        self.model = model


class OpenMCP:

    def __init__(self, server, *, config=Config(), **fastmcp_kwargs):
        if isinstance(server, FastMCP):
            self._server = server
        else:
            self._server = FastMCP(server, **fastmcp_kwargs)
        self._config = config

        provider_cls = PROVIDER_REGISTRY[config.provider_type]
        self._provider = provider_cls()
        self._provider.initialize(config)

    def run(self, *args, **kwargs):
        tools = self._server._tool_manager.list_tools()

        self._provider.index_tools(tools)

        self._server._tool_manager._tools.clear()

        for tool_fn in self._provider.serve_tools():
            self._server.tool()(tool_fn)

        return self._server.run(*args, **kwargs)

    def __getattr__(self, name):
        return getattr(self._server, name)
