import logging
from functools import wraps


def slot_error_boundary(func):
    """Wrap a @Slot method so exceptions are logged + signalled to QML.

    Usage (stack under @Slot):
        @Slot()
        @slot_error_boundary
        def myMethod(self) -> None:
            ...

    On exception:
      - Logs full traceback via logger.exception()
      - Emits logMessage signal with human-readable error (if available)
      - Returns None so QML never sees a crash
    """
    @wraps(func)
    def wrapper(self, *args, **kwargs):
        try:
            return func(self, *args, **kwargs)
        except Exception as e:
            logger = logging.getLogger(self.__class__.__module__)
            logger.exception("Slot '%s' raised: %s", func.__name__, e)
            if hasattr(self, "logMessage"):
                self.logMessage.emit(f"Error in {func.__name__}: {str(e)}")
            return None
    return wrapper
