import uuid


def get_user_uuid(details, backend, response, user=None, *args, **kwargs):
    """Add `uuid` argument to the pipeline.

    Makes `uuid` argument available to other pipeline entries.

    If the backend provides `get_user_uuid` method (as is the case with
    the ADFS backends and Keycloak suomi.fi backend), it is used to
    generate the UUID. Otherwise, the UUID is generated with `uuid.uuid1`
    function.

    The argument is named same as the django-helusers `uuid` field.
    This allows syncing the helusers `uuid`-field with uuid generated
    here using SOCIAL_AUTH_backend_name_USER_FIELDS.
    """

    if user and getattr(user, 'uuid'):
        return {
            'uuid': user.uuid,
        }
    if callable(getattr(backend, 'get_user_uuid', None)):
        new_uuid = backend.get_user_uuid(details, response)
    else:
        new_uuid = uuid.uuid1()

    return {
        'uuid': new_uuid,
    }