"""Check the actual distribution archives and execute their no-inference verifiers."""
import argparse
import hashlib
import json
import os
from pathlib import Path
import subprocess
import sys
import zipfile

from download_evidence import assemble,digest


def audit(export,out):
 export=Path(export).resolve();out=Path(out).resolve();out.mkdir(parents=True,exist_ok=False)
 index=json.loads((export/'DOWNLOADS.json').read_text(encoding='utf-8'));reports=[]
 for bundle in index['bundles']:
  parts=out/bundle['phase'];parts.mkdir()
  for part in bundle['download_files']:os.link(export/part['filename'],parts/part['filename'])
  archive=assemble(bundle,parts)
  with zipfile.ZipFile(archive) as z:
   manifest=json.loads(z.read('MANIFEST.json'))
   assert set(z.namelist())==set(manifest)|{'MANIFEST.json'},'Archive member census differs'
   for name,expected in manifest.items():
    data=z.read(name);assert len(data)==expected['bytes'] and hashlib.sha256(data).hexdigest()==expected['sha256'],name
   forbidden=[name for name in z.namelist() if '/provider/' in name and name.rsplit('/',1)[-1] in ['stdout.txt','stderr.txt','internal-agy.log']]
   assert not forbidden,'Private provider stream leaked'
  package=export/'packages'/bundle['phase']
  process=subprocess.run([sys.executable,'reproduce.py'],cwd=package,capture_output=True,text=True,encoding='utf-8')
  (out/(bundle['phase']+'-verification.txt')).write_text(process.stdout+process.stderr,encoding='utf-8')
  assert process.returncode==0,'Bundle verifier failed: '+bundle['phase']
  reports.append({'phase':bundle['phase'],'archive_sha256':digest(archive),'manifest_members_verified':len(manifest),'multipart_reassembly_verified':len(bundle['download_files'])>1,'stored_data_verifier_exit_code':process.returncode,'private_provider_streams_present':False})
 result={'passed':True,'bundles':reports,'note':'Verified actual ZIP members and byte hashes, assembled real multipart archives, and ran each package standard-library reproduce.py. No model calls. Logs are separate from frozen experimental evidence.'}
 (out/'release-audit.json').write_text(json.dumps(result,indent=2),encoding='utf-8');print(json.dumps(result,indent=2));return result


if __name__=='__main__':
 ap=argparse.ArgumentParser();ap.add_argument('export');ap.add_argument('--out',required=True);args=ap.parse_args();audit(args.export,args.out)
