import math, os, json
from glyphs import *
OUT='/workspace/w20/logo/out'
BEBAS='/workspace/w20/go-around-design/archive/live-2026-11-05-6aec92ba/site/fonts/app/bebas-neue-400.441b026d.woff2'
MONO='/workspace/w20/kit/auth-kit/fonts/jetbrains-mono-500.woff2'
# ---- themes (from auth-kit tokens + landing v4) ----
T={
 'pearl':    dict(house='#141413',thouse='#05060A',name='Pearl',    bg='#FAF9F5', ink='#141413', acc='#0019C9', red='#E0173A', lite='#141413', tile='#0019C9', tink='#FFFFFF', tacc='#FFFFFF', tred='#FF4D6A', tlite='#FFFFFF', sub='#5E5D59'),
 'midnight': dict(house='#24262B',thouse='#2A2C31',name='Midnight', bg='#08090A', ink='#F5F5F7', acc='#8C97FF', red='#FF3355', lite='#F5F5F7', tile='#111214', tink='#F5F5F7', tacc='#8C97FF', tred='#FF3355', tlite='#F5F5F7', sub='#8A8F98'),
 'amethyst': dict(house='#2B1F4F',thouse='#0B0716',name='Amethyst', bg='#0B0716', ink='#F7F4FF', acc='#C3B5FF', red='#FF5C7A', lite='#F7F4FF', tile='#1A0F33', tink='#F7F4FF', tacc='#C3B5FF', tred='#FF5C7A', tlite='#F7F4FF', sub='#B3A8D1'),
 'champagne':dict(name='Champagne',bg='#F4EEE3', ink='#1C1814', acc='#9C7424', red='#C41E3A', lite='#1C1814', tile='#1C1814', tink='#F4EEE3', tacc='#D4AE52', tred='#FF4D6A', tlite='#F4EEE3', sub='#6B5E4A', house='#1C1814', thouse='#0B0907'),
}
THEMES=['pearl','midnight','amethyst','champagne']
def f(v): return r(v)
# element: (kind, role, attrs)  kind: path|rect|circle|line|polyline ; role: ink|acc|red|lite|bg
def P(d,role='ink',**a): return ('path',role,dict(d=d,**a))
def R(x,y,w,h,role='ink',**a): return ('rect',role,dict(x=f(x),y=f(y),width=f(w),height=f(h),**a))
def C(cx,cy,rr,role='ink',**a): return ('circle',role,dict(cx=f(cx),cy=f(cy),r=f(rr),**a))
def S(d,role='ink',w=1,cap='butt',join='miter',**a): return ('path',role,dict(d=d,fill='none',**{'stroke-width':f(w),'stroke-linecap':cap,'stroke-linejoin':join},**a))
def colour(role,theme,tile):
    if theme=='mono': return 'currentColor'
    if role=='gnd': role='house' if tile else 'acc'
    if role=='wl': return '#FFFFFF'
    if role=='pr': return '#FF3355'
    t=T[theme]; k={'ink':'tink','acc':'tacc','red':'tred','lite':'tlite','house':'thouse'}[role] if tile else role
    return t[k]
def svg(els,vb,theme='mono',tile=False,bg=None,title='Go Around',extra=''):
    o=[f'<svg xmlns="http://www.w3.org/2000/svg" viewBox="{" ".join(f(v) for v in vb)}" role="img" aria-label="{title}">',f'<title>{title}</title>']
    if bg: o.append(f'<rect x="{f(vb[0])}" y="{f(vb[1])}" width="{f(vb[2])}" height="{f(vb[3])}" fill="{bg}"/>')
    o.append(extra)
    for kind,role,a in els:
        if theme=='mono' and role in ('wl','pr'): continue
        c=colour(role,theme,tile); a=dict(a)
        if a.get('fill')=='none': a['stroke']=c
        else: a.setdefault('fill',c)
        o.append('<'+kind+' '+' '.join(f'{k}="{v}"' for k,v in a.items())+'/>')
    o.append('</svg>'); return '\n'.join(o)
