"""Record the same real-client Stop interaction on each commit.
Authenticate the named browser session first. Run with origin, server origin,
ids.json from setup.py, capture directory, and side (base/head).
Only the environment's displayed computer name is redacted in public output.
"""
import sys,json,subprocess,time,pathlib,urllib.request,hashlib
origin,server,ids_path,out,side=sys.argv[1:]
out=pathlib.Path(out)/time.strftime('%Y%m%d-%H%M%S');out.mkdir(parents=True)
ids=json.loads(pathlib.Path(ids_path).read_text())
environment=json.load(urllib.request.urlopen(server+'/.well-known/t3/environment'))['environmentId']
session='stop-proof-0171b40de6ae'
def browser(*args):
 p=subprocess.run(['npx','--yes','agent-browser','--session',session,*args],text=True,capture_output=True)
 if p.returncode:raise RuntimeError(p.stderr+p.stdout)
 return p.stdout
def open_thread(id):
 browser('open',f'{origin}/{environment}/{id}')
 browser('wait','--text','first fixture turn complete')
 state=browser('snapshot','-i')
 if 'region "Thread details"' not in state:
  browser('find','role','button','click','--name','Toggle thread details panel')
 return browser('snapshot','-i')
def stable_still(label):
 a=out/(label+'-a.png');b=out/(label+'-raw.png')
 for attempt in range(20):
  browser('batch','--bail','screenshot '+str(a),'wait 500','screenshot '+str(b))
  if hashlib.sha256(a.read_bytes()).digest()==hashlib.sha256(b.read_bytes()).digest():break
 else:raise RuntimeError('View never stabilized: '+label)
 # A computer name is private; this rectangle covers only that label.
 subprocess.run(['convert',str(b),'-fill','#eeeeee','-draw','rectangle 1190,74 1380,105',str(out/(label+'.png'))],check=True)
open_thread(ids[1])
browser('record','start',str(out/(side+'-raw.webm')),'--cursor')
time.sleep(2)
open_thread(ids[0]);time.sleep(2)
browser('find','role','button','click','--name','Stop subagent Finished delegated child')
time.sleep(3)
(out/'parent-after.txt').write_text(browser('snapshot'))
open_thread(ids[1]);time.sleep(2)
(out/'child-after.txt').write_text(browser('snapshot'))
open_thread(ids[0]);time.sleep(2)
browser('record','stop')
browser('eval','document.activeElement?.blur()')
browser('set','media','light','reduced-motion')
stable_still(side+'-after-stop')
subprocess.run(['ffmpeg','-y','-loglevel','error','-i',str(out/(side+'-raw.webm')),
 '-vf','drawbox=x=1190:y=74:w=190:h=31:color=0xeeeeee:t=fill','-c:v','libx264','-crf','20','-pix_fmt','yuv420p',str(out/(side+'-stop.mp4'))],check=True)
print(out)
