"""Download/assemble public evidence, verifying each part and the whole ZIP.

Python standard library only. No account access, model calls or extraction.
"""
import argparse
import hashlib
import json
from pathlib import Path
import re
import urllib.request

BASE='https://agentcollusion.ai/research/capability-asymmetry-20260906/'
USER_AGENT='AgentCollusionEvidence/1.0 (+'+BASE+')'


def digest(path):
 h=hashlib.sha256()
 with Path(path).open('rb') as f:
  for chunk in iter(lambda:f.read(1024*1024),b''):h.update(chunk)
 return h.hexdigest()


def safe_name(name):
 if not re.fullmatch(r'[a-zA-Z0-9_.-]+',name) or name.startswith('.'):raise ValueError('Unexpected public filename')
 return name


def fetch(name,path):
 # Fixed public site, never a credential-bearing endpoint or arbitrary manifest URL.
 request=urllib.request.Request(BASE+safe_name(name),headers={'User-Agent':USER_AGENT})
 with urllib.request.urlopen(request,timeout=120) as response,Path(path).open('xb') as f:
  for chunk in iter(lambda:response.read(1024*1024),b''):f.write(chunk)


def assemble(bundle,directory,download=False):
 directory=Path(directory);directory.mkdir(parents=True,exist_ok=True)
 parts=[]
 for item in bundle['download_files']:
  path=directory/safe_name(item['filename'])
  if not path.exists():
   if not download:raise RuntimeError('Missing part: '+str(path)+'; download it or use --download.')
   fetch(item['filename'],path)
  if path.stat().st_size!=item['bytes'] or digest(path)!=item['sha256']:raise RuntimeError('Part hash mismatch: '+str(path))
  parts.append(path)
 target=directory/safe_name(bundle['filename'])
 if len(parts)>1 and not target.exists():
  with target.open('xb') as output:
   for path in parts:
    with path.open('rb') as source:
     for chunk in iter(lambda:source.read(1024*1024),b''):output.write(chunk)
 if target.stat().st_size!=bundle['bytes'] or digest(target)!=bundle['sha256']:raise RuntimeError('Whole-archive hash mismatch: '+str(target))
 print('PASS: '+str(target)+' | SHA-256 '+bundle['sha256'])
 return target


if __name__=='__main__':
 ap=argparse.ArgumentParser(description=__doc__);ap.add_argument('--bundle',default='all');ap.add_argument('--directory',default='.');ap.add_argument('--download',action='store_true');args=ap.parse_args();directory=Path(args.directory);directory.mkdir(parents=True,exist_ok=True);manifest=directory/'DOWNLOADS.json'
 if not manifest.exists():
  if not args.download:raise SystemExit('Place DOWNLOADS.json here or use --download.')
  fetch('DOWNLOADS.json',manifest)
 data=json.loads(manifest.read_text(encoding='utf-8'));selected=[b for b in data['bundles'] if args.bundle in ['all',b['phase']]]
 if not selected:raise SystemExit('Unknown bundle; see DOWNLOADS.json.')
 for bundle in selected:assemble(bundle,directory,args.download)
