"""Build hangulmath-sans*.otf: renamed subsets of Noto Sans CJK KR (SIL OFL 1.1).

Part of the hangulmath package. Requires fontTools and the Noto Sans CJK
DemiLight/Light .ttc files (paths below are Debian/Ubuntu defaults)."""
from fontTools.ttLib import TTCollection
from fontTools import subset

CODES = list(range(0x3131, 0x3164))  # all modern compatibility jamo incl. clusters
SRC = {
    "DemiLight": ("/usr/share/fonts/opentype/noto/NotoSansCJK-DemiLight.ttc", "Noto Sans CJK KR DemiLight", "hangulmath-sans.otf"),
    "Light": ("/usr/share/fonts/opentype/noto/NotoSansCJK-Light.ttc", "Noto Sans CJK KR Light", "hangulmath-sans-light.otf"),
}
for style, (path, fam, out) in SRC.items():
    font = next(f for f in TTCollection(path).fonts if f["name"].getDebugName(1) == fam)
    opts = subset.Options(); opts.layout_features = []; opts.name_IDs = ["*"]; opts.notdef_outline = True
    s = subset.Subsetter(opts); s.populate(unicodes=CODES + [0x20]); s.subset(font)
    family = "HangulMath Sans"; full = f"{family} {style}"; ps = f"HangulMathSans-{style}"
    name = font["name"]
    keep = {0, 13, 14}
    name.names = [r for r in name.names if r.nameID in keep]
    for nid, val in {1: full, 2: "Regular", 3: f"1.0;{ps}", 4: full, 5: "Version 1.000",
                     6: ps, 16: family, 17: style,
                     10: "Subset of Noto Sans CJK KR (OFL 1.1) containing modern Hangul compatibility jamo, renamed for the hangulmath LaTeX package."}.items():
        name.setName(val, nid, 3, 1, 0x409)
    cff = font["CFF "].cff
    old = cff.fontNames[0]; cff.fontNames[0] = ps
    top = cff[ps] if ps in cff else cff.topDictIndex[0]
    for k in ("FullName", "FamilyName"):
        if hasattr(top, k): setattr(top, k, full if k == "FullName" else family)
    if hasattr(top, "Notice"): top.Notice = "Subset of Noto Sans CJK, Copyright 2014-2021 Adobe. SIL OFL 1.1."
    font.save(out)
    print("wrote", out)
