"""Offline Session 119 replay; run beside the two fixtures, transcription and Session 118 results."""
from pathlib import Path
import base64, hashlib, json, re, subprocess, tempfile
from math import isqrt
P=Path(__file__).resolve().parent
key=P/'public_key_119.gpg'
signed=base64.b64decode((P/'handoff_119.b64').read_bytes())
def oid(data):return hashlib.sha1(b'blob '+str(len(data)).encode()+b'\0'+data).hexdigest()
def body(data):return data.split(b'\n\n',1)[1].split(b'-----BEGIN PGP SIGNATURE-----',1)[0]
trim=b'\n'.join(line.rstrip(b' \t') for line in signed.split(b'\n'))
assert oid(signed)=='e2b7382ac2cfb0adfe028cc063fc6048e0ad718e'
assert oid(trim)=='5bfaaeaf5364291e8a38d27222946f9db93cd50b'
runs=[len(m[0]) for m in re.finditer(b' {2,}',body(signed))]
controls={}
fp='6D854CD7933322A601C3286D181F01E57A35090F'
with tempfile.TemporaryDirectory() as tmp:
    for label,data,expect in [('preserved',signed,True),('trimmed_mirror',trim,True),
            ('23_trailing_spaces_changed_to_19',signed.replace(b'Good luck.'+b' '*23+b'\n',b'Good luck.'+b' '*19+b'\n'),True),
            ('visible_word_changed',signed.replace(b'Good luck.',b'Good news.'),False)]:
        if label not in ('preserved','trimmed_mirror'):assert data!=signed
        msg=Path(tmp)/'message.asc';msg.write_bytes(data)
        p=subprocess.run(['gpg','--homedir',tmp,'--batch','--no-default-keyring','--keyring',str(key),'--no-auto-key-retrieve','--status-fd=1','--verify',str(msg)],capture_output=True)
        valid=p.returncode==0 and b'[GNUPG:] VALIDSIG '+fp.encode()+b' ' in p.stdout
        assert valid==expect and (valid or b'[GNUPG:] BADSIG ' in p.stdout)
        controls[label]={'bytes':len(data),'valid_signature':valid}
old=json.loads((P/'page56_release_118.json').read_text())
r='ᚠᚢᚦᚩᚱᚳᚷᚹᚻᚾᛁᛄᛇᛈᛉᛋᛏᛒᛖᛗᛚᛝᛟᛞᚪᚫᚣᛡᛠ'
letters='F U TH O R K G W H N I J EO P X S T B E M L ING OE D A AE Y IO EA'.split()
raw=(P/'liber-primus__transcription--master.txt').read_text()
page=raw[raw.index('ᚱ-'):].split('%')[71].replace('/\n','')
def decode(drop):
    primes=(p for p in range(2,1000) if p!=drop and all(p%i for i in range(2,isqrt(p)+1)))
    indices=[];words=[]
    for c in page:
        if c in r:
            v=r.index(c)
            if len(indices)==56:assert v==0
            else:v=(v-next(primes)+1)%29
            indices.append(v);words.append(letters[v])
        elif c in '.-;&':words.append(' ')
        elif c in '0123456789abcdef':words.append(c)
    return indices,' '.join(''.join(words).split())
a,plain=decode(None);b,_=decode(19)
assert len(a)==len(b)==85 and plain==old['reading']
out={'multispace_runs':runs,'signature_checks':controls,'full_prime_runes_correct':len(a),'omit_19_runes_correct':sum(x==y for x,y in zip(a,b)),'omit_19_first_mismatch_one_based':next(i for i,(x,y) in enumerate(zip(a,b),1) if x!=y),'target_page_candidates_identified':0,'pgp_fingerprint':fp}
print(json.dumps(out,indent=2))
