"""Auto-restart servizi trading dopo black-out.
Uso: python _restart_all.py
Killa tutti i python, riavvia webhook (5580) + dashboard (5503), verifica stato.
"""
import subprocess, sys, time, os, urllib.request, urllib.error

os.chdir(r"G:\AI TRADING ENGINE\live_deploy")

print("="*60)
print("RESTART SERVIZI")
print("="*60)

# 1. killa tutti i python
print("\n[1/3] Killo tutti i python...")
out = subprocess.run(["taskkill", "/F", "/IM", "python.exe"],
                     capture_output=True, text=True)
print(f"  taskkill stdout: {out.stdout.strip()[:200]}")
print(f"  taskkill stderr: {out.stderr.strip()[:200]}")
time.sleep(3)

# 2. riavvia webhook
print("\n[2/3] Riavvio webhook (5580)...")
subprocess.Popen(
    ["powershell.exe", "-ExecutionPolicy", "Bypass", "-File",
     r"G:\AI TRADING ENGINE\live_deploy\_run_server.ps1"],
    stdout=subprocess.DEVNULL, stderr=subprocess.DEVNULL
)
time.sleep(4)

# 3. riavvia dashboard
print("[3/3] Riavvio dashboard (5503)...")
p = subprocess.Popen(
    [sys.executable, "stats_dashboard.py"],
    stdout=subprocess.DEVNULL, stderr=subprocess.DEVNULL
)
print(f"  dashboard PID: {p.pid}")
time.sleep(4)

# verifica finale
print()
print("="*60)
print("VERIFICA STATO")
print("="*60)
services = [
    ("Webhook 5580", "http://127.0.0.1:5580/health"),
    ("Dashboard 5503 /", "http://127.0.0.1:5503/"),
    ("Dashboard 5503 /monitor3", "http://127.0.0.1:5503/monitor3"),
]
all_up = True
for name, url in services:
    try:
        r = urllib.request.urlopen(url, timeout=3)
        print(f"  {name}: UP ({r.status})")
    except urllib.error.URLError as e:
        print(f"  {name}: DOWN ({e})")
        all_up = False

print()
if all_up:
    print("[OK] Tutti i servizi sono UP. Trading system operativo.")
else:
    print("[WARN] Alcuni servizi sono ancora DOWN. Riprova tra 10 sec.")
