"""Inspect top-of-book quotes for one Gamma CTF binary market; never trades."""
import json
import time
from datetime import datetime, timezone
from decimal import Decimal
from urllib.parse import urlencode
from urllib.request import Request, urlopen

def get(url):
    with urlopen(Request(url, headers={"User-Agent": "NickAI-pair-scanner-example/1.0"}), timeout=20) as response:
        return json.load(response)

def array(value):
    return json.loads(value) if isinstance(value, str) else value

markets = get("https://gamma-api.polymarket.com/markets?active=true&closed=false&limit=20")
selected = None
for market in markets:
    labels = array(market.get("outcomes") or [])
    tokens = array(market.get("clobTokenIds") or [])
    if market.get("enableOrderBook") and market.get("acceptingOrders") and len(tokens) == 2 and set(labels) == {"Yes", "No"}:
        selected = market, dict(zip(labels, tokens))
        break
if selected is None:
    raise SystemExit("No compatible CTF binary market in this bounded sample.")
market, tokens = selected
started = time.monotonic()
quotes = {}
for outcome in ("Yes", "No"):
    book = get("https://clob.polymarket.com/book?" + urlencode({"token_id": tokens[outcome]}))
    asks = [(Decimal(level["price"]), Decimal(level["size"])) for level in book.get("asks", [])]
    asks = [(p, s) for p, s in asks if p.is_finite() and s.is_finite() and 0 < p < 1 and s > 0]
    if not asks:
        raise SystemExit(f"No executable ask levels for {outcome}; skip.")
    best_price = min(p for p, _ in asks)
    size_at_price = sum(s for p, s in asks if p == best_price)
    quotes[outcome] = (best_price, size_at_price)
quote_sum = quotes["Yes"][0] + quotes["No"][0]
print(json.dumps({
    "observed_at": datetime.now(timezone.utc).isoformat(),
    "condition_id": market["conditionId"], "question": market["question"],
    "quotes": {side: {"ask": str(p), "size_at_ask": str(s)} for side, (p, s) in quotes.items()},
    "gross_gap_before_costs": str(Decimal("1") - quote_sum),
    "top_level_pair_size": str(min(quotes["Yes"][1], quotes["No"][1])),
    "read_elapsed_seconds": round(time.monotonic() - started, 3),
    "net_gap": None, "note": "Fees unknown; sequential snapshots; not an execution signal."
}, indent=2))
