#!/usr/bin/env python3
"""Decode native video frames and measure first-chevron orientation changes.
Matches the 16 taps at (52,301) with successive visible orientation changes.
Video timestamps minus telemetry have an arbitrary constant offset, removed
by the two-file series inside that same recording. No wall-clock CLI timings.
Usage: analyze.py VIDEO TELEMETRY OUTPUT_JSON
"""
import subprocess,json,sys,statistics
video,telemetry,output=sys.argv[1:]
frames=json.loads(subprocess.check_output(['ffprobe','-v','error','-select_streams','v:0','-show_entries','frame=pts_time','-of','json',video]))['frames']
raw=subprocess.check_output(['ffmpeg','-v','fatal','-i',video,'-vf','crop=40:40:32:280','-vsync','0','-f','rawvideo','-pix_fmt','rgb24','-'])
size=40*40*3;states=[]
for i,f in enumerate(frames):
 data=raw[i*size:(i+1)*size];points=[]
 for y in range(40):
  for x in range(40):
   r,g,b=data[(y*40+x)*3:(y*40+x)*3+3]
   if 65<r<175 and abs(r-g)<20 and abs(r-b)<20:points.append((x,y))
 if not points:continue
 width=max(x for x,y in points)-min(x for x,y in points)
 height=max(y for x,y in points)-min(y for x,y in points)
 state='expanded' if width>height else 'folded'
 states.append({'tMs':float(f['pts_time'])*1000,'state':state,'width':width,'height':height})
changes=[]
for s in states:
 if not changes or s['state']!=changes[-1]['state']:changes.append(s)
taps=[e for e in json.load(open(telemetry))['events'] if e['kind']=='tap' and e['x']==52 and e['y']==301]
print('states',changes);print('taps',len(taps))
# Navigation changes the first arrow's state when the tiny review opens.
# Separate series by the large gap between their taps, and retain 8 alternating
# transitions nearest each series with the same constant clock offset.
series=[]
for label,start in [('10000 files',0),('2 files',8)]:
 ts=taps[start:start+8]
 candidates=[c for c in changes[1:] if ts[0]['tMs']-1800<c['tMs']<ts[-1]['tMs']+1800]
 if len(candidates)!=8:raise RuntimeError(f'{label}: expected 8 visible transitions, got {len(candidates)}')
 deltas=[round(c['tMs']-t['tMs'],1) for c,t in zip(candidates,ts)]
 series.append({'fixture':label,'deltasMs':deltas,'medianMs':statistics.median(deltas),'minMs':min(deltas),'maxMs':max(deltas),'transitions':candidates})
result={'series':series,'addedLatencyMs':round(series[0]['medianMs']-series[1]['medianMs'],1),'note':'Deltas include a constant clock offset; addedLatencyMs cancels it using the same recording.'}
open(output,'w').write(json.dumps(result,indent=2));print(json.dumps(result,indent=2))
