"""
Re-measure the Poly spread on NEAR-TERM match-winner markets only (game date within
the next ~16 days), excluding far-future outright/futures markets that polluted the
first sample. Late June 2026 -> this is dominated by World Cup 2026 match markets,
which are real, liquid, near-KO games -- the right comparable for our pre-KO bets.
Lists the events it used so the market is transparent. Read-only.
"""
import sys, re
from datetime import date, datetime, timedelta
sys.path.insert(0, r"E:\soccer\main")
import polymarket_live as P

HORIZON_DAYS = 16

def main():
    today = date.today()
    evs = P.fetch_soccer_events()
    rows = []         # (mid,bid,ask,title,gdate)
    used_events = {}
    for e in evs:
        title = e.get('title', '')
        if ' vs' not in title.lower() or 'more market' in title.lower():
            continue
        gd = P._event_date(e)
        if not gd:
            continue
        try:
            d = datetime.strptime(gd, '%Y-%m-%d').date()
        except ValueError:
            continue
        if not (today - timedelta(days=1) <= d <= today + timedelta(days=HORIZON_DAYS)):
            continue
        for m in (e.get('markets') or []):
            q = (m.get('question') or '').lower()
            if 'end in a draw' not in q and not re.search(r'will (.+?) (?:beat|win on)', q):
                continue
            bid, ask, mid = P._yes_prices(m)
            if ask and 0 < ask < 1:
                rows.append((mid, bid, ask, title, gd))
                used_events[title] = gd
    print(f"near-term (<= {HORIZON_DAYS}d) Poly match-winner YES markets: {len(rows)} "
          f"across {len(used_events)} fixtures\n")
    if not rows:
        print("No near-term markets found.")
        return
    print("sample fixtures used:")
    for t, gd in sorted(used_events.items(), key=lambda kv: kv[1])[:15]:
        print(f"  {gd}  {t}")
    if len(used_events) > 15:
        print(f"  ... +{len(used_events)-15} more")

    buckets = [(0.0,0.05),(0.05,0.10),(0.10,0.15),(0.15,0.25),(0.25,0.35),
               (0.35,0.50),(0.50,0.70),(0.70,1.01)]
    def med(xs):
        xs = sorted(xs); k = len(xs)
        return (xs[k//2] if k%2 else (xs[k//2-1]+xs[k//2])/2) if k else float('nan')
    print(f"\n{'mid bucket':14s} {'n':>4} {'noBid%':>7} {'medHalf':>8} {'medHalf%ofMid':>14}")
    for lo, hi in buckets:
        sel = [r for r in rows if lo <= r[0] < hi]
        n = len(sel)
        if not n:
            print(f"  [{lo:.2f},{hi:.2f})   {0:4d}"); continue
        nobid = sum(1 for _,bid,_,_,_ in sel if not bid or bid <= 0)
        real = [(mid,bid,ask) for mid,bid,ask,_,_ in sel if bid and bid > 0]
        halves  = [ask-(ask+bid)/2 for _,bid,ask in real]
        halfpct = [(ask-(ask+bid)/2)/((ask+bid)/2)*100 for _,bid,ask in real if (ask+bid)>0]
        mh = med(halves) if halves else float('nan')
        mhp = med(halfpct) if halfpct else float('nan')
        print(f"  [{lo:.2f},{hi:.2f})   {n:4d}  {100*nobid/n:6.1f}%  {mh:8.3f}  {mhp:13.1f}%")
    ls = [(mid,bid,ask) for mid,bid,ask,_,_ in rows if 0.05 <= mid < 0.35 and bid and bid > 0]
    if ls:
        halves = sorted(ask-(ask+bid)/2 for _,bid,ask in ls)
        k = len(halves); m = halves[k//2] if k%2 else (halves[k//2-1]+halves[k//2])/2
        print(f"\nLONGSHOT mid[0.05,0.35) with a live bid: n={k}  "
              f"median half-spread={m:.3f}  mean={sum(halves)/k:.3f}")

if __name__ == '__main__':
    main()
