"""
Solution: pagination and breaking schema changes. Lab 06's logic for scripts 02_pagination.py
and 06_contracts.py (pagination.py and compat.py): page by offset and by cursor, page through a
stack that changes while you read and count what went wrong, and see why an old Protobuf reader
finds a total of 0 without an error.
"""
import random


def offset_page(stack, k, size=100):
    """Page k (0 = the first) by offset: skip k * size orders from the top, take size.
    stack: order ids, newest first."""
    return stack[k * size:(k + 1) * size]


def cursor_page(stack, last_seen, size=100):
    """The next page by cursor: the size newest orders with an id lower than last_seen.
    last_seen is None for the first page."""
    return [i for i in stack if last_seen is None or i < last_seen][:size]


def duplicates_and_skips(pages, present_throughout, low, high):
    """The lab's counter. pages: the ids on each page, in order. present_throughout: ids that
    existed for the whole run. low..high: the id range the reader covered.
    Return {"rows_returned", "duplicates", "skips"}: a duplicate is an id seen twice; a skip is
    an id present the whole time, inside the range, never seen."""
    seen = [i for p in pages for i in p]
    expected = {i for i in present_throughout if low <= i <= high}
    return {"rows_returned": len(seen), "duplicates": len(seen) - len(set(seen)),
            "skips": len(expected - set(seen))}


def paging_run(method, inserts, deletes, n_pages=50, size=100, first=9_980_001, last=10_000_000, seed=3):
    """The lab's Exercise 2 on a list instead of a database. Start with ids first..last, newest
    first. For each of n_pages pages: read a page ("offset" or "cursor"), then add `inserts` new
    orders on top (ids last + 1, last + 2, ...), then remove `deletes` orders the reader has already
    seen and that are still there, picked with random.Random(seed).sample, as the lab does.
    Return duplicates_and_skips(pages with only the ids that were there at the start,
    those ids minus the removed ones, the lowest id returned, last)."""
    stack = list(range(last, first - 1, -1))
    start = set(stack)
    next_id = last + 1
    rng = random.Random(seed)
    pages, deleted, last_seen = [], set(), None
    for k in range(n_pages):
        ids = offset_page(stack, k, size) if method == "offset" else cursor_page(stack, last_seen, size)
        pages.append(ids)
        last_seen = ids[-1]
        for _ in range(inserts):
            stack.insert(0, next_id)
            next_id += 1
        seen = [i for p in pages for i in p if i not in deleted]
        for i in rng.sample(seen, min(deletes, len(seen))):
            stack.remove(i)
            deleted.add(i)
    low = min(i for p in pages for i in p)
    return duplicates_and_skips([[i for i in p if i in start] for p in pages], start - deleted, low, last)


def expected_errors(n_pages, inserts, deletes):
    """Offset's errors, predicted: every gap between two pages shifts the stack by
    inserts - deletes. Return (duplicates, skips)."""
    shift = (n_pages - 1) * (inserts - deletes)
    return (max(shift, 0), max(-shift, 0))


def read_varint(data, pos):
    """Read one Protobuf varint at data[pos]: 7 bits per byte, low bits first; a byte with the
    top bit set means another byte follows. Return (value, position after it)."""
    value, shift = 0, 0
    while True:
        b = data[pos]
        pos += 1
        value |= (b & 0x7F) << shift
        if b < 0x80:
            return value, pos
        shift += 7


def read_whole_number(data, field):
    """What an old reader finds in box `field` if its form says that box holds a whole number
    (a varint). Walk the message: each value starts with a tag varint, tag = field * 8 + wire
    type. Wire type 0: a varint. 2: a varint length, then that many bytes. 1: 8 bytes. 5: 4 bytes.
    Skip anything that isn't (field, type 0). No such value: 0, the default, and no error."""
    pos, found = 0, 0
    while pos < len(data):
        tag, pos = read_varint(data, pos)
        number, wire = tag >> 3, tag & 7
        if wire == 0:
            value, pos = read_varint(data, pos)
            if number == field:
                found = value
        elif wire == 2:
            n, pos = read_varint(data, pos)
            pos += n
        elif wire == 1:
            pos += 8
        elif wire == 5:
            pos += 4
        else:
            raise ValueError(f"unknown wire type {wire}")
    return found


def breaking_json(old, new):
    """A response checker, as compat.json_schema_changes does it for old clients reading new
    responses. old, new: {field name: set of JSON types it can have}. Return a sorted list of
    problems: "removed: <name>" for a field the old schema had and the new one doesn't, and
    "type changed: <name>" when the new schema allows a type the old one didn't. A new field is
    fine (old clients ignore it)."""
    out = []
    for name in old:
        if name not in new:
            out.append(f"removed: {name}")
        elif new[name] - old[name]:
            out.append(f"type changed: {name}")
    return sorted(out)
