"""What if we had NEVER crossed early -- what would the paper maker have made?

FINDING THAT PROMPTED THIS (2026-07-28): complete_book() fires the instant a book
reaches 2-of-3 filled. In practice that was 8.6-10.1 HOURS before kickoff. We paid
~2c to cross while the third leg still had most of a twelve-hour window to sell at
our resting ask for free. The claim "9 of 9 books needed the completion rule" was
therefore never tested -- it was manufactured by our own trigger firing instantly.

THE COUNTERFACTUAL. For each leg we completed at the bid, ask the tape: did any
trade print at or above our ORIGINAL ask between the moment we crossed and
kickoff? If yes, a resting order would have been there to meet it, the leg fills
free, and the book earns its full gross with no fee. If no, we would still have
had to cross near kickoff, so we keep the cost we actually paid.

  net(delayed) = gross                      if the third leg would have sold
  net(delayed) = net(actual)                otherwise

KNOWN OPTIMISM, not buried: "a trade printed at our price" is not the same as
"we were filled". We join the queue behind existing size, so some of these would
not have been ours. This is the same ceiling assumption that made the earlier
historical replay predict 97.5% natural fills against a live 0-of-7 -- so treat
the output as an UPPER BOUND on the delayed rule, not an estimate. The live A/B
(cap arm filling 9/9) suggests our asks do get hit at the touch, which is why the
bound is worth computing at all.
"""
import csv
import datetime as dt
import re
import sys
from collections import defaultdict

sys.path.insert(0, r'E:\soccer\main')
import mm_settle as S

QUOTES = r'E:\soccer\research\mm_paper_quotes.csv'
SIZE = 10


def main():
    rows = list(csv.DictReader(open(QUOTES, encoding='utf-8')))
    comp = [r for r in rows if (r.get('reason') or '').startswith('COMPLETE_AT_BID')]
    print(f'{len(comp)} completion events in the quote log\n')

    # original ask per (event, side): last normal quote before the completion row
    hist = defaultdict(list)
    for r in rows:
        if (r.get('reason') or '').startswith('COMPLETE_AT_BID'):
            continue
        if r.get('our_ask'):
            hist[(r['event'], r['side'])].append((r['ts'], float(r['our_ask'])))

    books = {}
    for r in comp:
        ev, side = r['event'], r['side']
        prior = [a for t, a in hist.get((ev, side), []) if t < r['ts']]
        if not prior:
            continue
        books[ev] = {'side': side, 'ticker': r['leg_ticker'], 'bid': float(r['our_ask']),
                     'orig_ask': prior[-1], 'ts': S._pt(r['ts']), 'ko': S._pt(r['kickoff']),
                     'home': r['home'], 'away': r['away'], 'div': r['div'],
                     'net_actual': float(re.search(r'=> ([-+0-9.]+)c', r['reason']).group(1))}

    # gross per book = sum of the three original asks - 100
    for ev, b in books.items():
        legs = {}
        for side in ('home', 'draw', 'away'):
            h = [a for t, a in hist.get((ev, side), []) if t <= b['ts'].isoformat()]
            if h:
                legs[side] = h[-1]
        b['gross'] = (sum(legs.values()) * 100 - 100) if len(legs) == 3 else None

    print(f"  {'book':22s} {'leg':5s} {'our ask':>8s} {'trades>=ask':>12s} "
          f"{'actual':>8s} {'delayed':>8s}")
    tot_a = tot_d = 0.0
    nat = 0
    for ev, b in sorted(books.items(), key=lambda kv: kv[1]['ts']):
        if b['gross'] is None:
            continue
        tr = S.trades_tuples(b['ticker'], b['ts'])
        after = [x for x in tr if b['ts'] < x[0] < b['ko'] and x[1] >= b['orig_ask'] - 1e-9]
        would = len(after) > 0
        nat += would
        d = b['gross'] if would else b['net_actual']
        tot_a += b['net_actual'] * SIZE / 100
        tot_d += d * SIZE / 100
        print(f"  {b['home'][:22]:22s} {b['side']:5s} {b['orig_ask']*100:7.0f}c "
              f"{len(after):12d} {b['net_actual']:+7.2f}c {d:+7.2f}c")

    print(f'\n  third leg would have sold naturally: {nat}/{len(books)} books')
    print(f'  ACTUAL   (cross immediately) : ${tot_a:+.2f}')
    print(f'  DELAYED  (wait, cross late)  : ${tot_d:+.2f}   <- UPPER BOUND')
    print(f'  difference                   : ${tot_d-tot_a:+.2f}')


if __name__ == '__main__':
    main()
