"""One-shot: email the strategy equity path (B365 + Kalshi) as an embedded chart."""
import os, json, io, base64, smtplib, datetime as dt
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
import matplotlib.dates as mdates

# Load .env the same way daily_signals.py does
def _load_env(path='E:/soccer/.env'):
    out = {}
    try:
        with open(path) as f:
            for line in f:
                line = line.strip()
                if not line or line.startswith('#') or '=' not in line:
                    continue
                k, v = line.split('=', 1)
                out[k.strip()] = v.strip().strip('"').strip("'")
    except FileNotFoundError:
        pass
    return out

env = _load_env()
EMAIL_ADDRESS      = env.get('EMAIL_SENDER', '')
EMAIL_RECIPIENT    = env.get('EMAIL_RECIPIENT', '')
EMAIL_APP_PASSWORD = env.get('EMAIL_APP_PASSWORD', '')

# Load bet history
with open('E:/soccer/bet_history.json') as f:
    hist = json.load(f)

# Sort by resolved_at then by original order
hist = sorted(hist, key=lambda x: (x.get('resolved_at') or x['date'], x['date']))

b365_x, b365_y = [], []
kalshi_x, kalshi_y = [], []

# Seed starting bankrolls (both started at $1000 per memory)
START = 1000.0
b365_x.append(0); b365_y.append(START)
kalshi_x.append(0); kalshi_y.append(START)

last_b365 = START
last_kalshi = START
for i, bet in enumerate(hist, start=1):
    if 'bankroll_after' in bet:
        last_b365 = bet['bankroll_after']
    b365_x.append(i); b365_y.append(last_b365)
    if 'kalshi_bankroll_after' in bet:
        last_kalshi = bet['kalshi_bankroll_after']
    kalshi_x.append(i); kalshi_y.append(last_kalshi)

# Stats
b365_pnl = last_b365 - START
kalshi_pnl = last_kalshi - START
b365_roi = b365_pnl / START * 100
kalshi_roi = kalshi_pnl / START * 100
n_bets = len(hist)
n_b365_wins = sum(1 for x in hist if x.get('won') is True)
b365_wr = n_b365_wins / n_bets * 100 if n_bets else 0
# Kalshi wins: same 'won' flag (same outcomes), but only count bets that have kalshi_stake
k_bets = [x for x in hist if 'kalshi_bankroll_after' in x]
k_wins = sum(1 for x in k_bets if x.get('won') is True)
k_wr = k_wins / len(k_bets) * 100 if k_bets else 0

# Build chart
fig, ax = plt.subplots(figsize=(11, 6))
ax.plot(b365_x, b365_y, color='#1f77b4', linewidth=2, label=f'B365  (${last_b365:,.2f}, {b365_roi:+.1f}%)')
ax.plot(kalshi_x, kalshi_y, color='#d62728', linewidth=2, label=f'Kalshi  (${last_kalshi:,.2f}, {kalshi_roi:+.1f}%)')
ax.axhline(START, color='gray', linestyle='--', linewidth=1, alpha=0.6)
ax.set_xlabel('Bet number')
ax.set_ylabel('Bankroll ($)')
ax.set_title(f'Live equity path — {hist[0]["date"]} to {hist[-1]["date"]}  ({n_bets} bets)')
ax.legend(loc='best', frameon=True)
ax.grid(True, alpha=0.3)
fig.tight_layout()

buf = io.BytesIO()
fig.savefig(buf, format='png', dpi=120)
buf.seek(0)
img_bytes = buf.getvalue()
plt.close(fig)

# Build email with embedded image
html = f"""
<html><body style="font-family: -apple-system, Segoe UI, sans-serif;">
<h2>Strategy Equity Path</h2>
<p><b>Window:</b> {hist[0]['date']} &rarr; {hist[-1]['date']}<br>
<b>Bets resolved:</b> {n_bets}</p>

<table cellpadding="6" style="border-collapse: collapse; margin: 12px 0;">
  <tr style="background:#f0f0f0;">
    <th align="left">Book</th><th align="right">Final $</th><th align="right">P&amp;L</th><th align="right">ROI</th><th align="right">Win rate</th>
  </tr>
  <tr>
    <td><b>B365</b></td>
    <td align="right">${last_b365:,.2f}</td>
    <td align="right" style="color:{'green' if b365_pnl>=0 else 'red'};">{b365_pnl:+.2f}</td>
    <td align="right" style="color:{'green' if b365_pnl>=0 else 'red'};">{b365_roi:+.1f}%</td>
    <td align="right">{b365_wr:.1f}% ({n_b365_wins}/{n_bets})</td>
  </tr>
  <tr>
    <td><b>Kalshi</b></td>
    <td align="right">${last_kalshi:,.2f}</td>
    <td align="right" style="color:{'green' if kalshi_pnl>=0 else 'red'};">{kalshi_pnl:+.2f}</td>
    <td align="right" style="color:{'green' if kalshi_pnl>=0 else 'red'};">{kalshi_roi:+.1f}%</td>
    <td align="right">{k_wr:.1f}% ({k_wins}/{len(k_bets)})</td>
  </tr>
</table>

<p><img src="cid:equitychart" alt="equity path" style="max-width:100%;"></p>

<p style="color:#888;font-size:12px;">Both books started at $1,000.
Bets ordered by resolution date. Kalshi line only updates on bets where a Kalshi position was placed.</p>
</body></html>
"""

msg = MIMEMultipart('related')
msg['Subject'] = f"Equity path — {hist[-1]['date']} ({n_bets} bets, B365 {b365_roi:+.1f}% / Kalshi {kalshi_roi:+.1f}%)"
msg['From']    = EMAIL_ADDRESS
msg['To']      = EMAIL_RECIPIENT

alt = MIMEMultipart('alternative')
msg.attach(alt)
alt.attach(MIMEText(html, 'html'))

img = MIMEImage(img_bytes, _subtype='png')
img.add_header('Content-ID', '<equitychart>')
img.add_header('Content-Disposition', 'inline', filename='equity.png')
msg.attach(img)

if not EMAIL_ADDRESS or not EMAIL_APP_PASSWORD:
    print("Email creds missing in .env — aborting.")
    raise SystemExit(1)

with smtplib.SMTP_SSL('smtp.gmail.com', 465) as s:
    s.login(EMAIL_ADDRESS, EMAIL_APP_PASSWORD)
    s.sendmail(EMAIL_ADDRESS, EMAIL_RECIPIENT, msg.as_string())

print(f"Sent equity path email -> {EMAIL_RECIPIENT}")
print(f"B365:   ${last_b365:,.2f} ({b365_roi:+.1f}%)")
print(f"Kalshi: ${last_kalshi:,.2f} ({kalshi_roi:+.1f}%)")
