"""
Avvia il webhook receiver in background su Windows.
Uso: python start_webhook_receiver.py
Prima: installa dipendenze -> pip install flask requests
"""

import subprocess
import sys
import time
from pathlib import Path

HERE = Path(__file__).resolve().parent
RECEIVER = HERE / "webhook_receiver.py"
LOG = HERE / "webhook_receiver.stdout.log"

if not RECEIVER.exists():
    print(f"ERRORE: non trovo {RECEIVER}")
    sys.exit(1)

print(f"[start_webhook] Avvio {RECEIVER.name} su 127.0.0.1:5580 ...")
print(f"[start_webhook] Log: {LOG}")

# Avvia in background, separato dalla console corrente
creationflags = 0
if sys.platform == "win32":
    creationflags = subprocess.CREATE_NO_WINDOW

proc = subprocess.Popen(
    [sys.executable, str(RECEIVER)],
    stdout=open(LOG, "a", encoding="utf-8"),
    stderr=subprocess.STDOUT,
    cwd=str(HERE),
    creationflags=creationflags,
)

print(f"[start_webhook] PID: {proc.pid}")
print(f"[start_webhook] Health check: http://127.0.0.1:5580/health")
print(f"[start_webhook] Webhook URL:  http://127.0.0.1:5580/webhook")
print()
print("Aspetto 2 secondi e verifico health ...")
time.sleep(2)

import urllib.request
try:
    with urllib.request.urlopen("http://127.0.0.1:5580/health", timeout=3) as r:
        print(f"[start_webhook] HEALTH OK: {r.read().decode()}")
except Exception as e:
    print(f"[start_webhook] HEALTH FAIL: {e}")
    print("Controlla il log:", LOG)
