#!/usr/bin/env python3
"""Reuse round-1 driver against exact scratch source snapshots, never mutate a checkout."""
import datetime,pathlib,subprocess,sys,os,json,shlex
S=pathlib.Path('/tmp/lead-25999-r1/evidence-capture-2')
run=S/('run-'+datetime.datetime.now(datetime.timezone.utc).strftime('%Y%m%dT%H%M%S.%fZ'));run.mkdir()
legacy=str(run/'genuine-base-legacy')
selected=sys.argv[1:] or ['K1','K2','K3R','K7','K8','O1','O3']
manifest=[]
for bundle in selected:
 for side,rev in [('before','36d4d711b79c73eb33131944f73ea4a8c6156484'),('after','7a90b56c54a924d63d91c40e3eecd96d048c1da4')]:
  avail=int(subprocess.check_output(['df','-BG','--output=avail','/'],text=True).splitlines()[-1].strip().rstrip('G'))
  print('DISK',avail,'GB',flush=True)
  if avail<8:raise SystemExit('FRICTION infra: below 8 GB; captures stopped')
  package=S/'sources'/side/'apps/server';driver=package/'evidence-capture-driver.ts';driver.write_bytes((S/'capture-driver.ts').read_bytes())
  root=run/(bundle+'-'+side+'-home');raw=run/(bundle+'-'+side+'.raw.txt')
  print('START',bundle,side,raw,flush=True)
  env={**os.environ,'CAPTURE_REVISION':rev}
  with raw.open('w') as out:
   proc=subprocess.run(['node','evidence-capture-driver.ts',bundle,side,str(root),legacy],cwd=package,stdout=out,stderr=subprocess.STDOUT,env=env)
  manifest.append({'bundle':bundle,'side':side,'raw':str(raw),'code':proc.returncode,'root':str(root),'legacy':legacy,'fixture':'synthetic/harness' if bundle=='O3' else 'native Linux release A/B','sourceRevision':rev})
  (run/'manifest.json').write_text(json.dumps(manifest,indent=2)+'\n')
  print('END',bundle,side,'exit',proc.returncode,flush=True)
  if proc.returncode:
   print(raw.read_text()[-10000:],flush=True);raise SystemExit(proc.returncode)
  # Literal absolute deletion, one path per shell command, logged verbatim. Evidence stays outside run homes.
  if root.exists():
   command='rm -rf '+shlex.quote(str(root));print('CLEANUP',command,flush=True);subprocess.run(command,shell=True,check=True)
 if bundle=='K1' and pathlib.Path(legacy).exists():
  command='rm -rf '+shlex.quote(legacy);print('CLEANUP',command,flush=True);subprocess.run(command,shell=True,check=True)
print('RUN_DIRECTORY',run,flush=True)
