"""Check that a font file draws every character of an SRT file and shapes Devanagari conjuncts.
Usage: python3 check-font.py font.ttf captions.srt     (pip install fonttools uharfbuzz)
Exit 0 = every character has a glyph, exit 1 = at least one is missing."""
import sys, re
from fontTools.ttLib import TTFont
import uharfbuzz as hb
font, srt = sys.argv[1], sys.argv[2]
lines = open(srt, encoding="utf-8-sig").read().splitlines()
text = "\n".join(l for l in lines if not re.match(r"^\d+\s*$|^[\d:,]+ --> ", l.strip()))
cps = sorted({ord(c) for c in text if not c.isspace()})
tt = TTFont(font, fontNumber=0)
cmap = tt.getBestCmap()
fam = tt["name"].getDebugName(1)
missing = [c for c in cps if c not in cmap]
f = hb.Font(hb.Face(hb.Blob.from_file_path(font)))
def shape(s):
    b = hb.Buffer(); b.add_str(s); b.guess_segment_properties(); hb.shape(f, b, {})
    return [i.codepoint for i in b.glyph_infos]
words = text.split()
notdef = sum(1 for w in words for g in shape(w) if g == 0)
total = sum(len(shape(w)) for w in words)
ksha = shape("क्ष")
print(f"{fam}: code points needed={len(cps)} missing={len(missing)} {[hex(c) for c in missing][:8]} | words={len(words)} glyphs={total} notdef_glyphs={notdef} | glyphs for 3 code points of ksha={len(ksha)}")
sys.exit(1 if missing else 0)
