"""python -B fragments_357.py EVIDENCE_DIRECTORY OUT.json.gz (NumPy). Session 357.
Search raw bytes of each original JPEG separately; hash checks before excluding / grouping.
"""
from collections import defaultdict
from pathlib import Path
import gzip,hashlib,json,random,statistics,sys
import numpy as np
SIZE=range(3,9); H=lambda b:hashlib.sha256(b).hexdigest()
G='a6fd639ff34993c4a55b9cebe11386f5de7e7e154ed456d98402bfa9b3617040'
M='ba38a8a86899497b0aaf74e5d909138466b52982cd963e1edc1c45dc22d73c89'
def windows(b,k):return [b[i:i+k] for i in range(len(b)-k+1)]
def index(targets):
 flat={x for t in targets for k in SIZE for x in windows(t,k)}
 lut=np.zeros(1<<24,dtype=bool)
 for x in flat:
  if len(x)==3:lut[int.from_bytes(x,'big')]=True
 return flat,lut
def scan(files,targets):
 pats,mask=index(targets);found={};counts=defaultdict(int)
 for filename,b in files:
  if len(b)<3:continue
  arr=np.frombuffer(b,dtype=np.uint8).astype(np.uint32)
  pres=(arr[:-2]<<16)|(arr[1:-1]<<8)|arr[2:]
  for i0 in np.flatnonzero(mask[pres]):
   i=int(i0)
   for k in SIZE:
    if i+k>len(b):break
    w=b[i:i+k]
    if w not in pats:break # all proper prefixes of each query's windows are indexed
    if w not in found:found[w]=(filename,i)
    counts[w]+=1
 return found,counts
def brute(files,targets):
 return {w for t in targets for k in SIZE for w in windows(t,k) if any(w in b for f,b in files)}
def summarize(t,fd):
 out={}
 for k in SIZE:
  q=windows(t,k);known=sorted(set(q)&fd.keys())
  out[k]=dict(total_windows=len(q),distinct_queries=len(set(q)),distinct_matches=len(known),
              windows_matching=sum(x in fd for x in q))
 return out
def main(d):
 manifest=(d/'jpeg_source_manifest.json').read_bytes();g=(d/'grid_cells_254.json').read_bytes()
 assert H(g)==G and H(manifest)==M
 m=json.loads(manifest);cells=json.loads(g)['cells'];seq=bytes(c['byte'] for c in cells)
 assert len(seq)==256 and [(x['page'],x['row'],x['col']) for x in cells]==sorted((x['page'],x['row'],x['col']) for x in cells)
 assert [x['file'] for x in m['files']]==[f'{i:02}.jpg' for i in range(75)]
 drops={'66.jpg','67.jpg','68.jpg'};exclude_hashes={x['sha256'] for x in m['files'] if x['file'] in drops}
 used={};files=[];excluded=[];dups=[]
 for x in m['files']:
  b=(d/x['file']).read_bytes();assert H(b)==x['sha256']
  if x['sha256'] in exclude_hashes:excluded.append(x['file']);continue
  if x['sha256'] in used:dups.append([x['file'],used[x['sha256']]]);continue
  used[x['sha256']]=x['file'];files.append((x['file'],b))
 assert len(files)+len(excluded)+len(dups)==75
 rng=random.Random(357);shuffles=[]
 for _ in range(32):
  t=list(seq);rng.shuffle(t);assert sorted(t)==sorted(seq);shuffles.append(bytes(t))
 control=[];cn=[]
 for f,b in (files[0],files[-1]):
  start=len(b)//2;t=b[start:start+256];assert len(t)==256
  control.append(t);cn.append(dict(file=f,start=start,sha256=H(t)))
 edge=[('left',bytes(range(8))),('right',bytes(range(8,16)))]
 # Would find this query if page ends were erroneously joined.
 assert bytes(range(4,12)) not in scan(edge,[bytes(range(4,12))])[0]
 probe=[seq,shuffles[0],*control]
 # Independent whole-window substring implementation on short prefixes of several files.
 sample=[(f,b[:8192]) for f,b in files[::9]]
 assert set(scan(sample,probe)[0])==brute(sample,probe)
 fd,ct=scan(files,[seq,*shuffles,*control]);summ=summarize(seq,fd)
 cc=[summarize(t,fd) for t in control];assert all(s[k]['windows_matching']==257-k for s in cc for k in SIZE)
 detail={}
 for k in SIZE:
  distinct={}
  for i,w in enumerate(windows(seq,k)):
   if w in fd:
    # Preserve every grid position, but only the first file/offset plus multiplicity in the corpus.
    if w.hex() not in distinct:distinct[w.hex()]=dict(grid_offsets=[],first_file_and_offset=fd[w],occurrences=ct[w])
    distinct[w.hex()]['grid_offsets'].append(i)
  detail[k]=distinct
 sh=[summarize(t,fd) for t in shuffles]
 return dict(plan='format_probes_354_357_plan.txt',source_manifest_sha256=M,grid_source_sha256=G,
  preferred_grid_sha256=H(seq),source_revision=m['repository_revision'],source_files=list(used.values()),
  excluded_including_hash_aliases=excluded,eligible_duplicate_to_first=dups,distinct_jpegs=len(files),
  total_bytes=sum(len(b) for f,b in files),possible_file_starts={k:sum(len(b)-k+1 for f,b in files) for k in SIZE},
  tested_lengths=list(SIZE),registered_minimum=8,coordinate_system='zero-based byte offsets from each file or grid start; never spans files',
  preferred=summ,matched_preferred_windows=detail,shuffle_seed=357,shuffle_method='32 fresh permutations of all 256 preferred bytes using Python random.Random(357).shuffle',
  shuffled_distinct_counts=[{k:s[k]['distinct_matches'] for k in SIZE} for s in sh],
  shuffled_summary={k:{'min':min(v),'median':statistics.median(v),'max':max(v),'number_gte_real':sum(a>=summ[k]['distinct_matches'] for a in v)}
   for k in SIZE for v in [[s[k]['distinct_matches'] for s in sh]]},
  positive_controls=[{**n,'scores':s} for n,s in zip(cn,cc)],cross_file_negative='passed',naive_scan_oracle='passed; eight 8192-byte prefixes, first shuffled grid, original grid, two positives')
if __name__=='__main__':
 d=Path(sys.argv[1]);v=main(d)
 Path(sys.argv[2]).write_bytes(gzip.compress((json.dumps(v,sort_keys=True,separators=(',',':'))+'\n').encode(),mtime=0))
