import inspect
import traceback
from functools import wraps
from typing import Any, Callable, Optional, Type

import axipy
from PySide2.QtCore import Slot


# noinspection PyPep8Naming
def _SlotTryExcept(*args: Type) -> Callable:
    """Enhanced @Slot decorator with error handling."""

    def decorator(func: Callable) -> Callable:

        @Slot(*args)  # Preserve original Slot behavior
        @wraps(func)  # Preserve function metadata
        def wrapper(*f_args: Any) -> Optional[Any]:
            try:
                sig = inspect.signature(func)
                # Count maximum allowable positional args
                max_positional = 0
                for param in sig.parameters.values():
                    if param.kind in (param.POSITIONAL_ONLY, param.POSITIONAL_OR_KEYWORD):
                        max_positional += 1
                return func(*f_args[:max_positional])
            except Exception as e:
                traceback.print_exc()
                axipy.Notifications.push(
                    "Ошибка",
                    f"Ошибка в функции '{func.__name__}': {str(e)}",
                    axipy.Notifications.Critical,
                )
                raise e

        return wrapper

    return decorator
