"""Replay the constructive unrestricted bounds in pagedata/dyadic-firsts.txt.

Each ternary stencil comes from an integer pigeonhole argument and is padded
with trailing zeros to its stated length. The checker computes the lengths of exponentially
long Littlewood polynomials directly. Both the padded center lengths and the
final dyadic lengths are exact.
Run python3 -B -I -S proofs/dyadicfirsts.py from anywhere in the checkout.
Add --brackets to print the cubic lower bound and the proved upper bound for every excess.
"""
from functools import cache
from math import gcd
from pathlib import Path
import json
import sys

ROOT = Path(__file__).resolve().parents[1]
sys.path.insert(0, str(ROOT/'proofs'))
from catalogue_cancellation import codes
from pow2rate import chart
from primerates import prefix as prime_prefix
from sharpdyadic import center_bound
from stencilcount import fits, levels_for
from symcenters import coefficients
from symseam import length as seam_length, odd_coefficients, stride_coefficients
from thresholdliminf import prefix_steps


@cache
def choices():
    """The stated orders of the chart sequences used as radix factors."""
    return {n: row[0] for n,row in enumerate(chart('mstar')['cols'],1)}


@cache
def check_witness(n,u):
    """Check exact order from Thue–Morse, a first-half code, or a chart product."""
    if n==2**u:
        return  # Thue–Morse has exact order u.
    halves=codes().get((n,u))
    if not halves:
        data=chart('mstar')
        rows=dict(enumerate(data['cols'],1)) | {k:row for k,*row in data['past']}
        assert n in rows and rows[n][0]==u and rows[n][2][0]=='product', (n,u)
        a,b=rows[n][2][1:]
        assert 1<a<n and 1<b<n and a*b==n
        # F(x)G(x^a) adds the two exact orders since x^a-1 has a simple root at 1.
        s,t=rows[a][0],rows[b][0]
        assert s+t==u
        check_witness(a,s)
        check_witness(b,t)
        return
    h = min(halves)
    left = [2*int(b)-1 for b in f'{int(h,16):0{4*len(h)}b}'[:n//2]]
    signs = left + [(-1)**u*x for x in reversed(left)]
    jet = coefficients(signs,u)
    assert len(signs)==n and jet[:u]==[0]*u and jet[u], (n,u)


@cache
def stencil_length(r):
    """P exceeds the base-two logarithm of the number of subset moment vectors."""
    s = r*(r-1)//2
    P = s*(2*r.bit_length()+r.bit_length().bit_length()+2)+1
    while s*P.bit_length()+1 < P:
        P = s*P.bit_length()+1
    # product_{j<r} (1+binom(P,j)) <= 2^(r-1) P^s / product_{j<r} j!.
    factorial, saving = 1, 0
    for j in range(1,r):
        factorial *= j
        saving += factorial.bit_length()-1
    while r+s*(P-1).bit_length()-saving < P:
        P = r+s*(P-1).bit_length()-saving
    assert P>r-1+s*(P-1).bit_length()-saving and P>r
    return P


def grouped_steps(v,r):
    """Dyadic scales of Q(x)=(1-x)^2(1-x²), followed by single differences."""
    h = (r-v)//3
    steps = prefix_steps(v,r)
    yield ((1,h),), steps[3*h:]
    # Also fit the same triples at several scales. Each step 2^i is represented
    # modulo two by (1+x)^(2^i), so their degree sum still makes all entries odd.
    a = 2+(r-2)%3
    h = (r-a)//3
    tail = {2:(1,2), 3:(1,1,1), 4:(1,1,1,4)}[a]
    W, rem = divmod((1<<v)-1-sum(tail),4)
    assert rem==0
    groups = {1<<j:1 for j in range(v) if W>>j&1}
    if len(groups)<=h<=W:
        count = len(groups)
        while count<h:
            d = min(z for z in groups if z>1 and groups[z])
            n = min(groups[d],h-count)
            groups[d] -= n
            groups[d//2] = groups.get(d//2,0)+2*n
            count += n
        yield tuple(sorted((d,n) for d,n in groups.items() if n)),tail


def prefix_coefficients(triples,tail,positive=()):
    """Multiply the dyadic differences, starting from the longest power of Q."""
    d,h = max(triples,key=lambda t:t[1])
    assert len({scale for scale,count in triples})==len(triples)
    # (1-x²)(Q^h)'=(-2h-4hx)Q^h gives its coefficients from left to right.
    g = [0,1]
    for i in range(4*h):
        z,rem = divmod(-2*h*g[-1]+(i-1-4*h)*g[-2],i+1)
        assert rem==0
        g.append(z)
    coeffs = [0]*(4*d*h+1)
    coeffs[::d] = g[1:]
    for scale,count in triples:
        if scale!=d:
            for _ in range(count):
                a = coeffs+[0]*(4*scale)
                b = [0]*scale+coeffs+[0]*(3*scale)
                c = [0]*(3*scale)+coeffs+[0]*scale
                e = [0]*(4*scale)+coeffs
                coeffs = [w-2*x+2*y-z for w,x,y,z in zip(a,b,c,e)]
    for d in tail:
        coeffs = [x-y for x,y in zip(coeffs+[0]*d,[0]*d+coeffs)]
    for d in positive:
        coeffs = [x+y for x,y in zip(coeffs+[0]*d,[0]*d+coeffs)]
    assert all(z%2 for z in coeffs)
    return coeffs


def prefix_height(triples,tail,positive=()):
    return max(map(abs,prefix_coefficients(triples,tail,positive)))


@cache
def length(v,r,kind):
    T = 1 << v
    H = 1440**((r+14)//16)
    if kind == 'bound':
        return center_bound(v,r,r**3,H)
    assert kind=='exact'
    P = stencil_length(r)
    height = min(prefix_height(triples,tail) for triples,tail in grouped_steps(v,r))
    R = (height-1)//2
    tiles = H*((max(1,(P-1)*R)+H-1)//H)
    return T*(1+P*tiles)


@cache
def recipe(k,m,v,kind,radices):
    """Actual center lengths, successive (base,digit) pairs, terminal copies."""
    T = 1 << v
    assert radices and k>=v
    left,r = 1<<(k-v),m
    lengths,digits = [],[]
    while r>v:
        b = radices[min(len(digits),len(radices)-1)]
        N = length(v,r,kind)
        core,rem = divmod(N,T)
        assert rem==0 and core%2 and core%3
        g = gcd(core,b)
        assert left%g==0
        digit = (left//g)*pow(core//g,-1,b//g)%(b//g)
        left,rem = divmod(left-digit*core,b)
        assert rem==0 and left>=1, (k,m)
        lengths.append(N)
        digits.append((b,digit))
        u = choices()[b]
        check_witness(b,u)
        r -= u
    # The remaining Thue–Morse sequence at length T has order v, so every
    # terminal product attains at least m even when r is negative.
    return lengths,digits,left


@cache
def head_cases():
    """Each recorded digit lists its radix and sign-sequence factors with multiplicities."""
    return json.loads(Path(__file__).with_name('dyadicheads.json').read_text())


@cache
def head_recipe(d,k,m,v):
    """Replay a digit supplied by a sum of several three-free product lengths."""
    T = 1<<v
    left,r = 1<<(k-v),m
    stages = []
    for b,u,parts in head_cases()[str(d)]:
        check_witness(b,u)
        N = 0
        for n,j,count in parts:
            assert n%3 and count>=1
            check_witness(n,j)
            w = v-((n&-n).bit_length()-1)
            assert w>=0
            core = 1<<w if r-j<=w else length(w,r-j,'exact')
            assert (core&-core)==1<<w
            N += count*n*core
        assert r>v and N%T==0
        left,rem = divmod(left-N//T,b)
        assert rem==0 and left>=1
        stages.append((b,N))
        r -= u
    assert r<=v
    return stages,left


@cache
def chebyshev_length(r):
    """A shorter collision using integer-valued polynomials close to Chebyshev.

    On [0,P], the degree j scaled Chebyshev polynomial with leading coefficient
    1/j! has uniform norm L_j=2(P/4)^j/j!. Start from binom(x,j), subtract the
    scaled Chebyshev polynomial, and round its coordinates in the previously
    constructed integer-valued basis. The resulting basis element has norm at
    most L_j + half the sum of the earlier norms, at most 2L_j since P>=8r.
    The range of subset sums of that coordinate thus has <=1+2P L_j integers.
    Counting these through j=r-2 gives a ternary stencil of order >=r-1.
    """
    P=stencil_length(r)
    s=(r-1)*(r-2)//2
    factorial,saving=1,0
    for j in range(1,r-1):
        factorial*=j
        saving+=factorial.bit_length()-1
    while True:
        bound=(s+r-1)*P.bit_length()+3*(r-1)-2*s-saving+1
        if bound>=P:
            return P
        assert bound>8*r
        P=bound


def tile_coefficients(v,r,layout):
    """The odd signed coefficients, in the physical order across the seam."""
    if isinstance(layout[0],tuple):
        return stride_coefficients(v,r,layout)
    if len(layout)==1:
        assert layout[0] in (0,1)
        triples,tail=list(grouped_steps(v,r))[layout[0]]
        return prefix_coefficients(triples,tail)
    if len(layout)==2:
        j,t=layout
        if t<0:
            g,_=prime_prefix(-t,v,r)
            assert len(g)==j<<v
            return g
        return odd_coefficients(v,r,*layout)
    start,count,levels=layout
    h,a=divmod(r,3)
    assert min(start,count,levels,h-count*levels)>=0
    groups=((1,h-count*levels),)+tuple((1<<i,count) for i in range(start,start+levels))
    left=(1<<v)-1-a-4*sum(scale*n for scale,n in groups)
    assert left>=0
    # Each (1+x^d) has the same residue as (1-x)^d modulo two for dyadic d.
    positive=tuple(1<<i for i in range(left.bit_length()) if left&(1<<i))
    return prefix_coefficients(groups,(1,)*a,positive)


@cache
def tile_height(v,r,layout):
    return max(map(abs,tile_coefficients(v,r,layout)))


def terminal_orders(radices,tail,target):
    """Give one terminal product exact order, leaving its length unchanged."""
    need=target-sum(u for b,u in radices)
    factors=[]
    for b,u in radices:
        # A lower-order sequence of the same length can absorb an overshoot.
        if need<0 and (b,u-1) in codes():
            u-=1
            need+=1
        check_witness(b,u)
        factors.append((b,u))
    assert 0<=need and tail%(1<<need)==0
    # Repeat the order-need Thue–Morse sequence to fill the terminal length.
    return factors,need


def side_radix(b,u):
    """Undo the doubled length and raised order recorded for the outer fold."""
    assert b%2==0 and u>=1
    return b//2,u-1


def tile_recipe(d,k,m,v,mirrored=False):
    """Replay the head products, tile padding, and valuation of each radix step."""
    rows=head_cases()[str(d)]
    assert rows[0][2]==v
    left,r=1<<k,m
    stages=[]
    for i,(b,u,v,parts) in enumerate(rows):
        radix,order=b,u
        if mirrored and i==0:
            # The first join reserves two reversed sides and one shared center.
            assert len(parts)==1 and parts[0][1]==1
            radix,order=side_radix(b,u)
        check_witness(radix,order)
        total=0
        for atoms,count,spec in parts:
            n,s=1,r
            for size,order in atoms:
                check_witness(size,order)
                n*=size
                s-=order
            w=v-((n&-n).bit_length()-1)
            assert count>=1 and w>=0
            center=1<<w
            if spec:
                P,base,offset,layout=spec
                assert s>w and P>=chebyshev_length(s) and offset>=0
                u0={1440:16,1728:15}[base]
                check_witness(base,u0)
                H=base**((s-2+u0)//u0)
                ht=tile_height(w,s,tuple(layout))
                if len(layout)==3 and layout[1]:
                    # The search used the next ceiling with nine significant bits.
                    shift=max(0,ht.bit_length()-9)
                    ht=((ht>>shift)+1)<<shift
                needed=max(1,(P-1)*((ht-1)//2))
                A=H*((needed+H-1)//H+offset)
                center*=1+P*A
            else:
                assert s<=w  # Thue-Morse on the full remaining power of two.
            total+=count*n*center
        left,rem=divmod(left-total,b)
        assert rem==0 and left>=1
        stages.append((b,total,v))
        r-=u
    assert r<=(left&-left).bit_length()-1
    return stages,left


@cache
def split_cases():
    """Signed joins of the transported centers with sources across the seam."""
    return json.loads(Path(__file__).with_name('dyadicsplit.json').read_text())


@cache
def allowed_stencil(r,P,entropy):
    if entropy and r>48:
        return fits(r,P,levels_for(r))
    return P>=chebyshev_length(r)


@cache
def filler_length(r,base):
    """Multiply filler sequences until their combined order reaches r-1."""
    if isinstance(base,int):
        u={1440:16,1728:15}[base]
        base=((base,(r-2+u)//u),)
    H,order=1,0
    for n,c in base:
        assert c>=1
        u=choices()[n]
        check_witness(n,u)
        H*=n**c
        order+=u*c
    assert order>=r-1 and H%2==0
    return H


@cache
def split_center(w,r,P,base,layout,pad,groups,entropy):
    assert r>w and allowed_stencil(r,P,entropy)
    H=filler_length(r,base)
    g=tile_coefficients(w,r,layout)
    assert (len(g)&-len(g))==1<<w
    return seam_length(g,pad,P,H,groups)


@cache
def split_recipe(key,k,m,v,mirrored=False,entropy=False):
    """Replay each signed center's length, its multiplicity, and its radix."""
    rows,tail=split_cases()[key]
    assert key==('r' if mirrored else '')+('e' if entropy else '')+f'{k}-{m}' and rows[0][2]==v
    left,r=1<<k,m
    stages=[]
    for i,(b,u,v,parts) in enumerate(rows):
        radix,order=b,u
        if mirrored and i==0:
            assert len(parts)==1 and parts[0][2]==1
            radix,order=side_radix(b,u)
        check_witness(radix,order)
        total=0
        for atoms,offset,count,spec in parts:
            n,s=1,r
            for size,order in atoms:
                check_witness(size,order)
                n*=size
                s-=order
            w=v-((n&-n).bit_length()-1)
            assert w>=0 and offset>=0 and count>=1
            center=1<<w
            if spec:
                P,base,layout,pad,groups=spec
                if isinstance(base,list):
                    base=tuple(map(tuple,base))
                layout=tuple(tuple(d) if isinstance(d,list) else d for d in layout)
                center=split_center(w,s,P,base,layout,pad,groups+offset,entropy)
            else:
                assert s<=w and offset==0
            assert (n*center & -(n*center))==1<<v
            total+=count*n*center
        left,rem=divmod(left-total,b)
        assert rem==0 and left>=1
        stages.append((b,total))
        r-=u
    assert left==tail and r<=(tail&-tail).bit_length()-1
    return stages,tail


@cache
def seeds():
    """Direct witnesses, including earlier constructions for the same excess."""
    lines=Path(__file__).with_name('dyadicseeds.txt').read_text().splitlines()
    assert lines[0]=='k order v prefix radices'
    out=[]
    for line in lines[1:]:
        k,m,v,kind,bs=line.split()
        out.append((int(k),int(m),int(v),kind,bs))
    assert all(0<k<m and v>0 for k,m,v,kind,bs in out)
    assert len(set(out))==len(out)
    return out


def closed_rows(direct=None):
    """Least cost to cover each excess by any number of the verified sequences."""
    catalogue=[tuple(map(int,s.split())) for s in (ROOT/'pagedata/pow2-firsts.txt').read_text().splitlines()[1:]]
    assert [d for d,c in catalogue]==list(range(1,len(catalogue)+1))
    sources=[(k,k+d,0,'catalogue','-') for d,k in catalogue]
    sources.extend(seeds() if direct is None else direct)
    rows=[]
    for d,c in catalogue:
        # If no single factor suffices, distribute the wanted positive excess
        # between two proper subtargets. Each factor's actual order is retained.
        candidates=[q for q in sources if q[1]-q[0]>=d]
        for a in range(1,d//2+1):
            b=d-a
            _,_,k1,m1,*_=rows[a-1]
            _,_,k2,m2,*_=rows[b-1]
            candidates.append((k1+k2,m1+m2,0,'product',f'{a},{b}'))
        k,m,v,kind,bs=min(candidates,key=lambda q:(q[0],-q[1]))
        assert 0<k<=c and m>=k+d
        rows.append((d,c,k,m,v,kind,bs))
    return rows


def check_seed(k,m,v,kind,bs):
    """Replay one direct construction, including its independently signed terminal product."""
    mirrored=kind.endswith('mirror')
    if kind.startswith('split'):
        entropy='entropy' in kind
        _,left=split_recipe(bs,k,m,v,mirrored,entropy)
        rows,tail=split_cases()[bs]
        odd=any(spec and len(spec[2])==2 for _,_,_,parts in rows for _,_,_,spec in parts)
        family='-entropy' if entropy else ('-odd' if odd else '')
        assert kind=='split'+family+('-mirror' if mirrored else '')
        radices=[(b,u) for b,u,v,parts in rows]
    elif kind in ('heads','mirror'):
        assert int(bs)==m-k
        rows=head_cases()[bs]
        radices=[(row[0],row[1]) for row in rows]
        if mirrored:
            _,left=tile_recipe(int(bs),k,m,v,True)
        else:
            _,tail=head_recipe(int(bs),k,m,v)
            left=tail<<v
    else:
        bases=tuple(map(int,bs.split(',')))
        ns,ds,tail=recipe(k,m,v,kind,bases)
        total,scale=0,1
        for n,(b,digit) in zip(ns,ds):
            total+=scale*digit*n
            scale*=b
        left=tail<<v
        assert total+scale*left==1<<k
        radices=[(b,choices()[b]) for b,digit in ds]
    if mirrored:
        radices[0]=side_radix(*radices[0])
        m-=1  # The terminal product fixes one side before reflection.
    factors,last=terminal_orders(radices,left,m)
    return factors,left,last


def verify():
    for row in seeds():
        check_seed(*row)
    assert set(head_cases())=={bs for k,m,v,kind,bs in seeds() if kind in ('heads','mirror')}
    assert set(split_cases())=={bs for k,m,v,kind,bs in seeds() if kind.startswith('split')}
    result=closed_rows()
    lines=(ROOT/'pagedata/dyadic-firsts.txt').read_text().splitlines()
    assert lines==['excess catalogue_k_exact unrestricted_k_upper_bound order v prefix radices']+[
        ' '.join(map(str,row)) for row in result]
    return result


def reflected_excess(rows,direct=None):
    """Exact-order reflected sequences from the known symmetric atoms and order-raising folds."""
    from symfirsts import by_transport, certified, firsts
    catalogue=firsts()
    atoms={(k,catalogue[k]-k) for k in certified()|by_transport()}
    seed_rows=seeds() if direct is None else direct
    atoms.update((k,m-k) for k,m,v,kind,bs in seed_rows if kind.endswith('mirror'))
    # At least one orientation supplies a reflected fold of exact order
    # m+1 at 2^(k+1). These folds are also available as product factors.
    atoms.update((k+1,m-k) for d,c,k,m,v,kind,bs in rows)
    last=max(k for d,c,k,m,v,kind,bs in rows)
    best=[0]*(last+1)  # Thue–Morse supplies the unspent exponent.
    for cost,gain in sorted(atoms):
        for k in range(cost,last+1):
            best[k]=max(best[k],best[k-cost]+gain)
    return best


def reflected_records(rows,direct=None):
    """Record orders attained with the required reflection at the same exponent."""
    best=reflected_excess(rows,direct)
    records={}
    for d,c,k,m,v,kind,bs in rows:
        records[k]=max(m,records.get(k,0))
    assert all(k+best[k]<=m for k,m in records.items())
    return records,{k for k,m in records.items() if k+best[k]==m}


def first_possible(d):
    """First k at which the actual cubic class sizes permit excess d>=1."""
    assert d>=1
    # At the first allowed k, k+d=2h-1 and 2^k >= 3^h. Thus h is
    # the least integer with 4^h >= 2^(d+1) 3^h. (4/3)^3 > 2.
    lo,hi=0,3*(d+1)
    while hi-lo>1:
        h=(lo+hi)//2
        if 4**h >= (3**h)<<(d+1):
            hi=h
        else:
            lo=h
    return 2*hi-d-1


if __name__=='__main__':
    import argparse
    parser=argparse.ArgumentParser(description=__doc__)
    output=parser.add_mutually_exclusive_group()
    output.add_argument('--reflections',action='store_true',help='Count exact reflected table orders through the final record.')
    output.add_argument('--brackets',action='store_true',help='Print the first allowed and first constructed exponents for each excess.')
    args=parser.parse_args()
    rows = verify()
    if args.brackets:
        print('excess first_possible_k unrestricted_k_upper_bound')
        for d,c,k,*_ in rows:
            lo=first_possible(d)
            assert lo<=k
            print(d,lo,k)
    elif args.reflections:
        records,active=reflected_records(rows)
        last=max(records)
        print(f'{len(active)} of {len(records)} record exponents have a certified exact reflection.')
        print(f'Including intermediate exponents: {last-len(records)+len(active)} of {last}.')
    else:
        gains = [(d,c,k) for d,c,k,*_ in rows if k<c]
        print(f'{len(rows)} records checked; {len(gains)} improved. First {gains[0]}, last {gains[-1]}.')
