#!/usr/bin/env python3
"""Pastel mascot badge collection — single source of truth.

Every badge is built from the same frame (sticker rim, pastel disc, shine,
sparkle) plus a mascot bust. Shared rules live in the constants below;
only the artwork and the colour assignment differ per badge.

Usage:  python3 badges/tools/build.py        (needs rsvg-convert + fontTools)
"""
import math
import os
import subprocess
from pathlib import Path

from fontTools.pens.svgPathPen import SVGPathPen
from fontTools.pens.transformPen import TransformPen
from fontTools.ttLib import TTFont
from fontTools.varLib.instancer import instantiateVariableFont

ROOT = Path(__file__).resolve().parent.parent
FONT = ROOT / "tools" / "fonts" / "Nunito.ttf"

# ---------------------------------------------------------------- tokens
INK = "#45405E"        # soft plum-navy outline; replaces the originals' black ink
CREAM = "#FFFBF5"      # sticker rim, light fills
WHITE = "#FFFFFF"
BLUSH = "#FF9FB5"
SW = 7                 # the one outline weight used for all artwork (256 grid)

# Pastel disc tints: each one is used by exactly two badges.
BG = {
    "blue":     "#D5E5FF",
    "butter":   "#FFF0C2",
    "lavender": "#E5DEFF",
    "mint":     "#D2F1E1",
    "peach":    "#FFE0CC",
    "pink":     "#FFDDE8",
}

# Frame geometry (viewBox 0 0 256 256)
CX, CY = 128, 125      # medallion centre
R_RIM = 120            # outer cream rim
R_DISC = 107           # pastel disc
SHADOW_DY = 6

def o(w=SW):
    return f'stroke="{INK}" stroke-width="{w}" stroke-linejoin="round" stroke-linecap="round"'


O = o()


# ---------------------------------------------------------------- primitives
def eye(x, y, r=7.5):
    return (f'<circle cx="{x}" cy="{y}" r="{r}" fill="{INK}"/>'
            f'<circle cx="{x - r * .3:.1f}" cy="{y - r * .35:.1f}" r="{r * .33:.1f}" fill="{WHITE}"/>')


def big_eye(x, y, r=21, px=0, py=0, pr=8.5):
    """Round white eye with an inked pupil (gopher / crab style)."""
    return (f'<circle cx="{x}" cy="{y}" r="{r}" fill="{WHITE}" {O}/>' + eye(x + px, y + py, pr))


def sleepy_eye(x, y, r=8):
    """Half-lidded eye: the GNU's signature contented look."""
    return (f'<circle cx="{x}" cy="{y}" r="{r}" fill="{INK}"/>'
            f'<path d="M{x - r - 3} {y - 1} Q{x} {y - r - 6} {x + r + 3} {y - 1} Z" fill="#E7CFB4"/>'
            f'<path d="M{x - r - 3} {y - 1} Q{x} {y - 3} {x + r + 3} {y - 1}" fill="none" {o(5)}/>'
            f'<circle cx="{x - 2.5}" cy="{y + 2.5}" r="2.4" fill="{WHITE}"/>')


def blush(x, y, rx=9.5, ry=5.5):
    return f'<ellipse cx="{x}" cy="{y}" rx="{rx}" ry="{ry}" fill="{BLUSH}" opacity=".6"/>'


def smile(x, y, w=12, d=6, sw=5):
    return (f'<path d="M{x - w / 2} {y} Q{x} {y + d} {x + w / 2} {y}" fill="none" '
            f'stroke="{INK}" stroke-width="{sw}" stroke-linecap="round"/>')


def tube(d, w, fill):
    """Thick stroked path with an outline of the shared weight."""
    return (f'<path d="{d}" fill="none" stroke="{INK}" stroke-width="{w + SW}" '
            f'stroke-linecap="round" stroke-linejoin="round"/>'
            f'<path d="{d}" fill="none" stroke="{fill}" stroke-width="{w - SW}" '
            f'stroke-linecap="round" stroke-linejoin="round"/>')


