import glob, os, io, json, hashlib, sys
from fontTools.ttLib import TTFont
import brotli

S='/System/Library/Fonts/'; SUP=S+'Supplemental/'
SPEC=[
 (SUP+'Arial Unicode.ttf',    'Arial Unicode — 50 tys. glifów, CJK'),
 (S+'SFNS.ttf',               'SF Pro — variable, glyf'),
 (SUP+'Georgia.ttf',          'Georgia — klasyczny TTF tekstowy'),
 (SUP+'Verdana.ttf',          'Verdana — TTF ekranowy'),
 (SUP+'Times New Roman.ttf',  'Times New Roman'),
 (SUP+'Courier New.ttf',      'Courier New — monospace'),
 (SUP+'NotoSansLycian-Regular.ttf','Noto Sans Lycian — skrajnie mały'),
 (SUP+'NotoSansPhoenician-Regular.ttf','Noto Sans Phoenician — bardzo mały'),
 (SUP+'NotoSansThaana-Regular.ttf','Noto Sans Thaana — mały'),
 (SUP+'NotoSansJavanese-Regular.otf','Noto Sans Javanese — CFF'),
 (SUP+'NotoSansTifinagh-Regular.otf','Noto Sans Tifinagh — CFF'),
 (SUP+'NotoSansCanadianAboriginal-Regular.otf','Noto Sans Can. Aboriginal — CFF'),
 (SUP+'NotoSansSiddham-Regular.otf','Noto Sans Siddham — CFF'),
]
def sha(p):
    h=hashlib.sha256()
    with open(p,'rb') as f:
        for c in iter(lambda:f.read(65536), b''): h.update(c)
    return h.hexdigest()[:16]

out=[]
for path,label in SPEC:
    if not os.path.exists(path):
        print('POMIJAM (brak):', path, file=sys.stderr); continue
    orig=os.path.getsize(path)
    try:
        f=TTFont(path, lazy=True, fontNumber=0 if path.endswith('.ttc') else -1)
        outl='CFF2' if 'CFF2' in f else ('CFF' if 'CFF ' in f else 'glyf')
        var='variable' if 'fvar' in f else 'static'
        glyphs=len(f.getGlyphOrder())
        dsig='DSIG' in f
        f.close()
        # WOFF2
        f2=TTFont(path, fontNumber=0 if path.endswith('.ttc') else -1)
        f2.flavor='woff2'
        buf=io.BytesIO(); f2.save(buf); w2=len(buf.getvalue()); f2.close()
        # Brotli surowego oryginału (q11) — porównanie transferu HTTP
        br=len(brotli.compress(open(path,'rb').read(), quality=11))
    except Exception as e:
        print('BŁĄD', label, type(e).__name__, e, file=sys.stderr); continue
    out.append(dict(label=label, file=os.path.basename(path), sha=sha(path),
        outlines=outl, kind=var, glyphs=glyphs, dsig=dsig,
        orig=orig, woff2=w2, brotli=br,
        red=round((orig-w2)/orig*100,1),
        w2_vs_br=round((br-w2)/br*100,1)))
    print(f"OK {label[:42]:44} {orig:>9} -> {w2:>9}  ({out[-1]['red']:5.1f}%)", file=sys.stderr)
json.dump(out, open('results.json','w'), indent=1, ensure_ascii=False)
print(f"\nzapisano {len(out)} pomiarów", file=sys.stderr)
