import sys, math, numpy as np, skia, importlib
def skpath(segs):
    p = skia.Path(); p.moveTo(*segs[0][0])
    for (a,b,c,d) in segs:
        if np.linalg.norm(np.array(a)-np.array(p.getLastPt())) > 0.5: p.moveTo(*a)
        p.cubicTo(*b, *c, *d)
    return p
def bez(seg, t):
    a,b,c,d = map(np.array, seg); u=1-t
    return u**3*a+3*u*u*t*b+3*u*t*t*c+t**3*d
def dbez(seg,t):
    a,b,c,d = map(np.array, seg); u=1-t
    return 3*u*u*(b-a)+6*u*t*(c-b)+3*t*t*(d-c)
def ddbez(seg,t):
    a,b,c,d = map(np.array, seg); u=1-t
    return 6*u*(c-2*b+a)+6*t*(d-2*c+b)
def render(strokes, out, W=2000, H=1300, fg=0xFF0B1B33, bg=0xFFFFFFFF, comb=False, sw=30, extra=None, box=None):
    surf = skia.Surface(W, H); cv = surf.getCanvas(); cv.clear(bg)
    allp = [skpath(s) for s in strokes]
    bounds = skia.Rect.MakeEmpty()
    for p in allp: bounds.join(p.computeTightBounds())
    if extra is not None: bounds.join(extra.computeTightBounds())
    if box: bounds = skia.Rect(*box)
    bounds.outset(sw, sw)
    sc = min(W*0.88/bounds.width(), H*0.84/bounds.height())
    cv.translate(W/2, H/2); cv.scale(sc, sc); cv.translate(-bounds.centerX(), -bounds.centerY())
    paint = skia.Paint(AntiAlias=True, Color=fg, Style=skia.Paint.kStroke_Style, StrokeWidth=sw,
                       StrokeCap=skia.Paint.kRound_Cap, StrokeJoin=skia.Paint.kRound_Join)
    for p in allp: cv.drawPath(p, paint)
    if extra is not None: cv.drawPath(extra, skia.Paint(AntiAlias=True, Color=fg))
    if comb:
        cp = skia.Paint(AntiAlias=True, Color=0xFFE0457B, StrokeWidth=1/sc*1.2, Style=skia.Paint.kStroke_Style)
        hp = skia.Paint(AntiAlias=True, Color=0xFF2E9BFF, StrokeWidth=1/sc*1.5, Style=skia.Paint.kStroke_Style)
        for s in strokes:
            for seg in s:
                prev=None
                for t in np.linspace(0,1,40):
                    p=bez(seg,t); d=dbez(seg,t); dd=ddbez(seg,t); sp=np.linalg.norm(d)
                    if sp<1e-9: continue
                    k=(d[0]*dd[1]-d[1]*dd[0])/sp**3; nrm=np.array([-d[1],d[0]])/sp
                    q=p-nrm*k*3000
                    cv.drawLine(*p,*q,cp)
                    if prev is not None: cv.drawLine(*prev,*q,cp)
                    prev=q
                a,b,c,d=seg
                cv.drawLine(*a,*b,hp); cv.drawLine(*d,*c,hp)
                for pt in (a,d): cv.drawCircle(*pt, 3/sc*1.5, skia.Paint(AntiAlias=True,Color=0xFF2E9BFF))
    surf.makeImageSnapshot().save(out, skia.kPNG)
if __name__=='__main__':
    import design; importlib.reload(design)
    st = design.sheared(design.letters())
    render(st, sys.argv[1], sw=design.SW)
    render(st, sys.argv[2], sw=design.SW, comb=True, fg=0x330B1B33)
