"""Writes SVGs (stroke, outlined navy, outlined white), previews, compare sheet, draw-on HTML."""
import os, json, math, skia, numpy as np
import base as B, runs as R, wordmark as W
D='/workspace/logo-ga-18nov/wordmark'
NAVY='#0B1B33'; PAD=28
NAMES={'signature':'A · Signature — "Go Around", word break, lift-off finish',
       'linked':'B · Linked — the o flows into the A\'s crossbar',
       'loop':'C · Loop — one horizon line: G bar, the o as a loop, A crossbar'}
def f(v): s=f'{v:.2f}'.rstrip('0').rstrip('.'); return '0' if s in ('-0','') else s
def segs_d(segs):
    d=''; last=None
    for (a,b,c,e) in segs:
        if last is None or math.dist(a,last)>0.01: d+=f'M{f(a[0])} {f(a[1])}'
        d+=f'C{f(b[0])} {f(b[1])} {f(c[0])} {f(c[1])} {f(e[0])} {f(e[1])}'; last=e
    return d
def path_d(p):
    d=''; it=skia.Path.Iter(p, False)
    while True:
        verb,pts=it.next()
        if verb==skia.Path.kDone_Verb: break
        if verb==skia.Path.kMove_Verb: d+=f'M{f(pts[0].x())} {f(pts[0].y())}'
        elif verb==skia.Path.kLine_Verb: d+=f'L{f(pts[1].x())} {f(pts[1].y())}'
        elif verb==skia.Path.kQuad_Verb: d+=f'Q{f(pts[1].x())} {f(pts[1].y())} {f(pts[2].x())} {f(pts[2].y())}'
        elif verb==skia.Path.kCubic_Verb: d+=f'C{f(pts[1].x())} {f(pts[1].y())} {f(pts[2].x())} {f(pts[2].y())} {f(pts[3].x())} {f(pts[3].y())}'
        elif verb==skia.Path.kConic_Verb:
            w=it.conicWeight(); qs=skia.Path.ConvertConicToQuads(pts[0],pts[1],pts[2],w,3)
            for i in range(1,len(qs),2): d+=f'Q{f(qs[i].x())} {f(qs[i].y())} {f(qs[i+1].x())} {f(qs[i+1].y())}'
        elif verb==skia.Path.kClose_Verb: d+='Z'
    return d
def fr(p): return 'evenodd' if p.getFillType() in (skia.PathFillType.kEvenOdd, skia.PathFillType.kInverseEvenOdd) else 'nonzero'
def geometry(v):
    """per stroke: list of (out-space segs, width) pieces + outline; all offset to a 0,0 viewBox"""
    strokes=W.build(W.variant(v)); G=[]
    for s in strokes:
        pcs=[pc for r in s['runs'] for pc in R.pieces(R.sheared_run(r))]
        G.append(dict(id=s['id'], pieces=pcs, runs=[R.sheared_run(r) for r in s['runs']]))
    for g in G:
        acc=None
        for run in g['runs']:
            o=B.outline(run[0],run[1]) if abs(run[1]-run[2])<1e-6 else R.taper_outline(run)
            acc=o if acc is None else B.U(acc,o)
        g['outline']=skia.Simplify(acc)
    r=skia.Rect.MakeEmpty()
    for g in G: r.join(g['outline'].computeTightBounds())
    r.outset(PAD,PAD); dx,dy=-math.floor(r.left()),-math.floor(r.top())
    vb=[0,0,math.ceil(r.width())+1,math.ceil(r.height())+1]
    for g in G:
        g['pieces']=[([tuple((p[0]+dx,p[1]+dy) for p in s) for s in segs],w) for segs,w in g['pieces']]
        g['runs']=[([tuple((p[0]+dx,p[1]+dy) for p in s) for s in r_[0]],)+tuple(r_[1:]) for r_ in g['runs']]
        q=skia.Path(g['outline']); q.offset(dx,dy); g['outline']=q
    return G,vb
