"""mDNS publisher para que agents/UIs encuentren el servidor automaticamente."""
import socket
import threading
from config import SERVER_PORT, VENUE_ID, VENUE_NAME

_zeroconf = None
_lock = threading.Lock()


def publish_service():
    """Publica el servicio ICEBERG en la red local via mDNS (en thread separado)."""
    thread = threading.Thread(target=_do_publish, daemon=True)
    thread.start()


def _do_publish():
    """Ejecuta la publicacion mDNS en thread separado para no bloquear el event loop."""
    global _zeroconf
    try:
        from zeroconf import ServiceInfo, Zeroconf

        local_ip = _get_local_ip()

        info = ServiceInfo(
            "_iceberg._tcp.local.",
            f"ICEBERG-{VENUE_ID}._iceberg._tcp.local.",
            addresses=[socket.inet_aton(local_ip)],
            port=SERVER_PORT,
            properties={
                "venue_id": VENUE_ID,
                "venue_name": VENUE_NAME,
                "version": "1.0",
            },
        )
        with _lock:
            _zeroconf = Zeroconf()
            _zeroconf.register_service(info)
        print(f"[mDNS] Servicio publicado: ICEBERG-{VENUE_ID} en {local_ip}:{SERVER_PORT}")
    except ImportError:
        print("[mDNS] zeroconf no instalado (pip install zeroconf). mDNS deshabilitado.")
    except Exception as e:
        print(f"[mDNS] Error al publicar servicio: {type(e).__name__}: {e}")


def unpublish_service():
    """Limpia el servicio mDNS al apagar."""
    global _zeroconf
    with _lock:
        if _zeroconf:
            try:
                _zeroconf.unregister_all_services()
                _zeroconf.close()
                print("[mDNS] Servicio removido")
            except Exception:
                pass
            _zeroconf = None


def _get_local_ip():
    """Obtiene la IP local de la maquina en la red."""
    try:
        s = socket.socket(socket.AF_INET, socket.SOCK_DGRAM)
        s.connect(("8.8.8.8", 80))
        ip = s.getsockname()[0]
        s.close()
        return ip
    except Exception:
        return "127.0.0.1"
