#!/usr/bin/env python
"""Patch 3: aggiunge epsilon a tutti i check lock-in step (5%, 3%, 2%, 1.5%)."""
import sys

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

OLD = '''        if pnl_pct >= 0.05:  # >= 5%
            lock_in = 0.030  # +3% lock-in
        elif pnl_pct >= 0.03:  # >= 3%
            lock_in = 0.020  # +2% lock-in
        elif pnl_pct >= 0.02:  # >= 2%
            lock_in = 0.010  # +1% lock-in
        else:  # 1.5% - 2%
            lock_in = 0.005  # +0.5% lock-in'''

NEW = '''        # Epsilon 1e-9 per evitare float rounding sui boundary (es. PnL=5% esatto = 0.04999...)
        if pnl_pct >= 0.05 - 1e-9:  # >= 5%
            lock_in = 0.030  # +3% lock-in
        elif pnl_pct >= 0.03 - 1e-9:  # >= 3%
            lock_in = 0.020  # +2% lock-in
        elif pnl_pct >= 0.02 - 1e-9:  # >= 2%
            lock_in = 0.010  # +1% lock-in
        else:  # 1.5% - 2%
            lock_in = 0.005  # +0.5% lock-in'''

def main():
    with open(FILE, encoding='utf-8') as f:
        content = f.read()
    if NEW in content:
        print("PATCH 3: gia' applicata, skip")
        return
    if OLD not in content:
        print("ERRORE: pattern non trovato")
        sys.exit(1)
    content = content.replace(OLD, NEW)
    with open(FILE, 'w', encoding='utf-8') as f:
        f.write(content)
    print("PATCH 3: epsilon su lock-in steps aggiunti")

if __name__ == "__main__":
    main()
