"""Rehydrate two pinned collections, isolate clearsigned blocks, verify the full fingerprint.
python signed_339.py EVIDENCE_DIR CACHE_DIR OUTPUT.json.gz
All remote requests go only to named archive files; no payload-derived addresses are followed.
"""
from pathlib import Path
from urllib.request import Request,urlopen
from urllib.parse import quote
import base64, concurrent.futures, gzip, hashlib,json,re,subprocess,sys,tempfile,time
FP='6D854CD7933322A601C3286D181F01E57A35090F'
H=lambda b:hashlib.sha256(b).hexdigest()
BLOB=lambda b:hashlib.sha1(b'blob '+str(len(b)).encode()+b'\0'+b).hexdigest()
def em(x,p):p.write_bytes(gzip.compress((json.dumps(x,separators=(',',':'),sort_keys=True)+'\n').encode(),mtime=0))
def load(p):return json.loads(gzip.decompress(p.read_bytes()))
def rawbody(armor):
 b=armor.split(b'-----BEGIN PGP SIGNED MESSAGE-----',1)[1]
 b=re.split(rb'\n[ \t]*\n',b,maxsplit=1)[1].split(b'-----BEGIN PGP SIGNATURE-----')[0]
 return re.sub(b'^- ',b'',b,flags=re.M)
def main(d,cache,out):
 cache.mkdir(parents=True,exist_ok=True)
 old=json.loads((d/'berkeley_extended_results.json').read_bytes())
 pri={x['id']:x for x in old['signed_blocks']}
 extra=load(d/'signed_manifest_339.json.gz')
 cfg=[]
 for v in old['sources']:cfg.append((str(v['year']),v['url'],v['sha256'],None,'65'))
 for v in old['asset_manifest']:
  if v['signed_starts']:cfg.append((v['path'],v['url'],v['sha256'],None,'65'))
 for n,sha in extra['files'].items():cfg.append((n,'https://raw.githubusercontent.com/'+extra['repo']+'/'+extra['commit']+'/'+quote(extra['directory']+'/'+n),None,sha,'new'))
 def fetch(x):
  name,url,sha,blob,corpus=x;p=cache/((sha or blob)+'.raw')
  if not p.exists():
   for attempt in range(3):
    try: b=urlopen(Request(url,headers={'User-Agent':'Cicada-Research-Notebook'}),timeout=40).read();break
    except OSError:
     if attempt==2:raise
     time.sleep(1)
   p.write_bytes(b)
  b=p.read_bytes()
  if sha and H(b)!=sha:
   assert H(b.replace(b'\r\n',b'\n'))==sha
  if blob:assert BLOB(b)==blob
  return x,b
 records=[];accepted={}
 with tempfile.TemporaryDirectory() as tmp,concurrent.futures.ThreadPoolExecutor(8) as pool:
  for (n,u,sha,blob,c),b in pool.map(fetch,cfg):
   s=b.decode('utf8',errors='replace').replace('\r\n','\n').replace('\r','\n')
   matches=list(re.finditer('-----BEGIN PGP SIGNED MESSAGE-----',s))
   for i,m in enumerate(matches,1):
    ident=(n+('-' if n in ('2012','2013','2014') else '#')+str(i))
    item={'id':ident,'collection':c,'source':u,'container_sha256':H(b)}
    wrap=s[s.rfind('\n',0,m.start())+1:m.start()]
    indent='\t' if wrap.startswith('\t') else ('    ' if wrap.startswith('    ') else '')
    tail=s[m.start():matches[i].start() if i<len(matches) else len(s)]
    end=tail.find('-----END PGP SIGNATURE-----')
    if end<0:
     item['state']='incomplete';records.append(item);continue
    ar=tail[:end+len('-----END PGP SIGNATURE-----')]
    if indent:ar=re.sub('^'+re.escape(indent),'',ar,flags=re.M)
    ar=(ar+'\n').encode()
    if c=='65':assert H(ar)==pri[ident]['sha256'],ident
    p=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=ar,capture_output=True)
    ok=p.returncode==0 and b'[GNUPG:] VALIDSIG '+FP.encode()+b' ' in p.stdout
    if c=='65':assert ok==(pri[ident]['result']=='valid'),ident
    item.update(state='valid' if ok else 'not verified',armor_sha256=H(ar))
    if ok:
     body=rawbody(ar)
     if c=='65':assert H(body)==pri[ident]['body_sha256']
     # Canonicalize only trailing spaces/tabs (cleartext framework), and remove exactly the final separator newline.
     canonical=b'\n'.join(l.rstrip(b' \t') for l in body.removesuffix(b'\n').split(b'\n'))
     # Read packet identifier separately for mirrors sharing the same signature and content.
     sig=ar.split(b'-----BEGIN PGP SIGNATURE-----')[1].split(b'-----END PGP SIGNATURE-----')[0]
     pkt=base64.b64decode(b''.join(t.strip() for t in sig.splitlines() if re.fullmatch(rb'[A-Za-z0-9+/]+={0,2}',t.strip())),validate=True)
     item.update(body_sha256=H(body),canonical_sha256=H(canonical),signature_packet_sha256=H(pkt),canonical_length=len(canonical),visible_token_stream_sha256=H(b' '.join(body.split())))
     accepted[ident]=body.decode()
    records.append(item)
 assert sum(r['collection']=='65' for r in records)==38
 em({'records':records,'fingerprint':FP,'archive_directory_entries':len(extra['files']),'archive_commit':extra['commit']},out)
 (cache/'verified_bodies.json').write_text(json.dumps(accepted,sort_keys=True))
if __name__=='__main__':main(*[Path(s) for s in sys.argv[1:]])
