"""Exact conditional rank histograms from local circular orders. Requires NumPy."""
import argparse
from collections import Counter
from fractions import Fraction
from functools import lru_cache
from itertools import permutations
import json
from math import factorial, gcd, isqrt
from pathlib import Path
from statistics import median
from time import perf_counter_ns

import numpy as np

HERE = Path(__file__).resolve().parent


def pattern(k, ell, p, source):
    if not 1 < ell < p <= k or len(source) != ell+1 or len(set(source)) != len(source):
        raise ValueError("Invalid support or wheel")
    if any(p % j == 0 for j in range(2, isqrt(p)+1)):
        raise ValueError("The large modulus must be prime")
    if any(not 0 <= i < k for i in source):
        raise ValueError("Position outside permutation")
    outer = tuple(range(max(0,k-p-1), k))
    positions = tuple(dict.fromkeys((*outer, *source)))
    return ell, p, p == k, tuple(positions.index(i) for i in source)


@lru_cache(maxsize=6)
def orders(m):
    rows = np.empty((factorial(m-1), m), dtype=np.int16)
    rows[:,0] = 0
    rows[:,1:] = list(permutations(range(1,m)))
    return rows


def suffix_rank(rows, positions):
    """After each symbol, start counting at its successor in the remaining label circle."""
    modulus = rows.shape[1]
    value = np.zeros(len(rows), dtype=np.int64)
    for j in range(1,len(positions)):
        live = (rows[:,positions[j:]] - rows[:,positions[j-1],None]) % modulus
        digit = (live < live[:,:1]).sum(axis=1)
        value = value*live.shape[1] + digit
    return value


@lru_cache(maxsize=256)
def local(ell, p, full, source):
    width = p if full else p+1
    n = max(width, max(source)+1)
    rows = orders(n)
    small = tuple(range(width-ell-1, width))
    allowed = np.array([gcd(i,factorial(ell)) == 1 for i in range(factorial(ell))])
    target_ok = allowed[suffix_rank(rows, small)]
    mask = allowed[suffix_rank(rows, source)] & target_ok
    if full:
        # Global label origin is fixed for rank mod p. Each orbit has all p residues.
        return dict(positions=n, orders=len(rows), denominator=factorial(p),
                    counts=[int(mask.sum())]*p, leaving=0)
    residues = suffix_rank(rows, tuple(range(width))) % p
    histogram = np.bincount(residues[mask], minlength=p)
    rotated = rows.copy()
    suffix = rows[:,1:width]
    sort = np.argsort(suffix,axis=1)
    next_values = np.roll(np.take_along_axis(suffix,sort,axis=1),-1,axis=1)
    np.put_along_axis(rotated[:,1:width],sort,next_values,axis=1)
    after = allowed[suffix_rank(rotated, source)] & allowed[suffix_rank(rotated, small)]
    assert np.all((suffix_rank(rotated,tuple(range(width))) - residues) % p == p-1)
    return dict(positions=n, orders=len(rows), denominator=len(rows), counts=histogram.tolist(),
                leaving=int((mask & ~after).sum()))


def global_parity_counts(k, source, prime):
    """Independent check through the original full rank, using one-based labels."""
    from frontiere import rank

    source_order = [i for i in range(k) if i not in source] + list(source)
    counts = [0]*prime
    for word in permutations(range(1,k+1)):
        target = rank(word)
        if target % 2 and rank(tuple(word[i] for i in source_order)) % 2:
            counts[target % prime] += 1
    return counts


