"""
Practice: splitting data across shards. Lab 10's logic for 01_partitioning.py (Exercise 1) and
02_shards.py, from partitioner.py and service/app.py: the remainder rule (modulo), a ring with
points per shard (consistent hashing), how many keys move when a shard is added, how uneven the
shards are, a hot counter split into rows, and what a query over every shard waits for.

Fill in the TODOs, then run the tests:
    pytest test_shard_practice.py        (locally)
or press "Run tests" on the chapter page.
"""
import bisect
import hashlib


def h64(key):
    """A stable 64-bit hash of str(key): BLAKE2b, as in the lab's partitioner.py. (Python's own
    hash() changes from process to process, so it can't decide where data lives.) Given."""
    return int.from_bytes(hashlib.blake2b(str(key).encode(), digest_size=8).digest(), "big")


def modulo_shard(key, shards):
    """The remainder rule: the shard at position h64(key) % len(shards)."""
    return shards[h64(key) % len(shards)]


def share_that_stays(n_old, n_new):
    """Under the remainder rule, the share of hashes whose shard is the same with n_old and with
    n_new shards. The remainders repeat every n_old * n_new numbers (4 × 5 = 20), so counting
    0 .. n_old * n_new - 1 is exact."""
    span = n_old * n_new
    return sum(h % n_old == h % n_new for h in range(span)) / span


def build_ring(shards, vnodes):
    """The ring: each shard gets `vnodes` points, at h64(f"{shard}#{i}") for i in 0 .. vnodes-1.
    Return a list of (point, shard), sorted by point."""
    return sorted((h64(f"{s}#{i}"), s) for s in shards for i in range(vnodes))


def ring_shard(ring, key):
    """The shard of the first point after h64(key), going clockwise; past the last point, wrap
    round to the first. (A key exactly on a point belongs to the next one, as in the lab.)"""
    # (h, "\uffff") sorts after every (h, shard), so this is bisect_right on the points alone,
    # without building a list of points on every call.
    i = bisect.bisect_right(ring, (h64(key), "\uffff"))
    return ring[i % len(ring)][1]


def arc_shares(ring):
    """Each shard's share of the ring: a point owns the stretch from the previous point up to
    itself (the first point's stretch wraps round from the last). Return {shard: share}."""
    full = 2 ** 64
    out = {}
    for i, (p, s) in enumerate(ring):
        prev = ring[i - 1][0] if i > 0 else ring[-1][0] - full
        out[s] = out.get(s, 0.0) + (p - prev) / full
    return out


def moves(before, after, keys):
    """before and after are functions key -> shard. Return {(from, to): number of keys} for the
    keys whose shard changed."""
    out = {}
    for k in keys:
        a, b = before(k), after(k)
        if a != b:
            out[(a, b)] = out.get((a, b), 0) + 1
    return out


def imbalance(counts):
    """Busiest ÷ average (1 = perfectly even). counts: {shard: keys or requests}."""
    vals = list(counts.values())
    return max(vals) / (sum(vals) / len(vals))


def like_key(post, split, row):
    """The key a like is stored under. One row (split 1): str(post). Split K: f"{post}#{row}",
    where the router picks row at random from 0 .. K-1."""
    return str(post) if split <= 1 else f"{post}#{row}"


def shards_to_read(ring, post, split):
    """Reading the count adds up all the rows: the sorted list of shards that hold one."""
    return sorted({ring_shard(ring, like_key(post, split, r)) for r in range(max(split, 1))})


def expected_like_shares(ring, post, split, hot_share):
    """Each shard's expected share of all likes: the hot post's hot_share spread over its rows
    (each row gets 1/split of it), plus the rest (1 - hot_share), spread like keys: by each
    shard's share of the ring. Return {shard: share}."""
    arcs = arc_shares(ring)
    out = {s: (1 - hot_share) * a for s, a in arcs.items()}
    for r in range(max(split, 1)):
        s = ring_shard(ring, like_key(post, split, r))
        out[s] += hot_share / max(split, 1)
    return out


def scatter_gather_ms(shard_ms):
    """A query that asks every shard and merges the answers finishes when the last shard
    answers: its time, given each shard's time."""
    return max(shard_ms)
