"""Identité META — réinterprétation plate du logo SRR.

Conserve : les anneaux fendus, le mot META, le triangle du A, le noir et l'or.
Abandonne : biseaux, dégradés brossés, ombres, reflets, l'argent, le fond incrusté.

Deux faits repris de l'original et non inventés :
  · les fentes s'alignent sur un axe commun (≈ -15°), ce qui tient la grappe ensemble ;
  · l'échelonnement des tailles, resserré ici pour que le plus petit anneau survive à 32 px.
Le trait est d'épaisseur CONSTANTE sur les trois anneaux — dans l'original il suit la taille,
ce qui faisait disparaître les petits dès la réduction.
"""
import math
from PIL import Image, ImageDraw, ImageFont

FONT='/Users/saidzouhdi/Documents/COS/04-Implementation/cos/ops/META27-site/cfp/Sora.ttf'
SS=4
GOLD=(216,180,106); GOLD_D=(134,104,44); NAVY=(6,18,28); BLACK=(0,0,0)
WHITE=(255,255,255); CREAM=(247,246,241)

# (cx, cy, r) en fraction du côté ; fente en degrés
RINGS=[(0.335,0.585,0.300,-15),(0.700,0.360,0.195,-15),(0.790,0.690,0.120,165)]
STROKE=0.082          # constant, c'est ce qui sauve le petit anneau
GAP_DEG=52            # ouverture angulaire de la fente

def sora(px,w=400):
    f=ImageFont.truetype(FONT,max(4,int(px)))
    try: f.set_variation_by_axes([w])
    except Exception: pass
    return f

def ring(d,S,cx,cy,r,gap_deg,col,stroke=None):
    """Anneau fendu : arc unique dont l'ouverture est la fente."""
    st=max(1,int(round((stroke or STROKE)*S)))
    R=r*S; x,y=cx*S,cy*S
    a0=gap_deg+GAP_DEG/2; a1=gap_deg-GAP_DEG/2+360
    d.arc([x-R,y-R,x+R,y+R],a0,a1,fill=col,width=st)

def symbol(S,bg=None,col=GOLD,rings=None):
    im=Image.new('RGBA',(S,S),(0,0,0,0) if bg is None else bg+(255,))
    d=ImageDraw.Draw(im)
    for (cx,cy,r,g) in (rings or RINGS): ring(d,S,cx,cy,r,g,col+(255,))
    return im

def wordmark(H,col,tri=GOLD,text='META',weight=800):
    """META à plat, en unités de fonte pour que le A sur mesure s'aligne exactement.

    M, E et T viennent de Sora ; le A est construit géométriquement, parce que le
    contre-poinçon de Sora est un trapèze bas et large à toutes les graisses, alors que la
    signature META demande un triangle. Ratio obtenu 1,74 contre 0,39.
    """
    import customA
    from fontTools.ttLib import TTFont
    from fontTools.varLib.instancer import instantiateVariableFont
    global _TT
    try: _TT
    except NameError: _TT={}
    if weight not in _TT:
        t=TTFont(FONT)
        try: t=instantiateVariableFont(t,{'wght':weight},inplace=False,updateFontNames=False)
        except Exception: pass
        _TT[weight]=t
    tt=_TT[weight]; upm=tt['head'].unitsPerEm; gsx=tt.getGlyphSet(); cmap=tt.getBestCmap()
    cap=tt['OS/2'].sCapHeight if hasattr(tt['OS/2'],'sCapHeight') else 730
    k=H/upm
    advances=[]; total=0
    for ch in text:
        if ch=='A': total+=customA.W
        else: total+=gsx[cmap[ord(ch)]].width
        advances.append(total)
    pad=int(H*0.10)
    Wpx=int(total*k)+2*pad; Hpx=int(cap*k)+2*pad
    im=Image.new('RGBA',(Wpx,Hpx),(0,0,0,0)); d=ImageDraw.Draw(im)
    base=pad+cap*k                                  # ligne de base en pixels
    f=sora(H,weight)
    x=0.0
    for i,ch in enumerate(text):
        if ch=='A':
            o,g,c=customA.contours()
            def P(pts): return [(pad+(x+px)*k, base-py*k) for px,py in pts]
            d.polygon(P(o),fill=col+(255,))
            d.polygon(P(g),fill=(0,0,0,0))
            d.polygon(P(c),fill=tri+(255,))
            x+=customA.W
        else:
            gn=cmap[ord(ch)]
            d.text((pad+x*k, base), ch, font=f, fill=col+(255,), anchor='ls')
            x+=gsx[gn].width
    return im

def trim(im):
    b=im.getbbox(); return im.crop(b) if b else im

# ---- géométries retenues ---------------------------------------------------
GAP_DEG=18
STROKE=0.095
RINGS=[(0.33,0.62,0.265,145),(0.68,0.34,0.175,-15),(0.75,0.735,0.115,-15)]
RINGS_ICON=[(0.38,0.50,0.300,145),(0.775,0.755,0.155,-15)]   # favicon : 2 anneaux

def lockup(H, ring_col, text_col, tri_col, tagline=True, sig_col=None, bg=None):
    """Symbole + META (+ signature scientifique).

    Proportions : symbole 0,60 H, mot 0,52 H. Dans l'original la grappe pesait plus lourd que
    le mot et déséquilibrait la composition ; ici META mène et les anneaux accompagnent.
    La largeur est calculée sur le contenu, jamais fixée d'avance.
    """
    sym_f, word_f = (0.60, 0.52) if tagline else (0.60, 0.58)
    sym_s=int(H*sym_f)
    sym=symbol(sym_s*SS,col=ring_col).resize((sym_s,sym_s),Image.LANCZOS)
    wm=trim(wordmark(int(H*word_f),text_col,tri_col))
    tag='METAMATERIALS  ·  PHOTONIC CRYSTALS  ·  PLASMONICS'
    ft=sora(int(H*0.115),400)
    tw=ImageDraw.Draw(Image.new('L',(4,4))).textlength(tag,font=ft) if tagline else 0
    gap=int(H*0.17); pad=int(H*0.06)
    W=pad+sym_s+gap+int(max(wm.width,tw))+pad
    im=Image.new('RGBA',(W,H),(0,0,0,0) if bg is None else bg+(255,))
    im.alpha_composite(sym,(pad,(H-sym_s)//2)); x=pad+sym_s+gap
    if tagline:
        im.alpha_composite(wm,(x,int(H*0.24)))
        ImageDraw.Draw(im).text((x,int(H*0.645)),tag,font=ft,
                                fill=(sig_col or (150,168,180))+(255,))
    else:
        im.alpha_composite(wm,(x,(H-wm.height)//2))
    return im