def sparkle(x, y, s=11):
    return (f'<path d="M{x} {y - s} Q{x} {y} {x + s} {y} Q{x} {y} {x} {y + s} '
            f'Q{x} {y} {x - s} {y} Q{x} {y} {x} {y - s} Z" fill="{WHITE}"/>'
            f'<circle cx="{x + s * .9:.1f}" cy="{y + s * 1.25:.1f}" r="2.6" fill="{WHITE}"/>')


def bezier(p, t):
    """Point and tangent of a cubic Bezier at t."""
    (x0, y0), (x1, y1), (x2, y2), (x3, y3) = p
    m = 1 - t
    pt = (m**3 * x0 + 3 * m * m * t * x1 + 3 * m * t * t * x2 + t**3 * x3,
          m**3 * y0 + 3 * m * m * t * y1 + 3 * m * t * t * y2 + t**3 * y3)
    d = (3 * m * m * (x1 - x0) + 6 * m * t * (x2 - x1) + 3 * t * t * (x3 - x2),
         3 * m * m * (y1 - y0) + 6 * m * t * (y2 - y1) + 3 * t * t * (y3 - y2))
    return pt, d


def polar(r, deg, cx=128, cy=128):
    a = math.radians(deg)
    return cx + r * math.cos(a), cy + r * math.sin(a)


# ---------------------------------------------------------------- mascots
def art_captain():
    c = (128, 128)
    angles = [-90 + 360 / 7 * i + 360 / 14 for i in range(7)]
    spokes = " ".join(
        "M{:.1f} {:.1f} L{:.1f} {:.1f}".format(*c, *polar(74, a, *c)) for a in angles)
    knobs = [polar(78, a, *c) for a in angles]
    ink, fill = [], []
    ink.append(f'<path d="{spokes}" stroke="{INK}" stroke-width="{15 + SW}" stroke-linecap="round"/>')
    fill.append(f'<path d="{spokes}" stroke="{CREAM}" stroke-width="{15 - SW}" stroke-linecap="round"/>')
    for x, y in knobs:
        ink.append(f'<circle cx="{x:.1f}" cy="{y:.1f}" r="{12 + SW / 2}" fill="{INK}"/>')
        fill.append(f'<circle cx="{x:.1f}" cy="{y:.1f}" r="{12 - SW / 2}" fill="{CREAM}"/>')
    ink.append(f'<circle cx="128" cy="128" r="52" fill="none" stroke="{INK}" stroke-width="{19 + SW}"/>')
    fill.append(f'<circle cx="128" cy="128" r="52" fill="none" stroke="{CREAM}" stroke-width="{19 - SW}"/>')
    # hub: rounded heptagon face (nod to the original's heptagon)
    hept = " ".join("{:.1f},{:.1f}".format(*polar(34, -90 + 360 / 7 * i, *c)) for i in range(7))
    hub = (f'<polygon points="{hept}" fill="{CREAM}" stroke="{INK}" stroke-width="{SW}" '
           f'stroke-linejoin="round"/>'
           + eye(116, 125, 6) + eye(140, 125, 6) + blush(108, 138, 6.5, 4) + blush(148, 138, 6.5, 4)
           + smile(128, 137, 10, 4, 4))
    return "".join(ink) + "".join(fill) + hub


def art_gopher():
    body = "#BFE5F2"
    return (
        f'<circle cx="78" cy="78" r="15" fill="{body}" {O}/>'
        f'<circle cx="178" cy="78" r="15" fill="{body}" {O}/>'
        f'<ellipse cx="128" cy="158" rx="70" ry="98" fill="{body}" {O}/>'
        + big_eye(102, 112, 22, 4, -2) + big_eye(154, 112, 22, -4, -2)
        + f'<ellipse cx="128" cy="146" rx="19" ry="13" fill="#F5E6D6" {O}/>'
        f'<ellipse cx="128" cy="139" rx="9" ry="6" fill="{INK}"/>'
        f'<path d="M120 156 L120 170 Q120 173 123 173 L133 173 Q136 173 136 170 L136 156" fill="{WHITE}" {o(5)}/>'
        f'<path d="M128 158 L128 172" stroke="{INK}" stroke-width="3.5" stroke-linecap="round"/>'
        + blush(84, 146) + blush(172, 146)
    )


