"""Live loop allineato alla chiusura candela 4H (xx:00 Europe/Rome).
Esegue live_engine ad ogni chiusura candela 4H: 02, 06, 10, 14, 18, 22 Europe/Rome."""
import sys
import time
from datetime import datetime, timezone, timedelta
from pathlib import Path

sys.path.insert(0, r"C:\Users\Mattia\.mavis\sessions\mvs_7410904bba534d318a61faac8876cd4c\workspace\live_deploy")

# Chiusure candela 4H Bybit (Europe/Rome = UTC+1/+2)
# Bybit 4H chiude a 00, 04, 08, 12, 16, 20 UTC = 02, 06, 10, 14, 18, 22 Europe/Rome (ora solare)
# o 01, 05, 09, 13, 17, 21 Europe/Rome (ora legale)
CLOSING_HOURS = [2, 6, 10, 14, 18, 22]


def seconds_until_next_4h_close():
    """Ritorna secondi fino alla prossima chiusura candela 4H (xx:00 Europe/Rome)."""
    tz = timezone(timedelta(hours=2))  # Europe/Rome (ora legale)
    now = datetime.now(tz)
    # Trova prossima ora di chiusura
    current_hour = now.hour
    for h in CLOSING_HOURS:
        if h > current_hour:
            target = now.replace(hour=h, minute=0, second=5, microsecond=0)  # 5 sec dopo la chiusura
            return int((target - now).total_seconds())
    # Dopo l'ultima chiusura di oggi, aspetta la prima di domani
    tomorrow_target = (now + timedelta(days=1)).replace(hour=CLOSING_HOURS[0], minute=0, second=5, microsecond=0)
    return int((tomorrow_target - now).total_seconds())


def main():
    print("=" * 60)
    print("LIVE LOOP ALIGNED — Chiusura candela 4H (xx:00 Europe/Rome)")
    print(f"Orari chiusura: {CLOSING_HOURS}")
    print("=" * 60)
    while True:
        secs = seconds_until_next_4h_close()
        tz = timezone(timedelta(hours=2))
        next_close = datetime.now(tz).replace(microsecond=0)
        # Trova prossima ora
        now = datetime.now(tz)
        for h in CLOSING_HOURS:
            if h > now.hour:
                next_close = now.replace(hour=h, minute=0, second=5)
                break
        else:
            next_close = (now + timedelta(days=1)).replace(hour=CLOSING_HOURS[0], minute=0, second=5)
        print(f"\n[{now.strftime('%Y-%m-%d %H:%M:%S')}] Prossima chiusura candela 4H: {next_close.strftime('%H:%M:%S')} (sleep {secs}s)")

        if secs > 60:
            # Aspetta 60s alla volta per essere responsivo a kill
            time.sleep(60)
        else:
            time.sleep(secs)
            # Esegui live_engine (NO POPUP CMD: pythonw + CREATE_NO_WINDOW 0x08000000)
            import subprocess
            print(f"[{datetime.now(tz).strftime('%H:%M:%S')}] ESECUZIONE live_engine.py --once --confirm-live (NO POPUP)")
            # Path pythonw.exe (no popup CMD)
            pythonw_exe = sys.executable.replace("python.exe", "pythonw.exe")
            if not Path(pythonw_exe).exists():
                pythonw_exe = sys.executable  # fallback se pythonw mancante
            subprocess.run(
                [pythonw_exe, str(Path(__file__).parent / "live_engine.py"),
                 "--once", "--confirm-live"],
                check=False,
                creationflags=0x08000000,  # CREATE_NO_WINDOW
            )


if __name__ == "__main__":
    main()
