#!/usr/bin/env python3
"""
APPLICAZIONE FINALE:
1. Backup robusto
2. Modifiche sltp_engine.py: EXCLUDED completo + skip per simboli classificati erroneamente
3. Restart
4. Backtest mirato (solo strategie attive: VPTR3, RETTANGOLO, MA_TRAILING)
"""
import os
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 ROBUSTO ===
print("=== STEP 1: BACKUP ===")
ts = datetime.now().strftime("%Y%m%d_%H%M%S")
backup_name = f"sltp_engine_v3_final_excludes_{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)
print(f"Backup: {backup_name}")

# === STEP 2: MODIFICHE ===
print("\n=== STEP 2: MODIFICHE ===")
with open(REMOTE, "r") as f:
    content = f.read()

new_content = content

# Mod 1: Aggiungere "rsi_swing_breakout" e "sqw" a EXCLUDED_STRATEGIES
old1 = 'EXCLUDED_STRATEGIES = {"rsi_swing", "rettangolo_simple", "sqw"}'
new1 = 'EXCLUDED_STRATEGIES = {"rsi_swing", "rsi_swing_breakout", "rettangolo_simple", "sqw"}'
if old1 in new_content:
    new_content = new_content.replace(old1, new1, 1)
    print("Mod 1 OK: aggiunto rsi_swing_breakout e sqw (gia' c'era sqw)")
else:
    print("Mod 1 SKIP: marker non trovato")

# Mod 2: Aggiungere skip per simboli classificati erroneamente
# Strategie: WIFUSDT, 1000BONKUSDT, NEARUSDT, ZECUSDT devono viaggiare liberi (SQW o RSI swing)
old2 = """                    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"""
new2 = """                    strategy = get_strategy_for_symbol(symbol)
                    # Mattia 14/08: SKIP strategie escluse (rsi_swing, rsi_swing_breakout, rettangolo_simple, sqw)
                    if strategy in EXCLUDED_STRATEGIES:
                        log(f"  {symbol} strategy={strategy}: ESCLUSA dal trailing (regola 09/08 rimossa), skip")
                        continue
                    # Mattia 14/08: skip per simboli specifici classificati erroneamente
                    # (WIFUSDT=rsi_swing, BONK=sqw, NEAR=sqw, ZEC=sqw sono in EXCLUDED ma la funzione li ritorna rettangolo/vptr3/ma_trailing)
                    if symbol in ("WIFUSDT", "1000BONKUSDT", "NEARUSDT", "ZECUSDT"):
                        log(f"  {symbol} strategy={strategy}: SKIP per simbolo (escluso manualmente, deve viaggiare libero), skip")
                        continue"""
if "skip per simbolo" not in content and old2 in new_content:
    new_content = new_content.replace(old2, new2, 1)
    print("Mod 2 OK: skip per simboli WIF/BONK/NEAR/ZEC")
else:
    print("Mod 2 SKIP: gia' presente o marker non trovato")

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

# Salva atomicamente
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 3: SYNTAX CHECK ===
print("\n=== STEP 3: 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)
    # rollback
    shutil.copy2(backup_path, REMOTE)
    print(f"ROLLBACK eseguito. File ripristinato da backup.")
    exit(1)

# === STEP 4: RESTART ===
print("\n=== STEP 4: RESTART ===")
subprocess.run(["pkill", "-9", "-f", "sltp_engine.py"], capture_output=True)
time.sleep(2)

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 -10 /opt/charter-live/live_deploy_v2/logs/sltp_engine_v2.out"], text=True)
print("LOG:", out)

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