import math, numpy as np, skia
import jetlib as J, letters as LT
from hobby import piece, path as hpath
U,D,I=J.U,J.D,J.I
NAVY=0xFF0B1B33; WHITE=0xFFFFFFFF
def hdir(h):  # heading deg clockwise from up -> unit vector (svg coords)
    r=math.radians(h); return np.array([math.sin(r), -math.cos(r)])
def plan_from_tail(tail_xy, heading, L, gap, detail='clean'):
    d=hdir(heading); c=np.array(tail_xy)+d*(gap+(9.47-4.71)*L/9.42)
    return J.place(J.plan(detail), c[0], c[1], L, heading)
def bez(seg,t):
    a,b,c,e=[np.array(p,float) for p in seg]; m=1-t
    return m**3*a+3*m*m*t*b+3*m*t*t*c+t**3*e, 3*m*m*(b-a)+6*m*t*(c-b)+3*t*t*(e-c)
def sample(segs, n=80):
    pts=[];tg=[]
    for k,s in enumerate(segs):
        for i in range(n):
            if k>0 and i==0: continue
            p,t=bez(s,i/(n-1)); pts.append(p); tg.append(t/np.linalg.norm(t))
    # arc length param
    L=np.r_[0,np.cumsum(np.linalg.norm(np.diff(pts,axis=0),axis=1))]
    return np.array(pts),np.array(tg),L/L[-1]
def taper(segs, wfun, knots=16):
    pts,tg,u=sample(segs)
    idx=[int(round(x)) for x in np.linspace(0,len(pts)-1,knots)]
    nrm=lambda t: np.array([-t[1],t[0]])
    left=[tuple(pts[i]+nrm(tg[i])*wfun(u[i])/2) for i in idx]
    right=[tuple(pts[i]-nrm(tg[i])*wfun(u[i])/2) for i in idx][::-1]
    sl=piece(left); sr=piece(right)
    p=skia.Path(); p.moveTo(*sl[0][0])
    for s in sl: p.cubicTo(*s[1],*s[2],*s[3])
    w1=wfun(1.0)
    if w1>0.3:  # round end cap
        e=pts[-1]; t=tg[-1]; r=w1/2; k=0.5523*r; a=np.array(sl[-1][3]); b=np.array(sr[0][0])
        p.cubicTo(*(a+t*k), *(e+t*r+nrm(t)*k), *(e+t*r)); p.cubicTo(*(e+t*r-nrm(t)*k), *(b+t*k), *b)
    else: p.lineTo(*sr[0][0])
    for s in sr: p.cubicTo(*s[1],*s[2],*s[3])
    p.close(); return skia.Simplify(p)
def moat(shape, m):
    return skia.Op(shape, J.ring(shape, 2*m), U)

# ---------- key points of the approved letters ----------
APEX=np.array([596.72,41.0])      # centre-line apex
EXIT=np.array([799.48,415.0])     # exit-tail end
EXIT_H=math.degrees(math.atan2(23.74,12.61))   # 62 deg
BAR_END=np.array([776.79,230.0])
def bar_at(x):
    s1,s2=LT.stroke_paths(); m=skia.PathMeasure(s2,False); best=None
    L=m.getLength(); 
    for i in range(2001):
        p,t=m.getPosTan(L*i/2000)
        if best is None or abs(p.x()-x)<abs(best[0].x()-x): best=(p,t)
    p,t=best; return np.array([p.x(),p.y()]), math.degrees(math.atan2(t.y(),t.x()))
def cubic(S,h0,T,h1,k0=0.38,k1=0.38):
    S=np.array(S,float); T=np.array(T,float); L=np.linalg.norm(T-S)
    return [(tuple(S),tuple(S+hdir(h0)*L*k0),tuple(T-hdir(h1)*L*k1),tuple(T))]

def swash(peak=3.0, a=0.0, b=0.0):
    """calligraphic hairline: grows from a point, swells, and releases to a point before the jet"""
    def w(u):
        x=min(1,u/0.22); y=min(1,(1-u)/0.30)
        return peak*(math.sin(min(x,1)*math.pi/2)**1.2)*(math.sin(min(y,1)*math.pi/2)**1.5)
    return w
