"""FontForge script: turn the traced bbm "1" into a one-glyph Type 1 font.

Usage: fontforge -lang=py -script build_t1.py GLYPHDIR FONTNAME OUT.pfb
GLYPHDIR holds meta.json (from pk2pbm.py) and 49.eps (potrace output).
"""
import json
import os
import sys

import fontforge
import psMat

ONE = 49

glyphdir, name, out = sys.argv[1:4]
meta = json.load(open(os.path.join(glyphdir, "meta.json")))
px_per_ds = meta["design_size"] / 72.27 * meta["dpi"]
scale = 1000.0 / px_per_ds
g = meta["glyphs"][str(ONE)]

font = fontforge.font()
font.encoding = "ISO8859-1"
font.em = 1000
font.fontname = name.upper()
font.familyname = "MathbbOne"
font.fullname = name.upper()
font.copyright = "Traced from Gilles F. Robert's bbm Metafont sources"

glyph = font.createChar(ONE)
glyph.importOutlines(os.path.join(glyphdir, f"{ONE}.eps"))
# EPS origin is the padded bitmap's lower-left corner (1px margin).
glyph.transform(psMat.translate(-1 - g["hoff"], g["voff"] - g["h"]))
glyph.transform(psMat.scale(scale))
glyph.width = int(round(g["tfm"] * 1000))
glyph.addExtrema()
glyph.round()
glyph.correctDirection()

font.selection.all()
font.autoHint()
font.generate(out)
print(f"wrote {out}")
