"""Poly-US version of touch_premium_curve.py -- what premium maximises E[book]?

Same question, different venue, and Poly-US differs in one way that matters:
it CREDITS the maker (MAKER_THETA = 0.0125 x p(1-p)) where Kalshi pays nothing.
That rebate is added per leg, so the comparison is on what each venue actually
pays rather than on gross spread alone.

WEAKER EVIDENCE THAN THE KALSHI CURVE, and the difference should be stated
rather than buried. Kalshi exposes a trade tape, so its curve is built from
actual prints. Poly-US does not; `last_px` is a LEVEL sampled every 20s, so a
print is inferred from a CHANGE in that level. That is conservative -- it misses
consecutive trades at the same price -- so Poly-US fill rates here are a FLOOR
where the Kalshi ones are a ceiling. The two are not directly comparable at the
level; compare the SHAPE.

Usage:  python research\\pus_premium_curve.py
"""
import csv
import shutil
import tempfile
from collections import defaultdict
from pathlib import Path

QUOTES = Path(r'E:\soccer\research\mm_polyus_quotes.csv')
MAKER_THETA = 0.0125          # mm_quoter_polyus.MAKER_THETA
PREMIUMS = [0, 1, 2, 3, 4, 5]


def _f(x):
    try:
        return float(x)
    except (TypeError, ValueError):
        return None


def maker_rebate_c(p):
    return MAKER_THETA * p * (1 - p) * 100.0


def main():
    tmp = Path(tempfile.gettempdir()) / 'mm_polyus_quotes.snap.csv'
    shutil.copyfile(QUOTES, tmp)
    legs = defaultdict(list)
    with tmp.open(newline='', encoding='utf-8', errors='replace') as fh:
        for r in csv.DictReader(fh):
            if r.get('market_slug') and not (r.get('reason') or ''):
                legs[r['market_slug']].append(r)
    for v in legs.values():
        v.sort(key=lambda r: r.get('ts') or '')

    info = {}
    for slug, rows in legs.items():
        r0 = rows[0]
        touch, over = _f(r0.get('p_ask')), _f(r0.get('over_ask'))
        if touch is None or over is None or not (0 < touch < 1):
            continue
        prev, mx = None, None
        for r in rows:
            lp = _f(r.get('last_px'))
            if lp is None:
                continue
            if prev is not None and lp != prev:
                mx = lp if mx is None else max(mx, lp)
            prev = lp
        info[slug] = {'event': r0.get('event_slug'), 'touch': touch,
                      'over_c': (over - 1.0) * 100.0,
                      'headroom': None if mx is None else (mx - touch) * 100.0}

    books = defaultdict(list)
    for v in info.values():
        books[v['event']].append(v)
    full = {e: v for e, v in books.items() if len(v) == 3}
    print(f'{len(info)} legs, {len(full)} three-leg books\n')
    if not full:
        return

    print(f'{"premium":>8} {"leg fill":>9} {"books complete":>16} '
          f'{"gross":>8} {"rebate":>8} {"E[book]":>9}')
    for d in PREMIUMS:
        lf = sum(1 for v in info.values()
                 if v['headroom'] is not None and v['headroom'] >= d)
        comp, gross, reb = 0, 0.0, 0.0
        for v3 in full.values():
            if all(x['headroom'] is not None and x['headroom'] >= d for x in v3):
                comp += 1
                gross += v3[0]['over_c'] + 3 * d
                reb += sum(maker_rebate_c(x['touch'] + d / 100.0) for x in v3)
        n = len(full)
        print(f'{d:>7}c {100.0*lf/len(info):>8.0f}% {comp:>7} / {n:<5} '
              f'{100.0*comp/n:>3.0f}% {gross:>7.0f}c {reb:>7.1f}c '
              f'{(gross+reb)/n:>8.2f}c')
    print('\nE[book] is per book QUOTED and INCLUDES the maker rebate, which is')
    print('credited win or lose. Fills inferred from last_px changes -- a FLOOR.')


if __name__ == '__main__':
    main()
