"""First strict byte loss for two deterministic positive-length streams."""
import json
from math import comb
from gamma23 import decode as gamma
from longueur22 import header,decode as aligned
from global21 import study as payload, pack, unrank

def study():
    rows=[]
    for profile in (0,1):
        n=0;wins=ties=0
        while True:
            n+=1
            # Alternation permits typed runs of length one only. For weight four,
            # even one word saves 16 payload bits for at most 13 overhead bits.
            bits=1+(min(32*n,16*n+13*((n+63)//64)) if profile else 32*n)
            g=2*n.bit_length()-1
            gamma_bytes=(g+bits+7)//8
            byte_bytes=len(header(n))+(bits+7)//8
            if gamma_bytes>byte_bytes:break
            wins+=gamma_bytes<byte_bytes;ties+=gamma_bytes==byte_bytes
        wires=[]
        for k in (n-1,n):
            weights=[4 if profile else (16,15)[j%2] for j in range(k)]
            d=payload(weights)
            assert d['bits']==1+(min(32*k,16*k+13*((k+63)//64)) if profile else 32*k)
            body=bytes.fromhex(d['wire']);raw=''.join(f'{v:08b}' for v in body)[:d['bits']]
            w=pack('0'*(k.bit_length()-1)+format(k,'b')+raw);v=header(k)+body
            expected=[unrank(32,h,(17+7919*j)%comb(32,h)) for j,h in enumerate(weights)]
            assert gamma(w)==aligned(v)==expected and (len(w)>len(v))==(k==n)
            wires.append(dict(n=k,body_bits=d['bits'],gamma=len(w),byte=len(v),gamma_hex=w.hex(),byte_hex=v.hex()))
        rows.append(dict(profile=profile,first=n,prior_wins=wins,prior_ties=ties,rows=wires))
    return rows
if __name__=='__main__':print(json.dumps(study()))
