"""Indexed delta blocks on a finite real CRT constellation, with exact bounds."""
from bisect import bisect_right
from math import gcd
import json


def encode(n):
    data=bytearray()
    while n>=128:
        data.append(128+(n&127));n>>=7
    data.append(n)
    return data


def experiment():
    period=2*3*5*7*11*13
    positions=[x for x in range(period) if all(gcd(x+h,period)==1 for h in (0,2,6))]
    results=[]
    for stride in (8,16,32,64):
        anchors=[];offsets=[];payload=bytearray()
        for i,pos in enumerate(positions):
            if i%stride==0: anchors.append(pos);offsets.append(len(payload))
            else: payload.extend(encode(pos-positions[i-1]))
        max_reads=0
        for q in range(period):
            b=bisect_right(anchors,q)-1
            count=0
            if b>=0:
                count=b*stride+1;pos=anchors[b];j=offsets[b];reads=0
                while count<min((b+1)*stride,len(positions)):
                    delta=0;shift=0
                    while True:
                        octet=payload[j];j+=1;delta|=(octet&127)<<shift
                        if octet<128:break
                        shift+=7
                    reads+=1;pos+=delta
                    if pos>q:break
                    count+=1
                max_reads=max(max_reads,reads)
            assert count==bisect_right(positions,q)
        assert max(anchors+offsets)<65536
        results.append(dict(stride=stride,bytes=len(payload)+4*len(anchors),max_decodes=max_reads))
    return dict(period=period,count=len(positions),packed_u16=2*len(positions),blocks=results)


if __name__=='__main__': print(json.dumps(experiment(),indent=2))
