"""A cursor-paginated list client, in about forty lines.

The server includes the cursor row in every page (the row you last saw) and
reports `has_more`. `has_more` is what lets a caller stop. Get it wrong and the
caller either stops early or loops forever.
"""
import sys

ROWS = [{"lt": i, "tx": f"tx{i}"} for i in range(1, 11)]  # 10 rows, newest first

def server_page(cursor, n):
    """Server: up to n rows starting at the cursor row, plus its own has_more."""
    start = 0 if cursor is None else next(i for i, r in enumerate(ROWS) if r["lt"] == cursor)
    window = ROWS[start:start + n]
    return window, start + len(window) < len(ROWS)

def fetch_page_buggy(cursor, limit):
    rows, _ = server_page(cursor, limit + 1)             # over-fetch by one, for has_more
    if cursor is not None:
        rows = [r for r in rows if r["lt"] != cursor]    # drop the row we already showed
    has_more = len(rows) > limit                         # <-- the bug: can never be true when paging
    return rows[:limit], has_more

def fetch_page_fixed(cursor, limit):
    n = limit + (2 if cursor is not None else 1)         # cursor row + one probe row
    rows, _ = server_page(cursor, n)
    if cursor is not None:
        rows = [r for r in rows if r["lt"] != cursor]
    has_more = len(rows) > limit                         # still true after the drop
    return rows[:limit], has_more

def test_page_two_does_not_repeat_the_cursor_row(fetch):
    page1, more1 = fetch(None, 3)
    assert [r["lt"] for r in page1] == [1, 2, 3]
    page2, more2 = fetch(page1[-1]["lt"], 3)
    assert 3 not in [r["lt"] for r in page2]      # the assertion the suite had
    assert [r["lt"] for r in page2] == [4, 5, 6]
    print(f"  page1 lts={[r['lt'] for r in page1]} has_more={more1}")
    print(f"  page2 lts={[r['lt'] for r in page2]} has_more={more2}   (4 rows remain)")

def drain(fetch):
    t, seen, pages = None, [], 0
    while True:
        p, more = fetch(t, 3)
        seen += [r["lt"] for r in p]; pages += 1
        t = p[-1]["lt"] if p else t
        if not more or pages > 10:
            return seen, pages, more

if __name__ == "__main__":
    fixed = "--fixed" in sys.argv
    fetch = fetch_page_fixed if fixed else fetch_page_buggy
    print(("fixed" if fixed else "buggy") + ":")
    test_page_two_does_not_repeat_the_cursor_row(fetch)
    seen, pages, more = drain(fetch)
    print(f"  drained: {len(seen)} of {len(ROWS)} rows in {pages} pages, unique={len(set(seen))}, last_has_more={more}")
