"""Re-run the Poly-US maker P&L settlement and EMAIL the result.

WHY THIS EXISTS RATHER THAN A BARE SCHEDULED TASK. The 2026-08-24 read said
Poly-US market making is NOT worth it -- but on 13 settled books, which is
nowhere near enough to act on. A job whose output lands in a log nobody opens
is not a re-check, so this mails it.

TWO THINGS CHANGED THE DAY THE BASELINE WAS TAKEN, and both push the number
being measured:

  * WINDOW_H went 6h -> 72h (user, 2026-08-24). Completion is the whole
    equation, and fill rate is 25.3% at 0-0.5h against 6.8% at 24h+, so a wider
    window plausibly makes completion WORSE while making coverage better. If
    completion has fallen, the widening is the first suspect.
  * The probe budget stopped being spent on in-play books it could never open,
    which should raise the number of books quoted per cycle.

WHAT WOULD CHANGE THE VERDICT. Break-even was 74.2% completion against 53.8%
actual. Poly-US pays far more per complete book than Kalshi (+9.09c vs +1.78c)
but loses far more per partial (-26.12c vs -2.82c), because a partial here is a
naked short at a price chosen for being attractive. So the question is only ever
"did completion move", and the honest answer at n=13 was "unknown, leaning no".

Usage:  python research\\pus_maker_pnl_rerun.py [--no-email]
"""
import datetime as dt
import subprocess
import sys
from pathlib import Path

sys.path.insert(0, r'E:\soccer\main')
sys.path.insert(0, r'E:\soccer\research')

PY = sys.executable
ROOT = Path(r'E:\soccer')
LOG = ROOT / 'logs' / 'pus_maker_pnl_rerun.log'

BASELINE = """2026-08-28 baseline -- SUPERSEDES the 08-24 read, which was WRONG.

The 08-24 numbers (13 books, 53.8% completion, "not worth it") came from
pus_live_state.json, which detect_fills stops writing whenever the venue 503s --
and it 503s for hours. It undercounted books badly. This now reads the VENUE's
own settlement record (ACTIVITY_TYPE_POSITION_RESOLUTION) and uses
afterPosition.realized, the venue's own P&L, filtered to books the maker
actually quoted.

  venue settled books    62  ->  28 the maker quoted (rest are manual/futures)
  COMPLETE books   n=19   mean +10.94c/book
  PARTIAL  books   n= 9   mean -20.78c/book
  ALL      books   n=28   mean  +0.75c/book   (realised +$0.21)
  completion 67.9%  vs  BREAK-EVEN 65.5%   -> marginally ABOVE, not below

WHAT IS NOT THE PROBLEM (measured 2026-08-24, still stands):
  Every leg was offered AT the touch; fill rate there 21.6%, better than
  Kalshi's 11.9%. Spread sits at the 1c tick floor. Quoting level costs nothing.

THE GATE HYPOTHESIS IS DEAD, on both venues. It came from the same lossy data:
  thin books re-price more, re-priced legs missed the join, so they LOOKED like
  they failed to complete. On corrected Kalshi data completion by opening gross
  is flat (82.7% / 81.0% / 80.0%). Do not raise the gate on this evidence.

WHAT TO CHECK ON THE RERUN: completion against 65.5%, and whether the 72h
window (set 08-24) moved it. Margin is ~2pp on n=28 -- that is noise, so the
question is still open, not settled."""


def run(cmd):
    p = subprocess.run([PY] + cmd, capture_output=True, text=True,
                       encoding='utf-8', errors='replace',
                       cwd=str(ROOT), timeout=1800)
    return (p.stdout or '') + (p.stderr or '')


def main():
    stamp = dt.datetime.now().strftime('%Y-%m-%d %H:%M')
    out = [f'=== Poly-US maker P&L re-run  {stamp} ===', '']
    out.append(run([str(ROOT / 'research' / 'pus_maker_pnl.py')]))
    out.append('')
    out.append('=' * 66)
    out.append(BASELINE)
    text = '\n'.join(out)

    try:
        LOG.parent.mkdir(parents=True, exist_ok=True)
        with LOG.open('a', encoding='utf-8') as fh:
            fh.write(text + '\n')
    except OSError:
        pass
    print(text)

    if '--no-email' in sys.argv:
        return 0
    try:
        from daily_signals import send_email
        body = ('<pre style="font:12px ui-monospace,Consolas,monospace">'
                + text.replace('&', '&amp;').replace('<', '&lt;')
                + '</pre>')
        send_email(f'[MM] Poly-US maker P&L re-run {stamp}', body)
    except Exception as e:
        print(f'email failed: {type(e).__name__}: {e}')
    return 0


if __name__ == '__main__':
    sys.exit(main())
