"""Costruisce in fonts/ i font TrueType completi usati da build.py (fonts/<stile>_it.ttf).

Whitney: nel PDF ci sono solo sottoinsiemi CFF, a volte più d'uno per lo stesso peso, con lettere diverse.
Si uniscono e si convertono in TrueType. Una lettera che manca si cerca, nell'ordine:
  1. negli altri sottoinsiemi dello stesso stile;
  2. per i corsivi, nel tondo dello stesso peso inclinato di 9° (come il corsivo di Whitney);
  3. in un peso vicino di Whitney (Semibold <- Bold);
  4. in Seravek di sistema, scalata sull'altezza della x (minuscole) o delle maiuscole di Whitney.
Le accentate (à è é ì ò ù, maiuscole comprese) si compongono: lettera dello stile + accento di Seravek.
Saniretro (titoli): il sottoinsieme TrueType non ha la cmap; si ricostruisce (glifo = codice - 31)."""
import glob, math
from fontTools.ttLib import TTFont, TTCollection
from fontTools.cffLib import CFFFontSet
from fontTools.fontBuilder import FontBuilder
from fontTools.pens.ttGlyphPen import TTGlyphPen
from fontTools.pens.cu2quPen import Cu2QuPen
from fontTools.pens.transformPen import TransformPen
from fontTools.pens.boundsPen import BoundsPen
from fontTools.pens.recordingPen import RecordingPen, DecomposingRecordingPen
from fontTools import agl

SER = {f['name'].getDebugName(4): f for f in TTCollection('/System/Library/Fonts/Supplemental/Seravek.ttc').fonts}
FAM = {'B': 'Whitney-Book', 'Bi': 'Whitney-BookItalic', 'M': 'Whitney-Medium', 'Mi': 'Whitney-MediumItalic',
       'S': 'Whitney-Semibold', 'Si': 'Whitney-SemiboldItalic', 'BD': 'Whitney-Bold', 'BDi': 'Whitney-BoldItalic'}
# catena di ripiego: (stile, inclinato?) ... poi Seravek
CHAIN = {'B': [], 'Bi': [('B', 1)], 'M': [], 'Mi': [('M', 1)], 'S': [('BD', 0)], 'Si': [('S', 1), ('BD', 1)],
         'BD': [], 'BDi': [('BD', 1)]}
SERF = {'B': 'Seravek Light', 'Bi': 'Seravek Light Italic', 'M': 'Seravek', 'Mi': 'Seravek Italic',
        'S': 'Seravek Medium', 'Si': 'Seravek Medium Italic', 'BD': 'Seravek Bold', 'BDi': 'Seravek Bold Italic'}
WANT = ''.join(chr(c) for c in range(32, 127)) + 'àèéìòùÀÈÉÌÒÙ’‘“”«»–—…°×·'
ACCENTED = {'à': ('a', '`'), 'è': ('e', '`'), 'é': ('e', '´'), 'ì': ('i', '`'), 'ò': ('o', '`'), 'ù': ('u', '`'),
            'À': ('A', '`'), 'È': ('E', '`'), 'É': ('E', '´'), 'Ì': ('I', '`'), 'Ò': ('O', '`'), 'Ù': ('U', '`')}
SLANT = math.tan(math.radians(9))

def rec(draw):
    r = RecordingPen(); draw(r); return r.value

def bounds(ops):
    bp = BoundsPen(None)
    for op, a in ops: getattr(bp, op)(*a)
    return bp.bounds

def xform(ops, m):
    r = RecordingPen(); tp = TransformPen(r, m)
    for op, a in ops: getattr(tp, op)(*a)
    return r.value

# 1) glifi di ogni stile Whitney: {carattere: (contorni registrati, avanzamento)}
WH = {}
for code, fam in FAM.items():
    d = {}
    for fn in sorted(glob.glob(f'fonts/*+{fam}_*.cff')):
        c = CFFFontSet(); c.decompile(open(fn, 'rb'), None)
        top = c[c.fontNames[0]]; cs = top.CharStrings
        for n in top.charset:
            u = agl.toUnicode(n)
            if len(u) != 1 or u in d: continue
            ch = cs[n]; ch.decompile(); ops = rec(ch.draw)
            if not ops and u != ' ': continue
            d[u] = (ops, ch.width)
    WH[code] = d

def metrics(d):
    def h(chars, default):
        for c in chars:
            if c in d and bounds(d[c][0]): return bounds(d[c][0])[3]
        return default
    return h('xzvwuonmr', 517), h('HIEFTLNMKZ', 697)

