"""ML21 factual-source Python wrapper. Download this file and bundle together.
Run: python ml21-reproduce.py --out NEW-OUTDIR [--bundle FILE]
"""
from pathlib import Path
import argparse,zipfile,tempfile,subprocess,sys,hashlib
p=argparse.ArgumentParser();p.add_argument('--out',type=Path,required=True);p.add_argument('--bundle',type=Path,default=Path(__file__).with_name('ml21-source-bundle.zip'));a=p.parse_args()
if a.out.exists():raise SystemExit('Choose NEW output directory')
expected='d002166441d0b52588ca8181346ef477c2b6fc236bc8c30f85da27e5eb4695af'
if hashlib.sha256(a.bundle.read_bytes()).hexdigest()!=expected:raise SystemExit('Bundle SHA256 mismatch')
with tempfile.TemporaryDirectory(prefix='ml21-source-')as name:
 stage=Path(name).resolve()
 with zipfile.ZipFile(a.bundle)as archive:
  for entry in archive.namelist():
   if not(stage/entry).resolve().is_relative_to(stage):raise SystemExit('Unsafe archive path')
  archive.extractall(stage)
 command=[sys.executable,str(stage/'reproduce-causal-representation.py'),str(stage),str(a.out.resolve())]
 subprocess.run(command,check=True)
