import json
from pathlib import Path
from collections import Counter
from scipy.stats import binomtest

root=Path(__file__).resolve().parents[1]/"outputs"
r=json.loads((root/"Hamming-A-Kingston.json").read_text())
positions=[3,5,6,7,9,10,11,12]
book={}
for data in range(256):
    bits={p:(data>>i)&1 for i,p in enumerate(positions)}
    for p in (1,2,4,8):
        bits[p]=sum(bits[q] for q in positions if q&p)%2
    book[data]=sum(v<<(q-1) for q,v in bits.items())
totals=Counter()
dist_hist=Counter()
for raw,n in r["counts"][0].items():
    w=int(raw[:12],2)
    candidates=[k for k,c in book.items() if (c^w).bit_count()<=1]
    assert len(candidates)<=1
    before=sum(((w>>(p-1))&1)<<i for i,p in enumerate(positions))==65
    after=candidates==[65]
    for k,f in (("raw_byte_exact",before),("decoded_byte_exact",after),("rescued",after and not before),
                ("lost",before and not after),("uncorrectable_flags",not candidates),
                ("wrong_returned",bool(candidates) and not after)):
        totals[k]+=n*f
    dist_hist[(w^book[65]).bit_count()]+=n
assert sum(dist_hist.values())==256 and all(r["analysis"][k]==v for k,v in totals.items())
print(totals,dist_hist,binomtest(totals["decoded_byte_exact"],256).proportion_ci(method="wilson"))
print(r["job_id"],r["metrics"]["usage"])
