"""Read one bounded page of public Kalshi markets. No credentials or orders."""
import json
from datetime import datetime, timezone
from decimal import Decimal, InvalidOperation
from urllib.parse import urlencode
from urllib.request import Request, urlopen

BASE = "https://external-api.kalshi.com/trade-api/v2"
params = {"series_ticker": "KXHIGHNY", "status": "open", "limit": 5}
url = BASE + "/markets?" + urlencode(params)
request = Request(url, headers={"User-Agent": "NickAI-market-monitor-example/1.0"})
with urlopen(request, timeout=20) as response:
    data = json.load(response)
observed_at = datetime.now(timezone.utc).isoformat()

def price(value):
    if value is None or value == "":
        return None
    try:
        result = Decimal(str(value))
        return result if result.is_finite() and 0 <= result <= 1 else None
    except InvalidOperation:
        return None

rows = []
for market in data.get("markets", []):
    bid = price(market.get("yes_bid_dollars"))
    ask = price(market.get("yes_ask_dollars"))
    # Zero is preserved as data; it is not evidence of executable depth.
    spread = ask - bid if bid is not None and ask is not None and ask >= bid else None
    rows.append({
        "ticker": market["ticker"], "title": market.get("title"),
        "yes_bid_dollars": str(bid) if bid is not None else None,
        "yes_ask_dollars": str(ask) if ask is not None else None,
        "spread_dollars": str(spread) if spread is not None else None,
        "rules_primary": market.get("rules_primary"),
    })
print(json.dumps({"observed_at": observed_at, "source": url,
                  "markets": rows, "next_cursor": data.get("cursor")}, indent=2))
