import base64 import json import uuid from bisect import bisect_right def _key(item: dict): return (item["created_at"], uuid.UUID(item["id"]).int) def encode_cursor(scope: str, created_at: str, item_id: str) -> str: raw = json.dumps({"s": scope, "c": created_at, "i": item_id}, separators=(",", ":")).encode() return base64.urlsafe_b64encode(raw).decode().rstrip("=") def decode_cursor(value: str): try: raw = base64.urlsafe_b64decode(value + "=" * (-len(value) % 4)) obj = json.loads(raw) except Exception: return None if not isinstance(obj, dict) or not obj.get("c") or not obj.get("i"): return None return obj def paginate(items: list[dict], scope: str, limit_raw, cursor_raw): if not limit_raw: limit = 50 else: try: limit = int(limit_raw) except (ValueError, TypeError): return None, None, "invalid_request" if limit < 1 or limit > 100: return None, None, "invalid_request" ordered = sorted(items, key=_key) keys = [_key(x) for x in ordered] start = 0 if cursor_raw: cur = decode_cursor(cursor_raw) if cur is None or cur.get("s") != scope: return None, None, "invalid_request" try: cursor_key = (cur["c"], uuid.UUID(cur["i"]).int) except (KeyError, ValueError, TypeError): return None, None, "invalid_request" start = bisect_right(keys, cursor_key) page = ordered[start:start + limit] next_cursor = None if start + limit < len(ordered): last = page[-1] next_cursor = encode_cursor(scope, last["created_at"], last["id"]) return page, next_cursor, None