"""Identify width and a fixed header-padding offset using adaptive exact byte-gap queries."""
from functools import lru_cache
from itertools import product
import json

def gap(n,w,h):
    b=n.bit_length();body=1+13*((n+63)//64)+n*w+h
    return (body+2*b+6)//8-(body+7)//8-(b+6)//7

def design(states,max_n=2048):
    masks={};full=(1<<len(states))-1
    for n in range(1,max_n+1):
        values=[gap(n,*z) for z in states];a,b=min(values),max(values)
        if a==b:continue
        assert b==a+1
        mask=sum(1<<i for i,x in enumerate(values) if x==b)
        masks.setdefault(mask,(n,b))
    ordered=sorted(masks)
    @lru_cache(None)
    def tree(mask,depth):
        size=mask.bit_count()
        if size==1:return mask.bit_length()-1
        if size>1<<depth:return None
        splits=sorted([(abs(size-2*(mask&m).bit_count()),m) for m in ordered if 0<(mask&m)<mask])
        for _,m in splits:
            low,high=mask&~m,mask&m
            if max(low.bit_count(),high.bit_count())>1<<(depth-1):continue
            left=tree(low,depth-1)
            if left is None:continue
            right=tree(high,depth-1)
            if right is not None:return [*masks[m],left,right]
        return None
    for depth in range((len(states)-1).bit_length(),12):
        root=tree(full,depth)
        if root is not None:break
    else:raise ValueError('no identification')
    traces=[]
    for i,(w,h) in enumerate(states):
        node=root;path=[]
        while isinstance(node,list):
            n,b,left,right=node;v=gap(n,w,h);path.append([n,v]);node=right if v==b else left
        assert node==i;traces.append(path)
    return dict(states=states,depth=depth,patterns=len(masks),max_n=max_n,tree=root,traces=traces)
if __name__=='__main__':print(json.dumps([design([(w,0) for w in range(8)]),design(list(product(range(8),repeat=2)))]))
