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

One working version of durability_practice.py.
"""
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."""
    return ok_at not in EMPTIED[crash]


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."""
    body = struct.pack("<II", len(key), len(value)) + key + value
    return struct.pack("<I", zlib.crc32(body)) + body


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
    """
    pos, n = 0, len(buf)
    while pos + 12 <= n:
        crc, klen, vlen = struct.unpack_from("<III", buf, pos)
        end = pos + 12 + klen + vlen
        if end > n:
            return pos, "past end"
        if zlib.crc32(buf[pos + 4:end]) != crc:
            return pos, "checksum"
        pos = end
    return pos, ("clean" if pos == n else "short header")


def us_per_write(writes_per_second):
    """Microseconds per write at a given rate."""
    return 1e6 / writes_per_second


def slowdown(fast_rate, slow_rate):
    """How many times slower the slow rate is than the fast one."""
    return fast_rate / slow_rate


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)."""
    return sum(1 for i in acked if i not in present)


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%)."""
    return sum(lost for _, lost in rounds) / sum(acked for acked, _ in rounds)
