"""Apply Final-Minutes Sniper strategy changes to Automated/paper_trade.py"""
import re

path = r"C:\kalshibot\Automated\paper_trade.py"
with open(path, "r", encoding="utf-8") as f:
    content = f.read()

changes = []

# ── 1. Fix duplicate comment fragments ──
content = content.replace(
    "ENTRY_COOLDOWN        = 20    # 20s between entries between entries",
    "ENTRY_COOLDOWN        = 20    # 20s between entries"
)
content = content.replace(
    "SCORE_HIGH             = 25    # score >= 25 \u2192 HIGH confidence \u2192 HIGH confidence",
    "SCORE_HIGH             = 25    # score >= 25 \u2192 HIGH confidence"
)
content = content.replace(
    "SCORE_MEDIUM           = 20    # score >= 20 \u2192 MEDIUM (raised \u2014 weak plays lose money) \u2192 MEDIUM (raised from 7 \u2014 weak signals were losing)",
    "SCORE_MEDIUM           = 20    # score >= 20 \u2192 MEDIUM (raised \u2014 weak plays lose money)"
)
content = content.replace(
    "MIN_MISPRICING         = 0.012  # 1.2% threshold \u2014 catch more mispricings mispricing needed to score any points",
    "MIN_MISPRICING         = 0.012  # 1.2% threshold \u2014 catch more mispricings near expiry"
)
changes.append("Cleaned duplicate comment fragments")

# ── 2. EXP signal: enhanced time bonuses ──
old_bonus = (
    "    # Bonus: add points when < 5 min left \u2014 contract is near resolution, higher certainty\n"
    "    if mins_left < 5 and z_score >= 1.5:\n"
    "        score = min(50, score + 5)\n"
    "    return score, direction"
)
new_bonus = (
    "    # Time bonuses \u2014 closer to expiry with strong z-score = higher certainty = bigger bonus\n"
    "    if   mins_left < 1.5 and z_score >= 1.0: score = min(50, score + 15)  # final 90s: near-certain\n"
    "    elif mins_left < 2.5 and z_score >= 1.5: score = min(50, score + 10)  # final 2.5min: high conviction\n"
    "    elif mins_left < 3.0 and z_score >= 1.5: score = min(50, score + 5)   # final 3min: solid conviction\n"
    "    return score, direction"
)
if old_bonus in content:
    content = content.replace(old_bonus, new_bonus)
    changes.append("EXP time bonuses updated")
else:
    changes.append("WARNING: EXP bonus block NOT FOUND")

# ── 3. Sniper EXP-only exception in final 90s ──
old_mom = (
    "    # Require MOM on ALL trades \u2014 data shows nothing wins without momentum confirming\n"
    "    # EXP+MOM=83% WR, EXP+LAG+MOM=100% WR. Everything without MOM loses.\n"
    "    if mom_score == 0:\n"
    '        return 0, None, None, ""'
)
new_mom = (
    "    # MOM required on most trades \u2014 proven by data (EXP+MOM=83% WR, EXP+LAG+MOM=100% WR).\n"
    "    # SNIPER EXCEPTION: allow EXP-only trade in final 90s when signal is extreme.\n"
    "    # <90s left + EXP score 40+ = near-certain outcome, momentum irrelevant.\n"
    "    if mom_score == 0:\n"
    "        secs_remaining = market.get(\"secs_left\", 999) if market else 999\n"
    "        if exp_score >= 40 and secs_remaining < 90:\n"
    "            pass  # SNIPER: final-90s EXP override\n"
    "        else:\n"
    '            return 0, None, None, ""'
)
if old_mom in content:
    content = content.replace(old_mom, new_mom)
    changes.append("Sniper EXP-only exception added")
else:
    changes.append("WARNING: MOM block NOT FOUND")

# ── 4. Bet sizing overhaul ──
old_bet = (
    "    if score < SCORE_MEDIUM: return 0.0\n"
    "    if   score >= 90: pct = 0.15\n"
    "    elif score >= 85: pct = 0.12\n"
    "    elif score >= 75: pct = 0.08\n"
    "    elif score >= 65: pct = 0.05\n"
    "    elif score >= 55: pct = 0.03\n"
    "    elif score >= 45: pct = 0.02\n"
    "    else:             pct = 0.01   # score 38-44\n"
    "    bet = round(current_balance * pct, 2)\n"
    "    bet = max(0.50, min(bet, current_balance * 0.15))  # floor $0.50, cap 15%\n"
    "    return bet"
)
new_bet = (
    "    if score < SCORE_MEDIUM: return 0.0\n"
    "    # Practical score range: EXP(0-50)+LAG(0-30)+MOM(0-20)=max 100\n"
    "    # Size aggressively on HIGH conviction, conservatively on MEDIUM.\n"
    "    if   score >= 55: pct = 0.14   # very strong:  14% = ~$70 on $500\n"
    "    elif score >= 45: pct = 0.10   # strong HIGH:  10% = ~$50\n"
    "    elif score >= 35: pct = 0.07   # solid HIGH:    7% = ~$35\n"
    "    elif score >= 25: pct = 0.04   # low HIGH:      4% = ~$20\n"
    "    else:             pct = 0.02   # MEDIUM:        2% = ~$10\n"
    "    bet = round(current_balance * pct, 2)\n"
    "    bet = max(1.00, min(bet, current_balance * 0.18))  # floor $1, cap 18%\n"
    "    return bet"
)
if old_bet in content:
    content = content.replace(old_bet, new_bet)
    changes.append("Bet sizing overhauled")
else:
    changes.append("WARNING: bet sizing block NOT FOUND")

with open(path, "w", encoding="utf-8") as f:
    f.write(content)

print("Changes applied:")
for c in changes:
    print(f"  {'OK' if 'WARNING' not in c else 'FAIL'} {c}")

with open(path, "r", encoding="utf-8") as f:
    lines = f.readlines()

print("\nVerification:")
print(f"  STARTING_BALANCE=500: {any('500.00' in l and 'STARTING_BALANCE' in l for l in lines)}")
print(f"  PROFIT_TARGET=0.35:   {any('0.35' in l and 'PROFIT_TARGET' in l for l in lines)}")
print(f"  SNIPER MODE 3min:     {any('SNIPER MODE' in l for l in lines)}")
print(f"  90s bonus +15:        {any('score + 15' in l for l in lines)}")
print(f"  Sniper exception:     {any('secs_remaining < 90' in l for l in lines)}")
print(f"  New bet pct=0.14:     {any('pct = 0.14' in l for l in lines)}")
print(f"  SCORE_HIGH=25:        {any('= 25' in l and 'SCORE_HIGH' in l for l in lines)}")
print(f"  SCORE_MEDIUM=20:      {any('= 20' in l and 'SCORE_MEDIUM' in l for l in lines)}")
print(f"  File size: {sum(len(l) for l in lines)} bytes")
