import uuid
import re


def identifier_str(value=None, allow_prefix=False):
    """Generate or validate a unique identifier.

    If generating, you will get a UUID in hex format

    .. testsetup:: idstr

        from idaes.core.dmf.resource import identifier_str

    .. doctest:: idstr

        >>> identifier_str()  #doctest: +ELLIPSIS
        '...'

    If validating, anything that is not 32 lowercase letters
    or digits will fail.

    .. doctest:: idstr

        >>> identifier_str('A' * 32)   #doctest: +NORMALIZE_WHITESPACE
        Traceback (most recent call last):
        ValueError: Bad format for identifier "AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA":
        must match regular expression "[0-9a-f]{32}"

    Args:
        value (str): If given, validate that it is a 32-byte str
                     If not given or None, set new random value.
    Raises:
        ValuError, if a value is given, and it is invalid.
    """
    # regular expression for identifier: hex string len=32
    if allow_prefix:
        id_expr = "[0-9a-f]{1,32}"
    else:
        id_expr = "[0-9a-f]{32}"
    if value is None:
        value = uuid.uuid4().hex
    elif not re.match(id_expr, value):
        raise ValueError(
            'bad format for identifier "{}": must match '
            'regular expression "{}"'.format(value, id_expr)
        )
    return value