#!/usr/bin/env python3
"""
Modifica sltp_engine.py sul VPS (no paramiko, no esecuzioni remote).
Tutto fatto in locale sul VPS via python3 + filesystem.
"""
import os
import re
import shutil
import subprocess
import time
from datetime import datetime
from pathlib import Path

REMOTE = "/opt/charter-live/live_deploy_v2/sltp_engine.py"
BACKUP_DIR = "/opt/charter-live/backups"

# === STEP 1: BACKUP ===
print("=== STEP 1: BACKUP ===")
ts = datetime.now().strftime("%Y%m%d_%H%M%S")
backup_name = f"sltp_engine_v2_pre_skip_and_pre_{ts}.py"
backup_path = f"{BACKUP_DIR}/{backup_name}"
shutil.copy2(REMOTE, backup_path)
out = subprocess.check_output(["sha256sum", REMOTE, backup_path], text=True)
print(out)

# === STEP 2: LEGGI FILE ===
print("\n=== STEP 2: LETTURA ===")
with open(REMOTE, "r") as f:
    content = f.read()
print(f"File: {len(content)} chars, {content.count(chr(10))+1} righe")

# === STEP 3: MODIFICHE ===
new_content = content

# Mod 1: Aggiungere EXCLUDED_STRATEGIES dopo RETTANGOLO_SL_HARD_PCT
old1 = "RETTANGOLO_SL_HARD_PCT = 0.04"
new1 = """# 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:
# - vptr3: logica VPTR3-style con HWM e pre-trailing 1%
# - rettangolo: logica RETTANGOLO-style con lista 5 step e pre-trailing 1%
# - ma_trailing: logica VPTR3-style con HWM e pre-trailing 1%

RETTANGOLO_SL_HARD_PCT = 0.04"""
if old1 in new_content and "EXCLUDED_STRATEGIES" not in new_content:
    new_content = new_content.replace(old1, new1, 1)
    print("Mod 1 OK: aggiunto EXCLUDED_STRATEGIES")
else:
    print("Mod 1 SKIP")

# Mod 2: Pre-trailing 1% in compute_sltp_rettangolo
old2 = "        if profit_pct >= RETTANGOLO_TRAILING_TRIGGER_PCT:"
new2 = """        # 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
        if state.get("pre_trailing_active", False) and not state.get("trailing_active", False):
            if "trailing_sl_price" not in state or state["trailing_sl_price"] < state["pre_trailing_sl_price"]:
                state["trailing_sl_price"] = state["pre_trailing_sl_price"]

        if profit_pct >= RETTANGOLO_TRAILING_TRIGGER_PCT:"""
if "pre_trailing_active" not in new_content and old2 in new_content:
    new_content = new_content.replace(old2, new2, 1)
    print("Mod 2 OK: pre-trailing 1% in RETTANGOLO")
else:
    print("Mod 2 SKIP")

# Mod 3: Skip per strategie escluse nel main loop
old3 = """                    strategy = get_strategy_for_symbol(symbol)
                    # Carica tf_dict da TUTTI i CSV strategia (non solo rettangolo_assets)"""
new3 = """                    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 old3 in new_content:
    new_content = new_content.replace(old3, new3, 1)
    print("Mod 3 OK: skip strategie escluse")
else:
    print("Mod 3 SKIP")

# Mod 4: Pre-trailing 1% in process_vptr3_position
old4 = """    if side == "Buy":
        sl_trailing = current_price * (1 - VPTR3_TRAILING_TRIGGER_PCT)
    else:
        sl_trailing = current_price * (1 + VPTR3_TRAILING_TRIGGER_PCT)"""
new4 = """    # Mattia 14/08: pre-trailing 1% → SL a breakeven (entry)
    if not sym_state.get("pre_trailing_active", False) and pnl_pct >= 0.01:
        sym_state["pre_trailing_active"] = True
    breakeven_sl = entry_price if sym_state.get("pre_trailing_active", False) else None

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

    # Applica breakeven se pre-trailing attivo e migliore del trailing
    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 old4 in new_content:
    new_content = new_content.replace(old4, new4, 1)
    print("Mod 4 OK: pre-trailing 1% in process_vptr3_position")
else:
    print("Mod 4 SKIP")

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

tmp = REMOTE + ".tmp"
with open(tmp, "w") as f:
    f.write(new_content)
os.replace(tmp, REMOTE)
out = subprocess.check_output(["sha256sum", REMOTE], text=True)
print(f"Nuovo SHA256: {out}")

# === STEP 5: SYNTAX CHECK ===
print("\n=== STEP 5: SYNTAX CHECK ===")
code = """
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)
"""
r = subprocess.run(["/opt/charter/venv/bin/python", "-c", code], capture_output=True, text=True, timeout=15)
print(r.stdout)
if r.returncode != 0:
    print("STDERR:", r.stderr)

# === STEP 6: RESTART ===
print("\n=== STEP 6: RESTART ===")
subprocess.run(["pkill", "-9", "-f", "sltp_engine.py"], capture_output=True)
time.sleep(2)
out = subprocess.check_output(["bash", "-c", "ps -ef | grep sltp_engine | grep -v grep | wc -l"], text=True)
print("DOPO KILL:", out)

# Avvia con env var
subprocess.Popen(
    ["bash", "-c", "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 &"],
    stdout=subprocess.DEVNULL, stderr=subprocess.DEVNULL
)
time.sleep(5)
out = subprocess.check_output(["bash", "-c", "ps -ef | grep sltp_engine | grep -v grep"], text=True)
print("DOPO RESTART:", out)
out = subprocess.check_output(["bash", "-c", "head -20 /opt/charter-live/live_deploy_v2/logs/sltp_engine_v2.out"], text=True)
print("LOG:", out)

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