"""Independent shot-count check for both routes and the eight balanced cases."""
import json
from pathlib import Path
from collections import Counter
from scipy.stats import norm
from math import sqrt

root=Path(__file__).resolve().parent
r=json.loads((root/"VF2-Kingston.json").read_bytes())
assert r["stage"]=="done"
blocks=[]
for start in range(0,32,8):
    cells={}
    for k,counts in zip(r["order"][start:start+8],r["counts_by_block"][start:start+8]):
        active=[i for i,bit in enumerate(k) if bit!="-"]
        result=Counter()
        for s,n in counts.items():
            # Qiskit prints the receivers first, highest classical bit first.
            got=s[:len(active)][::-1]
            ok=[bit==k[path] for bit,path in zip(got,active)]
            for i,path in enumerate(active):
                result["AB"[path]]+=n*ok[i]
            result["all"]+=n*all(ok)
        assert sum(counts.values())==64
        cells[k]=result
    assert len(cells)==8
    blocks.append(cells)
for k,row in r["correct"].items():
    assert all(sum(block[k][col] for block in blocks)==val for col,val in row.items())
print(r["selection"],r["metrics"]["usage"],r["job_id"],r["contrasts"])
for i,path in enumerate("AB"):
    ts=var=0
    for bit in "01":
        n_s=n_p=0
        for b in blocks:
            single=sum(row[path] for k,row in b.items() if "-" in k and k[i]==bit)
            pair=sum(row[path] for k,row in b.items() if "-" not in k and k[i]==bit)
            n_s+=single
            n_p+=pair
            m=single+pair
            ts+=pair-m*2/3
            var+=128*64*m*(192-m)/(192**2*191)
        print(path,bit,n_s,n_p)
    print("two-sided stratified p",2*norm.sf(abs(ts)/sqrt(var)))
print("correct joint",sum(v["all"] for k,v in r["correct"].items() if "-" not in k))
print("ideal",json.loads((root/"VF2-simulator.json").read_bytes())["correct"])
