"""Prime rank through the first missing cube. Standard library, Python 3.10+."""
from bisect import bisect_right
from math import isqrt
from statistics import median
from time import perf_counter_ns
import argparse
import json
import platform
import subprocess
import tracemalloc

CASES = ((5,7),(7,11),(11,13),(19,23))
RANK_OFFSETS = (0,1,2,5,10,25,50)


def trial(limit):
    primes = []
    for v in range(2,limit+1):
        if all(v%p for p in primes if p*p<=v):
            primes.append(v)
    return primes


def oracle(limit):
    good = bytearray([1])*(limit+1)
    good[:2] = bytes(2)
    for i in range(2,isqrt(limit)+1):
        if good[i]:
            for j in range(i*i,limit+1,i):
                good[j] = 0
    return [i for i in range(limit+1) if good[i]]


def wheel(small):
    terms = [(1,1)]
    for p in small:
        terms += [(p*d,-s) for d,s in terms]
    return terms


def pair_list(factors, limit):
    return sorted(a*b for i,a in enumerate(factors) if a*a<=limit
                  for b in factors[i:] if a*b<=limit)


def grouped(x, factors):
    # Both factors <= sqrt(x), followed by equal floor(x/b) for the larger factor.
    small = bisect_right(factors,isqrt(x))
    count = small*(small+1)//2
    i = small
    while i<len(factors):
        quotient = x//factors[i]
        if quotient<factors[0]:
            break
        end = bisect_right(factors,x//quotient,lo=i+1)
        count += (end-i)*bisect_right(factors,quotient)
        i = end
    return count


def count(x, terms, size, correction):
    return sum(sign*(x//d) for d,sign in terms if d<=x)+size-1-correction(x)


def select(k, p, limit, counter):
    lo,hi = p,limit
    while lo<hi:
        mid=(lo+hi)//2
        if counter(mid)<k:
            lo=mid+1
        else:
            hi=mid
    return lo


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


def experiment(measure=False, binary=None):
    rows = []
    for p,q in CASES:
        cap=q**3
        small=trial(p)
        terms=wheel(small)
        factors=[v for v in trial(cap//q) if v>=q]
        products=pair_list(factors,cap)
        counters = [lambda x:count(x,terms,len(small),lambda y:bisect_right(products,y)),
                    lambda x:count(x,terms,len(small),lambda y:grouped(y,factors))]
        truth=oracle(cap)
        for x in range(p,cap+1):
            actual=bisect_right(truth,x)
            values=[f(x) for f in counters]
            assert values == [actual+int(x==cap)]*2,(p,x,actual,values)
        ranks=[len(small)+i for i in RANK_OFFSETS]
        selections=[select(k,p,cap-1,counters[0]) for k in ranks]
        assert selections==[select(k,p,cap-1,counters[1]) for k in ranks]==[truth[k-1] for k in ranks]
        row=dict(p=p,q=q,thresholds=cap-p+1,exact_through=cap-1,
                 first_failure=dict(x=cap,corrected=counters[0](cap),truth=len(truth)),
                 input_prime_limit=cap//q,factor_primes=len(factors),wheel_terms=len(terms),
                 stored_products=len(products),ranks=ranks,primes=selections)
        if binary:
            xs=[p,q*q-1,q*q,q*q+1,cap-1,cap]
            for x in xs:
                assert int(subprocess.check_output([binary,str(x)]))==bisect_right(truth,x)
            for k,v in zip(ranks,selections):
                assert int(subprocess.check_output([binary,str(k),'--nth-prime']))==v
            row['primecount_checks'] = len(xs)+len(ranks)
        if measure:
            queries=tuple(range(p,cap))
            def build_factors():
                return [v for v in trial(cap//q) if v>=q]
            tasks=dict(factor_primes=build_factors,wheel=lambda:wheel(trial(p)),
                       pair_preparation=lambda:pair_list(factors,cap),
                       oracle_preparation=lambda:oracle(cap),
                       oracle_batch=lambda:sum(bisect_right(truth,x) for x in queries))
            for name,counter in zip(('pair','quotient'),counters):
                tasks[name+'_batch']=lambda fn=counter:sum(fn(x) for x in queries)
                tasks[name+'_select']=lambda fn=counter:[select(k,p,cap-1,fn) for k in ranks]
            row['measures']={name:measured(fn) for name,fn in tasks.items()}
        rows.append(row)
    out=dict(rows=rows)
    if measure:out.update(python=platform.python_version(),machine=platform.machine(),system=platform.system())
    if binary:out['external_version']=subprocess.check_output([binary,'--version'],text=True).splitlines()[0]
    return out


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