"""Re-run the fill-prediction analysis and EMAIL the result.

WHY THIS EXISTS RATHER THAN A BARE SCHEDULED TASK. The findings on 2026-08-22
came from 193 books over ~5 days, and live selection in mm_maker_live was
changed TWICE that day on the strength of them -- first to rank on min-leg
volume, then corrected to whole-book volume when the ML said min-leg was null
(rho +0.095, p=0.189). A rule changed off a 5-day sample needs re-checking on a
bigger one, and a scheduled job whose output goes to a log nobody opens is not
a re-check.

The comparison that matters is against the 2026-08-22 baseline:

    LEG FILL       logistic  AUC 0.673  [0.630, 0.715]   n=1467, 174 fills
      top: log_volume_24h +0.054, above_touch_c +0.034, is_favourite +0.029
    BOOK COMPLETE  GBMd1     AUC 0.756  [0.675, 0.832]   n=193, 45 complete
      top: log_book_volume +0.091, gross_c +0.045, hrs_to_ko +0.026
      min_leg_volume -0.001  (the metric that did NOT replicate)
    Both: depth3 < depth1, i.e. more capacity hurts -- signal is simple.

If book volume stops leading, the ranking in mm_maker_live.books_in_window is
resting on nothing and should go back to kickoff order.

Usage:  python research\\mm_fill_ml_rerun.py [--no-email]
"""
import io
import sys
import contextlib
import datetime as dt
import subprocess
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' / 'mm_fill_ml_rerun.log'

BASELINE = """2026-08-22 baseline (193 books / 5 days):
  LEG FILL       logistic AUC 0.673 [0.630, 0.715]   n=1467, 174 fills
  BOOK COMPLETE  GBMd1    AUC 0.756 [0.675, 0.832]   n=193,  45 complete
  book volume was the top completion feature (+0.091);
  min-leg volume was null (-0.001, rho +0.095, p=0.189)."""


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'=== fill-prediction re-run  {stamp} ===', '']
    out.append('--- rebuilding dataset ---')
    out.append(run([str(ROOT / 'research' / 'mm_fill_dataset.py')]))
    out.append('--- model ---')
    out.append(run([str(ROOT / 'research' / 'mm_fill_ml.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] fill-prediction re-run {stamp}', body)
    except Exception as e:
        print(f'email failed: {type(e).__name__}: {e}')
    return 0


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