"""Bandwidth optimization utilities for sync payloads."""

from __future__ import annotations

import gzip
import hashlib


class BandwidthOptimizer:
    """Optimize and deduplicate sync payload data."""

    COMPRESSION_THRESHOLD = 1024

    def compress_bundle(self, data: bytes) -> bytes:
        if len(data) < self.COMPRESSION_THRESHOLD:
            return data
        return gzip.compress(data, compresslevel=6)

    def decompress_bundle(self, data: bytes) -> bytes:
        try:
            return gzip.decompress(data)
        except gzip.BadGzipFile:
            return data

    def compute_content_hashes(self, memory_texts: list[str]) -> set[str]:
        return {hashlib.sha256(text.encode("utf-8")).hexdigest()[:16] for text in memory_texts}

    def filter_already_synced(self, bundle_hashes: set[str], local_hashes: set[str]) -> set[str]:
        return bundle_hashes - local_hashes
