"""Repeat requested rows on existing authorized scratch checkouts. Never touches the lead checkout."""
from pathlib import Path
import subprocess,sys,datetime
scratch=Path('/tmp/lead-25675-r2/evidence-capture-1')
rows=sys.argv[1:] or ['R1','R2','R3','R4','R5','R7','R8']
for row in rows:
 assert row in ('R1','R2','R3','R4','R5','R7','R8')
 stamp=datetime.datetime.now(datetime.timezone.utc).strftime('%Y-%m-%dT%H-%M-%S')
 children=[]
 for side in ('before','after'):
  root=f'/home/ubuntu/wt/pr-25675-{side}'
  subprocess.run(['python3',str(scratch/'inject-fixture.py'),root,row if row not in ('R7','R8') else 'NONE'],check=True)
  log=open(scratch/f'launch-{row}-{side}-{stamp}.log','w')
  proc=subprocess.Popen(['vp','exec','node',str(scratch/'app-recording.mjs'),root,row],cwd=root,stdout=log,stderr=subprocess.STDOUT,env={**__import__('os').environ,'T3CODE_DEV_SEED':'0'})
  children.append((side,proc,log))
  print(f'{stamp} {row} {side} recorder wrapper pid={proc.pid}',flush=True)
 codes=[]
 for side,proc,log in children:
  code=proc.wait();log.close();codes.append(code)
  print(f'{datetime.datetime.now(datetime.timezone.utc).isoformat()} {row} {side} recorder exit={code}',flush=True)
 if any(codes):
  print(f'{row}: capture error; inspect retained logs before running further rows',flush=True)
  sys.exit(1)
