"""MCP server for mineralfyi — AI assistant tools for mineralfyi.com.

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

from mcp.server.fastmcp import FastMCP

mcp = FastMCP("MineralFYI")


@mcp.tool()
def list_crystal_systems(limit: int = 20, offset: int = 0) -> str:
    """List crystal_systems from mineralfyi.com.

    Args:
        limit: Maximum number of results. Default 20.
        offset: Number of results to skip. Default 0.
    """
    from mineralfyi.api import MineralFYI

    with MineralFYI() as api:
        data = api.list_crystal_systems(limit=limit, offset=offset)
        results = data.get("results", data) if isinstance(data, dict) else data
        if not results:
            return "No crystal_systems found."
        items = results[:limit] if isinstance(results, list) else []
        return "\n".join(f"- {item.get('name', item.get('slug', '?'))}" for item in items)


@mcp.tool()
def get_crystal_system(slug: str) -> str:
    """Get detailed information about a specific crystal_system.

    Args:
        slug: URL slug identifier for the crystal_system.
    """
    from mineralfyi.api import MineralFYI

    with MineralFYI() as api:
        data = api.get_crystal_system(slug)
        return str(data)


@mcp.tool()
def list_classes(limit: int = 20, offset: int = 0) -> str:
    """List classes from mineralfyi.com.

    Args:
        limit: Maximum number of results. Default 20.
        offset: Number of results to skip. Default 0.
    """
    from mineralfyi.api import MineralFYI

    with MineralFYI() as api:
        data = api.list_classes(limit=limit, offset=offset)
        results = data.get("results", data) if isinstance(data, dict) else data
        if not results:
            return "No classes found."
        items = results[:limit] if isinstance(results, list) else []
        return "\n".join(f"- {item.get('name', item.get('slug', '?'))}" for item in items)


@mcp.tool()
def search_mineral(query: str) -> str:
    """Search mineralfyi.com for minerals, crystal systems, and Mohs hardness.

    Args:
        query: Search query string.
    """
    from mineralfyi.api import MineralFYI

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


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


if __name__ == "__main__":
    main()
