"""Matched markets to a spreadsheet: every market that's the same bet on Kalshi and Polymarket US, as a CSV.

Open the file in Excel, Numbers or Google Sheets. Add --prices to also read each market's YES price
from both venues (slower: two order books per row). It only reads data: it never places an order.

    pip install uselayer
    export LAYER_API_KEY=lyr_...                # from uselayer.sh/dashboard/keys
    python matched_markets_csv.py               # writes matched_markets.csv
    python matched_markets_csv.py --prices      # same, with YES prices
"""

import csv
import sys

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

MAX_ROWS = 1000  # stop after this many matches
PAGE = 200  # Layer returns at most 200 matches per request
OUT = "matched_markets.csv"

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
with_prices = "--prices" in sys.argv


def all_matches():
    """Page through Layer's matches, soonest event first."""
    offset = 0
    while offset < MAX_ROWS:
        page = client.matches(limit=PAGE, offset=offset)
        yield from page
        if len(page) < PAGE:
            return
        offset += PAGE


def row(m):
    k, u = m.kalshi, m.polymarket_us
    r = {
        "event_date": m.event_date, "category": m.category,
        "kalshi_event": k.event, "kalshi_outcome": k.outcome, "kalshi_market_id": k.market_id, "kalshi_url": k.url,
        "polymarket_us_event": u.event, "polymarket_us_outcome": u.outcome,
        "polymarket_us_market_id": u.market_id, "polymarket_us_url": u.url,
        "confidence": m.confidence,
        "rule_differences": " | ".join(m.caveat_notes.values()),  # where the venues' rules differ
    }
    if with_prices:
        try:
            r["kalshi_yes_price"], r["polymarket_us_yes_price"] = yes_prices(m)
        except Exception:  # a venue that doesn't answer leaves the price blank
            r["kalshi_yes_price"] = r["polymarket_us_yes_price"] = None
    return r


if __name__ == "__main__":
    rows = [row(m) for m in all_matches()]
    if not rows:
        sys.exit("No matches came back. Check LAYER_API_KEY.")
    with open(OUT, "w", newline="") as f:
        writer = csv.DictWriter(f, fieldnames=list(rows[0]))
        writer.writeheader()
        writer.writerows(rows)
    print(f"Wrote {len(rows)} matched markets to {OUT}")
    for r in rows[:5]:
        print(f"  {r['event_date']}  {r['kalshi_event']} · {r['kalshi_outcome']}")
