import zlib


def compress_data(data, level=None):
    """Compress data for storage in archive.

    The behaviour is the same as
    [*sqlar_compress*](https://sqlite.org/sqlar/doc/trunk/README.md). The data
    is compressed using the zlib compress convenience function, adding the file
    header and CRC footer. If the compressed data is smaller than the original
    it is returned otherwise the original data is returned.

    Args:
        data: The data to compress.
        level (optional): The level of compression, see the *zlib* documentation
            for allowed values. If it is `None`, `zlib.Z_DEFALUT_COMPRESSION`
            is used.

    Returns:
        The compressed data if it is smaller than the original, otherwise the
        original data.
    """
    level = level if level else zlib.Z_DEFAULT_COMPRESSION

    compressed_data = zlib.compress(data, level=level)
    return compressed_data if len(compressed_data) < len(data) else data