import os
from httpx import AsyncClient

from mcp_server.src.schemas import RegistryServer, Tool
from mcp_server.src.settings import settings


class RegistryClient:
    def __init__(self):
        self.client = AsyncClient(base_url=settings.registry_url)
        self.timeout = 90
        # Auto-enable mock mode if MOCK_MODE is set or registry URL is localhost
        self.mock_mode = os.getenv("MOCK_MODE", "false").lower() == "true" or "localhost" in settings.registry_url

    async def search(self, request: str) -> list[RegistryServer]:
        if self.mock_mode:
            # Return mock data for local testing
            return [
                RegistryServer(
                    name="mock_server",
                    description="Mock MCP server for testing",
                    url="http://localhost:8000/sse",
                    logo=None,
                    id=1,
                    tools=[
                        Tool(
                            name="mock_tool",
                            description="A mock tool for testing",
                            input_schema={
                                "type": "object",
                                "properties": {
                                    "query": {"type": "string"}
                                }
                            }
                        )
                    ]
                )
            ]

        response = await self.client.get(
            "/servers/search", params=dict(query=request), timeout=self.timeout
        )
        assert (
            response.status_code == 200
        ), f"{response.status_code=} {response.content=}"
        data = response.json()
        return [RegistryServer.model_validate(server) for server in data]