"""
MCP tool definitions.

Each function is decorated with @mcp.tool and becomes a callable tool
for any AI agent connected via the Model Context Protocol.
"""

from fastmcp import FastMCP

from polymarket_client import (
    get_market_by_id,
    get_markets,
    get_orderbook,
    search_markets_api,
)
from analysis import (
    filter_closing_soon,
    format_market,
    format_market_summary,
    format_orderbook,
    rank_by_newest,
    rank_by_volume,
)


def register_tools(mcp: FastMCP) -> None:
    """Attach all Polymarket tools to the given FastMCP server."""

    # ── Market Discovery ─────────────────────────────────────────

    @mcp.tool
    async def search_markets(query: str, limit: int = 20) -> list[dict]:
        """Search Polymarket markets by keyword.

        Returns markets matching the query, sorted by relevance.
        Use this to find markets about any topic (e.g. "Bitcoin",
        "election", "AI").
        """
        raw = await search_markets_api(query, limit=limit)
        return [format_market(m) for m in raw]

    @mcp.tool
    async def trending_markets(limit: int = 10) -> list[dict]:
        """Get the hottest markets right now, ranked by 24-hour volume.

        Great for a quick overview of what the prediction-market
        crowd is trading today.
        """
        raw = await get_markets(limit=max(limit, 50), order="volume24hr")
        ranked = rank_by_volume(raw, limit=limit)
        return [format_market(m) for m in ranked]

    @mcp.tool
    async def new_markets(limit: int = 10) -> list[dict]:
        """Return the newest markets on Polymarket.

        Useful for discovering freshly launched prediction markets
        before they gain traction.
        """
        raw = await get_markets(limit=max(limit, 50), order="createdAt")
        ranked = rank_by_newest(raw, limit=limit)
        return [format_market(m) for m in ranked]

    @mcp.tool
    async def markets_closing_soon(hours: int = 24) -> list[dict]:
        """Find markets that resolve within the next *hours* hours.

        Handy for spotting last-minute trading opportunities or
        tracking imminent outcomes.
        """
        raw = await get_markets(limit=100, order="endDate", ascending=True)
        closing = filter_closing_soon(raw, hours=hours)
        return [format_market(m) for m in closing]

    # ── Market Analysis ──────────────────────────────────────────

    @mcp.tool
    async def market_summary(market_id: str) -> dict:
        """Get a detailed summary of a single market.

        Returns probability, volume, liquidity, category, end date,
        description, and more.
        """
        raw = await get_market_by_id(market_id)
        return format_market_summary(raw)

    @mcp.tool
    async def market_orderbook(token_id: str) -> dict:
        """Fetch the live orderbook for a market token.

        Shows current bids, asks, spread, and depth.
        You need a token_id (found in market data) to call this.
        """
        raw = await get_orderbook(token_id)
        return format_orderbook(raw)
