from typing import Tuple
from typing import Optional


def split_name_and_unit(s: str) -> Tuple[str, Optional[str]]:
    """For names of the form "ColumnName (unit)", separate out the name from the unit (by assuming the unit is within
    round brackets) and return a tuple ("ColumnName", "unit"). If no unit is is given (there are no round brackets),
    return ("ColumnName", None).

    Args:
        s: A string with a name and a possible unit specified in round brackets, i.e.:

    Returns:
        Tuple[str, Optional[str]]: A tuple with the first element being the name of the column extracted from the
            string, and the second being the string representing the unit extracted from the round brackets, or None
            if there are no brackets. I.e. the return values could be:

    Example:
        .. code-block ::

            >>> split_name_and_unit("ColumnName (unit)")
            ("ColumnName", "unit")
            >>> split_name_and_unit("ColumnName")
            ("ColumnName", None)
    """
    # If a unit is given:
    if "(" in s:  # pragma: no cover
        if s[-1] != ")":
            # The last symbol is expected to be ')'
            raise ValueError(
                f"If a unit is specified in the column name (is given in round brackets), the last element "
                f'must be the closing bracket for the unit: ")". The offending column name is:\n{s}'
            )
        name, unit = s.split("(", 1)
        # Remove the trailing closing bracket
        unit = unit[:-1]
        # Remove right whitespace after name
        name = name.rstrip()
        return name, unit
    # If no unit is given:
    else:
        return s, None