"""Session 118. Offline replay, Python 3 stdlib. Run beside the notebook inputs."""
from pathlib import Path
import hashlib, json, re, subprocess
from math import isqrt

root = Path(__file__).resolve().parent
rows = """36367763ab73783c7af284446c
59466b4cd653239a311cb7116
d4618dee09a8425893dc7500b
464fdaf1672d7bef5e891c6e227
4568926a49fb4f45132c2a8b4""".splitlines()  # visual read of LP2 56 = notebook 73.jpg
target = ''.join(rows)
assert len(bytes.fromhex(target)) == 64
raw = (root/'liber-primus__transcription--master.txt').read_text()
page = raw[raw.index('ᚱ-'):].split('%')[15+56]
assert re.findall(r'^([a-f0-9]+)/$', page, re.M) == rows
transcription2 = (root/'73.md').read_text()
assert re.findall(r'^([a-f0-9]{24,30})$', transcription2, re.M) == rows

runes = 'ᚠᚢᚦᚩᚱᚳᚷᚹᚻᚾᛁᛄᛇᛈᛉᛋᛏᛒᛖᛗᛚᛝᛟᛞᚪᚫᚣᛡᛠ'
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()
primes = (n for n in range(2,1000) if all(n%v for v in range(2,isqrt(n)+1)))
parts = []
pos = 0
for ch in page.replace('/\n',''):
    if ch in runes:
        if pos == 56:
            assert ch == 'ᚠ'
            parts.append('F')
        else:
            parts.append(letters[(runes.index(ch)-(next(primes)-1))%29])
        pos += 1
    elif ch in '.-;&': parts.append(' ')
    elif ch in '0123456789abcdef': parts.append(ch)
reading = ' '.join(''.join(parts).split())
expected = 'AN END WITHIN THE DEEP WEB THERE EXISTS A PAGE THAT HASHES TO '+target+' IT IS THE DUTY OF EUERY PILGRIM TO SEEK OUT THIS PAGE'
assert reading == expected, reading

def oid(kind, raw_bytes):
    return hashlib.sha1(kind+b' '+str(len(raw_bytes)).encode()+b'\0'+raw_bytes).digest()

def sha512(data):
    answer = hashlib.sha512(data).hexdigest()
    assert subprocess.run(['sha512sum'],input=data,capture_output=True,check=True).stdout.decode().split()[0] == answer
    return answer

assert sha512(b'abc') == ('ddaf35a193617abacc417349ae20413112e6fa4e89a97ea20a9eeee64b55d39a'
                          '2192992a274fc1a836ba3c23a3feebbd454d4423643ce80e2a9ac94fa54ca49f')
index = ('\n'.join(['<html>','<head><title>133</title></head>','<body>','<div id="331">',
                  *(f'<img src="{p}.jpg" /><br />' for p in range(58)),
                  '</div>','</body>','</html>'])+'\n').encode('ascii')
assert len(index)==1640 and oid(b'blob',index).hex()=='303db130705f0ef9be2a738f4336d5cfcebde80c'
files = {f'{p}.jpg': (root/f'{p+17}.jpg').read_bytes() for p in range(58)}
files['index.html'] = index
# Git's tree commits to each entry's archive name, mode and full blob ID.
tree = b''.join(b'100644 '+name.encode('ascii')+b'\0'+oid(b'blob',files[name]) for name in sorted(files))
tree_id = oid(b'tree',tree).hex()
assert tree_id == '48cc7a4094c9f4fb277348756ed1218861876382'
# A solver-side file outside the served directory is the digest itself.
binary_target_id = oid(b'blob',bytes.fromhex(target)).hex()
assert binary_target_id == 'cfd4a08cd8ffa31c8e40c5c7a544d2774ca764a4'
results = {name:{'bytes':len(data),'sha512':sha512(data)} for name,data in files.items()}
matches = [n for n,v in results.items() if v['sha512']==target]
out = dict(commit='6c3421a4d245596e403c88e037509d162a2afd17',tree=tree_id,page56_visual_rows=rows,
           row_lengths=list(map(len,rows)),stage11_56_bin_blob=binary_target_id,target=target,reading=reading,rune_count=pos,
           skip_zero_based=56,index_blob=oid(b'blob',index).hex(),jpeg_mapping='release n.jpg -> notebook (n+17).jpg',
           representation='complete file bytes; index includes final LF; no HTTP headers, transformations or concatenation',
           sha512_matches=matches,files=results)
print(json.dumps(out,indent=1))
