"""Exact prefix-oracle control and paired observation trials on products p × 5."""
from fractions import Fraction as F
from itertools import combinations
from math import comb,lcm
from random import Random
from time import perf_counter
import argparse,json
from bruit12 import hist,matrix

AUX={0,1,3}

def prefix_table(mask,p,v=1,w=1):
    target={v*x%p for x in mask};other={w*x%5 for x in AUX}
    table=[0]
    for x in range(5*p):table.append(table[-1]+int(x%p in target and x%5 in other))
    return table

def probes(p):
    return [next(x for x in range(r,5*p,p) if x%5 in AUX) for r in range(p)]

def direct(positions,prefix):
    cache={}
    def query(x):
        if x not in cache:cache[x]=prefix(x)
        return cache[x]
    return tuple(r for r,x in enumerate(positions) if query(x+1)-query(x)),len(cache)

def measurements(vals,positions,mode,R):
    groups=[[vals[x] for x in group] for group in positions]
    if mode=='pairs':
        v=groups[0]
        estimate=F(sum((v[i]-v[i+1])**2 for i in range(0,len(v),2)),len(v)*R**2)
    else:
        # Stratified estimate of E[D²] - E[D]², with unbiased variance-of-mean correction.
        h=len(groups);pop=R//h
        first=second=mean_var=F(0)
        for v in groups:
            n=len(v);s=sum(v);ss=sum(x*x for x in v)
            first+=F(s,n*h);second+=F(ss,n*h)
            sample_var=F(n*ss-s*s,n*(n-1))
            mean_var+=F(pop-n,pop*n*h*h)*sample_var
        estimate=(second-first*first+mean_var)/R**2
    used={x for group in positions for x in group};u=[vals[x] for x in used];n=len(u)
    lower=F(n*sum(x*x for x in u)-sum(u)**2,R**4)
    upper=lower+F(144*(comb(R,2)-comb(n,2)),R**2)
    return estimate,len(used),lower,upper

def observe(rng,mode,R,n):
    if mode=='pairs':return [[rng.randrange(R) for _ in range(n)]]
    if mode=='simple':return [rng.sample(range(R),n)]
    return [rng.sample(range(h,R,5),n//5) for h in range(5)]

def run(p,measure=False):
    R=5*p;start=perf_counter();positions=probes(p);reads=set();checked=0
    for mask in combinations(range(p),4):
        raw=prefix_table(mask,p)
        result,count=direct(positions,raw.__getitem__)
        assert result==mask;reads.add(count);checked+=1
    t1=perf_counter()
    reps={}
    for tail in combinations(range(1,p),3):
        mask=(0,)+tail;reps.setdefault(hist(mask,p),mask)
    hs=sorted(reps);rows=matrix(p,3)
    scores=[[r[0]*4+sum(x*y for x,y in zip(h,r[1:])) for r in rows] for h in hs]
    den=lcm(*(v.denominator for row in scores for v in row))
    integer=[[int(v*den) for v in row] for row in scores]
    pairs=[tuple(abs(x-y) for x,y in zip(a,b)) for a,b in combinations(integer,2)]
    designs=list(combinations(range(len(rows)),4))
    radii={c:min(max(d[i] for i in c) for d in pairs) for c in designs}
    cols=max(designs,key=radii.get);control=[designs[0]]+[Random(seed).choice(designs) for seed in (1401,1402)]
    t2=perf_counter();correct={};reserved=list(range(0,len(hs),5))
    for j in reserved:
        tables=[]
        for c in cols:
            tw=[]
            for w in (1,2):
                raw=prefix_table(reps[hs[j]],p,c+1,w)
                vals=[R*raw[x]-12*x for x in range(R)]
                mu=F(R*sum(v*v for v in vals)-sum(vals)**2,R**4)
                tw.append((vals,mu))
            assert (tw[0][1]+tw[1][1])/2==scores[j][c]
            tables.append(tw)
        for seed in range(14100,14116):
            for mode in ('pairs','simple','strata'):
                for n in (20,40,60):
                    key=f'{mode}-{n}';out=correct.setdefault(key,dict(trials=0,unique_correct=0,ties=0,distinct_calls_sum=0,certified=0))
                    rng=Random(seed);obs=[];bounds=[]
                    for tw in tables:
                        observed=lo=hi=F(0)
                        for vals,truth in tw:
                            value,used,left,right=measurements(vals,observe(rng,mode,R,n),mode,R)
                            assert left<=truth<=right
                            observed+=value;lo+=left;hi+=right;out['distinct_calls_sum']+=used
                        obs.append(observed/2);bounds.append((lo/2,hi/2))
                    unit=lcm(den,*(v.denominator for v in obs))
                    target=[int(v*unit) for v in obs]
                    costs=[max(abs(a-row[c]*(unit//den)) for a,c in zip(target,cols)) for row in integer]
                    winners=[i for i,x in enumerate(costs) if x==min(costs)]
                    candidates=[i for i,row in enumerate(scores) if all(a<=row[c]<=b for (a,b),c in zip(bounds,cols))]
                    assert j in candidates
                    out['trials']+=1;out['certified']+=len(candidates)==1
                    out['unique_correct']+=winners==[j];out['ties']+=len(winners)>1
    data=dict(p=p,all_masks=checked,probes=positions,distinct_direct_reads=sorted(reads),dictionary=len(hs),
                known_scores=len(hs)*len(rows),designs=len(designs),best=[i+1 for i in cols],radius=str(F(radii[cols],2*den)),
                controls=[dict(classes=[i+1 for i in c],radius=str(F(radii[c],2*den))) for c in control],
                reserved=reserved,exact_variance_reads=8*R,noise=correct)
    if measure:data['wall_seconds']={'all_direct_checks':t1-start,'dictionary_and_design':t2-t1,'reserved_trials':perf_counter()-t2}
    return data

if __name__=='__main__':
    parser=argparse.ArgumentParser();parser.add_argument('--measure',action='store_true');args=parser.parse_args()
    print(json.dumps([run(p,args.measure) for p in (13,17)],indent=2))
