import uharfbuzz as hb
from fontTools.ttLib import TTFont
from fontTools.pens.svgPathPen import SVGPathPen
from fontTools.pens.transformPen import TransformPen
from fontTools.pens.boundsPen import BoundsPen
import io
FONTS={}
def font(path):
    if path not in FONTS:
        tt=TTFont(path); buf=io.BytesIO(); tt.flavor=None; tt.save(buf); data=buf.getvalue()
        face=hb.Face(data); f=hb.Font(face)
        FONTS[path]=(TTFont(io.BytesIO(data)),f)
    return FONTS[path]
CLASH6='/workspace/w20/kit/auth-kit/fonts/clash-display-600.woff2'
CLASH5='/workspace/w20/kit/auth-kit/fonts/clash-display-500.woff2'
def r(v): 
    s=f"{v:.2f}".rstrip('0').rstrip('.'); return '0' if s in('-0','') else s
class RPen(SVGPathPen):
    def __init__(s,gs): super().__init__(gs,ntos=r)
def shape(text,path=CLASH6,size=100,track=0.0,x=0,y=0,features=None):
    """returns list of (glyphname, x, y) in font units scaled to size; baseline at y (svg coords, y down)"""
    tt,f=font(path); upem=tt['head'].unitsPerEm
    buf=hb.Buffer(); buf.add_str(text); buf.guess_segment_properties()
    hb.shape(f,buf,features or {"kern":True,"liga":True})
    order=tt.getGlyphOrder(); out=[]; cx=0
    sc=size/upem
    for info,pos in zip(buf.glyph_infos,buf.glyph_positions):
        out.append((order[info.codepoint],x+(cx+pos.x_offset)*sc,y-pos.y_offset*sc))
        cx+=pos.x_advance+track*upem
    return out,(cx-track*upem)*sc,sc,tt
def text_path(text,path=CLASH6,size=100,track=0.0,x=0,y=0,skip=()):
    gl,w,sc,tt=shape(text,path,size,track,x,y); gs=tt.getGlyphSet()
    pen=RPen(gs); bp=BoundsPen(gs); parts=[]
    for i,(g,gx,gy) in enumerate(gl):
        if i in skip: continue
        t=(sc,0,0,-sc,gx,gy)
        gs[g].draw(TransformPen(pen,t))
    return pen.getCommands(),w,gl
def glyph_bounds(g,path=CLASH6,size=100):
    tt,_=font(path); gs=tt.getGlyphSet(); bp=BoundsPen(gs); gs[g].draw(bp); sc=size/tt['head'].unitsPerEm
    return tuple(v*sc for v in bp.bounds)
