"""@xl_func decorator — marks functions for registration as Excel UDFs.

The C runtime scans _registry at xlAutoOpen time to register functions with Excel.
"""

import inspect

# Internal registry: list of (name, callable, n_args)
_registry = []


def xl_func(fn=None, *, name=None):
    """Decorator — mark a function as an Excel UDF.

    Usage:
        @xl_func
        def my_func(a, b):
            return a + b

        @xl_func(name="myCustomName")
        def my_func(a, b):
            return a + b
    """

    def _register(f):
        excel_name = name if name else f.__name__
        sig = inspect.signature(f)
        n_args = len(
            [
                p
                for p in sig.parameters.values()
                if p.kind
                in (
                    inspect.Parameter.POSITIONAL_OR_KEYWORD,
                    inspect.Parameter.POSITIONAL_ONLY,
                )
            ]
        )
        # Check if already registered (e.g. after a hot-reload)
        for i, (n, _, _) in enumerate(_registry):
            if n == excel_name:
                _registry[i] = (excel_name, f, n_args)
                return f
        _registry.append((excel_name, f, n_args))
        return f

    if fn is not None:
        return _register(fn)
    return _register
