"""Fixed prior selector, held-out thresholds, isolated timing and wheel state collision."""
import argparse,json,subprocess,sys,tracemalloc
from math import gcd,isqrt
from pathlib import Path
from time import perf_counter_ns
from statistics import median
from plages import run,oracle
from bisect import bisect_right
HERE=Path(__file__).resolve().parent
CASES=[[405000+d,810000] for d in (-3,0,3)]
MODEL=json.loads((HERE/'modele-08.json').read_bytes())

def exact():
    ref=oracle(810000);results=[]
    for seq in CASES:
        expected=[bisect_right(ref,x) for x in seq]
        for mode in ('one','several','union','auto'):
            out,chosen,_,_=run(seq,MODEL,mode);assert out==expected
        results.append(dict(thresholds=seq,pi=expected,choice=chosen))
    flags=lambda x:(x%30,x%7==0,x%11==0)
    accepted=[n for n in range(150,401) if gcd(n,30)==1 and not any(flags(n)[1:])]
    false=[x for x in accepted if any(x%d==0 for d in range(2,isqrt(x)+1))]
    assert false[0]==169
    collision=next((a,b) for a in range(150,169) for b in false if flags(a)==flags(b) and a in ref)
    example=next((x,y) for x in range(1,80) for y in range(x+1,150) if flags(x)==flags(y) and flags(x+1)!=flags(y+1))
    return dict(batches=results,first_false=false[0],equal_state=collision,addition_failure=example)

def measure():
    out=[]
    for seq in CASES:
        row={}
        for mode in ('one','several','union','auto'):
            vals=[];peaks=[]
            for _ in range(5):
                v=json.loads(subprocess.check_output([sys.executable,'-B',__file__,'--worker',str(seq[0]),mode]))
                vals.append(v[0]);peaks.append(v[1])
            row[mode]=dict(median_ns=median(vals),samples_ns=vals,peak=max(peaks))
        out.append(row)
    return out

if __name__=='__main__':
    p=argparse.ArgumentParser();p.add_argument('--measure',action='store_true');p.add_argument('--worker',nargs=2);p.add_argument('--primecount',type=Path)
    a=p.parse_args()
    if a.worker:
        x,mode=a.worker;seq=[int(x),810000];t=perf_counter_ns();run(seq,MODEL,mode);dt=perf_counter_ns()-t
        tracemalloc.start();run(seq,MODEL,mode);peak=tracemalloc.get_traced_memory()[1];tracemalloc.stop();v=[dt,peak]
    elif a.measure:v=measure()
    else:
        v=exact()
        if a.primecount:
            for r in v['batches']:assert r['pi']==[int(subprocess.check_output([str(a.primecount),str(x)])) for x in r['thresholds']]
    print(json.dumps(v,indent=2))