def svg_head(vb,title): return f'<svg xmlns="http://www.w3.org/2000/svg" viewBox="{" ".join(map(str,vb))}" width="{vb[2]}" height="{vb[3]}">\n<title>{title}</title>\n'
def svg_stroke(G,vb,v,ink=NAVY):
    s=svg_head(vb,f'Go Around wordmark, {v} (live strokes; tapers are stepped stroke pieces)')
    s+=f'<g id="wordmark" fill="none" stroke="{ink}" stroke-linecap="round" stroke-linejoin="round">\n'
    for g in G:
        s+=f'  <g id="{g["id"]}">\n'
        for ri,run in enumerate(g['runs']):
            segs,w0,w1=run[0],run[1],run[2]
            if abs(w0-w1)<1e-6: s+=f'    <path stroke-width="{f(w0)}" d="{segs_d(segs)}"/>\n'
            else:
                s+=f'    <g id="{g["id"]}-taper-{ri}">'
                for segs2,w in R.pieces(run,4.0): s+=f'<path stroke-width="{f(w)}" d="{segs_d(segs2)}"/>'
                s+='</g>\n'
        s+='  </g>\n'
    return s+'</g>\n</svg>\n'
def svg_outlined(G,vb,v,ink=NAVY):
    s=svg_head(vb,f'Go Around wordmark, {v} (outlined, Figma-ready)')
    s+='<g id="wordmark">\n'
    for g in G: s+=f'  <path id="{g["id"]}" fill="{ink}" fill-rule="{fr(g["outline"])}" d="{path_d(g["outline"])}"/>\n'
    return s+'</g>\n</svg>\n'
def filled(G):
    acc=None
    for g in G: acc=g['outline'] if acc is None else B.U(acc,g['outline'])
    return acc
def draw(p,vb,W_,H_,bg,fg,fit=0.82,label=None,lc=None):
    surf=skia.Surface(W_,H_); cv=surf.getCanvas(); cv.clear(bg)
    sc=min(W_*fit/vb[2],H_*fit/vb[3])
    cv.save(); cv.translate(W_/2,H_/2-(H_*0.04 if label else 0)); cv.scale(sc,sc); cv.translate(-vb[2]/2,-vb[3]/2)
    cv.drawPath(p,skia.Paint(AntiAlias=True,Color=fg)); cv.restore()
    if label:
        font=skia.Font(skia.Typeface('DejaVu Sans'),H_*0.04); w=font.measureText(label)
        cv.drawString(label,W_/2-w/2,H_*0.92,font,skia.Paint(AntiAlias=True,Color=lc))
    return surf.makeImageSnapshot()
