"""Sum circular ranks by reverse insertion, shared labels and the rank residue."""
from collections import Counter
from functools import lru_cache
from math import factorial, lcm, comb, gcd, prod
from pathlib import Path
import argparse
import json
from fusion_ordres import cycles, rank_on, signature, TARGETS

HERE=Path(__file__).resolve().parent
CASES={**TARGETS, 'new':(10,3,7,(1,4,0,6))}


def compressed(k,ell,p,source):
    if p>=k:
        raise ValueError("This recurrence uses a distinct outer anchor")
    outer=tuple(range(k-p-1,k))
    shared=set(source)&set(outer)
    f=factorial(ell)
    modulus=lcm(p,f)
    states=Counter({((),0):1})
    sizes=[1]
    transitions=0
    for length,label in enumerate(reversed(outer[1:]),1):
        next_states=Counter()
        for (seq,residue),weight in states.items():
            inserted=(label if label in shared else -1,)+seq
            for digit in range(length):
                rotated=inserted[-digit:]+inserted[:-digit] if digit else inserted
                next_states[rotated,(residue+digit*factorial(length-1))%modulus]+=weight
                transitions+=1
        states=next_states
        sizes.append(len(states))
    assert sum(states.values())==factorial(p)
    source_orders=[(signature(c,shared),rank_on(c,source)) for c in cycles(source)]
    @lru_cache(None)
    def completions(sig):
        counts=[0]*f
        for (anchors,gaps),s in source_orders:
            if anchors==sig[0]:
                if shared: ways=prod(comb(a+b,a) for a,b in zip(gaps,sig[1]))
                else: ways=factorial(len(outer)+len(source)-1)//(factorial(p)*f)
                counts[s]+=ways
        return counts
    matrix=[[0]*f for _ in range(p)]
    anchor=outer[0] if outer[0] in shared else -1
    for (seq,residue),weight in states.items():
        if gcd(residue,f)==1:
            counts=completions(signature((anchor,)+seq,shared))
            for s,n in enumerate(counts): matrix[residue%p][s]+=weight*n
    dead=[s for s in range(f) if gcd(s,f)>1 and gcd(f-1-s,f)>1]
    return dict(H=[sum(n for s,n in enumerate(row) if gcd(s,f)==1) for row in matrix],
                D=[sum(row[s] for s in dead) for row in matrix],T=list(map(sum,matrix)),
                state_counts=sizes,transitions=transitions,orders=factorial(p))


def predicted():
    return {name:compressed(*case) for name,case in CASES.items()}


def verified():
    from coupures import local,pattern
    from fusion_ordres import predict
    result=predicted()
    assert result==json.loads((HERE/'prediction-09.json').read_bytes())
    for name,case in CASES.items():
        other=predict(*case)
        assert all(other[key]==result[name][key] for key in ('H','D','T'))
        assert local(*pattern(*case))['counts']==result[name]['H']
    return result


def benchmark():
    from fusion_ordres import predict
    from statistics import median
    from time import perf_counter_ns
    import tracemalloc
    result={}
    for key,case in CASES.items():
        row={}
        for name,run in (("insert",compressed),("orders",predict)):
            samples=[]
            for _ in range(5):
                start=perf_counter_ns()
                run(*case)
                samples.append(perf_counter_ns()-start)
            tracemalloc.start()
            run(*case)
            peak=tracemalloc.get_traced_memory()[1]
            tracemalloc.stop()
            row[name]=dict(samples_ns=samples,median_ns=median(samples),python_peak_bytes=peak)
        result[key]=row
    return result


if __name__=='__main__':
    parser=argparse.ArgumentParser(description=__doc__)
    parser.add_argument('--predict',action='store_true')
    parser.add_argument('--measure',action='store_true')
    args=parser.parse_args()
    output=benchmark() if args.measure else predicted() if args.predict else verified()
    print(json.dumps(output,indent=2))
