#!/usr/bin/env python3
import datetime, hashlib, json, os, subprocess, sys
from pathlib import Path

ROOT=Path('/tmp/lead-32880-r1/evidence-capture')
FIXTURES=Path((ROOT/'fixtures-location.txt').read_text().strip())
BATCH=ROOT/('batch-'+datetime.datetime.now(datetime.timezone.utc).isoformat().replace(':','-'))
BATCH.mkdir()
manifest=json.loads((FIXTURES/'manifest.json').read_text())
selected=set(sys.argv[1:])
results=[]
def snapshot(home):
 return {str(p.relative_to(home)):hashlib.sha256(p.read_bytes()).hexdigest() for p in sorted(home.rglob('*')) if p.is_file() and not p.is_symlink() and '.cache' not in p.parts}
for fixturePath in manifest:
 fixture=json.loads(Path(fixturePath).read_text())
 if selected and fixture['name'] not in selected:continue
 for side,sha in [('before','fa2f4ff2a2bac5ac92e07749f6b83b0003d642a0'),('after','df3ffc1249ca06ef43aaebe6a534f96034354700')]:
  cwd=f'/home/user/wt/pr-32880-{side}/apps/server'
  home=Path(fixture['home']);env=os.environ.copy();env.update(HOME=str(home),CODEX_HOME=str(home/'.codex'),T3CODE_DEV_SEED='0')
  command=['/home/user/.local/share/vite-plus/js_runtime/node/26.12.1/bin/node','--experimental-import-meta-resolve',str(ROOT/'scanner-driver.mjs'),fixturePath,side]
  outfile=BATCH/f'{fixture["name"]}-{side}.log'
  before=snapshot(home)
  with outfile.open('w') as out:
   p=subprocess.Popen(command,cwd=cwd,env=env,stdout=out,stderr=subprocess.STDOUT)
   print(f'{fixture["name"]} {side}: captured PID {p.pid}',flush=True)
   try:code=p.wait(timeout=90)
   except subprocess.TimeoutExpired:
    p.terminate()
    try:code=p.wait(timeout=5)
    except subprocess.TimeoutExpired:p.kill();code=p.wait()
  after=snapshot(home)
  entry={'fixture':fixture['name'],'fixturePath':fixturePath,'rows':fixture['rows'],'side':side,'sha':sha,'pid':p.pid,'exitCode':code,'cwd':cwd,'command':command,'log':str(outfile),'fixtureHashesBefore':before,'fixtureHashesAfter':after,'inputFilesUnchanged':before==after}
  results.append(entry);(BATCH/'results.json').write_text(json.dumps(results,indent=2)+'\n')
  print(f'  exit={code}, inputs restored={before==after}, log={outfile}',flush=True)
  if code: print(outfile.read_text()[-6000:],flush=True)
(ROOT/'batch-location.txt').write_text(str(BATCH))
print('BATCH '+str(BATCH))