def art_foxy():
    fur, light, inner = "#FFB98C", "#FFF4E8", "#F7A1B8"
    ears = (
        f'<path d="M66 116 L72 46 L122 86 Z" fill="{fur}" {O}/>'
        f'<path d="M190 116 L184 46 L134 86 Z" fill="{fur}" {O}/>'
        f'<path d="M80 96 L83 66 L104 84 Z" fill="{inner}"/>'
        f'<path d="M176 96 L173 66 L152 84 Z" fill="{inner}"/>'
    )
    chest = (f'<ellipse cx="128" cy="232" rx="58" ry="46" fill="{fur}" {O}/>'
             f'<path d="M98 196 Q128 236 158 196 Q150 240 128 244 Q106 240 98 196 Z" fill="{light}"/>')
    head = (
        f'<path d="M60 134 Q58 92 96 86 Q128 80 160 86 Q198 92 196 134 Q194 186 128 192 Q62 186 60 134 Z" fill="{fur}" {O}/>'
        f'<path d="M63 138 Q100 132 128 166 Q156 132 193 138 Q184 186 128 189 Q72 186 63 138 Z" fill="{light}"/>'
        f'<path d="M60 134 Q58 92 96 86 Q128 80 160 86 Q198 92 196 134 Q194 186 128 192 Q62 186 60 134 Z" fill="none" {O}/>'
    )
    face = (eye(102, 128) + eye(154, 128)
            + f'<path d="M120 160 Q128 156 136 160 Q132 168 128 169 Q124 168 120 160 Z" fill="{INK}" {o(3)}/>'
            + smile(121, 173, 12, 5, 4) + smile(135, 173, 12, 5, 4)
            + blush(86, 154) + blush(170, 154))
    return chest + ears + head + face


def art_larry():
    hide, pink, horn = "#FFFDF8", "#FFC4D1", "#FFDB7A"
    return (
        f'<path d="M100 72 Q86 52 94 32 Q108 48 116 66 Z" fill="{horn}" {O}/>'
        f'<path d="M156 72 Q170 52 162 32 Q148 48 140 66 Z" fill="{horn}" {O}/>'
        f'<rect x="90" y="168" width="76" height="90" rx="26" fill="{hide}" {O}/>'
        f'<ellipse cx="62" cy="104" rx="28" ry="14" transform="rotate(-18 62 104)" fill="{hide}" {O}/>'
        f'<ellipse cx="65" cy="104" rx="16" ry="6.5" transform="rotate(-18 65 104)" fill="{pink}"/>'
        f'<ellipse cx="194" cy="104" rx="28" ry="14" transform="rotate(18 194 104)" fill="{hide}" {O}/>'
        f'<ellipse cx="191" cy="104" rx="16" ry="6.5" transform="rotate(18 191 104)" fill="{pink}"/>'
        f'<path d="M82 78 Q128 58 174 78 Q182 128 172 162 L84 162 Q74 128 82 78 Z" fill="{hide}" {O}/>'
        f'<path d="M150 74 Q166 72 172 82 Q176 100 164 104 Q150 102 150 74 Z" fill="#E7DCCB"/>'
        + eye(108, 118) + eye(148, 118)
        + f'<ellipse cx="128" cy="166" rx="48" ry="30" fill="{pink}" {O}/>'
        f'<ellipse cx="112" cy="162" rx="5" ry="7" fill="{INK}"/>'
        f'<ellipse cx="144" cy="162" rx="5" ry="7" fill="{INK}"/>'
        + smile(128, 180, 16, 5, 4)
        + blush(88, 136) + blush(168, 136)
    )


