"""Aggiunge ai font incorporati (sottoinsiemi) le lettere accentate italiane, che nel PDF originale
hanno il posto ma non il disegno: base + accento preso da Futura Medium di sistema."""
from fontTools.ttLib import TTFont, TTCollection
from fontTools.pens.ttGlyphPen import TTGlyphPen
from fontTools.pens.transformPen import TransformPen
from fontTools.pens.boundsPen import BoundsPen
from fontTools.pens.recordingPen import RecordingPen, DecomposingRecordingPen
from fontTools.pens.cu2quPen import Cu2QuPen

src = None
for f in TTCollection('/System/Library/Fonts/Supplemental/Futura.ttc').fonts:
    if f['name'].getDebugName(2) in ('Medium', 'Medio') and 'Condensed' not in f['name'].getDebugName(4):
        src = f; break
SGS = src.getGlyphSet(); SCM = src.getBestCmap(); SUPM = src['head'].unitsPerEm
SXH = src['OS/2'].sxHeight; SCH = src['OS/2'].sCapHeight

def bounds(gs, name):
    bp = BoundsPen(gs); gs[name].draw(bp); return bp.bounds

ACC = {'grave': SCM[ord('`')], 'acute': SCM[ord('´')]}
TARGET = {'à': ('a', 'grave'), 'è': ('e', 'grave'), 'é': ('e', 'acute'), 'ì': ('i', 'grave'),
          'ò': ('o', 'grave'), 'ù': ('u', 'grave'), 'È': ('E', 'grave'), 'À': ('A', 'grave'), 'É': ('E', 'acute')}

import glob
def fix(path, out):
    f = TTFont(path)
    # prima si recuperano i disegni dalle altre copie dello stesso font nel PDF
    fam = path.split('/')[-1].rsplit('_', 1)[0]
    for other in glob.glob(f'fonts/{fam}_*.ttf'):
        if other == path or other.endswith('_it.ttf'): continue
        o = TTFont(other); ogs = o.getGlyphSet()
        gs0 = f.getGlyphSet()
        for g in f.getGlyphOrder():
            if g in o['glyf'] and not bounds(gs0, g) and bounds(ogs, g):
                f['glyf'][g] = o['glyf'][g]; f['hmtx'][g] = o['hmtx'][g]
    gs = f.getGlyphSet(); cm = f.getBestCmap(); upm = f['head'].unitsPerEm
    if 'FuturaBT-Light_' in path:  # la S maiuscola manca: si prende da Avenir Light, scalata sull'altezza delle maiuscole
        av = [x for x in TTCollection('/System/Library/Fonts/Avenir.ttc').fonts if x['name'].getDebugName(4) == 'Avenir Light'][0]
        ags = av.getGlyphSet(); acm = av.getBestCmap()
        for c in 'S':
            g = cm[ord(c)]
            if bounds(gs, g): continue
            capref = bounds(gs, cm[ord('E')])[3]
            acap = bounds(ags, acm[ord('E')])[3]
            k = capref / acap
            pen = TTGlyphPen(gs)
            ags[acm[ord(c)]].draw(TransformPen(pen, (k, 0, 0, k, 0, 0)))
            f['glyf'][g] = pen.glyph()
            f['hmtx'][g] = (round(av['hmtx'][acm[ord(c)]][0] * k), round(av['hmtx'][acm[ord(c)]][1] * k))
            print('  S presa da Avenir Light')
        gs = f.getGlyphSet()
    sc = upm / SUPM
    def firsth(chars):
        for c in chars:
            g = cm.get(ord(c))
            if g:
                b = bounds(gs, g)
                if b: return b[3]
    xh = firsth('xzvwuonmr') or getattr(f['OS/2'],'sxHeight',0) or upm*0.48; ch = firsth('HIEFTLNMKZXPQWB') or getattr(f['OS/2'],'sCapHeight',0) or xh*1.4
    for ch_, (base, acc) in TARGET.items():
        gname = cm.get(ord(ch_))
        if not gname: continue
        bname = cm[ord(base)]
        if not bounds(gs, bname):
            print('  manca la base', base, 'per', ch_, 'in', path); continue
        rec = DecomposingRecordingPen(gs); gs[bname].draw(rec)
        ops = rec.value
        if base == 'i':  # togli il puntino: tieni solo il contorno più basso
            contours, cur = [], []
            for op in ops:
                cur.append(op)
                if op[0] in ('closePath', 'endPath'): contours.append(cur); cur = []
            def ymin(c):
                ys = [p[1] for op in c for p in op[1]]
                return min(ys) if ys else 0
            contours.sort(key=ymin)
            ops = [op for op in contours[0]]
        pen = TTGlyphPen(gs)
        RecordingPen.replay(type('R', (), {'value': ops})(), pen) if False else None
        for op, args in ops: getattr(pen, op)(*args)
        bb = bounds(gs, bname)
        ab = bounds(SGS, ACC[acc])
        top = ch if base.isupper() else xh
        stop = SCH if base.isupper() else SXH
        # posizione verticale: stessa distanza dall'altezza x (o maiuscola) che ha in Futura
        dy = top + (ab[1] - stop) * sc - ab[1] * sc
        if base == 'i': dy = xh + (ab[1] - SXH) * sc - ab[1] * sc
        cx_base = (bb[0] + bb[2]) / 2
        # nei corsivi l'accento si sposta un po' a destra
        slant = f['post'].italicAngle
        shift = 0
        if slant: shift = -__import__('math').tan(__import__('math').radians(slant)) * (top - (bb[1] + bb[3]) / 2) * 0.6
        dx = cx_base + shift - (ab[0] + ab[2]) / 2 * sc
        if base == 'i': dx -= (ab[2] - ab[0]) * sc * 0.22
        tp = TransformPen(Cu2QuPen(pen, max_err=1, reverse_direction=True), (sc, 0, 0, sc, dx, dy))
        SGS[ACC[acc]].draw(tp)
        f['glyf'][gname] = pen.glyph()
        adv, lsb = f['hmtx'][bname]
        f['hmtx'][gname] = (adv, f['glyf'][gname].xMin if hasattr(f['glyf'][gname], 'xMin') else lsb)
    f.save(out)

for name in ['SLACPI_FuturaBT-Light_2035', 'DMIQNM_FuturaBT-LightItalic_2032',
             'GYANDG_ProtestRevolution-Regular_1983', 'DULLNM_AlegreyaSans-Italic_1923']:
    fix(f'fonts/{name}.ttf', f'fonts/{name}_it.ttf')
    print('ok', name)

# kanji: da CFF a TrueType, perché MuPDF lo incorpori come TrueType
k = TTFont('fonts/kanji.ttf')
from fontTools.fontBuilder import FontBuilder
kgs = k.getGlyphSet(); order = k.getGlyphOrder(); kcm = k.getBestCmap()
glyphs = {}
for g in order:
    pen = TTGlyphPen(None)
    kgs[g].draw(Cu2QuPen(pen, max_err=1, reverse_direction=True))
    glyphs[g] = pen.glyph()
fb = FontBuilder(k['head'].unitsPerEm, isTTF=True)
fb.setupGlyphOrder(order); fb.setupCharacterMap(kcm); fb.setupGlyf(glyphs)
fb.setupHorizontalMetrics({g: k['hmtx'][g] for g in order})
fb.setupHorizontalHeader(ascent=k['hhea'].ascent, descent=k['hhea'].descent)
fb.setupNameTable({'familyName': 'KanjiIT', 'styleName': 'Regular'})
fb.setupOS2(); fb.setupPost(); fb.save('fonts/kanji_tt.ttf')
print('ok kanji')
