#!/usr/bin/env python
"""Patch 4: epsilon su SL hard check + TP parziale + TP finale (float rounding safety)."""
import sys

FILE = "/opt/charter-live/live_deploy_v2/sltp_engine.py"

# SL hard check
OLD1 = '''    # 1. SL hard a -3%
    if pnl_pct <= VPTR3_SL_HARD_PCT:'''
NEW1 = '''    # 1. SL hard a -4% (Charter V3 VPTR3, simmetrico RETTANGOLO +4%)
    # Epsilon per float rounding: PnL=-4% esatto potrebbe essere -0.039999...
    if pnl_pct <= VPTR3_SL_HARD_PCT + 1e-9:'''

# TP parziale check
OLD2 = '''    if not tp1_done and pnl_pct >= VPTR3_TP_PARTIAL_PCT:'''
NEW2 = '''    if not tp1_done and pnl_pct >= VPTR3_TP_PARTIAL_PCT - 1e-9:'''

# TP finale check
OLD3 = '''        if (side == "Buy" and current_price >= target) or (side == "Sell" and current_price <= target):'''
NEW3 = '''        if (side == "Buy" and current_price >= target - 1e-9) or (side == "Sell" and current_price <= target + 1e-9):'''

def main():
    with open(FILE, encoding='utf-8') as f:
        content = f.read()
    for i, (old, new, label) in enumerate([(OLD1, NEW1, "SL hard"), (OLD2, NEW2, "TP parziale"), (OLD3, NEW3, "TP finale")], 1):
        if new in content:
            print(f"PATCH 4.{i}: {label} gia' applicato, skip")
            continue
        if old not in content:
            print(f"PATCH 4.{i}: ERRORE {label} pattern non trovato")
            sys.exit(1)
        content = content.replace(old, new)
        print(f"PATCH 4.{i}: {label} epsilon aggiunto")
    with open(FILE, 'w', encoding='utf-8') as f:
        f.write(content)
    print("PATCH 4: completata")

if __name__ == "__main__":
    main()