def art_gnu():
    fur, mane, muzzle, horn = "#E7CFB4", "#C9A88C", "#F5E6D4", CREAM
    left = [(112, 98), (80, 106), (56, 90), (74, 62)]
    horns = (tube("M{} {} C{} {} {} {} {} {}".format(*sum(left, ())), 24, horn)
             + tube("M{} {} C{} {} {} {} {} {}".format(*sum([(256 - x, y) for x, y in left], ())), 24, horn))
    ridges = ""
    for t in (0.45, 0.68, 0.88):
        (x, y), (dx, dy) = bezier(left, t)
        n = math.hypot(dx, dy)
        nx, ny = -dy / n * 7, dx / n * 7
        for sx in (1, -1):
            cx = x if sx == 1 else 256 - x
            ridges += (f'<path d="M{cx + sx * nx:.1f} {y + ny:.1f} L{cx - sx * nx:.1f} {y - ny:.1f}" '
                       f'stroke="{INK}" stroke-width="3.5" stroke-linecap="round"/>')
    ears = (f'<ellipse cx="84" cy="122" rx="20" ry="10" transform="rotate(20 84 122)" fill="{fur}" {O}/>'
            f'<ellipse cx="172" cy="122" rx="20" ry="10" transform="rotate(-20 172 122)" fill="{fur}" {O}/>')
    beard = f'<path d="M108 184 Q128 236 148 184 Z" fill="{mane}" {O}/>'
    head = (f'<path d="M96 100 Q128 82 160 100 Q170 146 154 182 Q128 200 102 182 Q86 146 96 100 Z" fill="{fur}" {O}/>'
            f'<ellipse cx="128" cy="172" rx="30" ry="20" fill="{muzzle}" {O}/>'
            f'<ellipse cx="117" cy="170" rx="3.5" ry="5" fill="{INK}"/>'
            f'<ellipse cx="139" cy="170" rx="3.5" ry="5" fill="{INK}"/>'
            + smile(128, 182, 12, 4, 4)
            + f'<path d="M112 98 Q118 78 130 84 Q144 76 146 96 Q128 106 112 98 Z" fill="{mane}" {O}/>')
    face = sleepy_eye(112, 132) + sleepy_eye(144, 132) + blush(104, 150, 8, 4.5) + blush(152, 150, 8, 4.5)
    return ('<g transform="translate(128 140) scale(1.06) translate(-128 -140)">'
            + horns + ridges + ears + beard + head + face + "</g>")


def art_bunny():
    fur, inner, helm, helm_d, trim = "#FFF6F9", "#FFC2D3", "#B4D0F8", "#93B6EC", "#FFE08A"
    ears = (
        f'<ellipse cx="86" cy="54" rx="15" ry="36" transform="rotate(-26 86 54)" fill="{fur}" {O}/>'
        f'<ellipse cx="87" cy="56" rx="6.5" ry="24" transform="rotate(-26 87 56)" fill="{inner}"/>'
        f'<ellipse cx="124" cy="40" rx="15" ry="36" transform="rotate(-8 124 40)" fill="{fur}" {O}/>'
        f'<ellipse cx="124" cy="43" rx="6.5" ry="24" transform="rotate(-8 124 43)" fill="{inner}"/>'
    )
    return (
        f'<rect x="56" y="196" width="144" height="60" rx="18" fill="{fur}" {O}/>'
        + ears
        + f'<circle cx="132" cy="134" r="76" fill="{helm}" {O}/>'
        f'<ellipse cx="96" cy="78" rx="18" ry="8" transform="rotate(-26 96 78)" fill="{helm_d}" {o(5)}/>'
        f'<ellipse cx="128" cy="68" rx="18" ry="8" transform="rotate(-8 128 68)" fill="{helm_d}" {o(5)}/>'
        f'<circle cx="206" cy="128" r="9" fill="{helm_d}" {o(5)}/>'
        f'<path d="M70 196 Q132 222 194 196 L194 214 Q132 238 70 214 Z" fill="{helm_d}" {O}/>'
        f'<ellipse cx="138" cy="146" rx="56" ry="50" fill="{trim}" {O}/>'
        f'<ellipse cx="138" cy="146" rx="47" ry="41" fill="{fur}" {o(4)}/>'
        f'<path d="M160 116 Q176 124 178 142" fill="none" stroke="{WHITE}" stroke-width="5" stroke-linecap="round"/>'
        + eye(118, 140) + eye(158, 140)
        + f'<ellipse cx="138" cy="155" rx="7" ry="5" fill="{inner}" {o(3.5)}/>'
        f'<path d="M132 162 L132 172 Q132 174 134 174 L142 174 Q144 174 144 172 L144 162" fill="{WHITE}" {o(3.5)}/>'
        f'<path d="M138 163 L138 173" stroke="{INK}" stroke-width="2.5"/>'
        + blush(108, 158) + blush(168, 158)
    )


