#!/usr/bin/env python3
"""Build server/lib/blocks.json (append-only registry) and new unlockable
block PNGs in the existing 64×64 style: coloured silhouette, dark outline,
soft highlight, drop shadow.

Official catalog colours are listed first (Terra's five, then the other
planets in catalog order) and their existing PNGs are left untouched.
New icons are appended and rendered here.

Run from the repo root: python3 scripts/gen_unlock_blocks.py
"""
from __future__ import annotations

import json
import math
from pathlib import Path

from PIL import Image, ImageDraw, ImageFilter

ROOT = Path(__file__).resolve().parents[1]
CATALOG = ROOT / 'server' / 'lib' / 'planets.json'
OUT_JSON = ROOT / 'server' / 'lib' / 'blocks.json'
OUT_IMG = ROOT / 'build' / 'images'
SIZE = 64
SCALE = 4
SS = SIZE * SCALE


def hex_rgb(h):
    h = h.lstrip('#')
    return tuple(int(h[i:i + 2], 16) for i in (0, 2, 4))


def lighten(rgb, f=0.35):
    return tuple(min(255, int(c + (255 - c) * f)) for c in rgb)


def darken(rgb, f=0.28):
    return tuple(max(0, int(c * (1 - f))) for c in rgb)


def regular_poly(cx, cy, r, n, rot=-math.pi / 2):
    pts = []
    for i in range(n):
        a = rot + i * 2 * math.pi / n
        pts.append((cx + r * math.cos(a), cy + r * math.sin(a)))
    return pts


def star_pts(cx, cy, r, n=5, inner=0.42, rot=-math.pi / 2):
    pts = []
    for i in range(n * 2):
        a = rot + i * math.pi / n
        rr = r if i % 2 == 0 else r * inner
        pts.append((cx + rr * math.cos(a), cy + rr * math.sin(a)))
    return pts


# ---------- shape primitives (filled polygons / lines) ----------

def poly_stroke(draw, pts, fill, outline, width):
    draw.polygon(pts, fill=fill, outline=outline, width=width)


def thick_lines(draw, segs, color, width, closed=False):
    """segs: list of point lists."""
    for pts in segs:
        if len(pts) < 2:
            continue
        draw.line(pts, fill=color, width=width, joint='curve')
        # round caps
        r = width / 2
        for p in (pts[0], pts[-1]):
            draw.ellipse([p[0] - r, p[1] - r, p[0] + r, p[1] + r], fill=color)
        if closed and pts[0] != pts[-1]:
            draw.line([pts[-1], pts[0]], fill=color, width=width)


