"""Measure public CDN files for our own videos; never infer upload behavior."""
from pathlib import Path
import urllib.request,json,io,datetime,hashlib
from PIL import Image
p=Path(__file__).resolve().parent
rows=[]
for vid in ['jf5U0rfS7gI','dOtuo5qrnlE']:
 for variant in ['default','mqdefault','hqdefault','sddefault','maxresdefault']:
  url=f'https://i.ytimg.com/vi/{vid}/{variant}.jpg'
  try:
   with urllib.request.urlopen(url,timeout=25) as r: data=r.read();mime=r.headers.get_content_type();status=r.status
   im=Image.open(io.BytesIO(data));im.load();(p/f'{vid}-{variant}.jpg').write_bytes(data)
   # A near-black row contains at least 99% RGB components below 16.
   rgb=im.convert('RGB');dark=[]
   for y in range(im.height):
    vals=rgb.crop((0,y,im.width,y+1)).tobytes();dark.append(sum(v<16 for v in vals)/len(vals)>=.99)
   top=next((i for i,v in enumerate(dark) if not v),im.height)
   bottom=next((i for i,v in enumerate(reversed(dark)) if not v),im.height)
   rows.append(dict(video=vid,variant=variant,url=url,status=status,mime=mime,bytes=len(data),width=im.width,height=im.height,format=im.format,sha256=hashlib.sha256(data).hexdigest(),near_black_top_rows=top,near_black_bottom_rows=bottom))
  except Exception as e:rows.append(dict(video=vid,variant=variant,url=url,error=str(e)))
result={'checked_at':datetime.datetime.now(datetime.timezone.utc).isoformat(),'method':'GET five public CDN variants for two ThumbGlance videos. Dimensions verified by image decoding. Near-black rows: at least 99% RGB components below 16. Not an upload or device-display test.','rows':rows}
assert len(rows)==10
assert all(not r.get('error') and r['status']==200 and r['mime']=='image/jpeg' and r['format']=='JPEG' and r['width']>0 and r['height']>0 for r in rows), 'Incomplete or unexpected CDN response; do not treat this run as verified'
(p/'cdn-measurements.json').write_text(json.dumps(result,indent=2)+'\n')
print(json.dumps(result,indent=2))