def art_tux():
    body, light, beak = "#8983B8", "#FFFBF5", "#FFD27A"
    return (
        f'<ellipse cx="62" cy="200" rx="18" ry="40" transform="rotate(18 62 200)" fill="{body}" {O}/>'
        f'<ellipse cx="194" cy="200" rx="18" ry="40" transform="rotate(-18 194 200)" fill="{body}" {O}/>'
        f'<ellipse cx="128" cy="160" rx="72" ry="104" fill="{body}" {O}/>'
        f'<ellipse cx="128" cy="232" rx="50" ry="48" fill="{light}"/>'
        f'<path d="M128 102 C112 80 74 88 76 124 C78 156 106 166 128 164 C150 166 178 156 180 124 C182 88 144 80 128 102 Z" fill="{light}"/>'
        + eye(106, 120) + eye(150, 120)
        + f'<path d="M110 138 Q128 128 146 138 Q128 158 110 138 Z" fill="{beak}" {o(5)}/>'
        + blush(92, 144) + blush(164, 144)
    )


def art_ferris():
    shell, dark = "#FFAE98", "#F59A83"
    legs = "".join(
        f'<path d="M{x} 176 L{x + dx} 206" stroke="{INK}" stroke-width="{10 + SW}" stroke-linecap="round"/>'
        f'<path d="M{x} 176 L{x + dx} 206" stroke="{shell}" stroke-width="{10 - SW}" stroke-linecap="round"/>'
        for x, dx in [(82, -18), (100, -12), (156, 12), (174, 18)])
    claw = lambda cx, cy, flip: (
        f'<g transform="translate({cx} {cy}) scale({flip} 1)">'
        f'<path d="M0 0 L5 -21 A21 21 0 1 0 19 -9 Z" fill="{shell}" {O}/></g>')
    arms = tube("M70 150 Q52 136 54 108", 12, shell) + tube("M186 150 Q204 136 202 108", 12, shell)
    return (
        legs + arms + claw(54, 98, 1) + claw(202, 98, -1)
        + tube("M112 140 L106 104", 9, shell) + tube("M144 140 L150 104", 9, shell)
        + f'<path d="M50 160 Q52 118 128 116 Q204 118 206 160 Q204 190 128 192 Q52 190 50 160 Z" fill="{shell}" {O}/>'
        f'<path d="M66 132 Q128 112 190 132" fill="none" stroke="{dark}" stroke-width="5" stroke-linecap="round"/>'
        + big_eye(104, 96, 14, 1, 1, 6.5) + big_eye(152, 96, 14, -1, 1, 6.5)
        + smile(128, 156, 22, 9)
        + blush(94, 158) + blush(162, 158)
    )


