"""Frozen batches and exact prime counts in disjoint anchored windows. Standard library."""
import argparse
from bisect import bisect_right
import json
from math import isqrt
from pathlib import Path
import platform
from random import Random
from statistics import median
import subprocess
import sys
from time import perf_counter_ns as now
import tracemalloc

from partager import batches, independent_distinct, shared
from quotients import sieve_quotients
from rang_premiers import oracle

HERE = Path(__file__).resolve().parent
TRAIN_SEED = 7106
TEST_SEED = 7107


def grouped(start, step, gap):
    return [start + group*(7*step+gap) + i*step for group in range(8) for i in range(8)]


def fixtures():
    rng = Random(TRAIN_SEED)
    train = [grouped(rng.randrange(70000,300000),s,g) for s,g in ((1,256),(16,2048),(64,16384))]
    rng = Random(TEST_SEED)
    test = {f"g{s}_{g}":grouped(rng.randrange(400000,750000),s,g)
            for s in (1,4,16,64) for g in (256,2048,16384)}
    assert max(map(max,test.values())) <= 10**6
    return train, {**batches(), **test}


def flags(a,b,base):
    marks = bytearray([1])*(b-a+1)
    for p in base:
        if p*p>b:
            break
        first=max(p*p,((a+p-1)//p)*p)
        if first<=b:
            marks[first-a::p] = bytes(1+(b-first)//p)
    for x in range(a,min(2,b+1)):
        marks[x-a]=0
    return marks


def scan(a,marks,points):
    out={}
    it=iter(points)
    target=next(it)
    count=0
    for x,flag in enumerate(marks,a):
        count+=flag
        if x==target:
            out[x]=count
            target=next(it,None)
    return out


def window(points,base,stages):
    a,b=points[0],points[-1]
    t=now()
    anchor=sieve_quotients(a-1)
    u=now()
    marks=flags(a,b,base)
    v=now()
    result={x:anchor+n for x,n in scan(a,marks,points).items()}
    w=now()
    stages['anchor']+=u-t
    stages['mark']+=v-u
    stages['scan']+=w-v
    return result


def calibration():
    train,_=fixtures()
    anchor_rates=[]
    scan_rates=[]
    evidence=[]
    for points in train:
        a,b=points[0],points[-1]
        base=oracle(isqrt(b))
        marks=flags(a,b,base)
        t_anchor=timed(lambda:sieve_quotients(a-1))[0]
        t_span=timed(lambda:scan(a,flags(a,b,base),points))[0]
        anchor_rates.append(t_anchor/max(1,a-1)**0.75)
        scan_rates.append(t_span/len(marks))
        evidence.append(dict(a=a,b=b,anchor_ns=t_anchor,mark_scan_ns=t_span))
    return dict(train_seed=TRAIN_SEED,test_seed=TEST_SEED,anchor_rate=median(anchor_rates),
                span_rate=median(scan_rates),training=evidence)


def timed(fn,n=3):
    times=[]
    for _ in range(n):
        t=now()
        fn()
        times.append(now()-t)
    return int(median(times)),times


def model_costs(xs,model):
    return [[model['anchor_rate']*max(1,a-1)**0.75 + model['span_rate']*(b-a+1)
             for b in xs[i:]] for i,a in enumerate(xs)]


def optimum(cost):
    n=len(cost)
    dp=[0]
    previous=[]
    for j in range(1,n+1):
        value,i=min((dp[i]+cost[i][j-i-1],i) for i in range(j))
        dp.append(value)
        previous.append(i)
    parts=[]
    j=n
    while j:
        i=previous[j-1]
        parts.append((i,j))
        j=i
    return dp[n],list(reversed(parts))


def linear_windows(xs,model):
    """A cut saves exactly the unrequested interior of its gap, and buys one new anchor."""
    if not xs:
        return []
    boundaries=[0]
    for i in range(1,len(xs)):
        saved=model['span_rate']*(xs[i]-xs[i-1]-1)
        anchor=model['anchor_rate']*max(1,xs[i]-1)**0.75
        if saved>anchor:
            boundaries.append(i)
    return list(zip(boundaries,boundaries[1:]+[len(xs)]))


def enumerate_all(cost):
    n=len(cost)
    best=float('inf')
    for mask in range(1<<(n-1)):
        limits=[0]+[i for i in range(1,n) if mask>>(i-1)&1]+[n]
        best=min(best,sum(cost[i][j-i-1] for i,j in zip(limits,limits[1:])))
    return best


def stages():
    return dict(anchor=0,mark=0,scan=0)


def solve(seq,model,kind='plan',preset=None):
    start=now()
    xs=sorted(set(seq))
    after_sort=now()
    parts=(preset if preset is not None else optimum(model_costs(xs,model))[1]
           if kind=='plan' else linear_windows(xs,model) if kind=='linear' else [(0,len(xs))] if xs else [])
    after_decide=now()
    base=oracle(isqrt(xs[-1])) if xs else []
    after_base=now()
    clocks=stages()
    results={}
    for i,j in parts:
        results.update(window(xs[i:j],base,clocks))
    t=now()
    out=[results[x] for x in seq]
    clocks.update(sort=after_sort-start,decision=after_decide-after_sort,
                  base_primes=after_base-after_decide,scatter=now()-t)
    return out,parts,clocks


def check(model,executable=None):
    _,lots=fixtures()
    truth=oracle(10**6)
    controls={}
    probes=set()
    for name,seq in {**lots,'edge':[0,1,1,2,3],'empty':[]}.items():
        expected=[bisect_right(truth,x) for x in seq]
        out,parts,_=solve(seq,model)
        assert out==expected==solve(seq,model,'one')[0]==shared(seq)==independent_distinct(seq)
        perm=seq+seq[:8]
        Random(TEST_SEED+1).shuffle(perm)
        assert solve(perm,model)[0]==[bisect_right(truth,x) for x in perm]
        xs=sorted(set(seq))
        assert parts==linear_windows(xs,model)
        anchors=[xs[i]-1 for i,j in parts]
        assert all(sieve_quotients(a)==bisect_right(truth,a) for a in anchors)
        if xs:
            probes.update(x for x in (max(0,xs[0]-1),xs[-1],*anchors,*xs[::16]) if x>=0)
        controls[name]=dict(points=seq,answer=out,anchors=anchors,windows=len(parts),
                            covered=sum(xs[j-1]-xs[i]+1 for i,j in parts))
    exact={}
    for n in (8,12):
        xs=small(n)
        cost=model_costs(xs,model)
        value,parts=optimum(cost)
        assert value==enumerate_all(cost) and parts==linear_windows(xs,model)
        exact[n]=dict(partitions=1<<(n-1),boundaries=parts)
    if executable:
        for x in sorted(probes):
            assert int(subprocess.check_output([executable,str(x)]))==bisect_right(truth,x)
    result=dict(seed=TEST_SEED,batches=controls,exhaustive=exact)
    if executable:
        result['external']=dict(queries=sorted(probes),version=subprocess.check_output(
            [executable,'--version'],text=True).splitlines()[0])
    return result


def small(n):
    return [10007,10012,14113,14129,27001,27017,45001,45065,67001,67005,85400,85401][:n]


def measured_partitions(model):
    results={}
    for n in (8,12):
        xs=small(n)
        base=oracle(isqrt(xs[-1]))
        cost=[[timed(lambda i=i,j=j:window(xs[i:j+1],base,stages()))[0]
               for j in range(i,n)] for i in range(n)]
        value,parts=optimum(cost)
        assert value==enumerate_all(cost)
        predicted=optimum(model_costs(xs,model))[1]
        results[n]=dict(points=xs,additive_measured_ns=cost,best_ns=value,best_parts=parts,
                        model_parts=predicted,partitions=1<<(n-1),
                        predicted_cost_ns=sum(cost[i][j-i-1] for i,j in predicted),
                        remeasured_model_ns=timed(lambda:solve(xs,model,preset=predicted))[0],
                        remeasured_best_ns=timed(lambda:solve(xs,model,preset=parts))[0])
    return results


def benchmark(model):
    _,lots=fixtures()
    panels={}
    for name,seq in lots.items():
        actions={'union':lambda:shared(seq),'independent':lambda:independent_distinct(seq),
                 'one':lambda:solve(seq,model,'one'),'plan':lambda:solve(seq,model)}
        panel={}
        # Interleave wall-clock samples. Trace allocations only on a separate pass.
        samples={key:[] for key in actions}
        for rep in range(3):
            keys=list(actions)
            Random(TEST_SEED+rep).shuffle(keys)
            for key in keys:
                samples[key].append(timed(actions[key],1)[0])
        for key,fn in actions.items():
            tracemalloc.start()
            fn()
            peak=tracemalloc.get_traced_memory()[1]
            tracemalloc.stop()
            panel[key]=dict(median_ns=median(samples[key]),samples_ns=samples[key],peak_python_bytes=peak)
        for key in ('one','plan'):
            runs=[solve(seq,model,key) for _ in range(3)]
            panel[key]['stage_ns']={s:median([r[2][s] for r in runs]) for s in runs[0][2]}
            panel[key]['parts']=runs[0][1]
        panels[name]=panel
    return dict(python=sys.version.split()[0],architecture=platform.machine(),test_seed=TEST_SEED,
                panels=panels,small=measured_partitions(model))


def linear_probe(model):
    """Post-analysis comparison on the same batches. No refitting."""
    _,lots=fixtures()
    panels={}
    for name,seq in lots.items():
        rows={}
        decisions=[[],[]]
        for rep in range(7):
            for kind in (('one','linear') if rep%2==0 else ('linear','one')):
                start=now()
                out,parts,times=solve(seq,model,kind)
                rows.setdefault(kind,[]).append(now()-start)
                decisions[int(kind=='linear')].append(times['decision'])
        assert solve(seq,model,'plan')[1]==solve(seq,model,'linear')[1]
        assert solve(seq,model,'linear')[0]==solve(seq,model,'one')[0]
        panel={k:dict(median_ns=median(v),samples_ns=v) for k,v in rows.items()}
        for i,key in enumerate(('one','linear')):
            tracemalloc.start()
            solve(seq,model,key)
            panel[key].update(decision_ns=median(decisions[i]),peak_python_bytes=tracemalloc.get_traced_memory()[1])
            tracemalloc.stop()
        panels[name]=panel
    return dict(python=sys.version.split()[0],seed=TEST_SEED,panels=panels)


if __name__=='__main__':
    parser=argparse.ArgumentParser(description=__doc__)
    parser.add_argument('--linear',action='store_true')
    parser.add_argument('--fit',action='store_true')
    parser.add_argument('--measure',action='store_true')
    parser.add_argument('--primecount')
    args=parser.parse_args()
    if not __debug__:
        raise RuntimeError('Enable assertions')
    if args.fit:
        result=calibration()
    else:
        model=json.loads((HERE/'modele-07.json').read_text())
        result=linear_probe(model) if args.linear else benchmark(model) if args.measure else check(model,args.primecount)
    print(json.dumps(result,indent=2))
