"""Exhaust finite label-rotation orbits and conditional rank histograms (NumPy)."""
import argparse
from collections import defaultdict
import json
from math import factorial, gcd
from pathlib import Path

import numpy as np


def all_by_rank(k):
    """Apply the circular unranking rotations to all ranks at once."""
    ranks = np.arange(factorial(k), dtype=np.int64)
    words = np.tile(np.arange(k, dtype=np.int16), (len(ranks), 1))
    for size in range(k, 1, -1):
        digit = (ranks // factorial(size-1)) % size
        order = (np.arange(size) + digit[:, None]) % size
        words[:, -size:] = np.take_along_axis(words[:, -size:], order, axis=1)
    return ranks, words


def lexical_index(words):
    index = np.zeros(len(words), dtype=np.int64)
    width = words.shape[1]
    for j in range(width-1):
        below = (words[:, j+1:] < words[:, j, None]).sum(axis=1)
        index += below * factorial(width-j-1)
    return index


def signature(words, positions, k):
    values = words[:, positions]
    return lexical_index((values[:, 1:] - values[:, :1]) % k)


def rotated_ranks(words, p, index):
    tail = words[:, -p:]
    ordered = np.argsort(tail, axis=1)
    sorted_labels = np.take_along_axis(tail, ordered, axis=1)
    rotated = words.copy()
    np.put_along_axis(rotated[:, -p:], ordered, np.roll(sorted_labels, -1, axis=1), axis=1)
    return index[lexical_index(rotated)]


def support_classes(k, length):
    """Image of the ordered source suffix in the coordinates of the destination."""
    groups = defaultdict(list)
    for first in range(2, k+1):
        for word in [(first,)] + [(first, second) for second in range(2, k+1)]:
            inv = list(range(k))
            for width in reversed(word):
                inv[-width:] = reversed(inv[-width:])
            groups[tuple(inv[-length:])].append((word, tuple(inv)))
    return groups


def experiment(max_k=9):
    cases, witnesses, totals = [], {}, defaultdict(int)
    for k in range(5, max_k+1):
        ranks, words = all_by_rank(k)
        lex = lexical_index(words)
        assert np.array_equal(np.sort(lex), ranks)
        index = np.empty_like(ranks)
        index[lex] = ranks
        rot = {}
        for p in (3, 5, 7):
            if p > k:
                continue
            perm = rotated_ranks(words, p, index)
            unit = factorial(p-1)
            step = np.where((ranks//unit) % p == p-1, -(p-1)*unit, unit)
            assert np.array_equal(perm, ranks + step)
            assert np.all((perm-ranks) % p == p-1)
            rot[p] = perm
            totals["orbits"] += len(ranks)//p
        for ell in (2, 3):
            f = factorial(ell)
            target = tuple(range(k-ell-1, k))
            target_sig = signature(words, target, k)
            decoder = np.full(f, -1, dtype=np.int64)
            decoder[target_sig] = ranks % f
            assert np.array_equal(decoder[target_sig], ranks % f)
            assert sorted(decoder.tolist()) == list(range(f))
            allowed = np.array([gcd(i, f) == 1 for i in range(f)])
            target_ok = allowed[ranks % f]
            for source, members in support_classes(k, ell+1).items():
                word, inv = members[0]
                source_sig = signature(words, source, k)
                source_rank = index[lexical_index(words[:, inv])]
                assert np.array_equal(source_rank % f, decoder[source_sig])
                keep = target_ok & allowed[source_rank % f]
                disjoint = set(target).isdisjoint(source)
                if disjoint:
                    joint = np.bincount(f*source_sig + target_sig, minlength=f*f)
                    assert np.all(joint == len(ranks)//(f*f))
                for p, perm in rot.items():
                    if p <= ell:
                        continue
                    overlap = sum(i >= k-p for i in source)
                    kind = "inside" if overlap == len(source) else "outside" if not overlap else "cut"
                    direct = np.bincount(ranks[keep] % p, minlength=p)
                    # Enumerate the allowed orbit phases using the label rotation itself.
                    stride = factorial(p-1)
                    current = ranks[(ranks//stride) % p == 0]
                    orbit_counts = np.zeros(p, dtype=np.int64)
                    for _ in range(p):
                        orbit_counts += np.bincount(current[keep[current]] % p, minlength=p)
                        current = perm[current]
                    assert np.array_equal(direct, orbit_counts)
                    flat = bool(np.all(direct == direct[0]))
                    changed = keep & ~keep[perm]
                    if kind != "cut":
                        assert flat and not np.any(changed)
                    if disjoint:
                        assert direct[0]*p*sum(allowed) <= direct.sum()*f
                    row = dict(k=k, ell=ell, p=p, source=list(source), kind=kind, disjoint=disjoint,
                               words=[list(w) for w, _ in members], counts=direct.tolist(),
                               leaving=int(changed.sum()))
                    cases.append(row)
                    totals[kind] += 1
                    totals["word_cases"] += len(members)
                    if direct.sum() == 0:
                        totals["empty"] += 1
                    if kind == "cut" and not flat:
                        totals["biased_cut"] += 1
                        example = int(np.flatnonzero(changed)[0])
                        key = "disjoint_cut" if disjoint else "overlapping_cut"
                        candidate = dict(k=k, ell=ell, p=p, flips=list(word), coordinates=list(source),
                                         destination=words[example].tolist(), source_word=words[example,list(inv)].tolist(),
                                         rotated=words[perm[example]].tolist(), counts=direct.tolist(),
                                         source_signature_before=int(source_sig[example]),
                                         source_signature_after=int(source_sig[perm[example]]),
                                         target_signature_before=int(target_sig[example]),
                                         target_signature_after=int(target_sig[perm[example]]))
                        order = lambda x: (x["k"], len(x["flips"]), x["flips"], x["ell"], x["p"])
                        if key not in witnesses or order(candidate) < order(witnesses[key]):
                            witnesses[key] = candidate
                    elif kind == "cut" and flat and direct.sum() and np.any(changed):
                        totals["flat_cut_with_changed_membership"] += 1
    return dict(range=[5, max_k], labels="0-based", totals=dict(totals), witnesses=witnesses, cases=cases)


if __name__ == "__main__":
    parser = argparse.ArgumentParser(description=__doc__)
    parser.add_argument("--max-k", type=int, choices=range(5, 10), default=9)
    args = parser.parse_args()
    if not __debug__:
        raise RuntimeError("Enable Python assertions.")
    print(json.dumps(experiment(args.max_k), indent=2))
