"""
Practice: 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.

Fill in the TODOs, then run the tests:
    pytest test_reshard_practice.py        (locally)
or press "Run tests" on the chapter page.
"""
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."""
    # TODO
    raise NotImplementedError


def shard_for(ring, key):
    """The owner of the first mark strictly after h64(key), going clockwise (wrap round at the end)."""
    # TODO
    raise NotImplementedError


def moved_users(old_ring, new_ring, users):
    """{old shard: [users whose shard changes]}, as 03_resharding.py picks the rows to copy."""
    # TODO
    raise NotImplementedError


def modulo_shard(key, shards):
    """The remainder scheme: shards[h64(key) % len(shards)]."""
    # TODO
    raise NotImplementedError


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."""
    # TODO
    raise NotImplementedError


# --- 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."""
    # TODO
    raise NotImplementedError


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)."""
    # TODO
    raise NotImplementedError


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."""
    # TODO
    raise NotImplementedError


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."""
    # TODO
    raise NotImplementedError


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


def compose(ms, machine, seq):
    """ms in the top bits, then 10 bits of machine, then 12 bits of counter."""
    # TODO
    raise NotImplementedError


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):
        # TODO
        raise NotImplementedError


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):
        # TODO
        raise NotImplementedError