# ---- base wordmark (landing v4: Clash Display 600, letter-spacing -.02em) ----
WM,WMW,WGL=text_path('Go Around',size=100,track=-0.02)
CAP=67.0
def wm(role='ink',skip=()): 
    d,_,_=text_path('Go Around',size=100,track=-0.02,skip=skip); return P(d,role)
GX={g:x for g,x,y in WGL}  # first occurrence
AX=[x for g,x,y in WGL if g=='A'][0]
# runway A geometry (Clash A contour, crossbar removed)
def runway_A(x0,role_leg='ink',role_cl='acc',dashes=True):
    L=f"M{f(x0-0.5)} 0L{f(x0+28.8)} -67L{f(x0+50.2)} -67L{f(x0+79.7)} 0L{f(x0+62.5)} 0L{f(x0+40.0)} -53.3L{f(x0+38.9)} -53.3L{f(x0+16.3)} 0Z"
    els=[P(L,role_leg)]
    if dashes:
        cx=x0+39.6
        for y0,y1,w in ((-4,-19,7.0),(-27,-37,5.2)):
            els.append(R(cx-w/2,y1,w,y0-y1,role_cl))
    return els
def tile_box(els_fn,size=512): return els_fn
# ---------- directions ----------
D=[]
def direction(**k): D.append(k); return k
# helpers to centre a drawing inside a 512 tile: we pass (els, bbox) and scale
def fit(els,bb,box=512,pad=0.22,dy=0):
    x0,y0,x1,y1=bb; w=x1-x0; h=y1-y0; s=box*(1-2*pad)/max(w,h)
    tx=(box-w*s)/2-x0*s; ty=(box-h*s)/2-y0*s+dy*box
    return f'<g transform="matrix({f(s)} 0 0 {f(s)} {f(tx)} {f(ty)})">', '</g>', s
def tile_svg(els,bb,theme,pad=0.22,box=512,title='Go Around app icon',dy=0):
    g0,g1,_=fit(els,bb,box,pad,dy)
    bg=T[theme]['tile'] if theme!='mono' else None
    body=svg(els,(0,0,box,box),theme,tile=True,bg=bg,title=title)
    # wrap elements in transform group: insert after bg rect
    lines=body.split('\n'); i=3 if bg else 2
    return '\n'.join(lines[:i+1]+[g0]+lines[i+1:-1]+[g1,lines[-1]])
# 01 Landing word -------------------------------------------------
GO,GOW,_=text_path('Go',size=100,track=-0.02)
G1,G1W,_=text_path('G',size=100)
direction(id='01-landing-word',name='Landing word',kind='Wordmark',
 why='The exact nav word from landing v4, Clash Display 600 at −0.02em, drawn as outlines so it never depends on a font load. Icon says “Go”, the app’s own verdict word.',
 word=([wm()],(0,-68,520,1)),
 icon=([P(GO)],(0,-68,GOW,1)),
 fav=([P(G1)],(2.5,-68,74.1,1)))
# 02 Climb-out ---------------------------------------------------
def profile(x0,x1,y0,ylow,xlow,yend,w=5.0,role='acc'):
    return S(f"M{f(x0)} {f(y0)}L{f(xlow)} {f(ylow)}L{f(x1)} {f(yend)}",role,w=w,join='round',cap='round')
# icon: approach (long, shallow), decision point, climb-out (steeper); runway segment under the low point
def climb_icon(w=12,dash=(11,7.5),rw=7):
    # profile view as drawn on an approach chart: the approach is a solid line, the missed approach a dashed climb
    app=S("M2 36L46 58.5Q52 61.5 58 57.2",'ink',w=w,cap='butt',join='round')
    miss=S("M58 57.2L98 22",'ink',w=w,cap='butt',**{'stroke-dasharray':f"{dash[0]} {dash[1]}"})
    return [app,miss,R(34,72,40,rw,'acc')]
