"""Condition the two-moment bound on the root rank in its suffix block."""
from fractions import Fraction as F
from itertools import combinations
from math import factorial, gcd, prod
import json
from recouvrements import distances, exhaustive, primes_up_to, rank, unrank


def compare(n, k, d, histogram):
    block = factorial(k)
    words = [unrank(k,i) for i in range(block)]
    units = [s for s in range(block) if gcd(s,block)==1]
    primes = [p for p in primes_up_to(n) if p>k]
    den = prod(p-1 for p in primes)
    def joint(hs):
        return prod(p-len({0,*(h%p for h in hs)}) for p in primes)
    mean = second = union = conditional = F(0)
    singles = pairs = 0
    for s in units:
        distances_s = distances(words,s)
        hs = [j-s for j in units if j!=s and distances_s[j]<=d]
        singles += len(hs)
        pairs += len(hs)*(len(hs)-1)//2
        first = F(sum(joint((h,)) for h in hs),den)
        m2 = first + F(2*sum(joint(h) for h in combinations(hs,2)),den)
        if m2:
            conditional += first**2/m2
        mean += first
        second += m2
        if n<=8:
            # At these sizes there are at most two remaining prime coordinates.
            period = prod(primes)
            count = sum(any(all((t+h)%p for p in primes) for h in hs)
                        for t in range(period) if gcd(t,period)==1)
            union += F(count,den)
        else:
            union += F(sum((-1)**(i+1)*sum(joint(h) for h in combinations(hs,i))
                           for i in range(1,len(hs)+1)),den)
    roots = len(units)
    mean, second, union, conditional = (x/roots for x in (mean,second,union,conditional))
    lower = mean**2/second if second else F(0)
    assert lower <= conditional <= union
    if histogram is not None:
        count = sum(histogram.values())
        assert (mean,second,union) == (F(sum(z*v for z,v in histogram.items()),count),
               F(sum(z*z*v for z,v in histogram.items()),count),1-F(histogram[0],count))
    return dict(n=n,k=k,d=d,global_bound=str(lower),conditioned=str(conditional),
                exact=str(union),gap=str(union-conditional),single_terms=singles,pair_terms=pairs)


def protected():
    rows = []
    for k in (12,16):
        ell = k//2-1
        local_modulus = factorial(ell)
        for root in (1, factorial(k)//2-1, factorial(k)-1):
            assert gcd(root,factorial(k))==1
            x = unrank(k,root)
            for depth in (3,4):
                seen = set()
                for i in range(k//4):
                    for middle in combinations(range(2,k//4+1),depth-2):
                        flips = (k-i,*middle,k-i)
                        y = x
                        for length in flips:
                            y = y[:-length]+y[-length:][::-1]
                        new = rank(y)
                        assert y != x and y[-ell-1:] == x[-ell-1:] and y not in seen
                        assert root%local_modulus == new%local_modulus
                        seen.add(y)
                        rows.append(dict(k=k,root=root,flips=list(flips),destination=new,
                                         modulus=local_modulus,remainder=new%local_modulus))
    return rows


def experiment():
    rows = []
    for n in (5,6,7,8,97):
        for k in ((3,4,5) if n in (6,7,8) else (3,4)):
            hist = exhaustive(n,k) if n<=8 else None
            rows.extend(compare(n,k,d,hist[d-1] if hist else None) for d in (1,2,3))
    return dict(rows=rows, protected=protected())


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