from typing import Tuple
import re
import typing


def hex_to_rgb(hex: str, hsl: bool = False) -> Tuple[int, int, int]:
    """Converts a HEX code into RGB or HSL.

    Taken from https://stackoverflow.com/a/62083599/7853533

    Args:
        hex (str): Takes both short as well as long HEX codes.
        hsl (bool): Converts the given HEX code into HSL value if True.

    Returns:
        Tuple[int, int, int]: Tuple of RGB values.

    Raises:
        ValueError: If given value is not a valid HEX code.
    """
    if re.compile(r"#[a-fA-F0-9]{3}(?:[a-fA-F0-9]{3})?$").match(hex):
        div = 255 if hsl else 0
        if len(hex) <= 4:
            rgb = tuple(
                int(int(hex[i] * 2, 16) / div) if div else int(hex[i] * 2, 16)
                for i in (1, 2, 3)
            )
        else:
            rgb = tuple(
                int(int(hex[i : i + 2], 16) / div) if div else int(hex[i : i + 2], 16)
                for i in (1, 3, 5)
            )
        rgb = typing.cast(Tuple[int, int, int], rgb)
        return rgb
    raise ValueError(f"{hex} is not a valid HEX code.")