import json,sys
from pathlib import Path
p=Path(sys.argv[1]);side,row=sys.argv[2:];d=json.loads((p/'final.json').read_text());i=json.loads((p/'initial.json').read_text());m=json.loads((p/'manifest.json').read_text());checks=[]
def check(label,ok,detail=None):checks.append({'check':label,'passed':bool(ok),'detail':detail})
def entries(data):
 v=data['renderer']['storage'].get('t3code:browser-history:v1');b=json.loads(v)['state']['byProjectKey'] if v else {};return [e['url'] for es in b.values() for e in es]
reg=m['registered'];check('live registered guest',any(not g['destroyed'] and any(s['webContentsId']==g['id'] for s in reg['states'].values()) for g in reg['guests']),reg)

if row in ['R5b','R9']:
 initial_guests=i['native']['contents'];native_ids={s['webContentsId'] for s in i['renderer']['nativeStates'].values() if s['navStatus']['kind']=='Idle'}
 live_blank_ids={g['id'] for g in initial_guests if g['type']=='webview' and g['url']=='about:blank' and g['id'] in native_ids}
 calls=[e for e in d['native']['events'] if e['event']=='loadURL.start' and e['url'].endswith('/card' if row=='R9' else '/slow-redirect')]
 check('input uses registered Idle about:blank guest',bool(live_blank_ids) and any(e['id'] in live_blank_ids for e in calls),{'blankGuestIds':list(live_blank_ids),'calls':calls})

r=d['renderer'];check('theme matches capture label',r['appearance']==m.get('theme','dark'),r['appearance']);check('1100x780 DPR1 frozen clock reduced motion',(r['innerWidth'],r['innerHeight'],r['dpr'],r['clock'],r['reducedMotion'])==(1100,780,1,'2026-11-03T00:00:00.000Z',True))
ev=[e for e in d['native']['events'] if e['at']>=int(__import__('datetime').datetime.fromisoformat(m['startedAt'].replace('Z','+00:00')).timestamp()*1000)]
reject=[e for e in ev if e['event']=='loadURL.reject'];resolve=[e for e in ev if e['event']=='loadURL.resolve'];codes=[e.get('errno') for e in reject]
expected={'R1':[-3],'R5b':[-3],'R6':[-3],'R9':[-3],'R10':[-3,-102],'R4':[-102],'R2':[],'R3':[]}
if row in ['R2','R3']:
 check('entered native load resolves',any(e['url'].endswith('/302' if row=='R2' else '/fast') for e in resolve),resolve)
if row=='R6':check('successful B resolves',any(e['url'].endswith('/target') for e in resolve),resolve)
if row=='R10':check('errors retain source and destination identity',any(e.get('errno')==-3 and e['url'].endswith('/hold') for e in reject) and any(e.get('errno')==-102 and ':38918/' in e['url'] for e in reject),reject)
check('native promise result',sorted(codes)==sorted(expected[row]) if row in expected else len(codes)==1 and codes[0] in [-2,-3],reject)
conditional_affected=row in ['R7','R8'] and -3 in codes
affected=row in ['R1','R5b','R6','R9','R10'] or conditional_affected
has_toast=any(x['text'] for x in r['toasts']);want=(side=='base' and affected)or row in ['R4','R10']or (row in ['R7','R8'] and not conditional_affected)
check('navigation error toast presence',has_toast==want,{'actual':has_toast,'expected':want,'events':r['toasts']})
if row in ['R1','R2','R3','R5b','R6','R9']:check('final target retained',any(c['type']=='webview' and c['url'].endswith('/target') and not c['loading'] for c in d['native']['contents']))
if row in ['R4','R10']:check('genuine B failure remains visible',"This site can’t be reached" in r['text'] or "This site can't be reached" in r['text'],r['text'])
if row=='R10':check('two source/destination toasts before, only destination after',max([x.get('count',0) for x in r['toasts']]+[0])==(2 if side=='base' else 1),r['toasts'])
if row=='R5b':check('zero initial recent entries and local cards',entries(i)==[] and 'No preview yet' in i['renderer']['text'] and '\nLocal servers\n' not in i['renderer']['text'])
h=json.loads((p/'history.json').read_text()) if (p/'history.json').exists() else d;urls=entries(h)
if row in ['R1','R5b']:check('aborted source in project history only after',any(u.endswith('/slow-redirect') for u in urls)==(side=='head'),urls)
if row in ['R6','R10']:check('aborted A in project history only after',any(u.endswith('/hold') for u in urls)==(side=='head'),urls)
if row=='R9':check('recent source not duplicated',len(urls)==1 and urls[0].endswith('/card'),urls)
if row in ['R4','R10']:check('failed destination absent from visit history',not any(':38918' in u for u in urls),urls)
for stage in ['initial','toast','final']+(['history'] if (p/'history.png').exists() else []):
 a=[x for x in m['timeline'] if x['event']=='settled-comparison' and x['name']==stage];check(stage+' pixel identical over 500ms',bool(a) and a[-1]['changedPixels']==0)
print(json.dumps({'passed':all(x['passed'] for x in checks),'checks':checks,'projectHistory':urls}))
