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

Run: uvx --from "widesutra[mcp]" python -m widesutra.mcp_server
"""

from __future__ import annotations

from mcp.server.fastmcp import FastMCP

mcp = FastMCP("WideSutra")


@mcp.tool()
def list_collections(tradition: str | None = None) -> str:
    """List Buddhist scripture collections from widesutra.com.

    Args:
        tradition: Filter by tradition (e.g. 'theravada', 'mahayana'). Optional.
    """
    from widesutra.client import WideSutra

    with WideSutra() as client:
        data = client.list_collections(tradition=tradition)
        results = data.get("results", data) if isinstance(data, dict) else data
        if not results:
            return "No collections found."
        items = results if isinstance(results, list) else []
        return "\n".join(
            f"- {item.get('name', item.get('slug', '?'))}: {item.get('description', '')[:80]}"
            for item in items
        )


@mcp.tool()
def get_collection(slug: str) -> str:
    """Get detailed information about a scripture collection.

    Args:
        slug: URL slug identifier for the collection (e.g. 'tipitaka').
    """
    from widesutra.client import WideSutra

    with WideSutra() as client:
        data = client.get_collection(slug)
        return str(data)


@mcp.tool()
def list_figures(tradition: str | None = None) -> str:
    """List Buddhist figures (Buddhas, bodhisattvas, monks) from widesutra.com.

    Args:
        tradition: Filter by tradition (e.g. 'theravada', 'mahayana'). Optional.
    """
    from widesutra.client import WideSutra

    with WideSutra() as client:
        data = client.list_figures(tradition=tradition)
        results = data.get("results", data) if isinstance(data, dict) else data
        if not results:
            return "No figures found."
        items = results if isinstance(results, list) else []
        return "\n".join(
            f"- {item.get('name', item.get('slug', '?'))}"
            + (f" ({item['tradition']})" if item.get("tradition") else "")
            for item in items
        )


@mcp.tool()
def get_figure(slug: str) -> str:
    """Get detailed information about a Buddhist figure.

    Args:
        slug: URL slug identifier for the figure (e.g. 'siddhartha-gautama').
    """
    from widesutra.client import WideSutra

    with WideSutra() as client:
        data = client.get_figure(slug)
        return str(data)


@mcp.tool()
def list_concepts(category: str | None = None) -> str:
    """List Buddhist concepts (Four Noble Truths, Noble Eightfold Path, etc.).

    Args:
        category: Filter by concept category. Optional.
    """
    from widesutra.client import WideSutra

    with WideSutra() as client:
        data = client.list_concepts(category=category)
        results = data.get("results", data) if isinstance(data, dict) else data
        if not results:
            return "No concepts found."
        items = results if isinstance(results, list) else []
        return "\n".join(
            f"- {item.get('name', item.get('slug', '?'))}"
            + (f" (Pali: {item['pali_term']})" if item.get("pali_term") else "")
            for item in items
        )


@mcp.tool()
def search_sutra(query: str) -> str:
    """Search Buddhist scriptures on widesutra.com.

    Args:
        query: Search query string (e.g. 'four noble truths', 'nirvana').
    """
    from widesutra.client import WideSutra

    with WideSutra() as 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}".'
        items = results[:10] if isinstance(results, list) else []
        return "\n".join(
            f"- {item.get('reference', item.get('book_name', '?'))}: {item.get('text', '')[:100]}"
            for item in items
        )


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


if __name__ == "__main__":
    main()