def icon_path(cx, cy, r, kind):
    """Return ('poly', pts) or ('polys', [pts, ...]) or ('lines', [pts,...], wfrac)
    or ('combo', list of commands). Coordinates in actual pixels."""
    def P(x, y):
        return (cx + x * r, cy + y * r)

    k = kind.lower()
    if k == 'circle':
        return ('ellipse', [-1, -1, 1, 1])
    if k == 'square':
        s = 0.86
        return ('roundrect', [-s, -s, s, s], 0.12)
    if k == 'triangle':
        return ('poly', regular_poly(cx, cy + r * 0.08, r * 1.08, 3, -math.pi / 2))
    if k == 'diamond':
        return ('poly', regular_poly(cx, cy, r * 1.05, 4, 0))
    if k == 'star':
        return ('poly', star_pts(cx, cy, r * 1.12))
    if k == 'hexagon':
        return ('poly', regular_poly(cx, cy, r * 1.05, 6, 0))
    if k == 'pentagon':
        return ('poly', regular_poly(cx, cy, r * 1.08, 5))
    if k == 'arrow':
        return ('poly', [
            P(0, -1.1), P(0.85, 0.05), P(0.28, 0.05), P(0.28, 1),
            P(-0.28, 1), P(-0.28, 0.05), P(-0.85, 0.05),
        ])
    if k == 'chevron':
        return ('poly', [
            P(0, -1.05), P(0.95, 0.15), P(0.95, 0.55), P(0, -0.15),
            P(-0.95, 0.55), P(-0.95, 0.15),
        ])
    if k == 'double_arrow':
        return ('poly', [
            P(0, -1.15), P(0.72, -0.25), P(0.28, -0.25), P(0.28, 0.05),
            P(0.72, 0.05), P(0, 1.15), P(-0.72, 0.05), P(-0.28, 0.05),
            P(-0.28, -0.25), P(-0.72, -0.25),
        ])
    if k == 'return_arrow':
        return ('poly', [
            P(-0.15, -1.1), P(0.7, -0.4), P(0.25, -0.4), P(0.25, 0.15),
            P(0.85, 0.15), P(0.85, 0.55), P(-0.25, 0.55), P(-0.25, -0.4),
            P(-0.7, -0.4),
        ])
    # Runes — stylized, thick, readable
    if k == 'rune_fehu':
        return ('lines', [
            [P(-0.15, 1.0), P(-0.15, -1.0)],
            [P(-0.15, -0.55), P(0.85, -0.95)],
            [P(-0.15, -0.05), P(0.85, -0.45)],
        ], 0.28)
    if k == 'rune_ansuz':
        return ('lines', [
            [P(-0.2, 1.0), P(-0.2, -1.0)],
            [P(-0.2, -0.85), P(0.85, -0.25)],
            [P(-0.2, -0.15), P(0.7, 0.45)],
        ], 0.28)
    if k == 'rune_thurisaz':
        return ('lines', [
            [P(-0.35, 1.0), P(-0.35, -1.0)],
            [P(-0.35, -0.55), P(0.7, 0), P(-0.35, 0.55)],
        ], 0.28)
    if k == 'rune_raido':
        return ('lines', [
            [P(-0.3, 1.0), P(-0.3, -1.0)],
            [P(-0.3, -1.0), P(0.65, -0.55), P(-0.3, -0.1)],
            [P(-0.05, -0.1), P(0.7, 1.0)],
        ], 0.26)
    if k == 'rune_sowilo':
        return ('lines', [
            [P(0.55, -1.05), P(-0.45, -0.25), P(0.45, 0.25), P(-0.55, 1.05)],
        ], 0.30)
    if k == 'rune_algiz':
        return ('lines', [
            [P(0, 1.05), P(0, -1.05)],
            [P(0, -0.15), P(-0.75, -0.95)],
            [P(0, -0.15), P(0.75, -0.95)],
        ], 0.28)
    # Figures
    if k == 'person':
        # head + body + arms + legs as one silhouette
        head = []
        for i in range(16):
            a = i * 2 * math.pi / 16
            head.append(P(0.0 + 0.28 * math.cos(a), -0.72 + 0.28 * math.sin(a)))
        body = [
            P(-0.22, -0.42), P(-0.72, -0.15), P(-0.72, 0.12), P(-0.22, -0.08),
            P(-0.28, 0.35), P(-0.55, 1.05), P(-0.22, 1.05), P(0, 0.5),
            P(0.22, 1.05), P(0.55, 1.05), P(0.28, 0.35), P(0.22, -0.08),
            P(0.72, 0.12), P(0.72, -0.15), P(0.22, -0.42),
        ]
        return ('polys', [head, body])
    if k == 'walker':
        head = [P(0.15 + 0.26 * math.cos(i * 2 * math.pi / 16),
                  -0.7 + 0.26 * math.sin(i * 2 * math.pi / 16)) for i in range(16)]
        body = [
            P(-0.05, -0.42), P(-0.65, 0.05), P(-0.45, 0.25), P(-0.05, -0.05),
            P(-0.15, 0.35), P(-0.7, 0.95), P(-0.4, 1.08), P(0.05, 0.45),
            P(0.45, 1.08), P(0.7, 0.85), P(0.25, 0.3), P(0.25, -0.05),
            P(0.7, -0.25), P(0.5, -0.45), P(0.2, -0.42),
        ]
        return ('polys', [head, body])
    if k == 'hero':
        # arms up in a V
        head = [P(0.0 + 0.26 * math.cos(i * 2 * math.pi / 16),
                  -0.62 + 0.26 * math.sin(i * 2 * math.pi / 16)) for i in range(16)]
        body = [
            P(-0.18, -0.35), P(-0.95, -0.95), P(-0.7, -1.08), P(-0.1, -0.4),
            P(-0.25, 0.35), P(-0.5, 1.08), P(-0.18, 1.08), P(0, 0.5),
            P(0.18, 1.08), P(0.5, 1.08), P(0.25, 0.35), P(0.1, -0.4),
            P(0.7, -1.08), P(0.95, -0.95), P(0.18, -0.35),
        ]
        return ('polys', [head, body])
    # Faces
    if k == 'smile':
        return ('face', 'smile')
    if k == 'wink':
        return ('face', 'wink')
    if k == 'cool':
        return ('face', 'cool')
    if k == 'grin':
        return ('face', 'grin')
    # Icons
    if k == 'heart':
        pts = []
        for i in range(32):
            t = i * 2 * math.pi / 32
            # classic heart parametric, scaled
            x = 16 * math.sin(t) ** 3
            y = -(13 * math.cos(t) - 5 * math.cos(2 * t) - 2 * math.cos(3 * t) - math.cos(4 * t))
            pts.append(P(x / 16.5, y / 16.5 + 0.08))
        return ('poly', pts)
    if k == 'lightning':
        return ('poly', [
            P(0.15, -1.1), P(0.55, -1.1), P(0.05, -0.1), P(0.45, -0.1),
            P(-0.55, 1.15), P(-0.05, 0.15), P(-0.5, 0.15),
        ])
    if k == 'shield':
        return ('poly', [
            P(0, -1.1), P(0.95, -0.7), P(0.85, 0.25), P(0, 1.1),
            P(-0.85, 0.25), P(-0.95, -0.7),
        ])
    if k == 'crown':
        return ('poly', [
            P(-0.95, 0.45), P(-0.95, -0.15), P(-0.5, 0.25), P(0, -0.95),
            P(0.5, 0.25), P(0.95, -0.15), P(0.95, 0.45),
            P(0.85, 0.85), P(-0.85, 0.85),
        ])
    if k == 'eye':
        return ('eye',)
    if k == 'star6':
        return ('poly', star_pts(cx, cy, r * 1.12, n=6, inner=0.48))
    if k == 'spiral':
        pts = []
        for i in range(60):
            t = i / 59 * 3.4 * math.pi
            rr = 0.12 + 0.88 * (i / 59)
            pts.append(P(rr * math.cos(t), rr * math.sin(t)))
        return ('lines', [pts], 0.26)
    if k == 'wave':
        pts_top, pts_bot = [], []
        for i in range(21):
            x = -1.05 + i * 2.1 / 20
            y = 0.28 * math.sin(x * math.pi * 1.4)
            pts_top.append(P(x, y - 0.28))
            pts_bot.append(P(x, y + 0.28))
        return ('poly', pts_top + list(reversed(pts_bot)))
    if k == 'mountain':
        return ('poly', [
            P(-1.1, 0.9), P(-0.45, -0.55), P(-0.15, -0.05),
            P(0.15, -1.05), P(0.5, -0.25), P(0.7, -0.55),
            P(1.1, 0.9),
        ])
    if k == 'fish':
        return ('poly', [
            P(-1.05, 0), P(-0.55, -0.55), P(0.35, -0.55), P(0.75, -0.15),
            P(1.1, -0.55), P(0.85, 0), P(1.1, 0.55), P(0.75, 0.15),
            P(0.35, 0.55), P(-0.55, 0.55),
        ])
    if k == 'bird':
        return ('poly', [
            P(-1.05, 0.15), P(-0.3, -0.15), P(-0.05, -0.85), P(0.2, -0.15),
            P(0.55, -0.25), P(1.05, 0.05), P(0.45, 0.15),
            P(0.2, 0.85), P(-0.05, 0.2), P(-0.55, 0.45),
        ])
    if k == 'key':
        # head circle + shaft + teeth as one poly
        pts = []
        for i in range(12):
            a = -math.pi * 0.6 + i * 1.6 * math.pi / 11
            pts.append(P(-0.55 + 0.42 * math.cos(a), -0.55 + 0.42 * math.sin(a)))
        pts += [
            P(-0.25, -0.2), P(1.05, -0.2), P(1.05, 0.15),
            P(0.85, 0.15), P(0.85, 0.5), P(0.6, 0.5), P(0.6, 0.15),
            P(0.4, 0.15), P(0.4, 0.38), P(0.15, 0.38), P(0.15, 0.15),
            P(-0.25, 0.15),
        ]
        return ('poly', pts)
    if k == 'comet':
        return ('poly', [
            P(0.95, -0.95), P(0.35, -0.45), P(0.15, -0.7), P(-0.15, -0.15),
            P(0.15, -0.05), P(-1.05, 1.05), P(-0.05, 0.15), P(0.15, 0.35),
            P(0.55, -0.15), P(0.45, -0.45),
        ])
    if k == 'clover':
        lobes = []
        for ang, ox, oy in ((0, 0, -0.42), (2.1, -0.4, 0.18), (4.2, 0.4, 0.18)):
            pts = []
            for i in range(16):
                a = i * 2 * math.pi / 16
                pts.append(P(ox + 0.42 * math.cos(a), oy + 0.42 * math.sin(a)))
            lobes.append(pts)
        stem = [P(-0.08, 0.35), P(0.08, 0.35), P(0.18, 1.05), P(-0.05, 1.05)]
        lobes.append(stem)
        return ('polys', lobes)
    if k == 'paw':
        pads = []
        for ox, oy, rr in ((-0.5, -0.55, 0.28), (0, -0.75, 0.28), (0.5, -0.55, 0.28),
                           (0.0, 0.28, 0.52)):
            pts = []
            for i in range(16):
                a = i * 2 * math.pi / 16
                pts.append(P(ox + rr * math.cos(a), oy + rr * math.sin(a)))
            pads.append(pts)
        return ('polys', pads)
    if k == 'sword':
        return ('poly', [
            P(-0.18, 1.1), P(-0.18, 0.45), P(-0.55, 0.45), P(-0.55, 0.22),
            P(-0.18, 0.22), P(-0.18, -0.95), P(0, -1.15), P(0.18, -0.95),
            P(0.18, 0.22), P(0.55, 0.22), P(0.55, 0.45), P(0.18, 0.45),
            P(0.18, 1.1),
        ])
    if k == 'bell':
        pts = []
        for i in range(18):
            a = math.pi + i * math.pi / 17
            pts.append(P(0.85 * math.cos(a), -0.25 + 0.85 * math.sin(a)))
        pts += [P(0.95, 0.55), P(0.7, 0.75), P(0.15, 0.75), P(0.15, 0.95),
                P(-0.15, 0.95), P(-0.15, 0.75), P(-0.7, 0.75), P(-0.95, 0.55)]
        return ('poly', pts)
    if k == 'mushroom':
        cap = []
        for i in range(18):
            a = math.pi + i * math.pi / 17
            cap.append(P(0.95 * math.cos(a), -0.25 + 0.7 * math.sin(a)))
        cap += [P(0.95, 0.05), P(-0.95, 0.05)]
        stem = [P(-0.32, 0.05), P(0.32, 0.05), P(0.38, 1.05), P(-0.38, 1.05)]
        return ('polys', [cap, stem])
    if k == 'cactus':
        return ('poly', [
            P(-0.22, 1.05), P(-0.22, 0.15), P(-0.75, 0.15), P(-0.75, -0.35),
            P(-0.5, -0.35), P(-0.5, -0.05), P(-0.22, -0.05), P(-0.22, -1.05),
            P(0.22, -1.05), P(0.22, -0.25), P(0.55, -0.25), P(0.55, -0.7),
            P(0.8, -0.7), P(0.8, -0.02), P(0.22, -0.02), P(0.22, 1.05),
        ])
    if k == 'ring':
        return ('ring', 1.0, 0.55)
    if k == 'flag':
        return ('poly', [
            P(-0.7, 1.1), P(-0.7, -1.05), P(-0.5, -1.05), P(-0.5, -0.85),
            P(1.0, -0.85), P(0.7, -0.4), P(1.0, 0.05), P(-0.5, 0.05),
            P(-0.5, 1.1),
        ])
    if k == 'snowflake':
        arms = []
        for k0 in range(6):
            a = k0 * math.pi / 3
            c, s = math.cos(a), math.sin(a)
            def rot(x, y):
                return P(x * c - y * s, x * s + y * c)
            arms.append([rot(0, 0), rot(0, -1.05)])
            arms.append([rot(-0.28, -0.6), rot(0, -0.4), rot(0.28, -0.6)])
        return ('lines', arms, 0.22)
    if k == 'flame_icon':
        return ('poly', [
            P(0, -1.15), P(0.35, -0.45), P(0.55, -0.7), P(0.75, -0.15),
            P(0.55, 0.55), P(0.2, 1.0), P(-0.25, 1.0), P(-0.6, 0.5),
            P(-0.7, -0.05), P(-0.35, -0.55), P(-0.15, -0.2),
        ])
    if k == 'ankh':
        return ('lines', [
            [P(0, 1.05), P(0, -0.25)],
            [P(-0.55, 0.15), P(0.55, 0.15)],
        ], 0.28)  # loop added in combo
    if k == 'yinyang':
        return ('yinyang',)
    if k == 'crescent':
        # moon
        return ('crescent',)
    # fallback
    return ('ellipse', [-1, -1, 1, 1])


