#!/usr/bin/env python3
"""
Modifica completa sltp_engine.py:
  1. Aggiunge EXCLUDED_STRATEGIES (skip rsi_swing, rettangolo_simple, sqw)
  2. Aggiunge pre-trailing 1% per VPTR3/RETTANGOLO/MA_TRAILING
  3. Mantiene la logica trailing attuale per VPTR3 (HWM 1.5%) e RETTANGOLO (lista 5 step)
"""
import paramiko
import re
from datetime import datetime

VPS = {"hostname": "167.233.133.244", "port": 22, "username": "root", "password": "peAwhLJ9X73Huentt9Ch"}
REMOTE = "/opt/charter-live/live_deploy_v2/sltp_engine.py"
BACKUP = "/opt/charter-live/backups/sltp_engine_v2_pre_trailing1.5_20260814_175934.py"

def run(client, cmd, timeout=30):
    s, o, e = client.exec_command(cmd, timeout=timeout)
    return o.read().decode("utf-8", errors="replace"), e.read().decode("utf-8", errors="replace")

client = paramiko.SSHClient()
client.set_missing_host_key_policy(paramiko.AutoAddPolicy())
client.connect(**VPS, look_for_keys=False, allow_agent=False)
sftp = client.open_sftp()

# Backup (è già stato fatto, ma rifaccio per essere sicuro)
ts = datetime.now().strftime("%Y%m%d_%H%M%S")
backup_name = f"sltp_engine_v2_pre_skip_and_pre_20260814_{ts}.py"
backup_remote = f"/opt/charter-live/backups/{backup_name}"
out, _ = run(client, f"cp -p {REMOTE} {backup_remote} && sha256sum {REMOTE} {backup_remote}")
print("=== STEP 1: BACKUP ===")
print(out)

# Leggi file
with sftp.open(REMOTE, "r") as f:
    content = f.read().decode("utf-8")
print(f"\n=== STEP 2: LETTURA FILE ===\nFile letto: {len(content)} chars")

# Modifiche
new_content = content

# Mod 1: Aggiungere EXCLUDED_STRATEGIES dopo le altre costanti
# Cerchiamo RETTANGOLO_SL_HARD_PCT o simile per inserire la lista
old_marker = "RETTANGOLO_SL_HARD_PCT = 0.04"
new_marker = """# Mattia 14/08: strategie ESCLUSE dal trailing automatico (regola del 09/08 non si applica)
EXCLUDED_STRATEGIES = {"rsi_swing", "rettangolo_simple", "sqw"}
# Strategie su cui APPLICO la regola trailing (pre-trailing 1% + trailing 1.5% lista 5 step):
# - vptr3, rettangolo, ma_trailing

RETTANGOLO_SL_HARD_PCT = 0.04"""
if old_marker in new_content and "EXCLUDED_STRATEGIES" not in new_content:
    new_content = new_content.replace(old_marker, new_marker, 1)
    print("Mod 1 OK: aggiunto EXCLUDED_STRATEGIES")
else:
    print("Mod 1 SKIP: gia' presente o marker non trovato")

# Mod 2: Aggiungere pre-trailing 1% in compute_sltp_rettangolo
# Cerchiamo "if profit_pct >= RETTANGOLO_TRAILING_TRIGGER_PCT:"
# Aggiungiamo prima un check pre-trailing
old_pre_marker = """        if profit_pct >= RETTANGOLO_TRAILING_TRIGGER_PCT:"""
new_pre_marker = """        # Mattia 14/08: pre-trailing 1% → SL a breakeven (entry)
        if not state.get("pre_trailing_active", False) and profit_pct >= 0.01:
            state["pre_trailing_active"] = True
            state["pre_trailing_sl_price"] = entry_price  # breakeven
        # applica pre-trailing SL se attivo
        if state.get("pre_trailing_active", False) and not state.get("trailing_active", False):
            pre_sl = state.get("pre_trailing_sl_price")
            if pre_sl is not None:
                # calcola sl finale: max(pre_sl, eventuale trailing)
                if "trailing_sl_price" not in state or state["trailing_sl_price"] < pre_sl:
                    state["trailing_sl_price"] = pre_sl

        if profit_pct >= RETTANGOLO_TRAILING_TRIGGER_PCT:"""
if "pre_trailing_active" not in new_content and old_pre_marker in new_content:
    new_content = new_content.replace(old_pre_marker, new_pre_marker, 1)
    print("Mod 2 OK: aggiunto pre-trailing 1% in RETTANGOLO")
else:
    print("Mod 2 SKIP: gia' presente o marker non trovato")

# Mod 3: Aggiungere skip per le strategie escluse nel main loop
# Cerchiamo "strategy = get_strategy_for_symbol(symbol)" e aggiungiamo subito dopo il check
old_skip_marker = """                    strategy = get_strategy_for_symbol(symbol)
                    # Carica tf_dict da TUTTI i CSV strategia (non solo rettangolo_assets)"""