direction(id='02-climb-out',name='Climb-out',kind='Wordmark + symbol',
 why='The manoeuvre itself, drawn the way an approach chart draws it in profile: a solid line for the approach, a dashed line for the missed approach climb. The runway sits under the low point and the line never touches it.',
 word=None, lock=True,
 icon=(climb_icon(),(0,18,100,82)),
 fav=(climb_icon(w=15,dash=(14,9),rw=10),(0,16,100,84)))
# 03 Runway A ----------------------------------------------------
GOd,_,_=text_path('Go',size=100,track=-0.02)
rest,_,_=text_path('Go Around',size=100,track=-0.02,skip=(0,1,2,3))
direction(id='03-runway-a',name='Runway A',kind='Wordmark + monogram',
 why='The A of Around becomes a runway seen from short final: the two legs are the runway edges, the crossbar becomes centreline stripes. It reads as an A at every size.',
 word=([P(GOd),P(rest)]+runway_A(AX),(0,-68,520,1)),
 icon=(runway_A(0),(-0.5,-67,79.7,0)),
 fav=(runway_A(0,dashes=True),(-0.5,-67,79.7,0)))
# 04 PAPI --------------------------------------------------------
def papi(x0,cy,rr,gap,roles=('lite','lite','red','red')):
    return [C(x0+rr+i*(2*rr+gap),cy,rr,ro) for i,ro in enumerate(roles)]
direction(id='04-papi',name='PAPI',kind='Wordmark + symbol',
 why='The four precision approach path lights in their housing. Two white and two red means on the glide path; all red means too low, go around. A real object pilots read on every approach.',
 word=None, lock=True, lockh=0.62,
 icon=([P('M10 -19L85 -19A19 19 0 0 1 85 19L10 19A19 19 0 0 1 10 -19Z'+''.join(f'M{f(10+i*25)} -10A10 10 0 1 0 {f(10+i*25)} 10A10 10 0 1 0 {f(10+i*25)} -10Z' for i in range(4)),'house',**{'fill-rule':'evenodd'})]+papi(0,0,10,5,roles=('wl','wl','pr','pr')),(-9,-19,104,19)),
 fav=(papi(0,0,10,3.5,roles=('wl','wl','pr','pr')),(0,-10,90.5,10)))
# 05 Pitch-up ------------------------------------------------------
def attitude(ring=7,bar=8,hz=66,ladder=True):
    # attitude indicator in a go-around: nose up, so the horizon sits low; the aircraft symbol stays fixed in the middle
    r0=46
    dy=hz-50; hx=math.sqrt(r0*r0-dy*dy)
    ground=P(f"M{f(50-hx)} {f(hz)}L{f(50+hx)} {f(hz)}A{r0} {r0} 0 0 1 {f(50-hx)} {f(hz)}Z",'gnd')
    ringe=S(f"M50 {f(50-r0+ring/2)}A{f(r0-ring/2)} {f(r0-ring/2)} 0 1 1 49.99 {f(50-r0+ring/2)}Z",'ink',w=ring)
    # fixed aircraft symbol: wings level, the centre raised in a chevron (nose up)
    wing=[S(f"M14 52L37 52L50 {f(52-bar*1.5)}L63 52L86 52",'ink',w=bar,join='miter',cap='butt')]
    return [ground,ringe]+wing
direction(id='05-pitch-up',name='Pitch-up',kind='Symbol + wordmark',
 why='What the attitude indicator shows at the moment of a go-around: power up, nose up, the horizon drops away under a steady aircraft symbol. Calm, instrument-true, and it reads at 16 pixels.',
 word=None, lock=True,
 icon=(attitude(hz=68),(4,4,96,96)),
 fav=(attitude(ring=9,bar=10,hz=68,ladder=False),(4,4,96,96)))
# 06 Exit G ------------------------------------------------------
def exit_g(w=15):
    cx,cy,R0=50,52,34
    a=math.radians(-120); px,py=cx+R0*math.cos(a),cy+R0*math.sin(a)
    # from the spur at the centre, out to the right, clockwise around the bottom and left, leaving tangentially at top-left
    ex=px+70*math.cos(math.radians(-30)); ey=py+70*math.sin(math.radians(-30))
    d=f"M{f(cx+2)} {f(cy)}L{f(cx+R0)} {f(cy)}A{R0} {R0} 0 1 1 {f(px)} {f(py)}L{f(ex)} {f(ey)}"
    return [S(d,'ink',w=w,join='miter',cap='butt')]
