"""A bit-packed gamma count followed by the meaningful global-mode bits."""
from math import comb
import json
from global21 import study as payload,pack,unpack,unrank
from longueur22 import header


def decode(wire):
    bits=''.join(format(b,'08b') for b in wire)
    k=bits.find('1')
    if k<0 or 2*k+1>=len(bits):raise ValueError('invalid gamma header')
    n=int(bits[k:2*k+1],2);body=bits[2*k+1:];pos=1;count=0
    if body[0]=='0':pos+=32*n
    else:
        while count<n:
            if pos+7>len(body):raise ValueError('truncated block')
            mode=body[pos];length=1+int(body[pos+1:pos+7],2);pos+=7;width=32
            if mode=='1':
                if pos+6>len(body):raise ValueError('missing weight')
                w=int(body[pos:pos+6],2);pos+=6
                if w>32:raise ValueError('invalid weight')
                width=(comb(32,w)-1).bit_length()
            count+=length;pos+=length*width
        if count!=n:raise ValueError('excess words')
    if pos>len(body) or len(body)-pos>=8 or '1' in body[pos:]:raise ValueError('invalid end')
    return unpack(pack(body[:pos]),n)


def study():
    out=[]
    for n in (7,8,15,16,127,128):
        for profile in (0,1):
            weights=[(16,15)[i%2] if profile==0 else 4 for i in range(n)]
            d=payload(weights);body=''.join(format(b,'08b') for b in bytes.fromhex(d['wire']))[:d['bits']]
            prefix='0'*(n.bit_length()-1)+format(n,'b')
            wire=pack(prefix+body)
            expected=[unrank(32,k,(17+7919*i)%comb(32,k)) for i,k in enumerate(weights)]
            assert decode(wire)==expected
            for bad in (wire[:-1],wire+b'\x00'):
                try:decode(bad)
                except ValueError:pass
                else:raise AssertionError('accepted invalid end')
            out.append(dict(n=n,profile=profile,gamma=len(wire),byte=len(header(n))+d['bytes'],prefix_bits=len(prefix),body_bits=d['bits'],wire=wire.hex()))
    return out
if __name__=='__main__':print(json.dumps(study()))
