"""Glue two circular orders by counting shuffles between consecutive shared positions."""
import argparse
from collections import Counter
from functools import lru_cache
from fractions import Fraction
from itertools import permutations
import json
from math import comb, factorial, gcd, prod
from pathlib import Path
from statistics import median
from time import perf_counter_ns

HERE=Path(__file__).resolve().parent
TARGETS={"F8":(8,3,5,(3,2,1,0)), "archive9":(9,3,7,(3,2,1,0)),
         "fresh10":(10,3,7,(0,2,5,1))}


def cycles(positions):
    first,*tail=positions
    for perm in permutations(tail):
        yield (first,*perm)


def rank_on(cycle,positions):
    """Circular deletion digits with the first position as anchor."""
    live=[x for x in cycle if x in positions]
    rank=0
    for n,x in enumerate(positions):
        i=live.index(x)
        if n:
            rank=rank*len(live)+i
        live=live[i+1:]+live[:i]
    return rank


def signature(order,shared):
    if not shared:
        return (),()
    pivot=order.index(min(shared))
    seq=order[pivot:]+order[:pivot]
    anchors=tuple(x for x in seq if x in shared)
    stops=[seq.index(x) for x in anchors]+[len(seq)]
    return anchors,tuple(b-a-1 for a,b in zip(stops,stops[1:]))


def predict(k,ell,p,source):
    outer=tuple(range(max(0,k-p-1),k))
    shared=set(outer)&set(source)
    m=len(set(outer)|set(source))
    f=factorial(ell)
    base=tuple((signature(c,shared),rank_on(c,source)) for c in cycles(source))
    @lru_cache(None)
    def completions(sig):
        totals=[0]*f
        for (anchors,gaps),s in base:
            if anchors!=sig[0]:
                continue
            if shared:
                count=prod(comb(a+b,a) for a,b in zip(sig[1],gaps))
            else:
                count=factorial(m-1)//(factorial(len(outer)-1)*factorial(len(source)-1))
            totals[s]+=count
        return totals
    by_residue=[[0]*f for _ in range(p)]
    kept=0
    for order in cycles(outer):
        u=rank_on(order,outer if p<k else outer[-ell-1:])
        if gcd(u,f)!=1:
            continue
        kept+=1
        counts=completions(signature(order,shared))
        residues=(u%p,) if p<k else range(p)
        for r in residues:
            for s,count in enumerate(counts):
                by_residue[r][s]+=count
    H=[sum(row[s] for s in range(f) if gcd(s,f)==1) for row in by_residue]
    dead=[s for s in range(f) if gcd(s,f)!=1 and gcd(f-1-s,f)!=1]
    D=[sum(row[s] for s in dead) for row in by_residue]
    T=[sum(row) for row in by_residue]
    if set(source).isdisjoint((k-2,k-1)):
        assert len(set(T))==1 and all(H[r]+H[-r]==T[r]-D[r] for r in range(p))
    return dict(k=k,ell=ell,p=p,source=list(source),outer=list(outer),shared=sorted(shared),
                H=H,D=D,T=T,dead=dead,source_classes=by_residue,orders_joint=factorial(m-1),
                outer_orders=factorial(len(outer)-1),outer_kept=kept,source_orders=f,
                cached_signatures=completions.cache_info().currsize)


def predictions():
    return {name:predict(*case) for name,case in TARGETS.items()}


def check():
    from coupures import local, pattern
    frozen=json.loads((HERE/"prediction-08.json").read_text())
    assert predictions()==frozen
    for name,(k,ell,p,src) in TARGETS.items():
        assert frozen[name]["H"]==local(*pattern(k,ell,p,src))["counts"]
    old=json.loads((HERE/"controle-07.json").read_text())
    for case in old["records"]:
        result=predict(case["k"],case["ell"],case["p"],tuple(case["source"]))
        assert result["H"]==case["counts"]
    controls=[(7,3,7,(0,2,3,1)),(9,2,5,(0,1,2)),(8,2,5,(0,1,3)),(5,2,3,(3,2,1))]
    for k,ell,p,src in controls:
        result=predict(k,ell,p,src)
        assert result["H"]==local(*pattern(k,ell,p,src))["counts"]
    assert result["H"]==[0,1,0] and 2*result["H"][0]!=result["T"][0]-result["D"][0]
    a=frozen["F8"]
    deficiency=Fraction(a["D"][0]*5-sum(a["D"]),2*5*sum(a["H"]))
    assert deficiency==Fraction(1,140)
    return dict(predictions=frozen,census=len(old["records"]),boundary_controls=len(controls),
                deficit=str(deficiency),outside_hypotheses=result)


def measure():
    from coupures import local, orders, pattern
    out={}
    for name,case in TARGETS.items():
        out[name]={}
        for mode in ("glue","local"):
            samples=[]
            for _ in range(3):
                local.cache_clear()
                orders.cache_clear()
                t=perf_counter_ns()
                if mode=="glue":
                    predict(*case)
                else:
                    local(*pattern(*case))
                samples.append(perf_counter_ns()-t)
            out[name][mode]=dict(ns=samples,median_ns=median(samples))
    return out


if __name__=="__main__":
    parser=argparse.ArgumentParser(description=__doc__)
    group=parser.add_mutually_exclusive_group()
    group.add_argument("--predict",action="store_true")
    group.add_argument("--measure",action="store_true")
    args=parser.parse_args()
    if not __debug__:
        raise RuntimeError("Enable assertions")
    print(json.dumps(predictions() if args.predict else measure() if args.measure else check(),indent=2))
