"""python notice_363.py EVIDENCE OUTDIR S339_CACHE [--outguess /path/to/outguess]. Python/GnuPG/Tesseract/Pillow."""
from pathlib import Path
import re,subprocess,tempfile,json,gzip,hashlib,sys,argparse
from collections import Counter
import numpy as np
from PIL import Image
def H(b):return hashlib.sha256(b).hexdigest()
def words(s):return re.findall(r"[a-z0-9]+",s.lower())
def main(d,o,c,og):
 a=(d/'notice_2016_363.asc').read_bytes();img=d/'notice_2016_363.jpg';finger='6D854CD7933322A601C3286D181F01E57A35090F'
 assert H(img.read_bytes())=='a8340ad04b83fb3130e7ed9172867a440812e87089d6aa2b932d97c6ae38aebe' and H(a)=='fe89e77519dfaca998a257ed39c2861303029de2a49183db00eea0fda3a28010'
 with tempfile.TemporaryDirectory() as z:
  p=Path(z);ext=p/'extracted.asc'
  subprocess.run([og,'-r',str(img),str(ext)],check=True,capture_output=True)
  assert ext.read_bytes()==a
  def verify(s):
   r=subprocess.run(['gpg','--homedir',z,'--batch','--no-auto-key-retrieve','--no-default-keyring','--keyring',str((d/'public_key_119.gpg').resolve()),'--allow-weak-digest-algos','--status-fd','1','--verify'],input=s,capture_output=True)
   line=next((i for i in r.stdout.decode().splitlines() if '[GNUPG:] VALIDSIG ' in i),None);return r.returncode==0 and line is not None and finger in line,line
  ok,line=verify(a);bad,bb=verify(a.replace(b'the direction',b'the selection'));assert ok and not bad
  body=a.split(b'\n\n',1)[1].split(b'-----BEGIN PGP SIGNATURE-----')[0].decode().strip()
  ocr=subprocess.check_output(['tesseract',str(img),'stdout','--psm','6'],stderr=subprocess.DEVNULL).decode();bw=words(body);ow=words(ocr);assert bw==ow
 # Verify the actual cache records against the previously published identifiers before counting.
 rec=json.loads(gzip.decompress((d/'signed_339_results.json.gz').read_bytes()))['records'];bs=json.loads((c/'verified_bodies.json').read_bytes());unique={}
 for v in rec:
  if v['state']!='valid':continue
  s=bs[v['id']];assert H(s.encode())==v['body_sha256']; canon='\n'.join(t.rstrip(' \t') for t in s.removesuffix('\n').split('\n'));ch=H(canon.encode());assert ch==v['canonical_sha256'];unique[ch]=(v['id'],s)
 assert len(unique)==32
 grammar=re.compile(r'(?:[0-3][0-9A-Za-x]|4[0-9A-F])',re.ASCII)
 targets=[['their','numbers'],['the','words'],['words','are','the','map'],['numbers','are','the','direction']]
 def occ(w,term):return sum(w[i:i+len(term)]==term for i in range(len(w)-len(term)+1))
 trans=(d/'liber-primus__translation.txt').read_text().splitlines()
 clauses={m[1]:words(m[2]) for l in trans if (m:=re.match(r'^(\d+(?:\.\d+){3})\s+(.+)$',l))}
 qual={ ' '.join(q):{'dated_notice':occ(bw,q),'previous_signed_bodies':[{'id':i,'hits':occ(words(s),q)} for i,s in unique.values() if occ(words(s),q)],'solved_clauses':[k for k,v in clauses.items() if occ(v,q)]} for q in targets}
 pp=np.asarray(Image.open(img).convert('L'));box=pp[305:471,190:365];bg=pp[305:471,380:535]
 key_id=line.split();missing=[s for _,s in unique.values() if words(s)==bw];assert not missing
 out={'payload':{'bytes':len(a),'sha256':H(a),'carrier_sha256':H(img.read_bytes()),'extraction_identical':True,'valsig_status_fields':key_id[2:],'changed_signed_word_valid':bad,'fingerprint':finger},'ocr':{'words_after_alphanumeric_tokenization':len(ow),'identical':bw==ow,'signed_word_count':len(bw),'literal_nonblank_lines_after_whitespace_collapse_equal':[' '.join(x.split()) for x in body.splitlines() if x.strip()]==[' '.join(x.split()) for x in ocr.splitlines() if x.strip()],'visible_footer_in_signature':body.rstrip().endswith('Verify OpenPGP 7A35090F.')},'corpus':{'prior_unique':len(unique),'new_distinct_from_prior':not missing,'expanded_unique':len(unique)+1,'signed_2016_legal_full_tokens':[i for i in body.split() if grammar.fullmatch(i)],'hex_fingerprint_token':'7A35090F','phrase_counts':qual,'number_of_edition_clauses':len(clauses)},'image_signal':{'roi':[190,305,365,471],'right_blank_control':[380,305,535,471],'minmax_actual':[int(box.min()),int(box.max())],'minmax_blank':[int(bg.min()),int(bg.max())],'counts_above':{str(k):[int((box>k).sum()),int((bg>k).sum())] for k in (1,3,5,8,12,16,32,128)},'total_roi_pixels':box.size},'source_links':{'carrier1':'https://github.com/micheloosterhof/cicada-2016/blob/187ae28d21a7e42a14637bf95b77286a2193a1b8/stage01/4gq25.jpg','payload':'https://github.com/micheloosterhof/cicada-2016/blob/187ae28d21a7e42a14637bf95b77286a2193a1b8/stage01/4gq25.jpg.outguess','same_carrier2':'https://github.com/scream314/cicada3301/blob/10733feb487bb8beb9966d534727ee5897aa54fc/assets/2016/4gq25.jpg','historical_timeline':'https://github.com/scream314/cicada3301/blob/10733feb487bb8beb9966d534727ee5897aa54fc/2016.md'}}
 (o/'notice_363_results.json').write_text(json.dumps(out,sort_keys=True,indent=2)+'\n')
if __name__=='__main__':
 p=argparse.ArgumentParser();p.add_argument('evidence',type=Path);p.add_argument('out',type=Path);p.add_argument('cache',type=Path);p.add_argument('--outguess',default='outguess');a=p.parse_args();main(a.evidence,a.out,a.cache,a.outguess)