direction(id='06-exit-g',name='Climb-out G',kind='Monogram',
 why='A geometric G drawn as one stroke: it flies the circle, then leaves it on a straight 30° climb. The circuit and the go-around in a single letter.',
 word=None, lock=True,
 icon=(exit_g(),(8,-25,112,94)),
 fav=(exit_g(w=19),(6,-25,114,96)))
# 07 Centreline --------------------------------------------------
GOU,GOUW,_=text_path('GO',CLASH5,100,0.14)
ARU,ARUW,_=text_path('AROUND',CLASH5,100,0.14)
gapx=GOUW+20; dash=[(gapx+i*34,22) for i in range(3)]
x_ar=gapx+3*34-12+20
ARU2,_,_=text_path('AROUND',CLASH5,100,0.14,x=x_ar)
cl_word=[P(GOU),*[R(x,-36,w,6,'acc') for x,w in dash],P(ARU2)]
GAU,GAUW,_=text_path('GA',CLASH5,100,0.10)
direction(fpad=0.12,id='07-centreline',name='Centreline',kind='Wordmark (formal)',
 why='Go-around is spelt with a hyphen in the rule books. Here the hyphen becomes three centreline stripes, with capitals tracked wide like runway paint. Formal use: the Founding pass, certificates, the footer and print.',
 word=(cl_word,(0,-68,x_ar+ARUW,1)),
 icon=([P(text_path('GO',CLASH5,100,0.06)[0])]+[R(i*(text_path('GO',CLASH5,100,0.06)[1]+12)/4,14,(text_path('GO',CLASH5,100,0.06)[1]+12)/4-12,7,'acc') for i in range(4)],(0,-68,text_path('GO',CLASH5,100,0.06)[1],21)),
 fav=([P(text_path('GO',CLASH5,100,0.02)[0])]+[R(i*52,16,30,12,'acc') for i in range(3)],(0,-68,text_path('GO',CLASH5,100,0.02)[1],28)))
# 08 Threshold ---------------------------------------------------
def keys(n=4,bw=7,gap=6,mid=14,h=50,x0=0,y0=0,role='ink'):
    els=[];x=x0
    for side in range(2):
        for i in range(n): els.append(R(x,y0,bw,h,role)); x+=bw+gap
        x+=mid-gap
    return els,x-mid
def keys_persp(n=4,top=0,bot=60,wb=100,wt=46,mid=0.16,fill=0.58,role='ink',cl=True):
    # threshold markings seen from short final: 2 x n keys converging to the vanishing point, centreline above
    els=[]; cx=wb/2
    def xs(t,y):  # t in [-1,1] across the runway at height y
        hw=(wt+(wb-wt)*(y-top)/(bot-top))/2; return cx+t*hw
    slots=[]
    for side in (-1,1):
        for i in range(n):
            a=mid+(1-mid)*i/n; b=mid+(1-mid)*(i+fill)/n
            slots.append((side*a,side*b) if side>0 else (side*b,side*a))
    for a,b in slots:
        els.append(P(f"M{f(xs(a,bot))} {f(bot)}L{f(xs(b,bot))} {f(bot)}L{f(xs(b,top))} {f(top)}L{f(xs(a,top))} {f(top)}Z",role))
    return els
k_icon=keys_persp(); kw=100
k_fav=keys_persp(n=3,fill=0.62); kfw=100
direction(id='08-threshold',name='Threshold',kind='Symbol + wordmark',
 why='The piano keys painted across every runway threshold, seen from short final so they converge like the real thing. The threshold is the line where an approach either lands or goes around.',
 word=None, lock=True,
 icon=(k_icon,(0,0,100,60)),
 fav=(k_fav,(0,0,100,60)))
