"""
Hedge backtest: keep YES-underdog signal, add a NO-favorite bet alongside
to lay off draw losses. Test multiple hedge ratios and sizing modes.
"""
import json
import math
from pathlib import Path

h = json.loads(Path("E:/soccer/bet_history.json").read_text())

# Filter to resolved Kalshi bets with a score result
bets = [b for b in h
        if b.get("kalshi_ask") and b.get("kalshi_stake") and b.get("won") is not None and b.get("ftr")]

DRAW_PRICE = 0.25  # assumed Kalshi draw price


def compute_pnl(bets, hedge_ratio, keep_total_constant=False):
    """
    hedge_ratio: stake_no / stake_yes (0 = no hedge)
    keep_total_constant: if True, split original stake into yes + no so total = original
                         if False, ADD the hedge on top (more capital deployed)
    """
    total_pnl = 0.0
    total_capital = 0.0
    wins = 0
    draws = 0
    losses = 0
    n = 0

    for b in bets:
        side = b["bet"]
        is_home_bet = "HOME" in side.upper()
        ftr = b["ftr"]
        yes_price = b["kalshi_ask"]
        no_price = yes_price + DRAW_PRICE  # NO on opposite team
        if no_price >= 0.99:
            continue  # can't hedge meaningfully

        orig_stake = b["kalshi_stake"]
        if keep_total_constant:
            # split: stake_yes + stake_no = orig_stake
            stake_yes = orig_stake / (1 + hedge_ratio)
            stake_no = stake_yes * hedge_ratio
        else:
            stake_yes = orig_stake
            stake_no = orig_stake * hedge_ratio

        total_capital += stake_yes + stake_no
        n += 1

        yes_win = (is_home_bet and ftr == "H") or (not is_home_bet and ftr == "A")
        # NO on opposite: NO HOME wins if ftr != H; NO AWAY wins if ftr != A
        no_win = (is_home_bet and ftr != "A") or (not is_home_bet and ftr != "H")

        # Per-bet P&L
        pnl = 0.0
        if yes_win:
            pnl += stake_yes * (1 - yes_price) / yes_price
        else:
            pnl -= stake_yes

        if hedge_ratio > 0:
            if no_win:
                pnl += stake_no * (1 - no_price) / no_price
            else:
                pnl -= stake_no

        total_pnl += pnl

        if ftr == "D":
            draws += 1
        elif yes_win:
            wins += 1
        else:
            losses += 1

    return {
        "n": n,
        "pnl": total_pnl,
        "capital": total_capital,
        "roi_pct": (total_pnl / total_capital * 100) if total_capital else 0,
        "wins": wins,
        "draws": draws,
        "losses": losses,
    }


# ── Mode A: ADD hedge on top (more capital deployed) ──
print("=" * 78)
print("MODE A: Add hedge on top of original stake (more capital, more exposure)")
print("=" * 78)
print(f"{'Hedge ratio':<14} {'Capital':>10} {'P&L':>10} {'ROI':>7} {'YES W':>6} {'Hedged D':>9} {'Total L':>8}")
print("-" * 78)

baseline = compute_pnl(bets, 0.0)
print(f"{'0.0 (none)':<14} ${baseline['capital']:>8.0f} ${baseline['pnl']:>+8.2f} {baseline['roi_pct']:>5.1f}% {baseline['wins']:>6} {0:>9} {baseline['losses']+baseline['draws']:>8}")
for r in [0.25, 0.5, 0.75, 1.0, 1.5]:
    res = compute_pnl(bets, r)
    print(f"{r:<14.2f} ${res['capital']:>8.0f} ${res['pnl']:>+8.2f} {res['roi_pct']:>5.1f}% {res['wins']:>6} {res['draws']:>9} {res['losses']:>8}")

# Find draw-neutral hedge ratio per bet (variable) — average it
# stake_no * (1-no_price)/no_price = stake_yes  →  stake_no = stake_yes * no_price/(1-no_price)
ratios = []
for b in bets:
    no_p = b["kalshi_ask"] + DRAW_PRICE
    if no_p >= 0.99: continue
    ratios.append(no_p / (1 - no_p))
avg_neutral = sum(ratios) / len(ratios) if ratios else 0
print(f"\nDraw-neutral avg ratio across all bets: {avg_neutral:.3f}")

# ── Mode B: Split original stake (constant total exposure) ──
print()
print("=" * 78)
print("MODE B: Split original stake (constant total exposure)")
print("=" * 78)
print(f"{'Hedge ratio':<14} {'Capital':>10} {'P&L':>10} {'ROI':>7} {'YES W':>6} {'Hedged D':>9} {'Total L':>8}")
print("-" * 78)
print(f"{'0.0 (none)':<14} ${baseline['capital']:>8.0f} ${baseline['pnl']:>+8.2f} {baseline['roi_pct']:>5.1f}% {baseline['wins']:>6} {0:>9} {baseline['losses']+baseline['draws']:>8}")
for r in [0.25, 0.5, 0.75, 1.0, 1.5]:
    res = compute_pnl(bets, r, keep_total_constant=True)
    print(f"{r:<14.2f} ${res['capital']:>8.0f} ${res['pnl']:>+8.2f} {res['roi_pct']:>5.1f}% {res['wins']:>6} {res['draws']:>9} {res['losses']:>8}")

# ── Per-bet draw-neutral (variable ratio) ──
print()
print("=" * 78)
print("MODE C: Per-bet draw-neutral hedge (size NO so draw nets to 0)")
print("=" * 78)
print("Each bet: stake_no = stake_yes * no_price/(1 - no_price)")
print(f"This is Mode A but with a custom ratio per bet")
total_pnl = 0; total_cap = 0; wins = 0; draws = 0; losses = 0
for b in bets:
    side = b["bet"]; is_home_bet = "HOME" in side.upper()
    ftr = b["ftr"]
    yes_price = b["kalshi_ask"]
    no_price = yes_price + DRAW_PRICE
    if no_price >= 0.99: continue
    stake_yes = b["kalshi_stake"]
    stake_no = stake_yes * no_price / (1 - no_price)
    total_cap += stake_yes + stake_no

    yes_win = (is_home_bet and ftr == "H") or (not is_home_bet and ftr == "A")
    no_win = (is_home_bet and ftr != "A") or (not is_home_bet and ftr != "H")

    pnl = (stake_yes * (1-yes_price)/yes_price) if yes_win else -stake_yes
    pnl += (stake_no * (1-no_price)/no_price) if no_win else -stake_no
    total_pnl += pnl

    if ftr == "D": draws += 1
    elif yes_win: wins += 1
    else: losses += 1

print(f"P&L: ${total_pnl:+.2f}  Capital deployed: ${total_cap:.2f}  ROI: {total_pnl/total_cap*100:+.2f}%")
print(f"YES wins: {wins}  Draws hedged: {draws}  HOME-wins (now bigger losses): {losses}")
print(f"  vs original: P&L ${baseline['pnl']:+.2f}, ROI {baseline['roi_pct']:+.2f}%")
