import lz4.block
import zstandard

zst_cctx = zstandard.ZstdCompressor(level=1, threads=1, write_checksum=False)


def compress_zstd(data):
    if len(data) > 128:
        return zst_cctx.compress(data)
    else:
        return data


def decompress_zstd(data):
    if data[:4] == b"(\xb5/\xfd":
        return zstandard.decompress(data)
    else:
        return data


def compress_lz4(data):
    if len(data) > 1024:
        return lz4.block.compress(data, mode="fast", acceleration=1, compression=1)
    else:
        return data


def decompress_lz4(data):
    # todo this is really bad maybe always compress instead
    if (data[0] == b"{" and data[-1] == b"}") or data[:2] == b"\x80\x04":
        return data
    return lz4.block.decompress(data)


compressors = {
    "zstd": (compress_zstd, decompress_zstd),
    "lz4": (compress_lz4, decompress_lz4),
    "raw": (lambda x: x, lambda x: x),
}