def draw_kind(draw, img, kind, cx, cy, r, fill, outline, width):
    cmd = icon_path(cx, cy, r, kind)
    kind_l = kind.lower()

    def fill_poly(pts):
        if len(pts) >= 3:
            draw.polygon(pts, fill=fill, outline=outline, width=width)

    def fill_lines(segs, wfrac):
        w = max(width, int(r * wfrac))
        # draw in outline color slightly thicker, then fill
        thick_lines(draw, segs, outline, w + max(2, width // 2))
        thick_lines(draw, segs, fill, w)

    if cmd[0] == 'poly':
        fill_poly(cmd[1])
    elif cmd[0] == 'polys':
        for pts in cmd[1]:
            fill_poly(pts)
    elif cmd[0] == 'lines':
        fill_lines(cmd[1], cmd[2])
        if kind_l == 'ankh':
            # loop at top
            box = [cx - r * 0.42, cy - r * 1.15, cx + r * 0.42, cy - r * 0.25]
            draw.ellipse(box, outline=outline, width=int(r * 0.28) + width)
            draw.ellipse([box[0] + r * 0.14, box[1] + r * 0.14,
                          box[2] - r * 0.14, box[3] - r * 0.14],
                         outline=fill, width=int(r * 0.16))
            # fill ring by a second pass
            # simpler: thick ellipse
            w = int(r * 0.26)
            draw.ellipse(box, outline=outline, width=w + width)
            draw.ellipse(box, outline=fill, width=w)
    elif cmd[0] == 'ellipse':
        a, b, c, d = cmd[1]
        box = [cx + a * r, cy + b * r, cx + c * r, cy + d * r]
        draw.ellipse(box, fill=fill, outline=outline, width=width)
    elif cmd[0] == 'roundrect':
        a, b, c, d = cmd[1]
        box = [cx + a * r, cy + b * r, cx + c * r, cy + d * r]
        draw.rounded_rectangle(box, radius=r * cmd[2], fill=fill, outline=outline, width=width)
    elif cmd[0] == 'ring':
        _, ro, ri = cmd
        outer = [cx - r * ro, cy - r * ro, cx + r * ro, cy + r * ro]
        inner = [cx - r * ri, cy - r * ri, cx + r * ri, cy + r * ri]
        draw.ellipse(outer, fill=fill, outline=outline, width=width)
        # punch inner with destination-out
        # We'll handle punch at a higher level; draw inner as transparent later
        draw.ellipse(inner, fill=(0, 0, 0, 0), outline=outline, width=width)
    elif cmd[0] == 'face':
        box = [cx - r, cy - r, cx + r, cy + r]
        draw.ellipse(box, fill=fill, outline=outline, width=width)
        eye_c = outline
        er = r * 0.12
        if cmd[1] == 'wink':
            draw.ellipse([cx - r * 0.38 - er, cy - r * 0.28 - er,
                          cx - r * 0.38 + er, cy - r * 0.28 + er], fill=eye_c)
            draw.line([(cx + r * 0.18, cy - r * 0.28), (cx + r * 0.52, cy - r * 0.28)],
                      fill=eye_c, width=max(width, int(r * 0.12)))
        elif cmd[1] == 'cool':
            # sunglasses
            draw.rounded_rectangle([cx - r * 0.7, cy - r * 0.42, cx - r * 0.08, cy - r * 0.08],
                                   radius=r * 0.12, fill=eye_c)
            draw.rounded_rectangle([cx + r * 0.08, cy - r * 0.42, cx + r * 0.7, cy - r * 0.08],
                                   radius=r * 0.12, fill=eye_c)
            draw.line([(cx - r * 0.08, cy - r * 0.25), (cx + r * 0.08, cy - r * 0.25)],
                      fill=eye_c, width=max(3, int(r * 0.1)))
        else:
            draw.ellipse([cx - r * 0.38 - er, cy - r * 0.28 - er,
                          cx - r * 0.38 + er, cy - r * 0.28 + er], fill=eye_c)
            draw.ellipse([cx + r * 0.38 - er, cy - r * 0.28 - er,
                          cx + r * 0.38 + er, cy - r * 0.28 + er], fill=eye_c)
        # smile
        smile = []
        for i in range(9):
            a = math.pi * 0.2 + i * math.pi * 0.6 / 8
            smile.append((cx + r * 0.48 * math.cos(a), cy + r * 0.12 + r * 0.42 * math.sin(a)))
        sw = max(width, int(r * 0.12))
        if cmd[1] == 'grin':
            draw.chord([cx - r * 0.5, cy + r * 0.05, cx + r * 0.5, cy + r * 0.65],
                       start=0, end=180, fill=eye_c, outline=eye_c)
        else:
            draw.line(smile, fill=eye_c, width=sw, joint='curve')
    elif cmd[0] == 'eye':
        # almond
        pts = []
        for i in range(24):
            t = i * 2 * math.pi / 24
            x = math.cos(t)
            y = 0.5 * math.sin(t)
            pts.append((cx + r * 1.05 * x, cy + r * 0.85 * y))
        fill_poly(pts)
        iris_c = outline
        draw.ellipse([cx - r * 0.38, cy - r * 0.38, cx + r * 0.38, cy + r * 0.38],
                     fill=iris_c)
        draw.ellipse([cx - r * 0.14, cy - r * 0.18, cx + r * 0.06, cy + r * 0.02],
                     fill=lighten(fill[:3] if isinstance(fill, tuple) else (255, 255, 255), 0.8) + (255,))
    elif cmd[0] == 'yinyang':
        draw.ellipse([cx - r, cy - r, cx + r, cy + r], fill=fill, outline=outline, width=width)
        # right half dark via chord is messy; draw a dark semicircle + two dots
        # Use a path: top-center to bottom via right, with small circles
        # We'll approximate with a pie and two discs
        dark = outline
        draw.pieslice([cx - r, cy - r, cx + r, cy + r], start=90, end=270, fill=dark)
        draw.ellipse([cx - r * 0.5, cy - r, cx + r * 0.5, cy], fill=dark)
        draw.ellipse([cx - r * 0.5, cy, cx + r * 0.5, cy + r], fill=fill)
        # dots
        draw.ellipse([cx - r * 0.16, cy - r * 0.58, cx + r * 0.16, cy - r * 0.26], fill=fill)
        draw.ellipse([cx - r * 0.16, cy + r * 0.26, cx + r * 0.16, cy + r * 0.58], fill=dark)
        draw.ellipse([cx - r, cy - r, cx + r, cy + r], outline=outline, width=width)
    elif cmd[0] == 'crescent':
        # moon: two circles, punch later — draw a crescent polygon
        outer, inner = [], []
        for i in range(24):
            a = -math.pi * 0.75 + i * (1.5 * math.pi) / 23
            outer.append((cx + r * math.cos(a) - r * 0.05, cy + r * math.sin(a)))
        ox, oy = cx + r * 0.42, cy - r * 0.05
        for i in range(20, -1, -1):
            a = -math.pi * 0.7 + i * (1.4 * math.pi) / 20
            inner.append((ox + r * 0.72 * math.cos(a), oy + r * 0.72 * math.sin(a)))
        fill_poly(outer + inner)
    else:
        draw.ellipse([cx - r, cy - r, cx + r, cy + r], fill=fill, outline=outline, width=width)


def render_block(hex_color, shape):
    rgb = hex_rgb(hex_color)
    hi = lighten(rgb, 0.42)
    lo = darken(rgb, 0.32)
    img = Image.new('RGBA', (SS, SS), (0, 0, 0, 0))
    cx = cy = SS / 2
    r = SS * 0.36
    width = max(2, SCALE)
    # drop shadow
    shadow = Image.new('RGBA', (SS, SS), (0, 0, 0, 0))
    sd = ImageDraw.Draw(shadow)
    draw_kind(sd, shadow, shape, cx + SCALE * 1.2, cy + SCALE * 1.6, r,
              (0, 0, 0, 90), None, 0)
    shadow = shadow.filter(ImageFilter.GaussianBlur(radius=SCALE * 1.1))
    img = Image.alpha_composite(img, shadow)
    # For ring, punch a hole after drawing body
    body = Image.new('RGBA', (SS, SS), (0, 0, 0, 0))
    bd = ImageDraw.Draw(body)
    draw_kind(bd, body, shape, cx, cy, r, rgb + (255,), lo + (255,), width)
    if shape == 'ring':
        # punch inner hole
        mask = Image.new('L', (SS, SS), 0)
        md = ImageDraw.Draw(mask)
        ri = r * 0.55
        md.ellipse([cx - ri, cy - ri, cx + ri, cy + ri], fill=255)
        clear = Image.new('RGBA', (SS, SS), (0, 0, 0, 0))
        body = Image.composite(clear, body, mask)
        # redraw inner outline
        bd = ImageDraw.Draw(body)
        bd.ellipse([cx - ri, cy - ri, cx + ri, cy + ri], outline=lo + (255,), width=width)
    img = Image.alpha_composite(img, body)
    # highlight
    hi_layer = Image.new('RGBA', (SS, SS), (0, 0, 0, 0))
    hd = ImageDraw.Draw(hi_layer)
    draw_kind(hd, hi_layer, shape, cx - r * 0.06, cy - r * 0.10, r * 0.55,
              hi + (110,), None, 0)
    hi_layer = hi_layer.filter(ImageFilter.GaussianBlur(radius=SCALE * 0.6))
    # clip highlight to body alpha
    body_a = body.split()[3]
    ha = hi_layer.split()[3]
    from PIL import ImageChops
    ha = ImageChops.multiply(ha, body_a)
    hi_layer.putalpha(ha)
    img = Image.alpha_composite(img, hi_layer)
    return img.resize((SIZE, SIZE), Image.Resampling.LANCZOS)


# New unlockable blocks, appended after official catalog colours.
# ids are stable and must never be reordered or reused.
NEW_BLOCKS = [
    # Runes
    {'id': 'rune-fehu', 'name': 'Fehu', 'hex': '#e8a44a', 'shape': 'rune_fehu'},
    {'id': 'rune-ansuz', 'name': 'Ansuz', 'hex': '#6ab0e8', 'shape': 'rune_ansuz'},
    {'id': 'rune-thurisaz', 'name': 'Thurisaz', 'hex': '#c05040', 'shape': 'rune_thurisaz'},
    {'id': 'rune-raido', 'name': 'Raido', 'hex': '#d0c070', 'shape': 'rune_raido'},
    {'id': 'rune-sowilo', 'name': 'Sowilo', 'hex': '#f0d040', 'shape': 'rune_sowilo'},
    {'id': 'rune-algiz', 'name': 'Algiz', 'hex': '#80d0a0', 'shape': 'rune_algiz'},
    # Arrows
    {'id': 'arrow-up', 'name': 'Arrow', 'hex': '#f07040', 'shape': 'arrow'},
    {'id': 'arrow-chevron', 'name': 'Chevron', 'hex': '#50c0e0', 'shape': 'chevron'},
    {'id': 'arrow-double', 'name': 'Double Arrow', 'hex': '#e05080', 'shape': 'double_arrow'},
    {'id': 'arrow-return', 'name': 'Return', 'hex': '#a080e0', 'shape': 'return_arrow'},
    # Figures
    {'id': 'fig-person', 'name': 'Figure', 'hex': '#f0c0a0', 'shape': 'person'},
    {'id': 'fig-walker', 'name': 'Walker', 'hex': '#c09070', 'shape': 'walker'},
    {'id': 'fig-hero', 'name': 'Hero', 'hex': '#e8b070', 'shape': 'hero'},
    # Faces
    {'id': 'face-smile', 'name': 'Smile', 'hex': '#f0d060', 'shape': 'smile'},
    {'id': 'face-wink', 'name': 'Wink', 'hex': '#f0a050', 'shape': 'wink'},
    {'id': 'face-cool', 'name': 'Cool', 'hex': '#6090d0', 'shape': 'cool'},
    {'id': 'face-grin', 'name': 'Grin', 'hex': '#f0c848', 'shape': 'grin'},
    # Icons
    {'id': 'icon-heart', 'name': 'Heart', 'hex': '#e04060', 'shape': 'heart'},
    {'id': 'icon-moon', 'name': 'Moon', 'hex': '#d0d8f0', 'shape': 'crescent'},
    {'id': 'icon-bolt', 'name': 'Bolt', 'hex': '#f0e050', 'shape': 'lightning'},
    {'id': 'icon-shield', 'name': 'Shield', 'hex': '#5080c0', 'shape': 'shield'},
    {'id': 'icon-crown', 'name': 'Crown', 'hex': '#f0c030', 'shape': 'crown'},
    {'id': 'icon-eye', 'name': 'Eye', 'hex': '#70d0c0', 'shape': 'eye'},
    {'id': 'icon-star6', 'name': 'Hexastar', 'hex': '#f0e8a0', 'shape': 'star6'},
    {'id': 'icon-spiral', 'name': 'Spiral', 'hex': '#c070d0', 'shape': 'spiral'},
    {'id': 'icon-wave', 'name': 'Wave', 'hex': '#3090d0', 'shape': 'wave'},
    {'id': 'icon-mountain', 'name': 'Mountain', 'hex': '#809070', 'shape': 'mountain'},
    {'id': 'icon-fish', 'name': 'Fish', 'hex': '#40a8c8', 'shape': 'fish'},
    {'id': 'icon-bird', 'name': 'Bird', 'hex': '#e07050', 'shape': 'bird'},
    {'id': 'icon-key', 'name': 'Key', 'hex': '#d0b050', 'shape': 'key'},
    {'id': 'icon-comet', 'name': 'Comet', 'hex': '#90d0f0', 'shape': 'comet'},
    {'id': 'icon-clover', 'name': 'Clover', 'hex': '#40b060', 'shape': 'clover'},
    {'id': 'icon-paw', 'name': 'Paw', 'hex': '#c08050', 'shape': 'paw'},
    {'id': 'icon-sword', 'name': 'Sword', 'hex': '#b0b8c0', 'shape': 'sword'},
    {'id': 'icon-bell', 'name': 'Bell', 'hex': '#f0c848', 'shape': 'bell'},
    {'id': 'icon-mushroom', 'name': 'Mushroom', 'hex': '#e06050', 'shape': 'mushroom'},
    {'id': 'icon-cactus', 'name': 'Cactus', 'hex': '#50b068', 'shape': 'cactus'},
    {'id': 'icon-ring', 'name': 'Ring', 'hex': '#e8d080', 'shape': 'ring'},
    {'id': 'icon-flag', 'name': 'Flag', 'hex': '#d04050', 'shape': 'flag'},
    {'id': 'icon-snow', 'name': 'Snowflake', 'hex': '#c8e0f8', 'shape': 'snowflake'},
    {'id': 'icon-flame', 'name': 'Flame', 'hex': '#ff7030', 'shape': 'flame_icon'},
    {'id': 'icon-ankh', 'name': 'Ankh', 'hex': '#d0a060', 'shape': 'ankh'},
    {'id': 'icon-yin', 'name': 'Yin Yang', 'hex': '#606080', 'shape': 'yinyang'},
]


def official_blocks(catalog):
    out = []
    seen = set()
    for planet in catalog['planets']:
        pid = planet['id']
        for c in planet['colors']:
            bid = f"{pid}-{c['name']}"
            if bid in seen:
                raise SystemExit(f'duplicate official id {bid}')
            seen.add(bid)
            out.append({
                'id': bid,
                'name': c['name'].capitalize() if pid == 'terra' else f"{planet['name']} {c['name']}",
                'hex': c['hex'],
                'shape': c.get('shape') or 'circle',
                'image': c['image'],
                'terra': pid == 'terra',
            })
    return out


def main():
    catalog = json.loads(CATALOG.read_text())
    official = official_blocks(catalog)
    terra = [b for b in official if b.get('terra')]
    others = [b for b in official if not b.get('terra')]
    if len(terra) != 5 or terra[0]['id'] != 'terra-ember':
        raise SystemExit(f'Terra five unexpected: {[b["id"] for b in terra]}')

    new = []
    seen = {b['id'] for b in official}
    OUT_IMG.mkdir(parents=True, exist_ok=True)
    for b in NEW_BLOCKS:
        if b['id'] in seen:
            raise SystemExit(f'duplicate new id {b["id"]}')
        seen.add(b['id'])
        image = f"images/block-{b['id']}.png"
        path = ROOT / 'build' / image
        img = render_block(b['hex'], b['shape'])
        img.save(path, 'PNG', optimize=True)
        new.append({
            'id': b['id'],
            'name': b['name'],
            'hex': b['hex'],
            'shape': b['shape'],
            'image': image,
            'terra': False,
        })
        print(f'  wrote {path.relative_to(ROOT)} ({path.stat().st_size} bytes)')

    registry = {
        '_comment': (
            'Append-only block registry. Never reorder, rename ids, or insert '
            'in the middle. New blocks go at the end. The first five (Terra) '
            'are unlocked by default; index 5 requires 500 lifetime points, '
            'each next index requires 14.5% more (rounded).'
        ),
        'terraCount': 5,
        'firstThreshold': 500,
        'thresholdGrowth': 1.145,
        'blocks': terra + new + others,
    }
    OUT_JSON.write_text(json.dumps(registry, indent=2, ensure_ascii=False) + '\n')
    print(f'wrote {OUT_JSON.relative_to(ROOT)}: {len(terra)} terra + {len(new)} new + {len(others)} official = {len(registry["blocks"])} total')


if __name__ == '__main__':
    main()
