Apply desired SGR commands to given text.

    :param text:
        Text or anything convertible to text
    :param fg:
        (optional) Foreground color. Choose one of
        ``black``, ``red``, ``green``, ``yellow``, ``blue``, ``magenta``
        ``cyan`` or ``white``. Note that the ``bright`` *SGR* impacts
        effective color in most implementations.

def ansi_sgr(text, fg=None, bg=None, style=None, reset=True, **sgr):
    """
    Apply desired SGR commands to given text.

    :param text:
        Text or anything convertible to text
    :param fg:
        (optional) Foreground color. Choose one of
        ``black``, ``red``, ``green``, ``yellow``, ``blue``, ``magenta``
        ``cyan`` or ``white``. Note that the ``bright`` *SGR* impacts
        effective color in most implementations.

    """
    # Ensure that text is really a string
    text = type("")(text)
    # NOTE: SGR stands for "set graphics rendition"
    sgr_list = []  # List of SGR codes
    # Load SGR code associated with desired foreground color
    if isinstance(fg, (str, type(""))):
        try:
            sgr_code = getattr(ANSI, str('sgr_fg_{}'.format(fg)))
        except AttributeError:
            raise ValueError("incorrect foreground color: {!r}".format(fg))
        else:
            sgr_list.append(sgr_code)
    elif isinstance(fg, tuple):
        sgr_code = ANSI.sgr_fg_rgb(*fg)
        sgr_list.append(sgr_code)
    elif isinstance(fg, int):
        if fg < -8:
            assert fg in range(-16, -8), fg
            # -16 to -9: bright colors
            sgr_code = ANSI.sgr_fg_bright(-fg - 8 - 1)
        elif fg < 0:
            # -8 to -1 bright colors
            # Negative numbers represent the classic colors
            assert fg in range(-8, 0), fg
            sgr_code = ANSI.sgr_fg_classic(-fg - 1)
        else:
            assert fg in range(256)
            sgr_code = ANSI.sgr_fg_indexed(fg)
        sgr_list.append(sgr_code)
    elif fg is None:
        pass
    else:
        raise ValueError("incorrect foreground color: {!r}".format(fg))
    # Load SGR code associated with desired background color
    if isinstance(bg, (str, type(""))):
        try:
            sgr_code = getattr(ANSI, str('sgr_bg_{}'.format(bg)))
        except AttributeError:
            raise ValueError("incorrect background color: {!r}".format(bg))
        else:
            sgr_list.append(sgr_code)
    elif isinstance(bg, tuple):
        sgr_code = ANSI.sgr_bg_rgb(*bg)
        sgr_list.append(sgr_code)
    elif isinstance(bg, int):
        if bg < -8:
            assert bg in range(-16, -8), bg
            # -16 to -9: bright colors
            sgr_code = ANSI.sgr_bg_bright(-bg - 8 - 1)
        elif bg < 0:
            # -8 to -1 bright colors
            # Negative numbers represent the classic colors
            assert bg in range(-8, -1), bg
            sgr_code = ANSI.sgr_bg_classic(-bg - 1)
        else:
            assert bg in range(256)
            sgr_code = ANSI.sgr_bg_indexed(bg)
        sgr_list.append(sgr_code)
    elif bg is None:
        pass
    else:
        raise ValueError("incorrect background color: {!r}".format(bg))
    # Load single SGR code for "style"
    if style is not None:
        try:
            sgr_code = getattr(ANSI, str('sgr_{}'.format(style)))
        except AttributeError:
            raise ValueError("incorrect text style: {!r}".format(style))
        else:
            sgr_list.append(sgr_code)
    # Load additional SGR codes (custom)
    for name, active in sgr.items():
        try:
            sgr_code = getattr(ANSI, str('sgr_{}'.format(name)))
        except AttributeError:
            raise ValueError("incorrect custom SGR code: {!r}".format(name))
        else:
            if active:
                sgr_list.append(sgr_code)
    # Combine everything into one sequence
    if reset:
        return ANSI.cmd_sgr(sgr_list) + text + ANSI.cmd_sgr_reset_all
    else:
        return ANSI.cmd_sgr(sgr_list) + text