new_skip_marker = """                    strategy = get_strategy_for_symbol(symbol)
                    # Mattia 14/08: SKIP strategie escluse (rsi_swing, rettangolo_simple, sqw)
                    if strategy in EXCLUDED_STRATEGIES:
                        log(f"  {symbol} strategy={strategy}: ESCLUSA dal trailing (regola 09/08 rimossa), skip")
                        continue
                    # Carica tf_dict da TUTTI i CSV strategia (non solo rettangolo_assets)"""
if "ESCLUSA dal trailing" not in new_content and old_skip_marker in new_content:
    new_content = new_content.replace(old_skip_marker, new_skip_marker, 1)
    print("Mod 3 OK: aggiunto skip per strategie escluse")
else:
    print("Mod 3 SKIP: gia' presente o marker non trovato")

# Mod 4: Aggiungere pre-trailing 1% anche in process_vptr3_position (per VPTR3/RETTANGOLO_SIMPLE/MA_TRAILING)
# Cerchiamo "sl_trailing = current_price * (1 - VPTR3_TRAILING_TRIGGER_PCT)" e aggiungiamo pre-trailing prima
old_vp_pre = """    if side == "Buy":
        sl_trailing = current_price * (1 - VPTR3_TRAILING_TRIGGER_PCT)
    else:
        sl_trailing = current_price * (1 + VPTR3_TRAILING_TRIGGER_PCT)"""
new_vp_pre = """    # Mattia 14/08: pre-trailing 1% → SL a breakeven (entry)
    pre_trailing_active = sym_state.get("pre_trailing_active", False)
    if not pre_trailing_active and pnl_pct >= 0.01:
        pre_trailing_active = True
    if pre_trailing_active:
        breakeven_sl = entry_price  # breakeven
    else:
        breakeven_sl = None

    if side == "Buy":
        sl_trailing = current_price * (1 - VPTR3_TRAILING_TRIGGER_PCT)
    else:
        sl_trailing = current_price * (1 + VPTR3_TRAILING_TRIGGER_PCT)

    # Applica pre-trailing breakeven (se attivo e migliore del trailing calcolato)
    if breakeven_sl is not None:
        if side == "Buy" and breakeven_sl > sl_trailing:
            sl_trailing = breakeven_sl
        elif side == "Sell" and breakeven_sl < sl_trailing:
            sl_trailing = breakeven_sl"""
if "pre_trailing_active = sym_state.get" not in new_content and old_vp_pre in new_content:
    new_content = new_content.replace(old_vp_pre, new_vp_pre, 1)
    print("Mod 4 OK: aggiunto pre-trailing 1% in process_vptr3_position")
else:
    print("Mod 4 SKIP: gia' presente o marker non trovato")

# Verifica modifiche
diff_chars = sum(1 for a, b in zip(content, new_content) if a != b)
print(f"\nTotale caratteri modificati: {diff_chars}")

# Salva atomicamente
tmp = REMOTE + ".tmp"
with sftp.open(tmp, "w") as f:
    f.write(new_content)
sftp.posix_rename(tmp, REMOTE)
out, _ = run(client, f"sha256sum {REMOTE}")
print(f"Nuovo SHA256: {out}")

# Test syntax
out, err = run(client, f"/opt/charter/venv/bin/python -c \"import sys; sys.path.insert(0, '/opt/charter-live/live_deploy_v2'); import sltp_engine; print('IMPORT_OK'); print('EXCLUDED_STRATEGIES=', sltp_engine.EXCLUDED_STRATEGIES); print('RETTANGOLO_TRAILING_TRIGGER_PCT=', sltp_engine.RETTANGOLO_TRAILING_TRIGGER_PCT)\"", timeout=15)
print("\n=== SYNTAX CHECK ===")
print(out)
if err:
    print("STDERR:", err)

# Restart
print("\n=== RESTART ===")
out, _ = run(client, "pkill -9 -f 'sltp_engine.py' 2>&1; sleep 2; ps -ef | grep sltp_engine | grep -v grep | wc -l")
print("DOPO KILL:", out)

# Avvia con env var
client.exec_command("cd /opt/charter-live/live_deploy_v2 && WEBHOOK_SECRET='TV_2026_MATTIA_DEMO' nohup /opt/charter/venv/bin/python -u sltp_engine.py > logs/sltp_engine_v2.out 2>&1 < /dev/null &", timeout=5)

import time
time.sleep(5)
out, _ = run(client, "ps -ef | grep sltp_engine | grep -v grep")
print("DOPO RESTART:", out)
out, _ = run(client, "head -20 /opt/charter-live/live_deploy_v2/logs/sltp_engine_v2.out")
print("LOG:", out)

sftp.close()
client.close()
print(f"\n=== FATTO. Backup: {backup_name} ===")
