"""Scalar A05, exact prime-rank comparisons and explicit accounting of inputs."""
from bisect import bisect_right
import argparse
from math import isqrt
import json
from pathlib import Path
import subprocess
from time import perf_counter_ns
from statistics import median
import tracemalloc
from rang_premiers import CASES, count, grouped, oracle, pair_list, select, trial, wheel

LIMIT=23**3-1
SCALES=(1000,10000,100000,1000000)
RANKS=(10,100,1000)


def domain(x):
    root=isqrt(x)
    # floor(x/i) above the square root, followed by every smaller value down to one.
    top=[x//i for i in range(1,root+1)]
    return top+list(range(min(root,top[-1]-1),0,-1)) if top else []


def sieve_quotients(x,detail=False,prepared=None):
    if x<2:return (0,{}) if detail else 0
    values=domain(x) if prepared is None else prepared
    state={v:v-1 for v in values}
    updates=0
    history=[]
    for prime in range(2,isqrt(x)+1):
        if state[prime]==state[prime-1]:continue
        before=state[prime-1]
        for v in values:
            if v<prime*prime:break
            state[v]-=state[v//prime]-before
            updates+=1
        if detail:history.append([prime,state[x]])
    if detail:
        return state[x],dict(quotient_keys=len(values),count_slots=len(state),input_primes=0,
                 discovered=[p for p,_ in history],domain_divisions=isqrt(x),update_divisions=updates,
                 prime_tests=isqrt(x)-1,trace=history)
    return state[x]


def correction(p,q,cap,mode):
    small=trial(p)
    factors=[v for v in trial(cap//q) if v>=q]
    terms=wheel(small)
    if mode=="pairs":
        products=pair_list(factors,cap)
        return lambda x:count(x,terms,len(small),lambda y:bisect_right(products,y))
    return lambda x:count(x,terms,len(small),lambda y:grouped(y,factors))


def work_counts(x,p,q,cap):
    # Count floor divisions in a ready query. Trial-division remainders belong to preparation.
    factors=[v for v in trial(cap//q) if v>=q]
    terms=wheel(trial(p))
    n=sum(d<=x for d,_ in terms)
    i=bisect_right(factors,isqrt(x))
    quotient_divisions=0
    while i<len(factors):
        z=x//factors[i]
        quotient_divisions+=1
        if z<q:break
        i=bisect_right(factors,x//z,lo=i+1)
        quotient_divisions+=1
    return dict(wheel_primes=trial(p),factor_prime_count=len(factors),factor_limit=cap//q,
                signed_terms=len(terms),pair_index_keys=len(pair_list(factors,cap)),
                pair_query_divisions=n,grouped_query_divisions=n+quotient_divisions)


def rank_search(k,counter):
    probes=[]
    def traced(x):
        probes.append(x)
        return counter(x)
    value=select(k,19,LIMIT,traced)
    return dict(value=value,probes=probes)


def batch(cap):
    return [19+i*(cap-19)//63 for i in range(64)]


def experiment(external=None):
    thresholds=[]
    comparison=[]
    for p,q in CASES:
        cap=q**3+1
        known=oracle(cap)
        counters=[correction(p,q,cap,m) for m in ("pairs","grouped")]
        for x in sorted(z+h for z in (q*q,q**3) for h in (-1,0,1)):
            truth=bisect_right(known,x)
            observed=[f(x) for f in counters]
            val=sieve_quotients(x)
            assert val==truth and observed==[truth+int(x>=q**3)]*2
            thresholds.append(dict(p=p,q=q,x=x,true_rank=val,corrected=observed[0]))
    known=oracle(SCALES[-1])
    for x in SCALES:
        val,stats=sieve_quotients(x,True)
        assert val==bisect_right(known,x) and stats["discovered"]==known[:bisect_right(known,isqrt(x))]
        comparison.append(dict(x=x,rank=val,work=stats))
    counters=[sieve_quotients,correction(19,23,LIMIT,"pairs"),correction(19,23,LIMIT,"grouped")]
    selections=[rank_search(k,sieve_quotients) for k in RANKS]
    for k,s in zip(RANKS,selections):
        assert s["value"]==known[k-1] and all(rank_search(k,f)==s for f in counters)
    panels={}
    for cap in (LIMIT,SCALES[-1]):
        xs=batch(cap)
        answers=[sieve_quotients(x) for x in xs]
        assert answers==[bisect_right(known,x) for x in xs]
        if cap==LIMIT:
            for f in counters[1:]:assert answers==[f(x) for x in xs]
        panels[str(cap)]=dict(thresholds=xs,ranks=answers)
    result=dict(square_cube=thresholds,scales=comparison,trace30=sieve_quotients(30,True)[1],
                selections=selections,shared_preparation=work_counts(LIMIT,19,23,LIMIT),batches=panels)
    if external:
        xs=sorted({r["x"] for r in thresholds}|set(SCALES)|{v for d in panels.values() for v in d["thresholds"]})
        for x in xs:
            assert int(subprocess.check_output([external,str(x)]))==bisect_right(known,x)
        for k in RANKS:assert int(subprocess.check_output([external,str(k),"--nth-prime"]))==known[k-1]
        result["external"]={"version":subprocess.check_output([external,"--version"],text=True).splitlines()[0],
                            "counts":len(xs),"selections":len(RANKS)}
    return result


def cost(fn):
    samples=[]
    for _ in range(5):
        t=perf_counter_ns()
        fn()
        samples.append(perf_counter_ns()-t)
    tracemalloc.start()
    fn()
    _,peak=tracemalloc.get_traced_memory()
    tracemalloc.stop()
    return dict(median_ns=median(samples),samples_ns=samples,peak_python_bytes=peak)


def benchmark(binary=None):
    panels={}
    for cap in (LIMIT,SCALES[-1]):
        xs=batch(cap)
        table=oracle(cap)
        vals=domain(cap)
        tasks={
            "a05_domain":lambda:domain(cap),"a05_initialized_query":lambda:sieve_quotients(cap,prepared=vals),
            "a05_cold":lambda:sieve_quotients(cap),"a05_batch64":lambda:[sieve_quotients(x) for x in xs],
            "oracle_prepare":lambda:oracle(cap),"oracle_cold":lambda:bisect_right(oracle(cap),cap),
            "oracle_batch64_ready":lambda:[bisect_right(table,x) for x in xs]}
        if cap==LIMIT:
            tasks["a05_three_selects"]=lambda:[rank_search(k,sieve_quotients) for k in RANKS]
            tasks["oracle_three_selects"]=lambda:[rank_search(k,lambda x:bisect_right(table,x)) for k in RANKS]
            for m in ("pairs","grouped"):
                ready=correction(19,23,cap,m)
                tasks[m+"_prepare"]=lambda mode=m:correction(19,23,cap,mode)
                tasks[m+"_cold"]=lambda mode=m:correction(19,23,cap,mode)(cap)
                tasks[m+"_batch64_ready"]=lambda f=ready:[f(x) for x in xs]
                tasks[m+"_three_selects_ready"]=lambda f=ready:[rank_search(k,f) for k in RANKS]
        if binary:
            tasks["primecount_cli_cold"]=lambda:subprocess.check_output([binary,str(cap)])
            tasks["primecount_cli_batch64"]=lambda:[subprocess.check_output([binary,str(x)]) for x in xs]
            if cap==LIMIT:
                tasks["primecount_cli_three_native_selects"]=lambda:[subprocess.check_output([binary,str(k),"--nth-prime"]) for k in RANKS]
        panels[str(cap)]={label:cost(fn) for label,fn in tasks.items()}
    return panels


if __name__=="__main__":
    p=argparse.ArgumentParser(description=__doc__)
    p.add_argument("--primecount")
    p.add_argument("--measure",action="store_true")
    args=p.parse_args()
    print(json.dumps(benchmark(args.primecount) if args.measure else experiment(args.primecount),indent=2))
