def scramble_id(seq_id):
    """
    This is called a feistel chipher.
    It creates a pseudo random, but unique identifier from a number.
    It can be used instead of sequential primary keys in api functions
    to prevent exposing backend details.
    It is its own inverse, so converting back is done by calling it again.

    In case of an id other than an unsigned integer in the 32 bit range we
    assume its a uuid or similar and we return it as is.

    further reading: https://wiki.postgresql.org/wiki/Pseudo_encrypt
    """
    try:
        val = int(seq_id) & 4294967295
    except ValueError:
        return seq_id
    if val != int(seq_id):
        return seq_id
    l1 = val >> 16 & 65535
    r1 = val & 65535
    for _ in range(0, 3):
        l2 = r1
        r2 = l1 ^ int(round((1366 * r1 + 150889) % 714025 / 714025.0 * 32767)
            ) & 4294967295
        l1 = l2
        r1 = r2
    return ((r1 & 65535) << 16) + l1
