"""First two moments of distinct admissible destinations in a suffix-reversal ball."""
from collections import Counter
from fractions import Fraction as F
from itertools import combinations,permutations
from math import factorial,gcd,prod
import json

from experience import distances,profile
from roues import primes_up_to,rank,unrank


def crt(n,k,depth):
    block = factorial(k)
    words = [unrank(k,s) for s 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)
    singles = pairs = 0
    first = raw_pairs = union = 0
    # Counts of admissible root classes across the larger prime coordinates.
    def joint(offsets):
        return prod(p-len({0,*(h%p for h in offsets)}) for p in primes)

    for s in units:
        ds = distances(words,s)
        offsets = [j-s for j in units if j!=s and ds[j]<=depth]
        first += sum(joint((h,)) for h in offsets)
        raw_pairs += sum(joint(pair) for pair in combinations(offsets,2))
        singles += len(offsets)
        pairs += len(offsets)*(len(offsets)-1)//2
        for size in range(1,len(offsets)+1):
            union += (-1)**(size+1)*sum(joint(t) for t in combinations(offsets,size))
    roots = len(units)*den
    ez,ez2,prob = F(first,roots), F(first+2*raw_pairs,roots), F(union,roots)
    return ez,ez2,prob,singles,pairs


def exhaustive(n,k):
    # Rank each full permutation independently and search with no CRT or block reduction.
    modulus = factorial(n)
    good = {w for w in permutations(range(1,n+1)) if gcd(rank(w),modulus)==1}
    histograms = [Counter() for _ in range(3)]
    for root in good:
        seen = {root}
        boundary = {root}
        hits = 0
        for histogram in histograms:
            following = {w[:-j]+w[-j:][::-1] for w in boundary for j in range(2,k+1)} - seen
            hits += len(following & good)
            histogram[hits] += 1
            seen.update(following)
            boundary = following
    return histograms


def experiment():
    rows = []
    for n in (5,6,7,8,97):
        for k in (3,4):
            hist = exhaustive(n,k) if n<=8 else None
            law = profile(n,k)
            for d in (1,2,3):
                ez,ez2,prob,singles,pairs = crt(n,k,d)
                assert prob == sum(law.get(str(j),0) for j in range(1,d+1))
                lower = ez**2/ez2 if ez2 else F(0)
                assert lower <= prob <= min(ez,1)
                row = dict(n=n,k=k,depth=d,mean=str(ez),second=str(ez2),probability=str(prob),
                           lower=str(lower),gap=str(prob-lower),single_terms=singles,pair_terms=pairs)
                if hist is not None:
                    counter=hist[d-1]
                    roots=sum(counter.values())
                    assert ez == F(sum(z*v for z,v in counter.items()),roots)
                    assert ez2 == F(sum(z*z*v for z,v in counter.items()),roots)
                    assert prob == 1-F(counter[0],roots)
                    row["histogram"] = dict(sorted(counter.items()))
                rows.append(row)
    return dict(rows=rows)


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