"""Offline replay: python -B fives_358.py EVIDENCE_DIR OUTPUT.json [--archive /path/to/pinned/2014.md]; Python 3 + GnuPG."""
from pathlib import Path
from collections import Counter
import gzip,json,hashlib,re,sys,argparse,subprocess,tempfile
H=lambda b:hashlib.sha256(b).hexdigest()
KEY=[2,8,9,1,12,13,11,4,5,7,3,0,6,10]
def main(d,archive=None):
    sr=json.loads(gzip.decompress((d/'signed_339_results.json.gz').read_bytes()))
    rec=next(v for v in sr['records'] if v['id']=='2014-3')
    assert rec['state']=='valid' and sr['fingerprint']=='6D854CD7933322A601C3286D181F01E57A35090F'
    armor=(d/'fives_358_signed.asc').read_bytes()
    assert len(armor)==991 and H(armor)==rec['armor_sha256']=='81139c4d7e025878767fe79ad91024c6cf4b4ede6c763e6b5e500de43fd90866'
    with tempfile.TemporaryDirectory() as tmp:
        checked=subprocess.run(['gpg','--homedir',tmp,'--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=armor,capture_output=True)
    assert checked.returncode==0 and b'[GNUPG:] VALIDSIG '+sr['fingerprint'].encode()+b' ' in checked.stdout
    body=re.split(rb'\n[ \t]*\n',armor,maxsplit=1)[1].split(b'-----BEGIN PGP SIGNATURE-----')[0]
    body=re.sub(b'^- ',b'',body,flags=re.M).decode();assert H(body.encode())==rec['body_sha256']
    can='\n'.join(t.rstrip(' \t') for t in body.removesuffix('\n').split('\n'));assert H(can.encode())==rec['canonical_sha256']
    lines=[s.strip() for s in can.splitlines() if s.strip()];assert lines[2:]==['Good luck.','3301']
    rows=[s.split() for s in lines[:2]];words=rows[0]+rows[1];t=''.join(words)
    ok=re.compile(r'(?:[0-3][0-9A-Za-x]|4[0-9A-F])',re.ASCII)
    native=sum(bool(ok.fullmatch(w)) for w in words)
    bounds=[];s=0
    for w in words[:-1]:s+=len(w);bounds.append(s)
    rel=[]
    for off in (0,1):
        starts=list(range(off,len(t)-1,2));pairs=[t[i:i+2] for i in starts];flags=[bool(ok.fullmatch(w)) for w in pairs]
        long=max([0]+[len(x) for x in re.findall('1+',''.join('1' if v else '0' for v in flags))])
        rel.append(dict(start_one_based=off+1,pairs=len(pairs),legal=sum(flags),illegal=len(pairs)-sum(flags),longest_legal_run=long,
            legal_with_nonhex=sum(bool(v and not re.fullmatch(r'[A-Fa-f0-9]{2}',w)) for v,w in zip(flags,pairs)),
            pairs_starting_at_native_group_start=sum(i in [0]+bounds for i in starts),
            pairs_crossing_native_whitespace=sum(i+1 in bounds for i in starts),pairs_crossing_native_line=sum(i+1==sum(map(len,rows[0])) for i in starts)))
    starts=[(i+1,t[i:i+2]) for i in range(len(t)-1) if t[i].isdigit()]
    assert native==0 and not any(r['legal'] for r in rel)
    # Confirm the chosen permutation is the exact archival line, which is commentary outside the signature.
    key_excerpt=(d/'fives_358_order.txt').read_bytes()
    assert H(key_excerpt)=='a452050faf146b727fbb0149f7bebf56de63cb79d856987f0a1a81d09ae36fdb'
    assert list(map(int,key_excerpt.split()))==KEY and sorted(KEY)==list(range(14))
    if archive:
        source=archive.read_bytes();assert H(source)==rec['container_sha256'] and source.splitlines(keepends=True).count(key_excerpt)==1
    blocks=[t[i:i+14] for i in range(0,len(t),14)]
    assert len(blocks)==5 and all(len(r)==14 for r in blocks)
    plain=''.join(''.join(r[j] for j in KEY) for r in blocks)
    inv=[KEY.index(i) for i in range(14)]
    back=''.join(''.join(plain[i+j] for j in inv) for i in range(0,len(plain),14))
    prefix='GOODWORKULTIMATETRUTHISTHEULTIMATEILLUSIONJOINUSAT'
    assert plain.startswith(prefix) and plain.endswith('ONIO') and back==t
    return {'source':rec['source'],'source_id':rec['id'],'fingerprint':sr['fingerprint'],'body_sha256':rec['body_sha256'],'canonical_sha256':rec['canonical_sha256'],'archive_container_sha256':rec['container_sha256'],
        'signed_layout':{'grouped_lines':2,'word_lengths_by_line':[[len(w) for w in row] for row in rows],'length':len(t),'legal_native_tokens':native,'literal_alphabet':''.join(sorted(set(t))),'digit_led_adjacent_pairs_1based':starts,'remaining_nonblank_lines':lines[2:]},
        'hypothetical_pairings':rel,'documented_transposition':{'characters_per_row':14,'rows':5,'column_order_zero_based':KEY,'inverse_round_trip_equals_native_character_stream':back==t,
        'recovered_text_prefix':prefix,'recovered_final_four':plain[-4:],'plaintext_length':len(plain),'plaintext_sha256':H(plain.encode()),'extra_terminal_character_added':False}}
if __name__=='__main__':
    p=argparse.ArgumentParser(description=__doc__);p.add_argument('evidence',type=Path);p.add_argument('output',type=Path);p.add_argument('--archive',type=Path);x=p.parse_args()
    out=main(x.evidence,x.archive);x.output.write_text(json.dumps(out,sort_keys=True,indent=2)+'\n')