def art_moby():
    body, belly = "#A9CDF4", "#E9F2FF"
    crates = [("#FFC7A8", 100, 76), ("#B6E6CC", 124, 76), ("#FFC2D3", 112, 56)]
    boxes = "".join(
        f'<rect x="{x}" y="{y}" width="22" height="18" rx="4" fill="{c}" {o(5)}/>'
        f'<path d="M{x + 7} {y + 5} L{x + 7} {y + 13} M{x + 15} {y + 5} L{x + 15} {y + 13}" stroke="{INK}" stroke-width="2.5" stroke-linecap="round" opacity=".55"/>'
        for c, x, y in crates)
    return (
        boxes
        + f'<path d="M58 150 Q40 132 30 104 Q48 108 58 118 Q60 98 74 86 Q76 112 78 134 Z" fill="{body}" {O}/>'
        f'<path d="M60 150 Q60 98 124 96 Q206 94 214 152 Q216 196 144 200 Q74 202 60 150 Z" fill="{body}" {O}/>'
        f'<path d="M80 178 Q132 196 208 168 Q196 198 144 200 Q96 200 80 178 Z" fill="{belly}"/>'
        f'<path d="M60 150 Q60 98 124 96 Q206 94 214 152 Q216 196 144 200 Q74 202 60 150 Z" fill="none" {O}/>'
        + eye(166, 142) + smile(186, 158, 14, 6) + blush(160, 162)
        + f'<path d="M110 168 Q118 182 130 178" fill="none" {o(5)}/>'
    )


def art_slonik():
    skin, ear, inner = "#BAC7E6", "#C9D4EE", "#FFC2D3"
    return (
        f'<ellipse cx="66" cy="120" rx="36" ry="46" fill="{ear}" {O}/>'
        f'<ellipse cx="72" cy="122" rx="20" ry="30" fill="{inner}"/>'
        f'<ellipse cx="190" cy="120" rx="36" ry="46" fill="{ear}" {O}/>'
        f'<ellipse cx="184" cy="122" rx="20" ry="30" fill="{inner}"/>'
        f'<rect x="78" y="168" width="100" height="90" rx="30" fill="{skin}" {O}/>'
        f'<circle cx="128" cy="118" r="56" fill="{skin}" {O}/>'
        + tube("M128 140 Q124 192 152 198 Q170 198 166 180", 24, skin)
        + f'<path d="M118 160 Q120 172 128 176" fill="none" stroke="{INK}" stroke-width="3" stroke-linecap="round" opacity=".5"/>'
        + eye(108, 112) + eye(148, 112)
        + blush(94, 134) + blush(162, 134)
    )


def art_puffy():
    body, spike, fin = "#FFE08A", "#F5C46A", "#FFC9A6"
    spikes = []
    for i in range(12):
        a = -90 + i * 30
        if 140 < a % 360 < 220:
            continue
        tip = polar(74, a, 136, 132)
        l = polar(56, a - 10, 136, 132)
        r = polar(56, a + 10, 136, 132)
        spikes.append(f'<path d="M{l[0]:.1f} {l[1]:.1f} L{tip[0]:.1f} {tip[1]:.1f} L{r[0]:.1f} {r[1]:.1f} Z" fill="{spike}" {o(5)}/>')
    return (
        f'<path d="M80 132 Q56 104 36 102 Q46 132 36 162 Q56 160 80 132 Z" fill="{fin}" {O}/>'
        f'<path d="M50 122 L62 130 M50 142 L62 134" stroke="{INK}" stroke-width="3" stroke-linecap="round" opacity=".45"/>'
        + "".join(spikes)
        + f'<circle cx="136" cy="132" r="60" fill="{body}" {O}/>'
        f'<path d="M88 160 Q136 196 184 160 Q176 188 136 192 Q96 188 88 160 Z" fill="#FFF3CC"/>'
        f'<circle cx="136" cy="132" r="60" fill="none" {O}/>'
        f'<path d="M106 150 Q92 150 90 166 Q104 166 106 150 Z" fill="{fin}" {o(5)}/>'
        + eye(126, 122, 8.5) + eye(164, 122, 8.5)
        + f'<ellipse cx="146" cy="146" rx="5.5" ry="6.5" fill="{INK}"/>'
        + blush(114, 142) + blush(178, 140)
    )


