import json
import math
from pathlib import Path
from scipy.stats import fisher_exact

p=Path(__file__).resolve().parents[1]/"outputs"/"Kingston-known-bits.json"
rec=json.loads(p.read_text())
n=rec["shots_per_circuit"]
data={}
for row,counts in zip(rec["rows"],rec["counts"]):
    errors=sum(count for bits,count in counts.items() if (int(bits,2)>>2)!=row["bit"])
    assert errors==row["wrong"] and sum(counts.values())==n
    data[row["chain"],row["bit"],row["mode"]]=errors
print(sorted(data.items()),rec["metrics"]["usage"],rec["job_id"])


def wilson(p):
    z=1.95996398454
    den=1+z*z/n
    c=(p+z*z/(2*n))/den
    h=z*math.sqrt(p*(1-p)/n+z*z/(4*n*n))/den
    return c-h,c+h


for bit in (0,1):
    for mode in ("teleport","direct"):
        a,b=[data[chain,bit,mode] for chain in ("best","typical")]
        x,y=a/n,b/n
        lx,ux=wilson(x)
        ly,uy=wilson(y)
        diff=x-y
        ci=(diff-math.hypot(x-lx,uy-y),diff+math.hypot(ux-x,y-ly))
        print(bit,mode,100*x,100*y,"delta & CI",100*diff,[100*v for v in ci],
              "two-sided Fisher",fisher_exact([[a,n-a],[b,n-b]]).pvalue)
