"""Exact inclusion–exclusion under IID uniform unsigned bytes; no simulated p-values.
Optional argv 1=Reader A JSON; argv 2=output. Without arguments, use evidence directory."""
from pathlib import Path
from math import comb
from fractions import Fraction
from collections import Counter
from itertools import product
import sys,json
d=Path(__file__).resolve().parent
rows=json.loads((Path(sys.argv[1]) if len(sys.argv)>1 else d/'grid_read_a_254.json').read_text())['rows']
tok=' '.join(rows).split();N=len(tok);h4=sum(s[0]=='4' for s in tok);alpha='0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwx';freq=Counter(t[1] for t in tok)
def stats(N,h4,conditional):
    den=(60**(N-h4)*16**h4 if conditional else 256**N)
    def miss(i,j):
        return (60-i-j)**(N-h4)*(16-i)**h4 if conditional else (256-5*i-4*j)**N
    def exactly_none(a,b,prei=0,prej=0):
        return sum((-1)**(i+j)*comb(a,i)*comb(b,j)*miss(i+prei,j+prej) for i in range(a+1) for j in range(b+1))
    assert miss(0,0)==den
    none=exactly_none(16,44);justf=exactly_none(16,43,prej=1);justlow=exactly_none(15,44,prei=1);one=16*justlow+44*justf
    def pr(n,d=den):return float(Fraction(n,d)) if d else None
    return {'p_f_absent_fixed':pr(miss(0,1)),'p_any_absent':pr(den-none),'p_exactly_one_absent':pr(one),'p_only_f_absent':pr(justf),'p_identity_f_given_exactly_one_absent':pr(justf,one),'expected_missing':pr(16*miss(1,0)+44*miss(0,1))}
# Small independent control: exhaustive two-byte low-digit draws with full 256-way ranges.
s=stats(2,0,False);assert s['p_f_absent_fixed']==sum(x%60!=41 and y%60!=41 for x,y in product(range(256),repeat=2))/65536 and s['p_any_absent']==1
report={'assumption':'IID uniform raw bytes 0..255; null illustration, not inferred generation mechanism','draws':N,'prefix_4_count':h4,'letters_missing':[x for x in alpha if not freq[x]],'upper_F_count':freq['F'],'unconditional':stats(N,h4,False),'conditional_on_leading_digits':stats(N,h4,True),'counts':dict(sorted(freq.items()))}
(Path(sys.argv[2]) if len(sys.argv)>2 else d/'grid_occupancy_253.json').write_text(json.dumps(report,indent=2)+'\n');print(report)
