"""
Solution: Lab 10's logic for scripts 03_resharding.py and 04_ids.py (partitioner.py, the router
in service/app.py, the balance check, and snowflake.py): which users move when a shard joins the
ring, what a switch costs while rows are copied, how a dual ring finds every row, how to check
that no confirmed update was lost or doubled, and a Snowflake generator that survives a clock
stepping back.
"""
import bisect
import hashlib

# --- given -------------------------------------------------------------------------------------


def h64(key):
    """The lab's stable 64-bit hash of str(key) (BLAKE2b, 8 bytes)."""
    return int.from_bytes(hashlib.blake2b(str(key).encode(), digest_size=8).digest(), "big")


class FakeClock:
    """snowflake.py's controlled clock: 1 ms passes every `reads_per_ms` reads; jump() moves it."""

    def __init__(self, start_ms=1_000_000, reads_per_ms=1):
        self.ms, self.reads, self.reads_per_ms = start_ms, 0, reads_per_ms

    def __call__(self):
        self.reads += 1
        if self.reads % self.reads_per_ms == 0:
            self.ms += 1
        return self.ms

    def jump(self, delta_ms):
        self.ms += delta_ms


MACHINE_BITS, SEQ_BITS = 10, 12
MAX_SEQ = (1 << SEQ_BITS) - 1

# --- the ring ----------------------------------------------------------------------------------


def build_ring(shards, vnodes):
    """The consistent-hash ring: a sorted list of (h64(f"{shard}#{v}"), shard) for v in 0..vnodes-1."""
    return sorted((h64(f"{s}#{v}"), s) for s in shards for v in range(vnodes))


def shard_for(ring, key):
    """The owner of the first mark strictly after h64(key), going clockwise (wrap round at the end)."""
    points = [p for p, _ in ring]
    i = bisect.bisect_right(points, h64(key))
    return ring[i % len(ring)][1]


def moved_users(old_ring, new_ring, users):
    """{old shard: [users whose shard changes]}, as 03_resharding.py picks the rows to copy."""
    moved = {}
    for u in users:
        a, b = shard_for(old_ring, u), shard_for(new_ring, u)
        if a != b:
            moved.setdefault(a, []).append(u)
    return moved


def modulo_shard(key, shards):
    """The remainder scheme: shards[h64(key) % len(shards)]."""
    return shards[h64(key) % len(shards)]


def expected_misses(rate_per_s, copy_s, moved_share):
    """Steady-copy model: requests for a row not yet on its new shard while the copy runs.
    The share still missing falls evenly from moved_share to 0, so on average it's half."""
    return rate_per_s * copy_s * moved_share / 2


# --- the router ------------------------------------------------------------------------------
# store: {shard: {user: balance}}. old_ring is None for "switch, then copy"; given, it's the dual ring.


def read(store, uid, new_ring, old_ring=None):
    """The balance, or None for a 404. Dual ring: on a miss, read the user's old shard."""
    new = shard_for(new_ring, uid)
    if uid in store[new]:
        return store[new][uid]
    if old_ring is not None:
        old = shard_for(old_ring, uid)
        if old != new and uid in store[old]:
            return store[old][uid]
    return None


def move_row(store, uid, old, new):
    """Take the row out of the old shard and put it on the new one. If the copy job already put it
    there, do nothing: it's the same row (writes never go to the old shard during the move)."""
    if uid in store[old]:
        balance = store[old].pop(uid)
        store[new].setdefault(uid, balance)


def add(store, uid, amount, new_ring, old_ring=None):
    """Add to the balance on the user's new shard; True if done, False for a 404 (refused).
    Dual ring: if the row isn't there yet, move it from the old shard first, then update."""
    new = shard_for(new_ring, uid)
    if uid not in store[new] and old_ring is not None:
        old = shard_for(old_ring, uid)
        if old != new:
            move_row(store, uid, old, new)
    if uid not in store[new]:
        return False
    store[new][uid] += amount
    return True


def check_balances(store, initial, acked):
    """Every user's final balance against initial + the updates the client was told succeeded.
    initial: {user: balance}; acked: {user: total of acknowledged amounts}.
    Returns {"missing", "on_two_shards", "short", "over"}: counts of users."""
    final, copies = {}, {}
    for rows in store.values():
        for u, b in rows.items():
            final[u] = final.get(u, 0) + b
            copies[u] = copies.get(u, 0) + 1
    out = {"missing": 0, "on_two_shards": 0, "short": 0, "over": 0}
    for u, b0 in initial.items():
        n = copies.get(u, 0)
        if n == 0:
            out["missing"] += 1
        elif n > 1:
            out["on_two_shards"] += 1
        diff = final.get(u, 0) - (b0 + acked.get(u, 0))
        if n and diff < 0:
            out["short"] += 1
        elif n and diff > 0:
            out["over"] += 1
    return out


# --- Snowflake IDs ---------------------------------------------------------------------------


def compose(ms, machine, seq):
    """ms in the top bits, then 10 bits of machine, then 12 bits of counter."""
    return (ms << (MACHINE_BITS + SEQ_BITS)) | (machine << SEQ_BITS) | seq


class NaiveSnowflake:
    """Trusts the clock: a new millisecond (any other one, even an earlier one) restarts the counter."""

    def __init__(self, machine, clock):
        self.machine, self.clock = machine, clock
        self.last_ms, self.seq = -1, 0

    def next_id(self):
        ms = self.clock()
        if ms == self.last_ms:
            self.seq = (self.seq + 1) & MAX_SEQ
            if self.seq == 0:                       # 4,096 used this millisecond: wait for the next
                while ms <= self.last_ms:
                    ms = self.clock()
        else:
            self.seq = 0
        self.last_ms = ms
        return compose(ms, self.machine, self.seq)


class ClockWentBackwards(RuntimeError):
    pass


class Snowflake(NaiveSnowflake):
    """Remembers the last millisecond. Clock behind it: wait (reading the clock) until it isn't,
    adding how far behind it was to waited_ms; more than max_wait_ms behind: raise ClockWentBackwards."""

    def __init__(self, machine, clock, max_wait_ms=50):
        super().__init__(machine, clock)
        self.max_wait_ms, self.waited_ms = max_wait_ms, 0

    def next_id(self):
        ms = self.clock()
        if ms < self.last_ms:
            behind = self.last_ms - ms
            if behind > self.max_wait_ms:
                raise ClockWentBackwards(f"clock is {behind} ms behind the last ID")
            while ms < self.last_ms:
                ms = self.clock()
            self.waited_ms += behind
        if ms == self.last_ms:
            self.seq = (self.seq + 1) & MAX_SEQ
            if self.seq == 0:
                while ms <= self.last_ms:
                    ms = self.clock()
        else:
            self.seq = 0
        self.last_ms = ms
        return compose(ms, self.machine, self.seq)
