"""Run: python pointers_345_347.py EVIDENCE_DIR OUTPUT.json.gz [verified_bodies.json]
The optional final argument is the output cache from the session 339 signature replay.
"""
from pathlib import Path
from collections import Counter
import gzip,json,re,sys
d=Path(sys.argv[1]);load=lambda p:json.loads(gzip.decompress((d/p).read_bytes()))
allin=load('pointer_inputs_345.json.gz');out={}; counts={}
if len(sys.argv)>3:
 verified=json.loads(Path(sys.argv[3]).read_bytes())
 for rec in allin.values():
  lines=[s.strip() for s in verified[rec['verified_body_id']].splitlines()]
  ls=lines[lines.index(rec['first']):max(i for i,t in enumerate(lines) if t==rec['last'])+1]
  assert ls==rec['tokens']
alpha='0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwx'
def valid(t):
 return len(t)==2 and all(c in alpha for c in t) and 60*alpha.index(t[0])+alpha.index(t[1])<=255
for name,r in allin.items():
 ts=r['tokens'];ptr=[t for t in ts if ':' in t];lits=[t for t in ts if ':' not in t];assert ptr and all(len(t.split(':'))==len(ptr[0].split(':')) for t in ptr)
 counts[name]={'instructions':len(ts),'pointer_occurrences':len(ptr),'distinct_pointers':len(set(ptr)),'fields_per_pointer':len(ptr[0].split(':')),'pointer_char_width':[min(map(len,ptr)),max(map(len,ptr))],'characters_in_pointers_including_colons':sum(map(len,ptr)),'nonpointers':lits,'exact_two_position_byte_instructions':sum(map(valid,ts))}
out['known_pointer_lists']=counts
expected='https:--www.dropbox.com-s-r7sgeb5dtmzj14s-3301'
targets=load('crowley_witnesses_346.json.gz')['verses'];rules={'raw':lambda c:True,'strip_whitespace':lambda c:not c.isspace(),'letters_digits':lambda c:c.isalnum(),'letters_digits_hyphen':lambda c:c.isalnum() or c=='-'};crow={}
for rule,keep in rules.items():
 chars=[]
 for t in allin['Crowley']['tokens']:
  if ':' not in t:chars.append(t);continue
  ch,vs,n=t.split(':');r=targets[ch+':'+vs];idx=[i for i,c in enumerate(r['shape']) if keep(c)];k=int(n)-1
  chars.append(r['opened'][str(idx[k])].lower() if k<len(idx) else '?')
 s=''.join(chars);crow[rule]={'out':s,'score_of_46':sum(a==b for a,b in zip(s,expected)),'out_of_range':s.count('?'),'typographical_dash_equivalence_score':sum(a.replace('—','-')==b for a,b in zip(s,expected))}
out['crowley_rendering_controls']=crow
def outcome(pairs,rev,a,b):
 vals=[]
 for i,j in pairs:
  first,second=((j,i) if rev else (i,j));first-=a;second-=b
  vals.append([first,second,60*first+second,0<=first<60 and 0<=second<60 and 60*first+second<=255])
 return vals
packing={}
for name in ['Agrippa','Blake']:
 pairs=[[int(n) for n in t.split(':')] for t in allin[name]['tokens'] if ':' in t];assert all(len(p)==2 for p in pairs);rows=[]
 for rev in [False,True]:
  for a in (0,1):
   for b in (0,1):
    vals=outcome(pairs,rev,a,b)
    rows.append({'order':'character/line' if rev else 'line/character','subtract_from_first':a,'subtract_from_second':b,'fit':sum(v[-1] for v in vals),'first_failed_coordinate':next(p for p,v in zip(pairs,vals) if not v[-1])})
 packing[name]={'pointers':len(pairs),'best_all_8_conventions':max(r['fit'] for r in rows),'naive_two_digit_radix_60_without_byte_bound':sum(all(0<=v<60 for v in p) for p in pairs),'cases':rows}
out['base60_byte_pointer_controls']=packing
assert min(x['exact_two_position_byte_instructions'] for x in counts.values())==max(x['exact_two_position_byte_instructions'] for x in counts.values())==0
assert crow['strip_whitespace']['score_of_46']==45 and crow['strip_whitespace']['typographical_dash_equivalence_score']==46
assert (packing['Blake']['best_all_8_conventions']<22 and packing['Agrippa']['best_all_8_conventions']<20)
Path(sys.argv[2]).write_bytes(gzip.compress((json.dumps(out,sort_keys=True,separators=(',',':'),ensure_ascii=False)+'\n').encode(),mtime=0))
