#!/usr/bin/env python3
"""Validate scenarios, package full frame verification, and upload synthetic artifacts."""
import json,re,subprocess
from pathlib import Path
root=Path('/tmp/lead-28684-r1/evidence-capture-2');run=root/'2026-11-02T22-50-00Z'
names=['before-paging-dark','after-paging-dark','before-short-dark','after-short-dark','before-floating-dark','after-floating-dark','after-switch-dark']
selected={}
for name in names:
 candidates=[]
 for p in run.glob('*-'+name):
  f=p/'verification.json'
  if f.exists() and json.loads(f.read_text())['sourceAverageFps']>=10:candidates.append(p)
 assert candidates,name
 selected[name]=str(sorted(candidates)[-1])
(run/'selected-runs.json').write_text(json.dumps(selected,indent=2))
reports={};metas={};files=[]
for name,location in selected.items():
 p=Path(location);r=json.loads((p/'verification.json').read_text());m=json.loads((p/'metadata.json').read_text())
 assert r['maxRgbDelta']<=4
 assert r['decodedFramesVerified']==len(r['perFrame'])==len(r['frameMapping'])
 start=next(i for i,x in enumerate(m['timeline']) if x['action']=='recording-start');steps=m['timeline'][start:]
 find=lambda action:next(x for x in steps if x['action']==action)
 if name=='after-paging-dark':
  assert [find(x)['rows'] for x in ['click Show 4 more','click Show 2 more','click Show less']]==[8,10,4]
 elif name=='before-paging-dark':assert all(x['rows']==10 and not x.get('footer') for x in steps)
 elif name=='after-switch-dark':
  assert find('A expanded to eight')['rows']==8
  assert find('B starts at four')['rows']==4 and find('B starts at four')['footer']=='Show 1 more'
  assert find('A resets to four')['rows']==4 and find('A resets to four')['footer']=='Show 4 more'
 elif name.startswith('before-'):assert all(x['density']=='compact' and not x.get('rows') for x in steps)
 else:
  assert all(x['density']=='full' for x in steps)
  top=find('still '+name+'-expanded-top');bottom=find('still '+name+'-expanded-bottom');collapsed=find('still '+name+'-collapsed')
  assert top['rows']==bottom['rows']==10 and top['scroll'][0]['top']==0 and bottom['scroll'][0]['top']>0
  assert collapsed['rows']==4 and collapsed['scroll'][0]['top']==0
 reports[name]=r;metas[name]=m
 files.extend([p/(name+'.mp4'),p/(name+'-contact-sheet.png')])
(run/'verification-summary.json').write_text(json.dumps(reports,indent=2))
(run/'recordings.json').write_text(json.dumps(metas,indent=2))
files.extend(run/x for x in ['verification-summary.json','recordings.json'])
files.extend(root/x for x in ['rpc-driver.mjs','browser-driver.mjs','control.py','capture-driver.mjs','run-redo.py','encode-verify.py','bootstrap.py','build-evidence.py','package-evidence.py','rebuild-recordings.md'])
# Exact ghdrop Markdown is retained and printed, including Markdown image syntax.
p=subprocess.run(['ghdrop','upload','-m',*[str(x) for x in files]],check=True,capture_output=True,text=True)
(run/'uploads.md').write_text(p.stdout);print(p.stdout,flush=True)
urls={}
for line in p.stdout.splitlines():
 match=re.match(r'!?\[([^]]+)\]\(([^)]+)\)',line)
 if match:urls[match[1]]=match[2]
assert len(urls)==len(files),(len(urls),len(files))
(run/'upload-map.json').write_text(json.dumps(urls,indent=2))
subprocess.run(['python3',str(root/'build-evidence.py')],check=True)
p=subprocess.run(['ghdrop','upload','-m',str(root/'evidence.md')],check=True,capture_output=True,text=True)
(run/'evidence-upload.md').write_text(p.stdout);print(p.stdout,flush=True)
