"""Prospective rank histograms, exhaustive check and separate timing/allocation runs."""
from pathlib import Path
from time import perf_counter_ns
from statistics import median
import argparse,json,tracemalloc
from math import factorial
from signatures import compressed
from fusion_ordres import predict
HERE=Path(__file__).resolve().parent
CASES=((1,0,2,3),(1,0,3,4),(1,3,4,5),(2,3,4,5))

def prediction():
    return [compressed(10,3,7,s) for s in CASES]

def verify():
    import numpy as np
    from coupures import orders,pattern,suffix_rank
    frozen=json.loads((HERE/'engagement10.json').read_bytes())
    assert prediction()==frozen
    for s,expected in zip(CASES,frozen):
        _,p,_,src=pattern(10,3,7,s)
        width=p+1
        ar=orders(max(width,max(src)+1));small=suffix_rank(ar,src)
        u=suffix_rank(ar,tuple(range(width)))
        ok=np.isin(u%6,[1,5])
        for key,mask in [('H',ok & np.isin(small,[1,5])),('D',ok & np.isin(small,[2,3])),('T',ok)]:
            assert expected[key]==np.bincount(u[mask]%7,minlength=7).tolist()
            assert predict(10,3,7,s)[key]==expected[key]
    return dict(supports=CASES,predictions=frozen)

def measure():
    out=[]
    for s in CASES:
        row={}
        for label,fn in [('insertion',compressed),('outer',predict)]:
            ts=[]
            for _ in range(5):
                t=perf_counter_ns();fn(10,3,7,s);ts.append(perf_counter_ns()-t)
            tracemalloc.start();fn(10,3,7,s);peak=tracemalloc.get_traced_memory()[1];tracemalloc.stop()
            row[label]=dict(samples_ns=ts,median_ns=median(ts),peak_python_bytes=peak)
        out.append(row)
    return out

if __name__=='__main__':
    p=argparse.ArgumentParser();p.add_argument('--predict',action='store_true');p.add_argument('--measure',action='store_true')
    args=p.parse_args()
    print(json.dumps(prediction() if args.predict else measure() if args.measure else verify(),indent=2))
