import random


def generate_smallest_secret(poly_degree, crc_length, min_size=0, echo=False):
    """ Helper function to generate smallest secret which is:
        - divisible by 8, so that it can be encoded to bytes
        - secret length + crc_length is divisible by poly_degree + 1
            to be able to split secret into coefficients for polynomial
        :param poly_degree: polynomial degree as int
        :param crc_length: CRC length as int
        :param min_size: minimum bit size as int
        :param echo: if True, printing intermediate messages to console
        :returns bytes """

    if min_size % 8 == 0:
        candidate_size = min_size
    else:
        candidate_size = min_size + (8 - (min_size % 8))
    assert candidate_size % 8 == 0
    while not ((candidate_size + crc_length) % (poly_degree + 1) == 0):
        candidate_size += 8
    # generate random secret
    secret_int = random.randint(0, 2 ** candidate_size - 1)
    assert candidate_size % 8 == 0
    secret_bytes = secret_int.to_bytes(candidate_size // 8, byteorder='big')
    if echo:
        print('Secret size is {} bits'.format(candidate_size))
        print('Secret bytes are {}'.format(secret_bytes))
    return secret_bytes