"""python signed_340.py EVIDENCE_DIR CACHE_DIR OUTPUT.json.gz (after 339)"""
from pathlib import Path
import collections,json,re,sys
from signed_339 import load,em,H
pair=re.compile(r'(?:[0-3][0-9A-Za-x]|4[0-9A-F])',re.ASCII)
def scan(s):
 # Physical LF is handled explicitly. A stream may cross a line only through source whitespace.
 hits=[];runs=[];cur=[];line_max=0;best=0
 for n,l in enumerate(s.split('\n'),1):
  k=0
  for t in re.findall(r'[^ \t\v\f\r]+',l):
   if pair.fullmatch(t):
    hits.append([n,t]);cur.append([n,t]);k+=1;line_max=max(line_max,k)
   else:
    if cur:runs.append(cur)
    cur=[];k=0
 if cur:runs.append(cur)
 return {'accepted_cells':len(hits),'longest_same_line':line_max,'longest_allow_line_breaks':max([len(x) for x in runs] or [0]),'runs_ge8':[[v[0][0],v[-1][0],len(v)] for v in runs if len(v)>=8],'all_hits':hits}
def main(d,cache,out):
 results=load(d/'signed_339_results.json.gz')['records'];bs=json.loads((cache/'verified_bodies.json').read_bytes());groups={}
 for r in results:
  if r['state']!='valid':continue
  n=r['id'];s=bs[n];assert H(s.encode())==r['body_sha256']
  k=r['canonical_sha256'];result=scan(s)
  if k in groups:assert groups[k]['scan']==result
  else:groups[k]={'id':n,'scan':result,'occurrences':[]}
  groups[k]['occurrences'].append(n)
 cells=json.loads((d/'grid_cells_254.json').read_bytes())['cells'];rows=collections.defaultdict(list)
 for c in cells:rows[c['page'],c['row']].append((c['col'],c['a']))
 positive=scan('\n'.join(' '.join(s for _,s in sorted(v)) for _,v in sorted(rows.items())))
 assert (positive['accepted_cells'],positive['longest_same_line'],positive['longest_allow_line_breaks'])==(256,8,256)
 del positive['all_hits']
 em({'comparison_groups':groups,'positive_control':positive,'grid_rows':len(rows),'threshold':8},out)
if __name__=='__main__':main(*map(Path,sys.argv[1:]))