# 09 GA tile refined ---------------------------------------------
GAB,GABW,_=text_path('GA',BEBAS,100,0.02)
direction(id='09-ga-tile',name='GA tile, refined',kind='Monogram (existing)',
 why='The GA tile already on the live site, kept in its condensed letters, now with a threshold bar under it like a painted runway designator. Continuity for people who know the app.',
 word=None, lock=True,
 icon=([P(GAB),R(0,10,GABW,7,'acc')],(0,-71,GABW,17)),
 fav=([P(GAB)],(0,-71,GABW,1)))
# 10 Compass seal -------------------------------------------------
def seal(r_out=50,ticks=True,text=True,w=2.2):
    els=[S(f"M{50} {50-r_out}A{r_out} {r_out} 0 1 1 {49.99} {50-r_out}Z",'ink',w=w)]
    if ticks:
        for i in range(72):
            a=math.radians(i*5-90); L=5.5 if i%18==0 else (3.6 if i%6==0 else 2)
            r0=r_out-3.5; r1=r0-L
            els.append(S(f"M{f(50+r0*math.cos(a))} {f(50+r0*math.sin(a))}L{f(50+r1*math.cos(a))} {f(50+r1*math.sin(a))}",'ink',w=0.9 if i%6 else 1.3))
    if text:
        def arc_text(s,rad,start,step,flip=False,size=7.6):
            o=[];tt,_=font(CLASH5)
            gl,wid,sc,_=shape(s,CLASH5,size,0.18)
            n=wid/rad; a0=start-n/2
            for g,gx,gy in gl:
                gw=tt['hmtx'][g][0]*sc
                ang=a0+(gx+gw/2)/rad
                d,_,_=text_path(g if False else '',CLASH5,size)
            return o
        pass
    return els
def seal_full():
    els=seal()
    tt,_=font(CLASH5); gs=tt.getGlyphSet()
    def place(s,rad,centre_deg,bottom=False,size=7.4,track=0.22):
        gl,wid,sc,_=shape(s,CLASH5,size,track)
        tot=wid/rad
        for g,gx,gy in gl:
            if g=='space': continue
            gw=tt['hmtx'][g][0]*sc
            off=(gx+gw/2)/rad - tot/2
            if not bottom:
                ang=math.radians(centre_deg)+off; x=50+rad*math.cos(ang); y=50+rad*math.sin(ang); rot=math.degrees(ang)+90
                tr=f"translate({f(x)} {f(y)}) rotate({f(rot)}) translate({f(-gw/2)} {f(size*0.335)})"
            else:
                ang=math.radians(centre_deg)-off; x=50+rad*math.cos(ang); y=50+rad*math.sin(ang); rot=math.degrees(ang)-90
                tr=f"translate({f(x)} {f(y)}) rotate({f(rot)}) translate({f(-gw/2)} {f(size*0.335)})"
            from fontTools.pens.svgPathPen import SVGPathPen
            pen=RPen(gs); gs[g].draw(TransformPen(pen,(sc,0,0,-sc,0,0)))
            els.append(P(pen.getCommands(),'ink',transform=tr))
    place('GO AROUND',35.2,-90)
    place('SOUTH AFRICA',35.2,90,bottom=True,size=6.2,track=0.26)
    # centre: climb-out profile + runway
    for kind,role,a in climb_icon(w=4.4):
        a=dict(a); a['transform']='translate(33 31) scale(.34)'
        if 'stroke-width' in a: a['stroke-width']=f(float(a['stroke-width']))
        els.append((kind,role,a))
    return els
direction(id='10-compass-seal',name='Compass seal',kind='Seal',
 why='A compass ring with a tick every 5°, the name set on the ring and the climb-out profile at its heart. The formal mark for the Founding pass, certificates and the ATO verified seal.',
 word=None, lock=True,
 icon=(seal_full(),(-1.5,-1.5,101.5,101.5)),
 fav=(seal(ticks=False,text=False,w=7)+[ (k,ro,dict(a,transform='translate(18 18) scale(.64)')) for k,ro,a in climb_icon(w=16)],(-4,-4,104,104)))
