"""Bilingual circular patch studies using the approved vector emblem."""
from math import sin,cos,pi,sqrt
from graphics import *
from identity import reconstruct_mark,patch_mark,geometry,geometry_path,recolor

def arc_name(s,font,center=(375,375),radius=286,tracking=7,cap_height=52,small_height=38,rotation=0):
    text='STAND THE FIGHT';spec=[]
    for index,ch in enumerate(text):
        small=6<=index<=8
        cap=small_height if small else cap_height
        d,b,advance=font.glyph(ch)
        h=font.glyph('H')[1];scale=cap/(h[3]-h[1]);width=advance*scale
        spec.append((ch,d,b,scale,width))
    length=sum(v[4] for v in spec)+tracking*(len(spec)-1)
    offset=-length/2
    for ch,d,b,scale,width in spec:
        at=offset+width/2;theta=pi-at/radius+rotation
        x=center[0]+radius*cos(theta);y=center[1]+radius*sin(theta)
        tangent=theta-pi/2
        rot=(cos(tangent),sin(tangent),-sin(tangent),cos(tangent),x,y)
        if b:
            local=(scale,0,0,-scale,-(b[0]+b[2])/2*scale,(b[1]+b[3])/2*scale)
            s.path(d,INK,mul(rot,local),role='patch-english')
        offset+=width+tracking

def patch_japanese(s,font,style='arc'):
    chars=list('スタンド・ザ・ファイト');size=47
    for k,ch in enumerate(chars):
        y=150+450*k/(len(chars)-1)
        x=375+sqrt(286**2-(y-375)**2) if style=='arc' else 580
        d,b,_=font.glyph(ch);scale=size/font.upem
        if ch=='ァ':x+=4;y-=3
        local=(scale,0,0,-scale,x-(b[0]+b[2])/2*scale,y+(b[1]+b[3])/2*scale)
        s.path(d,INK,local,role='patch-japanese')

def bilingual_patch(f,mark,style='arc',english=None):
    s=Scene(750,750,title='Stand The Fight | Bilingual circular patch | '+style)
    s.circle(375,375,375,PAPER,role='fabric-ground')
    s.path('M375 9A366 366 0 1 1 374.999 9Z',None,stroke=INK,sw=18,role='merrow-border')
    open_mark=Scene(mark.w,mark.h)
    for item in mark.items:
        g=geometry(item['d'],item['m'])
        if item['role'] not in ['red-head','black-head']:g=g.buffer(-.7,join_style='round')
        open_mark.path(geometry_path(g),item['fill'],role=item['role'])
    s.add(open_mark,200,83,1.25)
    arc_name(s,f['display'],**(english or {}))
    jp=Typeface(ROOT/'fonts/notosansjp/NotoSansJP[wght].ttf',600)
    patch_japanese(s,jp,style)
    return s

def checks(s):
    labels=[geometry(i['d'],i['m']) for i in s.items if i['role'] in ['patch-english','patch-japanese']]
    figure=[geometry(i['d'],i['m']) for i in s.items if i['role'] in ['body','foreground-curve','foot','red-head','black-head']]
    min_clear=min(a.distance(b) for a in labels for b in figure)*.1
    border_r=357
    max_radius=0
    for g in labels:
        polys=[g] if g.geom_type=='Polygon' else list(g.geoms)
        for poly in polys:
            for x,y in poly.exterior.coords:max_radius=max(max_radius,sqrt((x-375)**2+(y-375)**2))
    figure_gap=min(a.distance(b) for k,a in enumerate(figure) for b in figure[:k])*.1
    return {'minimum_text_to_emblem_gap_mm_at_75mm':round(min_clear,3),'minimum_text_to_border_gap_mm_at_75mm':round((border_r-max_radius)*.1,3),'minimum_independent_figure_gap_mm_at_75mm':round(figure_gap,3)}

def main():
    out=ROOT/'patches/bilingual-studies';out.mkdir(exist_ok=True)
    f=fonts();mark=patch_mark(reconstruct_mark());report={}
    variants={}
    for name,style in [('M1','arc'),('M2','straight')]:
        s=bilingual_patch(f,mark,style);variants[name]=s;report[name]=checks(s)
        assert report[name]['minimum_text_to_emblem_gap_mm_at_75mm']>=1.0,report
        assert report[name]['minimum_text_to_border_gap_mm_at_75mm']>=1.0,report
        assert report[name]['minimum_independent_figure_gap_mm_at_75mm']>=1.0,report
        for mm in [75,90]:
            for kind in ['colour','black']:
                v=recolor(s,kind)
                v.export(out/f'stf-{name.lower()}-bilingual-patch-{mm}mm-{kind}',png_width=1500,physical=(mm/25.4*72,mm/25.4*72))
    proof=Scene(1700,1160,title='Stand The Fight | Bilingual emblem patch comparison')
    proof.rect(0,0,1700,1160,PAPER)
    f['medium'].text(proof,'STAND THE FIGHT / CIRCULAR PATCH REFINEMENT',62,45,16,tracking=.035)
    f['body'].text(proof,'75 MM + 90 MM ARTWORK',1638,45,13,align='right',fill=MUTED)
    proof.line(62,94,1638,94,RULE)
    for name,x,title,copy in [
        ('M1',60,'BOTH SIDES FOLLOW THE CIRCLE','English name on the left; upright Japanese characters trace the right-hand arc.'),
        ('M2',890,'ARC + VERTICAL COLUMN','Same English arc, with a straight Japanese column tucked inside the right edge.')]:
        f['display'].text(proof,name,x+18,140,48)
        proof.add(variants[name],x,218,.96)
        f['medium'].text(proof,title,x+18,990,15)
        f['body'].paragraph(proof,copy,x+18,1033,690,18,29)
    proof.export(out/'bilingual-patch-comparison',png_width=1700,transparent=False)
    (out/'spacing-review.json').write_text(json.dumps(report,indent=2)+'\n')
    print(json.dumps(report,indent=2))

if __name__=='__main__':main()
