from typing import Optional
from typing import Union
from typing import List


def normalize_scopes(
    v: Optional[Union[str, List[str]]]
) -> Optional[List[str]]:
    """Pydantic validator for scope fields.

    Scopes are stored in the database as a comma-delimited, sorted list.
    Convert to the list representation we want to use in Python, preserving
    `None`.

    Parameters
    ----------
    v : `str` or List[`str`] or `None`
        The field representing token scopes.

    Returns
    -------
    v : List[`str`] or `None`
        The scopes as a list.
    """
    if v is None:
        return None
    elif isinstance(v, str):
        return [] if v == "" else v.split(",")
    else:
        return v