import hashlib

from ..views.version import GIT_HASH


def compute_cache_version(shop):
    """Opaque token that changes when deploys land or the ring is reforged.

    Clients compare this to their localStorage copy; mismatch means
    cached ring state (ringProductIds, ringPosition, ringHistory) is
    stale and should be dropped before the next SPA navigation.

    Inputs:
        GIT_HASH — shifts on every deploy
        shop.json_discovery_ring — shifts on every reforge (including
            product adds/removes/visibility flips that trigger reforge)
    """
    ring_str = (shop.json_discovery_ring or "") if shop is not None else ""
    digest = hashlib.md5(f"{GIT_HASH}:{ring_str}".encode()).hexdigest()
    return digest[:12]


def apply_no_store_headers(response):
    """Tell browsers not to cache this HTML response — always revalidate."""
    response.headers["Cache-Control"] = "no-store, must-revalidate"
    response.headers["Pragma"] = "no-cache"
    response.headers["Expires"] = "0"
