"""
Recompute all Kalshi bet_history entries using ask for Kelly, floor at $1.
Drops nothing (except actual no-CLV-edge cases).
"""
import json, csv
from pathlib import Path

BET_HISTORY = Path(r'E:\soccer\bet_history.json')
LIVE_DATA   = Path(r'E:\soccer\live_data')
KALSHI_BR   = Path(r'E:\soccer\kalshi_bankroll.json')

EDGE_AWAY = 0.05
EDGE_HOME = 0.08
MIN_STAKE = 1.00

def kelly_stake(p, ask, bankroll):
    if ask <= 0 or ask >= 1:
        return 0
    b = (1 - ask) / ask
    f = (p * b - (1 - p)) / b
    if f <= 0:
        return 0
    raw = bankroll * f * 0.25
    return max(raw, MIN_STAKE)

# Build lookup: (date, home_lower, away_lower, side) -> {ask, pin_fair}
lookup = {}
for csv_file in sorted(LIVE_DATA.glob('*.csv')):
    date = csv_file.stem
    # Take first PRE row per fixture per side (earliest alert snapshot)
    seen = set()
    with open(csv_file, newline='', encoding='utf-8') as f:
        for row in csv.DictReader(f):
            if row.get('status','') not in ('PRE',''):
                continue
            home = row['home'].lower().strip()
            away = row['away'].lower().strip()
            
            # Away side
            key_a = (date, home, away, 'away')
            if key_a not in seen:
                clv_a = float(row.get('clv_kalshi_away') or 0)
                ask_a = float(row.get('kalshi_away_ask') or 0)
                pf_a  = float(row.get('pin_fair_away') or 0)
                if clv_a >= EDGE_AWAY and ask_a > 0 and pf_a > 0:
                    lookup[key_a] = {'ask': ask_a, 'pin_fair': pf_a, 'clv': clv_a}
                    seen.add(key_a)
            
            # Home side
            key_h = (date, home, away, 'home')
            if key_h not in seen:
                clv_h = float(row.get('clv_kalshi_home') or 0)
                ask_h = float(row.get('kalshi_home_ask') or 0)
                pf_h  = float(row.get('pin_fair_home') or 0)
                if clv_h >= EDGE_HOME and ask_h > 0 and pf_h > 0:
                    lookup[key_h] = {'ask': ask_h, 'pin_fair': pf_h, 'clv': clv_h}
                    seen.add(key_h)

print(f"Lookup entries: {len(lookup)}")

bets = json.loads(BET_HISTORY.read_text())

# Starting bankroll
kalshi_br = 1000.0

updated = removed = unchanged = 0

for b in bets:
    date = b.get('date','')
    home = b.get('home','').lower().strip()
    away = b.get('away','').lower().strip()
    side = b.get('bet','').lower().strip()
    
    # Skip non-Kalshi entries (B365-only bets have 'stake' not 'kalshi_stake'
    # but we need to check whether this was a Kalshi bet at all)
    # An entry is Kalshi if it has kalshi_ask OR it's in our lookup
    key = (date, home, away, side)
    has_kalshi_fields = bool(b.get('kalshi_ask') or b.get('kalshi_stake'))
    in_lookup = key in lookup
    
    if not has_kalshi_fields and not in_lookup:
        # Not a Kalshi bet
        continue
    
    if in_lookup:
        info = lookup[key]
        ask = info['ask']
        pf  = info['pin_fair']
        stake = kelly_stake(pf, ask, kalshi_br)
        
        won = b.get('won')
        if won is True:
            pnl = round(stake * (1/ask - 1), 2)
        elif won is False:
            pnl = -round(stake, 2)
        else:
            pnl = 0  # void/pending
        
        stake = round(stake, 2)
        kalshi_br = round(kalshi_br + pnl, 2)
        
        old_stake = b.get('kalshi_stake')
        b['kalshi_ask']   = ask
        b['kalshi_stake'] = stake
        b['pin_fair']     = pf
        b['kalshi_pnl']   = pnl
        b['kalshi_bankroll_after'] = kalshi_br
        
        if old_stake is None:
            updated += 1
            print(f"  ADDED  {date} {b['home']} vs {b['away']} {side}: ask={ask} stake=${stake} pnl=${pnl:+.2f} br=${kalshi_br}")
        else:
            updated += 1
    else:
        # Had kalshi fields but not in lookup — remove them
        for k in ['kalshi_ask','kalshi_stake','kalshi_pnl','kalshi_bankroll_after']:
            b.pop(k, None)
        removed += 1
        print(f"  STRIP  {date} {b['home']} vs {b['away']} (no lookup entry)")

print(f"\nAdded/updated: {updated}  |  Stripped: {removed}")
print(f"Final Kalshi bankroll: ${kalshi_br:.2f}")

BET_HISTORY.write_text(json.dumps(bets, indent=2))
json.dump({'bankroll': kalshi_br, 'updated': '2026-05-01'}, open(KALSHI_BR,'w'), indent=2)
print("Saved.")
