"""Generates the Solomon Rise & Care logo set.

Run: python3 make_logo.py <fonts_dir> <out_dir>
Outputs outlined SVGs (text converted to shapes so they look identical everywhere)
plus an editable master SVG that keeps live text.
"""
import math, sys, os
from fontTools.ttLib import TTFont
from fontTools.pens.svgPathPen import SVGPathPen
from fontTools.pens.transformPen import TransformPen

FONTS, OUT = sys.argv[1], sys.argv[2]
os.makedirs(OUT, exist_ok=True)

# ---- brand colours ----
YELLOW = '#F2B21C'   # Sea hibiscus yellow (petals)
HEART = '#8A1C2B'    # Hibiscus heart crimson (flower centre, "RISE & CARE")
LAGOON = '#0B4F6C'   # Lagoon blue ("Solomon")

# ---- flower geometry (viewBox -50 -50 100 100) ----
def catmull(points):
    """Closed Catmull-Rom spline -> SVG cubic path."""
    n = len(points); d = f'M{points[0][0]:.2f},{points[0][1]:.2f}'
    for i in range(n):
        p0, p1, p2, p3 = points[i-1], points[i], points[(i+1) % n], points[(i+2) % n]
        c1 = (p1[0] + (p2[0]-p0[0])/6, p1[1] + (p2[1]-p0[1])/6)
        c2 = (p2[0] - (p3[0]-p1[0])/6, p2[1] - (p3[1]-p1[1])/6)
        d += f'C{c1[0]:.2f},{c1[1]:.2f} {c2[0]:.2f},{c2[1]:.2f} {p2[0]:.2f},{p2[1]:.2f}'
    return d + 'Z'

def polar(axis, off, r, swirl=0.0):
    a = math.radians(axis + off + swirl * (r / 49))
    return (r * math.cos(a), r * math.sin(a))

# (angle offset from petal axis, radius). Petals span about +-33 deg, leaving small gaps
# so the five petals stay distinct in one-colour print and at 16 px.
PETAL = [(0, 12), (-26, 14), (-31.5, 23), (-33, 33), (-31, 42), (-18, 48.5), (-3, 50.5), (13, 49.5), (26, 44), (33, 33), (31.5, 23), (26, 14)]

def petals(shape, swirl=10):
    return ''.join(catmull([polar(k*72-90, o, r, swirl) for o, r in shape]) for k in range(5))

PETALS = petals(PETAL)

def flower(color=True, mono=None):
    if color:
        # crimson "eye" = the petals clipped to a circle, the dark centre a sea hibiscus has
        cid = 'eye' + str(abs(hash(PETALS)) % 9999)
        return (f'<defs><clipPath id="{cid}"><path d="{PETALS}"/></clipPath></defs>'
                f'<path d="{PETALS}" fill="{YELLOW}"/>'
                f'<circle r="22" fill="{HEART}" clip-path="url(#{cid})"/>'
                f'<circle r="6.5" fill="{HEART}"/><circle r="3" fill="{YELLOW}"/>')
    return f'<path d="{PETALS}" fill="{mono}"/><circle r="7" fill="{mono}"/>'

# ---- text to outlines ----
def text_path(font_file, text, size, x, y, tracking=0):
    f = TTFont(font_file); gs = f.getGlyphSet(); cmap = f.getBestCmap(); upm = f['head'].unitsPerEm
    s = size / upm; out = []; cx = x
    kern = {}
    for ch in text:
        g = cmap.get(ord(ch))
        if g is None:
            continue
        pen = SVGPathPen(gs)
        gs[g].draw(TransformPen(pen, (s, 0, 0, -s, cx, y)))
        out.append(pen.getCommands())
        cx += gs[g].width * s + tracking
    return ' '.join(out), cx - x - tracking

LORA = f'{FONTS}/lora-latin-700-normal.woff2'
SANS = f'{FONTS}/source-sans-3-latin-700-normal.woff2'

# ---- full logo: flower + two-line wordmark ----
def full(variant):
    col = variant == 'color'
    mono = {'black': '#000000', 'white': '#FFFFFF'}.get(variant)
    w1, wid1 = text_path(LORA, 'Solomon', 64, 124, 72)
    w2, wid2 = text_path(SANS, 'RISE & CARE', 24.5, 127, 108, tracking=4.2)
    W = 124 + max(wid1, wid2) + 6
    return f'''<svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 {W:.0f} 124" width="{W:.0f}" height="124">
<title>Solomon Rise &amp; Care</title>
<g transform="translate(56 62) scale(1.12)">{flower(col, mono)}</g>
<path d="{w1}" fill="{LAGOON if col else mono}"/>
<path d="{w2}" fill="{HEART if col else mono}"/>
</svg>
''', W

def icon(variant):
    col = variant == 'color'
    mono = {'black': '#000000', 'white': '#FFFFFF'}.get(variant)
    return f'''<svg xmlns="http://www.w3.org/2000/svg" viewBox="-52 -52 104 104" width="512" height="512">
<title>Solomon Rise &amp; Care</title>
{flower(col, mono)}
</svg>
'''

def app_icon():
    # Rounded-square app / favicon tile: colour flower on lagoon blue
    return f'''<svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 128 128" width="512" height="512">
<title>Solomon Rise &amp; Care</title>
<rect width="128" height="128" rx="28" fill="{LAGOON}"/>
<g transform="translate(64 64) scale(1.08)">{flower(True)}</g>
</svg>
'''

if __name__ == '__main__':
    sizes = {}
    for v in ('color', 'black', 'white'):
        svg, W = full(v)
        open(f'{OUT}/srca-logo-full-{v}.svg', 'w').write(svg); sizes['full'] = W
        open(f'{OUT}/srca-icon-{v}.svg', 'w').write(icon(v))
    open(f'{OUT}/srca-app-icon.svg', 'w').write(app_icon())
    # Editable master: live text, fonts named (install Lora + Source Sans 3 from Google Fonts to edit)
    open(f'{OUT}/srca-logo-full-EDITABLE.svg', 'w').write(f'''<svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 {sizes['full']:.0f} 124" width="{sizes['full']:.0f}" height="124">
<!-- EDITABLE MASTER. Text is live: needs the free fonts Lora (Bold) and Source Sans 3 (Bold) installed.
     Use the outlined files for everything else. Flower is in group "flower". -->
<g id="flower" transform="translate(56 62) scale(1.12)">{flower(True)}</g>
<text id="wordmark-solomon" x="124" y="72" font-family="Lora" font-weight="700" font-size="64" fill="{LAGOON}">Solomon</text>
<text id="wordmark-rise-care" x="127" y="108" font-family="Source Sans 3" font-weight="700" font-size="24.5" letter-spacing="4.2" fill="{HEART}">RISE &amp; CARE</text>
</svg>
''')
    print('full logo width', round(sizes['full']))
