"""Ask about markets: a tool your AI agent can call to find a market on Kalshi and Polymarket US.

It searches Layer's matched markets ("fed", "chiefs", "bitcoin"), then reads both venues' YES prices
on your machine. It only reads data: it never places an order.

    pip install uselayer
    export LAYER_API_KEY=lyr_...          # from uselayer.sh/dashboard/keys
    python ask_markets.py chiefs          # run the tool once and print what an agent would get
    python ask_markets.py --mcp           # serve it over MCP (needs: pip install mcp), e.g.
    claude mcp add layer -- python /full/path/to/ask_markets.py --mcp
"""

import json
import sys

from uselayer import Client
from uselayer.http import Http
from uselayer.venues.kalshi import KalshiMarkets
from uselayer.venues.polymarket_us import PolymarketUSPublic

# The tool definition, in the shape the Claude API takes. For OpenAI, rename input_schema to parameters.
TOOL = {
    "name": "find_markets",
    "description": "Find prediction markets that are the same bet on Kalshi and Polymarket US. "
    "Returns each venue's market, link and current YES price, plus any rule differences.",
    "input_schema": {
        "type": "object",
        "properties": {
            "query": {"type": "string", "description": "A few words, e.g. 'fed rates' or 'chiefs'"},
            "limit": {"type": "integer", "description": "How many matches to return, 1 to 10", "default": 5},
        },
        "required": ["query"],
    },
}

client = Client()  # reads LAYER_API_KEY; paper mode, so nothing is ever traded
kalshi, polymarket_us = KalshiMarkets(Http()), PolymarketUSPublic(Http())  # public order books, no venue keys


def yes_prices(m):
    """What one YES share costs right now on each venue, read from the venues on your machine."""
    k = kalshi.read_book(m.kalshi.market_id).book.outcome("yes").best_ask
    u = polymarket_us.book(m.polymarket_us.market_id).outcome("yes").best_ask
    return (k.price if k else None), (u.price if u else None)  # None: nobody is selling YES there


def find_markets(query: str, limit: int = 5) -> list[dict]:
    """Find prediction markets that are the same bet on Kalshi and Polymarket US, with YES prices."""
    results = []
    for m in client.matches(q=query, limit=max(1, min(limit, 10))):
        try:
            k, u = yes_prices(m)
            yes = {"kalshi": k, "polymarket_us": u}
        except Exception:  # a venue that doesn't answer leaves its price out
            yes = {"kalshi": None, "polymarket_us": None}
        results.append({
            "event": m.kalshi.event,
            "outcome": m.kalshi.outcome,
            "event_date": m.event_date,
            "kalshi": {"market_id": m.kalshi.market_id, "url": m.kalshi.url, "yes_price": yes["kalshi"]},
            "polymarket_us": {"market_id": m.polymarket_us.market_id, "url": m.polymarket_us.url,
                              "yes_price": yes["polymarket_us"]},
            "rule_differences": m.caveat_notes,  # where the two venues' rules don't say the same thing
        })
    return results


if __name__ == "__main__":
    if "--mcp" in sys.argv:
        from mcp.server.fastmcp import FastMCP

        server = FastMCP("layer")
        server.tool()(find_markets)
        server.run()  # talks to the agent over stdin/stdout
    else:
        query = " ".join(a for a in sys.argv[1:]) or "fed"
        print("Tool definition:\n" + json.dumps(TOOL, indent=2))
        print(f"\nfind_markets({query!r}) returned:\n" + json.dumps(find_markets(query), indent=2))