def html(G,vb,v,bg='#0B1B33',ink='#FFFFFF',dur=3.0):
    items=[]
    for si,g in enumerate(G):
        for segs,w in g['pieces']:
            L=sum(R.seglen(s) for s in segs); items.append((si,segs_d(segs),w,L))
    paths=''.join(f'<path d="{d}" stroke-width="{f(w)}"/>' for _,d,w,_ in items)
    meta=json.dumps([[si,round(L,2)] for si,_,_,L in items])
    return f'''<!doctype html><html><head><meta charset="utf-8"><title>Go Around wordmark ({v}) draw-on</title>
<style>html,body{{margin:0;height:100%;background:{bg}}}body{{display:flex;align-items:center;justify-content:center;flex-direction:column}}
svg{{width:min(84vw,calc(70vh*{vb[2]}/{vb[3]}));height:auto;display:block}}
button{{margin-top:4vh;font:500 14px -apple-system,Helvetica,Arial;color:{ink};background:transparent;border:1px solid {ink}55;border-radius:20px;padding:8px 18px;cursor:pointer;opacity:.7}}
body.capture button{{display:none}}</style></head><body>
<svg viewBox="0 0 {vb[2]} {vb[3]}" xmlns="http://www.w3.org/2000/svg"><g id="ink" fill="none" stroke="{ink}" stroke-linecap="round" stroke-linejoin="round">{paths}</g></svg>
<button onclick="play()">Replay</button>
<script>
const M={meta}, P=[...document.querySelectorAll('#ink path')], GAP=140, DUR={dur};
let acc=0, prev=0; const S=[];
M.forEach(([si,L],i)=>{{ if(si!==prev){{acc+=GAP;prev=si;}} S.push(acc); acc+=L; P[i].style.strokeDasharray=L+' '+(L+50); }});
const TOT=acc;
const ease=x=>x<.5?4*x*x*x:1-Math.pow(-2*x+2,3)/2;
const pace=x=>0.5*ease(x)+0.5*x;
function renderAt(t){{ const D=TOT*pace(Math.max(0,Math.min(1,t/DUR)));
  for(let i=0;i<P.length;i++){{ const L=M[i][1], vis=Math.max(0,Math.min(L,D-S[i]));
    if(vis<=0){{P[i].style.visibility='hidden';}} else {{P[i].style.visibility='visible'; P[i].style.strokeDashoffset=L-vis;}} }} }}
let t0=null,raf=null;
function frame(ts){{ if(t0===null)t0=ts; const t=(ts-t0)/1000; renderAt(t); if(t<DUR) raf=requestAnimationFrame(frame); }}
function play(){{ cancelAnimationFrame(raf); t0=null; renderAt(0); setTimeout(()=>raf=requestAnimationFrame(frame),350); }}
window.renderAt=renderAt;
if(!location.hash.includes('capture')) play(); else {{document.body.classList.add('capture'); renderAt(0);}}
</script></body></html>'''
if __name__=='__main__':
    for sub in ('svg','previews','anim'): os.makedirs(f'{D}/{sub}',exist_ok=True)
    shapes={}; meta={}
    for v in W.VARIANTS:
        G,vb=geometry(v); n=f'go-around-{v}'
        open(f'{D}/svg/{n}-stroke.svg','w').write(svg_stroke(G,vb,v))
        open(f'{D}/svg/{n}-outlined.svg','w').write(svg_outlined(G,vb,v))
        open(f'{D}/svg/{n}-outlined-white.svg','w').write(svg_outlined(G,vb,v,'#FFFFFF'))
        open(f'{D}/anim/{n}-draw.html','w').write(html(G,vb,v))
        p=filled(G); shapes[v]=(p,vb); meta[v]=vb
        draw(p,vb,2000,800,B.NAVY,B.WHITE).save(f'{D}/previews/{n}-navy.png',skia.kPNG)
        draw(p,vb,2000,800,B.WHITE,B.NAVY).save(f'{D}/previews/{n}-white.png',skia.kPNG)
    # compare sheet: 3 rows x (navy | white)
    Wc,Hc=1500,600; top=170
    surf=skia.Surface(2*Wc+8, top+3*(Hc+8)+70); cv=surf.getCanvas(); cv.clear(0xFFEEF1F5)
    tp=skia.Paint(AntiAlias=True,Color=B.NAVY)
    cv.drawString('Go Around — handwritten wordmark · 18 Nov 2026',60,80,skia.Font(skia.Typeface('DejaVu Sans'),46),tp)
    cv.drawString('Capital G and A are the approved v2-refined GA letters (verbatim). Lowercase is new, lighter monoline. No aircraft. Design only — do not merge.',60,135,skia.Font(skia.Typeface('DejaVu Sans'),24),skia.Paint(AntiAlias=True,Color=0xFF5A6A82))
    for row,v in enumerate(W.VARIANTS):
        p,vb=shapes[v]; y=top+row*(Hc+8)
        cv.drawImage(draw(p,vb,Wc,Hc,B.NAVY,B.WHITE,0.80,NAMES[v],0xFF9FB0C8),0,y)
        cv.drawImage(draw(p,vb,Wc,Hc,B.WHITE,B.NAVY,0.80,NAMES[v],0xFF6B7A90),Wc+8,y)
    surf.makeImageSnapshot().save(f'{D}/go-around-wordmark-compare.png',skia.kPNG)
    json.dump(meta,open(f'{D}/src/meta.json','w')); print(meta)
