"""python fetch_415.py MANIFEST CACHE. Pinned public artwork and a research thesis; decode figure 7 from physical PDF page 13."""
from urllib.request import Request,urlopen
from pathlib import Path
import json,sys,hashlib,subprocess
from PIL import Image
def main(m,s):
 s.mkdir(parents=True,exist_ok=True);v=json.loads(m.read_text())
 for e in v['source_files']:
  p=s/e['file'];data=p.read_bytes() if p.exists() else urlopen(Request(e['url'],headers={'User-Agent':'Cicada research notebook; source comparison'}),timeout=90).read()
  if hashlib.sha256(data).hexdigest()!=e['sha256']:raise ValueError(p.name+' no longer matches the pinned bytes')
  if not p.exists():p.write_bytes(data)
 subprocess.run(['pdfimages','-f','13','-l','13','-png',str(s/'borchers.pdf'),str(s/'thesis')],check=True)
 for n,h in v['thesis_panel_rgb_sha256'].items():assert hashlib.sha256(Image.open(s/n).convert('RGB').tobytes()).hexdigest()==h
if __name__=='__main__':main(*map(Path,sys.argv[1:]))
