"""MCP server for drinkfyi — unified beverage knowledge hub for AI assistants.

Run: uvx --from "drinkfyi[mcp]" python -m drinkfyi.mcp_server
"""
from __future__ import annotations

from mcp.server.fastmcp import FastMCP

mcp = FastMCP("DrinkFYI")


@mcp.tool()
def available_beverages() -> str:
    """List all installed beverage clients (cocktail, wine, beer, whiskey, tea, coffee, sake)."""
    from drinkfyi import available_clients

    clients = available_clients()
    if not clients:
        return "No beverage packages installed. Install with: pip install drinkfyi[all]"
    return "Installed beverage clients: " + ", ".join(clients)


@mcp.tool()
def search_beverage(beverage_type: str, query: str) -> str:
    """Search a specific beverage database.

    Args:
        beverage_type: Type of beverage — one of: cocktail, wine, beer, whiskey, tea, coffee, sake.
        query: Search query string.
    """
    from drinkfyi import get_client

    try:
        client = get_client(beverage_type)
    except (ValueError, ImportError) as e:
        return str(e)

    with client:
        data = client.search(query)
        results = data.get("results", data) if isinstance(data, dict) else data
        if not results:
            return f"No results found for \"{query}\" in {beverage_type}."
        items = results[:10] if isinstance(results, list) else []
        return "\n".join(f"- {item.get('name', item.get('slug', '?'))}" for item in items)


@mcp.tool()
def get_beverage_detail(beverage_type: str, slug: str) -> str:
    """Get details for a specific item from a beverage database.

    Args:
        beverage_type: Type of beverage — one of: cocktail, wine, beer, whiskey, tea, coffee, sake.
        slug: URL slug identifier for the item.
    """
    from drinkfyi import get_client

    method_map = {
        "cocktail": "get_cocktail",
        "wine": "get_grape",
        "beer": "get_category",
        "whiskey": "get_expression",
        "tea": "get_category",
        "coffee": "get_brew_method",
        "sake": "get_sake",
    }
    try:
        client = get_client(beverage_type)
    except (ValueError, ImportError) as e:
        return str(e)

    method_name = method_map.get(beverage_type, "get_category")
    with client:
        data = getattr(client, method_name)(slug)
        return str(data)


def main() -> None:
    """Run the MCP server."""
    mcp.run()


if __name__ == "__main__":
    main()