def build(code):
    own = WH[code]; xh, capH = metrics(own)
    ser = SER[SERF[code]]; sgs = ser.getGlyphSet(); scm = ser.getBestCmap()
    sops = lambda ch: rec(sgs[scm[ord(ch)]].draw)
    kx = xh / bounds(sops('x'))[3]; kc = capH / bounds(sops('H'))[3]
    glyphs = dict(own); src = {}
    def find(ch):
        if ch in glyphs: return glyphs[ch]
        for st, sl in CHAIN[code]:
            if ch in WH[st]:
                ops, w = WH[st][ch]
                src[ch] = st + ('/' if sl else '')
                return (xform(ops, (1, 0, SLANT, 1, 0, 0)) if sl else ops, w)
        return None
    for ch in WANT:
        if ch in glyphs: continue
        if ch in ACCENTED:
            base, acc = ACCENTED[ch]
            b = find(base)
            if b:
                bops, bw = b
                if base == 'i':  # via il puntino: si tiene il contorno più basso
                    cont, cur = [], []
                    for op in bops:
                        cur.append(op)
                        if op[0] in ('closePath', 'endPath'): cont.append(cur); cur = []
                    cont.sort(key=lambda c: bounds(c)[1]); bops = cont[0]
                aops = sops(acc); ab = bounds(aops)
                up = ch.isupper(); k = kc if up else kx
                sp = bounds(sops(ch)); sbase = bounds(sops('H' if up else 'x'))
                gap = sp[1] if False else None
                # posizione verticale: come nella lettera precomposta di Seravek
                acc_bottom_ser = sp[3] - (ab[3] - ab[1])
                top = capH if up else xh
                dy = top + (acc_bottom_ser - sbase[3]) * k - ab[1] * k
                bb = bounds(bops)
                cx = (bb[0] + bb[2]) / 2
                if code.endswith('i'): cx += SLANT * (top + 60 - (bb[1] + bb[3]) / 2)
                dx = cx - (ab[0] + ab[2]) / 2 * k
                glyphs[ch] = (bops + xform(aops, (k, 0, 0, k, dx, dy)), bw); src[ch] = 'composta'
                continue
        f = find(ch)
        if f: glyphs[ch] = f; continue
        if ord(ch) in scm:
            g = scm[ord(ch)]; k = kx if ch.islower() else kc
            glyphs[ch] = (xform(sops(ch), (k, 0, 0, k, 0, 0)), ser['hmtx'][g][0] * k); src[ch] = 'Seravek'
    # TrueType
    names = {ch: agl.UV2AGL.get(ord(ch), 'uni%04X' % ord(ch)) for ch in glyphs}
    order = ['.notdef'] + sorted(names.values())
    glyf, mt = {'.notdef': TTGlyphPen(None).glyph()}, {'.notdef': (500, 0)}
    for ch, (ops, w) in glyphs.items():
        pen = TTGlyphPen(None); cp = Cu2QuPen(pen, max_err=1, reverse_direction=True)
        for op, a in ops: getattr(cp, op)(*a)
        glyf[names[ch]] = pen.glyph()
        bb = bounds(ops)
        mt[names[ch]] = (round(w), round(bb[0]) if bb else 0)
    fb = FontBuilder(1000, isTTF=True)
    fb.setupGlyphOrder(order); fb.setupCharacterMap({ord(c): n for c, n in names.items()})
    fb.setupGlyf(glyf); fb.setupHorizontalMetrics(mt)
    fb.setupHorizontalHeader(ascent=900, descent=-250)
    fb.setupNameTable({'familyName': 'WhitneyIT' + code, 'styleName': 'Regular'})
    fb.setupOS2(sTypoAscender=900, sTypoDescender=-250, usWinAscent=900, usWinDescent=250)
    fb.setupPost(); fb.save(f'fonts/{code}_it.ttf')
    bysrc = {}
    for ch, s in src.items(): bysrc.setdefault(s, []).append(ch)
    print(code, ' | '.join(f'{s}: {"".join(v)}' for s, v in bysrc.items()))

for code in FAM: build(code)

# 2) Saniretro
t = TTFont(glob.glob('fonts/*SaniretroRegular_*.ttf')[0])
gs = t.getGlyphSet(); go = t.getGlyphOrder()
cm = {}
for cp in list(range(32, 127)) + [0xDF, 0xE4]:
    i = {0xDF: 147, 0xE4: 152}.get(cp, cp - 31)
    r = DecomposingRecordingPen(gs); gs[go[i]].draw(r); ops = r.value
    if ops or cp == 32: cm[chr(cp)] = (ops, t['hmtx'][go[i]][0])
for c in 'FJQXZ':  # nel font le minuscole sono maiuscole dello stesso disegno
    if c not in cm and c.lower() in cm: cm[c] = cm[c.lower()]
upm = t['head'].unitsPerEm
names = {ch: agl.UV2AGL.get(ord(ch), 'uni%04X' % ord(ch)) for ch in cm}
glyf, mt = {'.notdef': TTGlyphPen(None).glyph()}, {'.notdef': (upm // 2, 0)}
for ch, (ops, w) in cm.items():
    pen = TTGlyphPen(None); cp = Cu2QuPen(pen, max_err=1)
    for op, a in ops: getattr(cp, op)(*a)
    glyf[names[ch]] = pen.glyph(); bb = bounds(ops); mt[names[ch]] = (w, round(bb[0]) if bb else 0)
fb = FontBuilder(upm, isTTF=True)
fb.setupGlyphOrder(['.notdef'] + sorted(names.values())); fb.setupCharacterMap({ord(c): n for c, n in names.items()})
fb.setupGlyf(glyf); fb.setupHorizontalMetrics(mt)
fb.setupHorizontalHeader(ascent=t['hhea'].ascent, descent=t['hhea'].descent)
fb.setupNameTable({'familyName': 'SaniretroIT', 'styleName': 'Regular'})
fb.setupOS2(); fb.setupPost(); fb.save('fonts/T_it.ttf')
print('T Saniretro:', ''.join(sorted(cm)))