def art_konqi():
    scale, light, horn, crest = "#A9DFC0", "#DDF5E6", "#FFDB7A", "#7FCBA2"
    return (
        f'<path d="M108 74 L116 50 L126 70 L136 46 L146 70 L156 54 L160 78 Z" fill="{crest}" {o(5)}/>'
        f'<path d="M84 86 Q70 62 78 42 Q94 56 102 76 Z" fill="{horn}" {O}/>'
        f'<path d="M172 86 Q186 62 178 42 Q162 56 154 76 Z" fill="{horn}" {O}/>'
        f'<rect x="82" y="176" width="92" height="84" rx="30" fill="{scale}" {O}/>'
        f'<ellipse cx="128" cy="236" rx="30" ry="40" fill="{light}"/>'
        f'<path d="M110 206 L146 206 M112 222 L144 222" stroke="{INK}" stroke-width="3" stroke-linecap="round" opacity=".35"/>'
        f'<ellipse cx="128" cy="126" rx="66" ry="58" fill="{scale}" {O}/>'
        f'<ellipse cx="128" cy="154" rx="44" ry="26" fill="{light}" {O}/>'
        f'<ellipse cx="114" cy="148" rx="4" ry="5" fill="{INK}"/>'
        f'<ellipse cx="142" cy="148" rx="4" ry="5" fill="{INK}"/>'
        + smile(128, 164, 22, 7)
        + f'<path d="M120 166 L124 174 L128 167 Z" fill="{WHITE}" {o(2.5)}/>'
        + eye(100, 114) + eye(156, 114)
        + blush(84, 134) + blush(172, 134)
    )


# ---------------------------------------------------------------- catalogue
# id, slug, description, disc tint, artwork, sparkle position
BADGES = [
    (1,  "Captain", "Guardian of Cluster Stability", "blue",     art_captain, (206, 60)),
    (2,  "Gopher",  "Master of Concurrency",         "butter",   art_gopher,  (206, 132)),
    (3,  "Foxy",    "Red Fox Patron",                "lavender", art_foxy,    (128, 50)),
    (4,  "Larry",   "Compiles Everything From Source", "mint",   art_larry,   (206, 158)),
    (5,  "GNU",     "Champion of Software Freedom",  "peach",    art_gnu,     (128, 52)),
    (6,  "Bunny",   "Hops Between Planets",          "pink",     art_bunny,   (196, 62)),
    (7,  "Tux",     "Kernel Keeper",                 "lavender", art_tux,     (198, 62)),
    (8,  "Ferris",  "Fearless Borrow Checker",       "mint",     art_ferris,  (128, 52)),
    (9,  "Moby",    "Ships It in Containers",        "butter",   art_moby,    (186, 62)),
    (10, "Slonik",  "Never Forgets a Query",         "pink",     art_slonik,  (198, 54)),
    (11, "Puffy",   "Secure by Default",             "blue",     art_puffy,   (200, 56)),
    (12, "Konqi",   "Desktop Dragon Tamer",          "peach",    art_konqi,   (204, 72)),
]


def emblem(slug, tint, art, spark, standalone=True):
    cid = f"disc-{slug.lower()}"
    shine_a, shine_b = polar(R_DISC - 13, 200, CX, CY), polar(R_DISC - 13, 238, CX, CY)
    body = (
        f'<circle cx="{CX}" cy="{CY + SHADOW_DY}" r="{R_RIM + SW / 2}" fill="{INK}" opacity=".16"/>'
        f'<circle cx="{CX}" cy="{CY}" r="{R_RIM}" fill="{CREAM}" stroke="{INK}" stroke-width="{SW}"/>'
        f'<circle cx="{CX}" cy="{CY}" r="{R_DISC}" fill="{BG[tint]}"/>'
        f'<path d="M{shine_a[0]:.1f} {shine_a[1]:.1f} A{R_DISC - 13} {R_DISC - 13} 0 0 1 {shine_b[0]:.1f} {shine_b[1]:.1f}" '
        f'fill="none" stroke="{WHITE}" stroke-width="7" stroke-linecap="round" opacity=".85"/>'
        + sparkle(*spark)
        + f'<g clip-path="url(#{cid})"><g transform="translate(0 -3)">{art()}</g></g>'
        f'<circle cx="{CX}" cy="{CY}" r="{R_DISC}" fill="none" stroke="{INK}" stroke-width="4"/>'
    )
    defs = f'<defs><clipPath id="{cid}"><circle cx="{CX}" cy="{CY}" r="{R_DISC}"/></clipPath></defs>'
    if not standalone:
        return defs + body
    return (f'<svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 256 256" width="256" height="256" '
            f'role="img" aria-label="{slug} badge"><title>{slug}</title>{defs}{body}</svg>\n')


