"""Offline notation lab, Python 3 stdlib. python -B format_lab_348.py EVIDENCE_DIR OUTPUT.json"""
import re, sys, json, hashlib
from collections import Counter
from pathlib import Path
from decimal import Decimal, localcontext
from itertools import product
from string import ascii_letters,digits,hexdigits

ALPHA='0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwx'
VALID=re.compile(r'(?:[0-3][0-9A-Za-x]|4[0-9A-F])',re.ASCII)
HEX=re.compile(r'[0-9A-Fa-f]{2}',re.ASCII)
EIGHT='11 12 13 14 15 16 17 18'
def val(t): return 60*ALPHA.index(t[0])+ALPHA.index(t[1])
def enc(n): return ALPHA[n//60]+ALPHA[n%60]
def runs(tokens):
    out=[];cur=[]
    for w in tokens:
        if VALID.fullmatch(w):cur.append(w)
        else:
            if cur:out.append(cur)
            cur=[]
    if cur:out.append(cur)
    return out
def scan(s,k,evidence=False):
    # Explicit ASCII whitespace. A comma, colon or other punctuation is NOT normalized away.
    # Returning token lists, rather than byte offsets; line-preserving caller scans each line.
    return [r for r in runs(re.split(r'[ \t\f\v\r\n]+',s.strip(' \t\f\v\r\n'))) if len(r)>=k and (not evidence or any(not HEX.fullmatch(w) for w in r))]
def windows(rows,k):
    return [r[i:i+k] for r in rows for i in range(len(r)-k+1)]
def at_least_one(p,k,n):
    # Probability of at least one run of k successes in n independent draws.
    with localcontext() as ctx:
        ctx.prec=65
        probs=[Decimal(1)]+[Decimal(0)]*(k-1)
        for _ in range(n):probs=[sum(probs)*(1-p)]+[x*p for x in probs[:-1]]
        return format(1-sum(probs),'.12g')
def check_run_recurrence():
    # Independent full enumeration at a small size, including overlapping placements.
    for k in (2,3,4,8):
        n=10; target='1'*k
        hits=sum(target in ''.join(v) for v in product('01',repeat=n))
        assert abs(Decimal(at_least_one(Decimal(1)/2,k,n))-Decimal(hits)/2**n)<Decimal('1e-12')
def main(d):
    check_run_recurrence()
    inputs={x:hashlib.sha256((d/x).read_bytes()).hexdigest() for x in ('grid_cells_254.json','grid_read_a_254.json','grid_read_b_254.json','grid_digest_254_image.txt')}
    assert inputs['grid_cells_254.json']=='a6fd639ff34993c4a55b9cebe11386f5de7e7e154ed456d98402bfa9b3617040'
    cells=json.loads((d/'grid_cells_254.json').read_bytes())['cells'];readers=[json.loads((d/f'grid_read_{v}_254.json').read_bytes())['rows'] for v in 'ab']
    rows=[s.split() for s in readers[0]];assert rows==[s.split() for s in readers[1]]
    raw=[w for r in rows for w in r];assert raw==[c['a'] for c in cells]
    qr=[x+y for x,y in product(digits+ascii_letters,repeat=2)];codes={x for x in qr if VALID.fullmatch(x)}
    assert codes=={enc(i) for i in range(256)} and all(val(enc(i))==i for i in range(256))
    digest=(d/'grid_digest_254_image.txt').read_text().strip()
    assert len(''.join(digest.split()))==128
    sites=[(i,c) for i,c in enumerate(cells) if c['altsB']];assert len(sites)==10
    for i,c in sites:
        assert len(c['altsB'])==1 and {c['a'][1],c['altsB'][0][1]}=={'I','l'}
        assert c['a'] in codes and c['altsB'][0] in codes and abs(val(c['a'])-val(c['altsB'][0]))==29
        assert not HEX.fullmatch(c['a']) and not HEX.fullmatch(c['altsB'][0])
    assert all(w in codes for w in raw)
    limits=(4,6,8,12,16); line={k:sum(bool(scan(r,k)) for r in readers[0]) for k in limits}
    pages=[[w for r in rows[a:b] for w in r] for a,b in ((0,10),(10,23),(23,32))]
    strict={'ascii_alnum_pairs':len(qr),'codewords':len(codes),'value_range':[0,255],
        'lead_counts':dict(sorted(Counter(t[0] for t in codes).items())),
        'cells':len(raw),'different_printed_spellings':len(set(raw)), 'physical_rows':len(rows),
        'intact_line_counts_for_minimum_length':line,
        'page_maximal_runs':[len(scan(' '.join(p),8)[0]) for p in pages],
        'image_reading_alternative_sites':len(sites),'interpretation_combinations':2**len(sites),
        'example':{'page':49,'row':1,'col':3,'tokens':['2l','2I'],'values':[val('2l'),val('2I')]},
        'digest_line_lengths':[len(s) for s in digest.splitlines()],'digest_max_exact_runs':len(scan(digest,1))}
    assert ''.join(rows[0])==''.join(readers[0][0].split())
    formats={'uppercase_uniform_hex':[f'{v:02X}' for v in range(256)],'lowercase_uniform_hex':[f'{v:02x}' for v in range(256)],'two_digit_decimal_00_to_99':[f'{v:02d}' for v in range(100)],'decimal_unpadded_byte':[str(v) for v in range(256)],'row_column_11_to_88':[str(x)+str(y) for x in range(1,9) for y in range(1,9)],'uppercase_hex_00_to_3F':[f'{v:02X}' for v in range(64)]}
    controls={}
    for name,tokens in formats.items():
        n=sum(bool(VALID.fullmatch(t)) for t in tokens);m=len(tokens);p=Decimal(n)/m
        controls[name]={'one_accepted':n,'one_total':m,'one_window_length8':str(p**8),'one_or_more_in_1024':{k:at_least_one(p,k,1024) for k in limits}}
    collision={'text':EIGHT,'radix60':[val(t) for t in EIGHT.split()],'hex':[int(t,16) for t in EIGHT.split()],'decimal':[int(t) for t in EIGHT.split()],'coordinates':[[int(t[0]),int(t[1])] for t in EIGHT.split()]}
    assert all(EIGHT.split()[i] in codes for i in range(8))
    rowshex=[sum(not bool(HEX.fullmatch(w)) for w in r) for r in rows]
    bypage=[Counter('outside_hex' if not HEX.fullmatch(w) else 'hex_compatible' for w in page) for page in pages]
    onlyhex=max([0]+[len(r) for page in pages for r in re.findall(r'1+', ''.join('1' if HEX.fullmatch(w) else '0' for w in page))])
    k_sweep={}
    for k in limits:
        win=windows(pages,k);k_sweep[k]={'page_bounded_contiguous_windows':len(win),'all_valid_and_nonhex_witness':sum(any(not HEX.fullmatch(w) for w in group) for group in win)}
    canonical_octets=bytes([val(w) for w in raw]);upper=' '.join(f'{v:02X}' for v in canonical_octets);low=' '.join(f'{v:02x}' for v in canonical_octets)
    examples={'true_first_printed_row':readers[0][0], 'actual_values_as_uppercase_hex':upper,'actual_values_as_lowercase_hex':low,
        'LP2_digest_original_five_lines':digest, 'all_numeric_collision':EIGHT,
        'uppercase_hex_low_bytes':'00 01 02 03 04 05 06 07', 'invented_event_labels':'1G 1H 1I 1J 1K 1L 1M 1N',
        'ordinary_prose':'It is up to me to go on', 'comma_list':'1G,1H,1I,1J,1K,1L,1M,1N','joined_row':''.join(rows[0])}
    cases={n:{'valid_runs_len8':len(scan(s,8)),'with_nonhex':len(scan(s,8,True)),'longest_valid_run':max([0]+[len(a) for a in scan(s,1)])} for n,s in examples.items()}
    witness={'outside_hex_by_page':bypage,'rows_with_witness':sum(x>0 for x in rowshex),'outside_hex_range_per_row':[min(rowshex),max(rowshex)],'outside_hex_counts_per_row':rowshex,
        'outside_hex_distinct_codewords':sum(not bool(HEX.fullmatch(w)) for w in codes),'global_within_page_longest_hexonly_run':onlyhex,'k_sweep':k_sweep,
        'illustrative_controls':cases,'invented_event_labels':examples['invented_event_labels'],'hex_compatible_target_tokens':sorted(set(w for w in raw if HEX.fullmatch(w))),'no_witness_uniform_octets_8':str((Decimal(256-sum(not bool(HEX.fullmatch(w)) for w in codes))/256)**8)}
    return {'inputs_sha256':inputs,'348_grammar':strict,'349_collision_rates':controls,'349_ambiguous_known_string':collision,'350_nonhex_witness':witness}
if __name__=='__main__':
    out=main(Path(sys.argv[1]));Path(sys.argv[2]).write_text(json.dumps(out,indent=2,sort_keys=True)+'\n')
