from typing import Union
from typing import Callable
import inspect
import re


def _name_is_used_in_source(name: str, source: Union[Callable, str]) -> bool:
    """ Check if name is used within the source.

    This is a naive implementation for now. Should be refactored later.

    Parameters
    ----------
    name: an identifier which will be searched for in the source

    source: either a function of a source code of a function.

    Returns
    ----------
    search_result: whether the source contains a direct reference to the name

    """

    assert isinstance(name, str)
    assert name.replace("_", "").isalnum() and not name[0].isdigit(), (
            "name='" + name + "', must be a valid identifier.")

    if callable(source) and hasattr(source, "__wrapped__"):
        source = inspect.unwrap(source)
    if callable(source):
        source = inspect.getsource(source)

    searh_pattern = "[^a-zA-Z0-9_]" + name + "[^a-zA-Z0-9_]"
    search_outcome = re.search(searh_pattern, source)
    search_result = bool(search_outcome)
    return search_result