def census():
    received = json.loads((HERE/"controle-06.json").read_text())
    selected = [r for r in received["cases"] if r["kind"]=="cut" and r["disjoint"]]
    counts = Counter()
    records = []
    for r in selected:
        ell,p,k = r["ell"],r["p"],r["k"]
        key = pattern(k,ell,p,r["source"])
        h = local(*key)
        weight, rem = divmod(factorial(k),h["denominator"])
        assert rem == 0
        assert [v*weight for v in h["counts"]] == r["counts"]
        assert h["leaving"]*weight == r["leaving"]
        uniform = len(set(h["counts"]))==1
        zero = h["counts"][0]*p == sum(h["counts"])
        counts["uniform" if uniform else "only_zero_balanced" if zero else "zero_biased"] += 1
        records.append(dict(k=k,ell=ell,p=p,source=r["source"],canonical_source=key[-1],
                            factor=weight,zero=str(Fraction(h["counts"][0],sum(h["counts"]))),**h))
    full = [r for r in received["cases"] if r["k"]==r["p"]]
    for r in full:
        h = local(*pattern(r["k"],r["ell"],r["p"],r["source"]))
        assert h["counts"] == r["counts"] and h["leaving"] == r["leaving"]
    # Reflection of all labels followed by swapping the last two destination positions.
    reflection_controls = 0
    for r in received["cases"]:
        k,p,ell = r["k"],r["p"],r["ell"]
        if ell != 2 or set(r["source"]) & {k-2,k-1}:
            continue
        h = r["counts"]
        assert all((h[i]+h[-i])*p == 2*sum(h) for i in range(p))
        reflection_controls += 1
    # Direct involution check, independent of the algebraic digit argument.
    for p in (3,5,7):
        positions = tuple(range(p+1))
        rows = orders(p+1)
        rank = suffix_rank(rows,positions)
        image = p-rows.copy()
        image[:,[-2,-1]]=image[:,[-1,-2]]
        mapped = suffix_rank(image,positions)
        odd = rank%2==1
        assert np.all(mapped[odd]==factorial(p)-rank[odd])
        for source in permutations(range(p-1),3):
            assert np.all(suffix_rank(image,source)==1-suffix_rank(rows,source))
    examples={}
    for name,k,ell,p,s in (("eight",8,3,5,(3,2,1,0)),("five",5,2,3,(3,2,1)),
                           ("one_common",8,2,5,(0,1,3)),("converse_fails",6,2,5,(2,1,0))):
        h=local(*pattern(k,ell,p,s))
        factor=factorial(k)//h["denominator"]
        examples[name]=dict(k=k,ell=ell,p=p,source=s,full_counts=[v*factor for v in h["counts"]],**h)
    assert examples["eight"]["full_counts"] == [864,888,920,920,888]
    assert examples["five"]["full_counts"] == [0,20,0]
    for name in ("one_common","converse_fails"):
        assert len(set(examples[name]["counts"])) == 1 and examples[name]["leaving"] > 0
        witness = examples[name]
        assert global_parity_counts(witness["k"],witness["source"],5) == witness["full_counts"]
    assert global_parity_counts(7,(2,0,1),5) == [252,238,259,245,266]
    # The local input for F8 is unchanged by arbitrary common shifts of the positions.
    for k in (9,100,10**6):
        assert pattern(k,3,5,tuple(k-8+i for i in (3,2,1,0))) == pattern(8,3,5,(3,2,1,0))
    return dict(classes=len(selected),distinct_patterns=len({(r["ell"],r["p"],tuple(r["canonical_source"])) for r in records}),
                reflection_controls=reflection_controls,classifications=dict(counts),full_prime_controls=len(full),examples=examples,records=records)


def costs():
    result={}
    for k in (8,100,10**6):
        times=[]
        for _ in range(5):
            local.cache_clear()
            orders.cache_clear()
            start=perf_counter_ns()
            h=local(*pattern(k,3,5,tuple(k-8+i for i in (3,2,1,0))))
            times.append(perf_counter_ns()-start)
        result[k]=dict(orders=h["orders"], times_ns=times, median_ns=median(times))
    return result


if __name__=="__main__":
    parser=argparse.ArgumentParser(description=__doc__)
    parser.add_argument("--measure",action="store_true")
    args=parser.parse_args()
    print(json.dumps(costs() if args.measure else census(),indent=2))