# ---------------------------------------------------------------- typography
class Type:
    """Outlines Nunito text to paths so tags render identically everywhere."""

    def __init__(self, weight):
        f = TTFont(FONT)
        self.font = instantiateVariableFont(f, {"wght": weight})
        self.gs = self.font.getGlyphSet()
        self.cmap = self.font.getBestCmap()
        self.upm = self.font["head"].unitsPerEm

    def width(self, text, size):
        return sum(self.gs[self.cmap[ord(ch)]].width for ch in text) * size / self.upm

    def path(self, text, size, x, y):
        s = size / self.upm
        pen = SVGPathPen(self.gs)
        cursor = 0
        for ch in text:
            g = self.cmap[ord(ch)]
            self.gs[g].draw(TransformPen(pen, (s, 0, 0, -s, x + cursor * s, y)))
            cursor += self.gs[g].width
        return pen.getCommands()


def tag(slug, desc, tint, art, spark, t_bold, t_med):
    """Horizontal name tag: emblem + slug + description, height 80."""
    h, emb = 80, 80
    name_size, desc_size = 25, 13
    tx = emb + 10
    w = math.ceil(max(t_bold.width(slug, name_size), t_med.width(desc, desc_size)) + tx + 24)
    scale = emb / 256
    return (
        f'<svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 {w} {h}" width="{w}" height="{h}" '
        f'role="img" aria-label="{slug}: {desc}"><title>{slug} — {desc}</title>'
        f'<rect x="{emb / 2}" y="{14 + 3}" width="{w - emb / 2 - 3}" height="{h - 28}" rx="{(h - 28) / 2}" fill="{INK}" opacity=".16"/>'
        f'<rect x="{emb / 2}" y="14" width="{w - emb / 2 - 3}" height="{h - 28}" rx="{(h - 28) / 2}" '
        f'fill="{CREAM}" stroke="{INK}" stroke-width="2.5"/>'
        f'<rect x="{emb / 2}" y="14" width="{w - emb / 2 - 3}" height="{h - 28}" rx="{(h - 28) / 2}" '
        f'fill="{BG[tint]}" opacity=".55"/>'
        f'<g transform="scale({scale})">{emblem(slug, tint, art, spark, standalone=False)}</g>'
        f'<path d="{t_bold.path(slug, name_size, tx, 41)}" fill="{INK}"/>'
        f'<path d="{t_med.path(desc, desc_size, tx, 58)}" fill="{INK}" fill-opacity=".72"/>'
        f'</svg>\n'
    )


# ---------------------------------------------------------------- build
def render(svg, png, width):
    png.parent.mkdir(parents=True, exist_ok=True)
    subprocess.run(["rsvg-convert", "-w", str(width), "-o", str(png), str(svg)], check=True)


def main():
    t_bold, t_med = Type(850), Type(700)
    for d in ["svg", "svg/tag"]:
        (ROOT / d).mkdir(parents=True, exist_ok=True)
    for bid, slug, desc, tint, art, spark in BADGES:
        name = slug.lower()
        e = ROOT / "svg" / f"{name}.svg"
        e.write_text(emblem(slug, tint, art, spark))
        t = ROOT / "svg" / "tag" / f"{name}.svg"
        t.write_text(tag(slug, desc, tint, art, spark, t_bold, t_med))
        render(e, ROOT / "png" / "512" / f"{name}.png", 512)
        render(e, ROOT / "png" / "128" / f"{name}.png", 128)
        tw = int(t.read_text().split('width="')[1].split('"')[0])
        render(t, ROOT / "png" / "tag" / f"{name}.png", tw * 3)
    print(f"built {len(BADGES)} badges")


if __name__ == "__main__":
    os.chdir(ROOT)
    main()