def option(n):
    if n==1:
        h=11; L=98
        jet=plan_from_tail(APEX, h, L, 15+11)
        return dict(jet=jet, trail=None, knock=None, title='Apex', line='A plan-view Vision Jet lifts straight off the point of the A. Nothing else.')
    if n==2:
        S=EXIT+hdir(EXIT_H)*10; h1=22; T=S+np.array([86,-150])
        segs=cubic(S,EXIT_H,T,h1,0.45,0.35)
        trail=taper(segs, swash(3.4))
        jet=plan_from_tail(T, h1, 88, 9)
        return dict(jet=jet, trail=trail, knock=None, title='Exit', line='The exit stroke releases a hairline swash; the jet climbs away off the end of the tail.')
    if n==3:
        L=150; climb=9.0; x0=744
        p,ang=bar_at(x0); n_=np.array([math.sin(math.radians(ang)), -math.cos(math.radians(ang))])
        g=p+n_*(15+5.0)
        jet=J.place(J.side('full'), g[0], g[1], L, climb-ang, pivot=(4.5,0), view='side')
        return dict(jet=jet, trail=None, knock=None, title='Runway', line='The SF50 in profile rotating off the crossbar, which becomes its runway.')
    if n==4:
        # the crossbar IS the wing: at L=128 the real root chord (2.2 m) equals the 30-unit stroke,
        # and the real span (11.68 m) equals the bar's run from the A's leg to its tip.
        L=128; sc=L/9.42; xm=714
        p,ang=bar_at(xm); h=ang          # nose perpendicular to the bar
        P=J.plan_parts(); body=skia.Path(P['fus'])
        for t in P['tails']: body=J.op(body,t,U)
        body=J.op(body,P['nac'],U)
        solid=skia.Path(body)
        cut=0.075
        body=J.op(body, J.op(J.ring(P['fus'],cut), J.op(P['tails'][0],P['tails'][1],U), I), D)
        body=J.op(body, J.ring(P['nac'],cut), D)
        body=J.op(body, J.op(J.ellipse(0,5.00,0.27,0.10), J.ellipse(0,5.06,0.25,0.07), D), D)
        jet=J.place(body, p[0], p[1], L, h, pivot=(0,4.80))
        knock=moat(J.place(solid, p[0], p[1], L, h, pivot=(0,4.80)), 3.2)
        return dict(jet=jet, trail=None, knock=knock, title='Wingspan', line='The crossbar becomes the wing: a plan-view fuselage crosses it at true scale, root chord equal to the stroke.')
    if n==5:
        d0=30.0; S=APEX+hdir(d0)*(15+10); h1=60; T=S+np.array([205,-112])
        segs=cubic(S,d0,T,h1,0.42,0.40)
        trail=taper(segs, swash(2.4))
        jet=plan_from_tail(T, h1, 64, 7, detail='mini')
        return dict(jet=jet, trail=trail, knock=None, title='Contrail', line='A hairline contrail carries the upstroke past the apex to a tiny, precise jet.')
    if n==6:
        # an exact elliptical circuit, entered tangentially from the exit stroke
        rx,ry=430,290; S=EXIT+hdir(EXIT_H)*11
        t0=math.atan(math.tan(math.radians(90-EXIT_H))**-1*ry/rx) if False else math.atan(1/math.tan(math.radians(EXIT_H))*0+ (math.sin(math.radians(EXIT_H))/math.cos(math.radians(EXIT_H)))*ry/rx)
        ctr=S-np.array([rx*math.cos(t0), ry*math.sin(t0)])
        t1=math.radians(-125); segs=[]; N=5
        for k in range(N):
            a0=t0+(t1-t0)*k/N; a1=t0+(t1-t0)*(k+1)/N; d=a1-a0; kk=4/3*math.tan(d/4)
            P=lambda a: ctr+np.array([rx*math.cos(a), ry*math.sin(a)])
            T=lambda a: np.array([-rx*math.sin(a), ry*math.cos(a)])
            segs.append((tuple(P(a0)),tuple(P(a0)+T(a0)*kk),tuple(P(a1)-T(a1)*kk),tuple(P(a1))))
        trail=taper(segs, swash(2.8), knots=30)
        pts,tg,u=sample(segs); end=pts[-1]; t=tg[-1]; h=math.degrees(math.atan2(t[0],-t[1]))
        jet=plan_from_tail(end, h, 74, 8)
        return dict(jet=jet, trail=trail, knock=None, title='Go-Around', line='The exit stroke flies a full go-around circuit over the monogram; the jet turns back in above the G.')
