"""
Practice: did the write survive? Lab 04's durability arithmetic (scripts 01_kvstore.py and
04_durability.py, and the record format in kvstore/records.py): where a write can be when OK
is said, which crash empties which place, how a store finds the end of its last complete
record after a power cut, what a flush costs, and how many acknowledged writes a crash lost.

Fill in the TODOs, then run the tests:
    pytest test_durability_practice.py        (locally)
or press "Run tests" on the chapter page.
"""
import struct
import zlib

# Where a write can be, in order: the program's own memory, the operating system's memory,
# the drive's own cache, the disk itself.
PLACES = ["program", "os", "drive cache", "disk"]

# What each kind of crash empties.
EMPTIED = {
    "program killed": {"program"},
    "power cut": {"program", "os", "drive cache"},
}


def survives(ok_at, crash):
    """True if a write acknowledged while it was at place `ok_at` (one of PLACES) is still there
    after `crash` (a key of EMPTIED). The write only moves further right after the OK, so what
    matters is where it was when OK was said."""
    # TODO
    raise NotImplementedError


def encode(key, value):
    """One record in the lab's format: crc32 (4 bytes), key length (4), value length (4), all
    little-endian unsigned ints, then the key and the value. The crc32 (zlib.crc32) covers
    everything after itself: the two lengths, the key and the value."""
    # TODO
    raise NotImplementedError


def recover(buf):
    """Read records from the start of `buf` and stop at the first one that is incomplete or
    fails its checksum. Return (valid_length, reason): the number of bytes made of complete,
    valid records, and why the scan stopped:
      "clean"        - it ended exactly at the end of buf
      "short header" - fewer than 12 bytes were left
      "past end"     - the record's lengths say it runs past the end of buf
      "checksum"     - the record is all there but its crc32 doesn't match
    """
    # TODO
    raise NotImplementedError


def us_per_write(writes_per_second):
    """Microseconds per write at a given rate."""
    # TODO
    raise NotImplementedError


def slowdown(fast_rate, slow_rate):
    """How many times slower the slow rate is than the fast one."""
    # TODO
    raise NotImplementedError


def lost_acknowledged(acked, present):
    """How many of the acknowledged ids (`acked`, a list) are missing from `present` (a set of
    ids found after the restart)."""
    # TODO
    raise NotImplementedError


def share_lost(rounds):
    """`rounds` is a list of (acknowledged, lost) pairs, one per kill. Return the share of all
    acknowledged writes that were lost, as a fraction (0.05 = 5%)."""
    # TODO
    raise NotImplementedError
