"""
Counterfactual equity: compounded 1/4-Kelly Kalshi paper path, full history vs.
excluding USL+BSA. Replays each resolved paper bet chronologically using the
historical Kelly fraction (orig_stake/1000) against a running bankroll from
$1000 -- same engine that reproduced the fixed tracker to the cent.
Emails the chart.
"""
import json, io, smtplib, sys
from pathlib import Path
from email.mime.multipart import MIMEMultipart
from email.mime.text import MIMEText
from email.mime.image import MIMEImage
import matplotlib
matplotlib.use('Agg')
import matplotlib.pyplot as plt

sys.stdout.reconfigure(encoding='utf-8', errors='replace')
START, MAX_BET_PCT = 1000.0, 0.25
EXCL = {'USL', 'BSA'}

bets = json.load(open(r'E:\soccer\data\bet_history.json'))
idx = {id(b): i for i, b in enumerate(bets)}
paper = [b for b in bets if b.get('kalshi_stake') and b.get('kalshi_pnl') is not None]
paper.sort(key=lambda b: (b.get('date') or '', idx[id(b)]))

def replay(skip_leagues):
    eq = [START]
    run = START
    for b in paper:
        if b.get('div') in skip_leagues:
            continue
        ask = b['kalshi_ask']
        if not ask or ask <= 0:
            continue
        frac = min(b['kalshi_stake'] / 1000.0, MAX_BET_PCT)
        stake = round(frac * run, 2)
        if stake < 1.0:
            stake = 1.0
        if stake > run:
            stake = round(run, 2)
        bo = (1 - ask) / ask
        run += stake * bo if b.get('won') else -stake
        eq.append(run)
    return eq

full = replay(set())
excl = replay(EXCL)

# counts
n_excl_bets = sum(1 for b in paper if b.get('div') in EXCL)
print(f"all paper bets: {len(paper)}  | USL+BSA removed: {n_excl_bets}")
print(f"FULL    final: ${full[-1]:,.2f}  ({(full[-1]-START)/START*100:+.1f}%)")
print(f"ex-USL/BSA   : ${excl[-1]:,.2f}  ({(excl[-1]-START)/START*100:+.1f}%)")

fig, ax = plt.subplots(figsize=(11, 5.5))
ax.plot(range(len(full)), full, color='#d62728', lw=2,
        label=f'All leagues  (${full[-1]:,.0f}, {(full[-1]-START)/START*100:+.1f}%)')
ax.plot(range(len(excl)), excl, color='#2077b4', lw=2,
        label=f'Excl USL+BSA  (${excl[-1]:,.0f}, {(excl[-1]-START)/START*100:+.1f}%)')
ax.axhline(START, color='gray', ls='--', lw=1, alpha=0.6)
ax.set_xlabel('Bet number'); ax.set_ylabel('Bankroll ($)')
ax.set_title('Kalshi compounded equity — full vs. excluding USL + BSA')
ax.legend(loc='best'); ax.grid(True, alpha=0.3)
fig.tight_layout()
buf = io.BytesIO(); fig.savefig(buf, format='png', dpi=120); plt.close(fig)
png = buf.getvalue()
Path(r'E:\soccer\_equity_excl.png').write_bytes(png)

# email it
def _env(p):
    e = {}
    for ln in open(p):
        ln = ln.strip()
        if ln and not ln.startswith('#') and '=' in ln:
            k, v = ln.split('=', 1); e[k.strip()] = v.strip()
    return e
env = _env(r'E:\soccer\.env')
msg = MIMEMultipart('related')
msg['Subject'] = (f"Equity: full ${full[-1]:,.0f} vs ex-USL/BSA ${excl[-1]:,.0f}")
msg['From'] = env.get('EMAIL_SENDER', ''); msg['To'] = env.get('EMAIL_RECIPIENT', '')
alt = MIMEMultipart('alternative'); msg.attach(alt)
alt.attach(MIMEText(f'<html><body><h3>Kalshi compounded equity</h3>'
                    f'<p>Full: <b>${full[-1]:,.2f}</b> ({(full[-1]-START)/START*100:+.1f}%)<br>'
                    f'Excl USL+BSA ({n_excl_bets} bets removed): <b>${excl[-1]:,.2f}</b> '
                    f'({(excl[-1]-START)/START*100:+.1f}%)</p>'
                    f'<img src="cid:eq" style="max-width:100%"></body></html>', 'html'))
img = MIMEImage(png, _subtype='png'); img.add_header('Content-ID', '<eq>')
img.add_header('Content-Disposition', 'inline', filename='equity.png'); msg.attach(img)
with smtplib.SMTP_SSL('smtp.gmail.com', 465) as s:
    s.login(env['EMAIL_SENDER'], env['EMAIL_APP_PASSWORD'])
    s.sendmail(env['EMAIL_SENDER'], env['EMAIL_RECIPIENT'], msg.as_string())
print("emailed.")
