"""Photo -> 3 batter colours -> pancake toolpaths.

Written by Claude (AI) for Andrin Schmid, 17 Nov 2026 (pancake printer, MAS.863 machine week).

Turns any photo (jpg, png, ...) into stroke-only toolpaths for the three
syringes of the pancake printer. The output plugs into the existing pipeline:

    <name>.svg           one <g> per syringe, stroke-only polylines in mm,
                         groups in print order (feed this to print_ufp.py)
    <name>.events.json   same toolpath as an event list in machine mm
                         (SelectNozzle, Move, ExtrudeOn, ExtrudeOff, Dwell)
    <name>_preview.png   photo | 3 colours | on the griddle | after flipping

Steps:
  1. load, crop to the pancake shape, remove the background (rembg if it is
     installed, otherwise the tone that touches the rim), mirror (the pancake
     is flipped, so the griddle side is seen mirrored)
  2. darkest batter = line art: the outline of the subject, plus the thin dark
     features (eyes, nose, stripes) as single lines and big dark areas as loops
  3. the other two batters fill the subject in 2 tones (k-means on lightness,
     or nearest batter colour with --match color)
  4. clean up: remove features thinner than one bead
  5. per fill colour: one loop half a bead inside the edge, then a zigzag hatch
  6. print order: darkest batter first. The first batter touches the griddle,
     so after flipping the lines sit on top of the fill and stay visible

Needs numpy, Pillow, scipy and contourpy (comes with matplotlib).
Background removal: pip install "rembg[cpu]" (downloads a 176 MB model once).
--style tones: no line art, all 3 batters are fill tones.

Example:
    python scripts/image_to_pancake.py photo.jpg -o out --width 120 --show
"""

from __future__ import annotations

import argparse
import json
import math
from dataclasses import dataclass, field
from pathlib import Path

import numpy as np
from PIL import Image, ImageDraw, ImageFilter, ImageOps
from scipy import ndimage

try:
    import contourpy
except ImportError:  # pragma: no cover
    contourpy = None

# cooked look of plain batter at three browning levels: dark, medium, light
DEFAULT_BATTER = ["#5a3216", "#b07a3a", "#e8c27a"]  # = nozzle colours in machine.example.yaml

# Hector's measurement: 15.81 cm^3 per cm of plunger travel = 1581 mm^3 per mm
DEFAULT_SYRINGE_MM3_PER_MM = 1581.0


# --------------------------------------------------------------------------- colour


def hex_to_rgb(h: str) -> tuple[int, int, int]:
    h = h.strip().lstrip("#")
    if len(h) != 6:
        raise ValueError(f"colour must look like #rrggbb, got {h!r}")
    return tuple(int(h[i:i + 2], 16) for i in (0, 2, 4))


def rgb_to_hex(rgb) -> str:
    r, g, b = (int(round(float(c))) for c in rgb)
    return f"#{r:02x}{g:02x}{b:02x}"


def rgb_to_lab(rgb: np.ndarray) -> np.ndarray:
    """sRGB 0..255 (..., 3) -> CIE Lab (D65)."""
    c = rgb.astype(np.float64) / 255.0
    c = np.where(c <= 0.04045, c / 12.92, ((c + 0.055) / 1.055) ** 2.4)
    m = np.array([[0.4124564, 0.3575761, 0.1804375],
                  [0.2126729, 0.7151522, 0.0721750],
                  [0.0193339, 0.1191920, 0.9503041]])
    xyz = c @ m.T
    xyz /= np.array([0.95047, 1.0, 1.08883])
    eps = 216 / 24389
    f = np.where(xyz > eps, np.cbrt(xyz), (24389 / 27 * xyz + 16) / 116)
    L = 116 * f[..., 1] - 16
    a = 500 * (f[..., 0] - f[..., 1])
    b = 200 * (f[..., 1] - f[..., 2])
    return np.stack([L, a, b], axis=-1)


def kmeans(x: np.ndarray, k: int, iters: int = 40, seed: int = 0) -> np.ndarray:
    """Plain k-means with k-means++ init. x: (n, d). Returns centres (k, d)."""
    rng = np.random.default_rng(seed)
    n = len(x)
    centres = [x[rng.integers(n)]]
    for _ in range(1, k):
        d2 = np.min(((x[:, None, :] - np.array(centres)[None]) ** 2).sum(-1), axis=1)
        if d2.sum() == 0:
            centres.append(x[rng.integers(n)])
        else:
            centres.append(x[rng.choice(n, p=d2 / d2.sum())])
    centres = np.array(centres, dtype=np.float64)
    for _ in range(iters):
        lab = np.argmin(((x[:, None, :] - centres[None]) ** 2).sum(-1), axis=1)
        new = np.array([x[lab == j].mean(0) if np.any(lab == j) else centres[j]
                        for j in range(k)])
        if np.allclose(new, centres, atol=1e-3):
            break
        centres = new
    return centres


def assign(x: np.ndarray, centres: np.ndarray) -> np.ndarray:
    return np.argmin(((x[:, None, :] - centres[None]) ** 2).sum(-1), axis=1)


# --------------------------------------------------------------------------- geometry helpers


def rdp(points: np.ndarray, tol: float) -> np.ndarray:
    """Ramer-Douglas-Peucker simplification of an open polyline (n, 2)."""
    if len(points) < 3:
        return points
    keep = np.zeros(len(points), dtype=bool)
    keep[0] = keep[-1] = True
    stack = [(0, len(points) - 1)]
    while stack:
        i, j = stack.pop()
        if j <= i + 1:
            continue
        a, b = points[i], points[j]
        ab = b - a
        seg = points[i + 1:j] - a
        norm = math.hypot(*ab)
        if norm == 0:
            d = np.hypot(seg[:, 0], seg[:, 1])
        else:
            d = np.abs(ab[0] * seg[:, 1] - ab[1] * seg[:, 0]) / norm
        k = int(np.argmax(d))
        if d[k] > tol:
            m = i + 1 + k
            keep[m] = True
            stack += [(i, m), (m, j)]
    return points[keep]


def polyline_length(p: np.ndarray) -> float:
    if len(p) < 2:
        return 0.0
    return float(np.hypot(*np.diff(p, axis=0).T).sum())


def erode(mask: np.ndarray, r_px: float) -> np.ndarray:
    """Erode by a disk of radius r_px. Outside the image counts as empty."""
    if r_px <= 0:
        return mask.copy()
    pad = np.pad(mask, 1)
    d = ndimage.distance_transform_edt(pad)[1:-1, 1:-1]
    return d > r_px


def dilate(mask: np.ndarray, r_px: float) -> np.ndarray:
    if not mask.any():
        return mask.copy()
    d = ndimage.distance_transform_edt(~mask)
    return d <= r_px


def opening(mask: np.ndarray, r_px: float) -> np.ndarray:
    return dilate(erode(mask, r_px), r_px) & mask


# --------------------------------------------------------------------------- data


@dataclass
class Stroke:
    points: np.ndarray        # (n, 2) in mm, image frame (x right, y down)
    closed: bool = False      # closed loops may start at any vertex


@dataclass
class ColourLayer:
    nozzle: int
    colour: str               # batter colour (hex)
    mask: np.ndarray          # bool raster, image frame
    strokes: list[Stroke] = field(default_factory=list)

    @property
    def length(self) -> float:
        return sum(polyline_length(s.points) for s in self.strokes)


# --------------------------------------------------------------------------- step 1: image


def load_raster(path: Path, width_mm: float, px: float, shape: str):
    """Returns rgb (H, W, 3) float, inside (H, W) bool, alpha or None (H, W), cropped PIL image."""
    img = Image.open(path)
    img = ImageOps.exif_transpose(img)
    alpha = None
    if img.mode in ("RGBA", "LA") or (img.mode == "P" and "transparency" in img.info):
        rgba = img.convert("RGBA")
        alpha = np.asarray(rgba)[..., 3]
        white = Image.new("RGBA", rgba.size, (255, 255, 255, 255))
        img = Image.alpha_composite(white, rgba)
    img = img.convert("RGB")

    if shape == "circle":  # centre square crop for a round pancake
        s = min(img.size)
        left, top = (img.size[0] - s) // 2, (img.size[1] - s) // 2
        img = img.crop((left, top, left + s, top + s))
        if alpha is not None:
            alpha = alpha[top:top + s, left:left + s]

    w_px = max(8, int(round(width_mm / px)))
    h_px = max(8, int(round(w_px * img.size[1] / img.size[0])))
    rgb = np.asarray(img.resize((w_px, h_px), Image.LANCZOS)
                     .filter(ImageFilter.MedianFilter(3))).astype(np.float64)
    inside = np.ones((h_px, w_px), dtype=bool)
    if shape == "circle":
        yy, xx = np.mgrid[0:h_px, 0:w_px]
        cy, cx = (h_px - 1) / 2, (w_px - 1) / 2
        inside = (xx - cx) ** 2 + (yy - cy) ** 2 <= (min(h_px, w_px) / 2) ** 2
    if alpha is not None:
        alpha = np.asarray(Image.fromarray(alpha).resize((w_px, h_px), Image.BILINEAR)) > 127
    return rgb, inside, alpha, img


def foreground_mask(img, rgb, inside, alpha, px):
    """Subject mask: alpha channel if the image has one, else rembg, else the tone on the rim."""
    if alpha is not None:
        return inside & alpha, "alpha channel"
    h, w = inside.shape
    try:
        from rembg import new_session, remove
        # u2net: 176 MB, downloaded once. (newer rembg defaults to a 1 GB model)
        m = remove(img, session=new_session("u2net"), only_mask=True)
        m = np.asarray(m.resize((w, h), Image.BILINEAR)) > 127
        return inside & m, "rembg"
    except ImportError:
        pass
    # fallback: 4 tones, the one that touches the rim most is the background
    lab = rgb_to_lab(rgb)[inside]
    centres = kmeans(lab, 4)
    cl = np.full(inside.shape, -1)
    cl[inside] = assign(lab, centres)
    rim = inside & ~erode(inside, 2)
    counts = [np.sum((cl == j) & rim) for j in range(4)]
    bg = int(np.argmax(counts))
    if counts[bg] < 0.6 * rim.sum():  # no clear background tone: guessing would cut the subject
        return inside, "nothing (no clear background tone; pip install rembg to remove it)"
    m = inside & (cl != bg)
    lab_, n = ndimage.label(m)  # keep the biggest blob(s), drop crumbs
    if n:
        areas = ndimage.sum(m, lab_, index=np.arange(1, n + 1))
        m = np.isin(lab_, np.nonzero(areas >= 0.1 * areas.max())[0] + 1)
    return ndimage.binary_fill_holes(m), "rim tone (pip install rembg for better results)"


# --------------------------------------------------------------------------- step 2: colours


def split_colours(rgb, region, nozzles, batter_rgb, match, seed=0):
    """Split `region` into len(nozzles) tones and give each tone to one nozzle.
    lightness: darkest tone to darkest batter. color: nearest batter colour (Lab).
    Returns labels (H, W): nozzle id, or -1 outside region."""
    from itertools import permutations
    k = len(nozzles)
    labels = np.full(region.shape, -1, dtype=int)
    if not region.any():
        return labels
    lab = rgb_to_lab(rgb)
    feats = lab[region][:, :1] if match == "lightness" else lab[region]
    rng = np.random.default_rng(seed)
    sample = feats if len(feats) <= 20000 else feats[rng.choice(len(feats), 20000, replace=False)]
    centres = kmeans(sample, k, seed=seed)
    cl = assign(feats, centres)
    cluster_lab = np.array([lab[region][cl == j].mean(0) if np.any(cl == j) else [50.0, 0, 0]
                            for j in range(k)])
    batter_lab = rgb_to_lab(np.array([batter_rgb[n] for n in nozzles], dtype=np.float64))
    if match == "lightness":  # pair by rank of L*
        perm = [None] * k
        for c, b in zip(np.argsort(cluster_lab[:, 0]), np.argsort(batter_lab[:, 0])):
            perm[c] = b
    else:
        perm = min(permutations(range(k)),
                   key=lambda pm: sum(np.sum((cluster_lab[i] - batter_lab[pm[i]]) ** 2)
                                      for i in range(k)))
    sub = np.array([nozzles[perm[j]] for j in range(k)])
    labels[region] = sub[cl]
    return labels


def clean_labels(labels, region, min_feature_px: float):
    """Remove anything thinner than min_feature and give it to the nearest colour."""
    keep = np.zeros(labels.shape, dtype=bool)
    r = min_feature_px / 2
    min_area = math.pi * r * r * 1.5
    for c in np.unique(labels[region]):
        m = opening((labels == c) & region, r)
        lab, n = ndimage.label(m)
        if n:
            areas = ndimage.sum(m, lab, index=np.arange(1, n + 1))
            m &= ~np.isin(lab, np.nonzero(areas < min_area)[0] + 1)
        keep |= m
    if not keep[region].any():
        return labels
    _, (iy, ix) = ndimage.distance_transform_edt(~keep, return_indices=True)
    return np.where(region, np.where(keep, labels, labels[iy, ix]), -1)


# --------------------------------------------------------------------------- line art


def thin(mask: np.ndarray) -> np.ndarray:
    """Zhang-Suen thinning: reduce a mask to 1 px wide centre lines."""
    m = np.pad(mask.astype(np.uint8), 1)
    while True:
        changed = False
        for step in (0, 1):
            P = [np.roll(np.roll(m, -dy, 0), -dx, 1) for dy, dx in
                 ((-1, 0), (-1, 1), (0, 1), (1, 1), (1, 0), (1, -1), (0, -1), (-1, -1))]
            B = sum(P)
            A = sum(((P[i] == 0) & (P[(i + 1) % 8] == 1)).astype(np.uint8) for i in range(8))
            if step == 0:
                c = (P[0] * P[2] * P[4] == 0) & (P[2] * P[4] * P[6] == 0)
            else:
                c = (P[0] * P[2] * P[6] == 0) & (P[0] * P[4] * P[6] == 0)
            rm = (m == 1) & (B >= 2) & (B <= 6) & (A == 1) & c
            if rm.any():
                m[rm] = 0
                changed = True
        if not changed:
            return m[1:-1, 1:-1].astype(bool)


def trace_lines(skel: np.ndarray) -> list[np.ndarray]:
    """1 px wide skeleton -> list of pixel polylines (row, col), split at junctions."""
    nb = [(-1, -1), (-1, 0), (-1, 1), (0, -1), (0, 1), (1, -1), (1, 0), (1, 1)]
    pts = set(zip(*np.nonzero(skel)))

    def neigh(p):
        return [(p[0] + dy, p[1] + dx) for dy, dx in nb if (p[0] + dy, p[1] + dx) in pts]

    nodes = {p for p in pts if len(neigh(p)) != 2}
    used, lines = set(), []
    for start in list(nodes) + list(pts):  # nodes first, then leftover pure loops
        for nxt in neigh(start):
            if (start, nxt) in used:
                continue
            line, prev, cur = [start], start, nxt
            used.add((start, nxt))
            used.add((nxt, start))
            while True:
                line.append(cur)
                if cur in nodes or cur == start:
                    break
                cand = [q for q in neigh(cur) if q != prev and (cur, q) not in used]
                if not cand:
                    break
                prev, cur = cur, cand[0]
                used.add((prev, cur))
                used.add((cur, prev))
            lines.append(np.array(line, dtype=float))
    return lines


def line_art_strokes(fg, dark, px, bead, simplify_tol):
    """Dark batter: outline of the subject, thin dark features as single lines,
    big dark areas as a loop."""
    strokes = outline_strokes(fg, px, bead, simplify_tol)
    dark = dark & erode(fg, bead / px)  # not on top of the outline
    dark = opening(dark, 0.15 * bead / px)  # drop specks, keep thin lines (they print 1 bead wide)
    lab, n = ndimage.label(dark)
    if n:
        areas = ndimage.sum(dark, lab, index=np.arange(1, n + 1)) * px * px
        dark &= ~np.isin(lab, np.nonzero(areas < 1.5 * bead * bead)[0] + 1)
    thick = opening(dark, 1.5 * bead / px)  # wider than 3 beads: draw its edge
    strokes += outline_strokes(thick, px, bead, simplify_tol)
    thin_part = dark & ~dilate(thick, 0.5 * bead / px)
    if thin_part.any():
        for line in trace_lines(thin(thin_part)):
            p = (line[:, ::-1] + 0.5) * px  # (row, col) -> (x, y) mm
            if polyline_length(p) >= 1.5 * bead:
                strokes.append(Stroke(rdp(p, max(simplify_tol, 0.3))))
    return strokes


# --------------------------------------------------------------------------- step 3: toolpaths


def outline_strokes(mask, px, bead, simplify_tol):
    """Closed loops half a bead inside the region edge."""
    if contourpy is None:
        raise SystemExit("contourpy missing: pip install contourpy (comes with matplotlib)")
    inner = erode(mask, 0.5 * bead / px)
    if not inner.any():
        return []
    z = np.pad(inner, 1).astype(float)
    gen = contourpy.contour_generator(z=z, line_type="Separate")
    strokes = []
    for line in gen.lines(0.5):
        pts = (np.asarray(line) - 1 + 0.5) * px  # padded index -> mm (pixel centres)
        if len(pts) < 3 or polyline_length(pts) < 2 * bead:
            continue
        closed = np.allclose(pts[0], pts[-1])
        if closed:
            pts = pts[:-1]
        pts = rdp(np.vstack([pts, pts[:1]]) if closed else pts, simplify_tol)
        if closed:
            pts = pts[:-1]
        if len(pts) >= 2:
            strokes.append(Stroke(pts, closed=closed))
    return strokes


def _inside(mask, px, a, b, step):
    """True if the straight line a->b (mm) stays inside mask."""
    n = max(2, int(math.hypot(*(b - a)) / step) + 1)
    t = np.linspace(0, 1, n)[:, None]
    p = a + (b - a) * t
    ix = np.clip((p[:, 0] / px).astype(int), 0, mask.shape[1] - 1)
    iy = np.clip((p[:, 1] / px).astype(int), 0, mask.shape[0] - 1)
    return bool(mask[iy, ix].all())


def hatch_strokes(mask, px, bead, spacing, angle_deg, inset, max_link):
    """Zigzag fill of every blob of `mask`, lines about `spacing` apart."""
    region = erode(mask, inset / px)
    lab, n = ndimage.label(region)
    strokes = []
    for i in range(1, n + 1):
        strokes += _hatch_blob(lab == i, mask, px, bead, spacing, angle_deg, max_link)
    return strokes


def _hatch_blob(region, mask, px, bead, spacing, angle_deg, max_link):
    """Hatch one blob. The line grid is fitted to the blob so that the first and
    last line sit close to its edges (no slivers at the top and bottom)."""
    h, w = mask.shape
    th = math.radians(angle_deg)
    u = np.array([math.cos(th), math.sin(th)])     # along the hatch line
    nrm = np.array([-math.sin(th), math.cos(th)])  # across the lines
    iy, ix = np.nonzero(region)
    centres = np.stack([(ix + 0.5) * px, (iy + 0.5) * px], axis=1)
    cu, cn = centres @ u, centres @ nrm
    lo, hi = cn.min() + 0.3 * spacing, cn.max() - 0.3 * spacing
    if hi <= lo:
        offsets = np.array([(cn.min() + cn.max()) / 2])
    else:
        offsets = np.linspace(lo, hi, int(math.ceil((hi - lo) / spacing)) + 1)
    step = px / 2
    ts = np.arange(cu.min() - px, cu.max() + px + step, step)

    chains: list[dict] = []
    for k, d in enumerate(offsets):
        p = ts[:, None] * u + d * nrm
        ix = (p[:, 0] / px).astype(int)
        iy = (p[:, 1] / px).astype(int)
        ok = (ix >= 0) & (ix < w) & (iy >= 0) & (iy < h)
        v = np.zeros(len(ts), dtype=bool)
        v[ok] = region[iy[ok], ix[ok]]
        if not v.any():
            continue
        edges = np.diff(np.concatenate([[0], v.astype(int), [0]]))
        starts, ends = np.nonzero(edges == 1)[0], np.nonzero(edges == -1)[0] - 1
        segs = [(ts[s], ts[e]) for s, e in zip(starts, ends) if ts[e] - ts[s] >= 0.5 * bead]

        used = set()
        for t0, t1 in segs:
            best = None
            for ci, ch in enumerate(chains):
                if ch["line"] != k - 1 or ci in used:
                    continue
                end = ch["pts"][-1]
                # start the new segment at the end closer to the chain end
                e_t = end @ u
                a_t, b_t = (t0, t1) if abs(t0 - e_t) <= abs(t1 - e_t) else (t1, t0)
                start = a_t * u + d * nrm
                dist = math.hypot(*(start - end))
                if dist > max_link or not _inside(mask, px, end, start, px / 2):
                    continue
                if best is None or dist < best[0]:
                    best = (dist, ci, a_t, b_t)
            if best:
                _, ci, a_t, b_t = best
                chains[ci]["pts"] += [a_t * u + d * nrm, b_t * u + d * nrm]
                chains[ci]["line"] = k
                used.add(ci)
            else:
                # new chain; direction alternates with the line number
                a_t, b_t = (t0, t1) if k % 2 == 0 else (t1, t0)
                chains.append({"pts": [a_t * u + d * nrm, b_t * u + d * nrm], "line": k})
                used.add(len(chains) - 1)
    return [Stroke(np.array(c["pts"])) for c in chains]


def order_strokes(strokes, start):
    """Nearest-neighbour order; open strokes may be reversed, loops rotated."""
    left = list(strokes)
    out, pos = [], np.asarray(start, dtype=float)
    while left:
        best = None
        for i, s in enumerate(left):
            if s.closed:
                d = np.hypot(*(s.points - pos).T)
                j = int(np.argmin(d))
                cand = (d[j], i, "rot", j)
            else:
                d0 = math.hypot(*(s.points[0] - pos))
                d1 = math.hypot(*(s.points[-1] - pos))
                cand = (d0, i, "fwd", 0) if d0 <= d1 else (d1, i, "rev", 0)
            if best is None or cand[0] < best[0]:
                best = cand
        _, i, how, j = best
        s = left.pop(i)
        if how == "rot":
            pts = np.vstack([s.points[j:], s.points[:j], s.points[j:j + 1]])  # close the loop
        elif how == "rev":
            pts = s.points[::-1]
        else:
            pts = s.points
        out.append(Stroke(pts, closed=False))
        pos = pts[-1]
    return out, pos


# --------------------------------------------------------------------------- outputs


def write_svg(path, layers, w_mm, h_mm, bead, note):
    lines = [
        '<?xml version="1.0" encoding="UTF-8"?>',
        f'<svg xmlns="http://www.w3.org/2000/svg" width="{w_mm:.2f}mm" height="{h_mm:.2f}mm" '
        f'viewBox="0 0 {w_mm:.3f} {h_mm:.3f}">',
        f"<!-- {note} -->",
    ]
    for L in layers:
        lines.append(f'<g id="nozzle{L.nozzle}" data-nozzle="{L.nozzle}">')
        for s in L.strokes:
            d = "M " + " L ".join(f"{x:.2f} {y:.2f}" for x, y in s.points)
            lines.append(f'<path d="{d}" fill="none" stroke="{L.colour}" '
                         f'stroke-width="{bead:g}" stroke-linecap="round" stroke-linejoin="round"/>')
        lines.append("</g>")
    lines.append("</svg>")
    Path(path).write_text("\n".join(lines), encoding="utf-8")


def to_machine(p, h_mm, origin):
    """Image frame (y down) -> machine frame (y up), shifted by origin."""
    return [round(origin[0] + float(p[0]), 3), round(origin[1] + h_mm - float(p[1]), 3)]


def write_events(path, layers, h_mm, origin, dwell_s, stats):
    ev = []
    for n, L in enumerate(layers):
        if n > 0 and dwell_s > 0:
            ev.append({"type": "Dwell", "seconds": dwell_s})
        ev.append({"type": "SelectNozzle", "nozzle": L.nozzle})
        for s in L.strokes:
            x, y = to_machine(s.points[0], h_mm, origin)
            ev.append({"type": "Move", "x": x, "y": y})
            ev.append({"type": "ExtrudeOn"})
            for p in s.points[1:]:
                x, y = to_machine(p, h_mm, origin)
                ev.append({"type": "Move", "x": x, "y": y})
            ev.append({"type": "ExtrudeOff"})
    Path(path).write_text(json.dumps({"units": "mm", "frame": "machine, y up",
                                      "origin": list(origin), "stats": stats,
                                      "events": ev}, indent=1), encoding="utf-8")
    return ev


def render(layers, w_mm, h_mm, bead, scale, travel=True, bg=(60, 60, 60), reverse=False):
    """Draw the beads in print order (reverse=True: seen from the griddle side, the first
    batter on top); travel moves as thin lines on top.
    Drawn at 4x and scaled down, so bead overlaps are not lost to rounding."""
    ss = 4
    out_size = (int(round(w_mm * scale)), int(round(h_mm * scale)))
    scale = scale * ss
    W, H = int(round(w_mm * scale)), int(round(h_mm * scale))
    img = Image.new("RGB", (W, H), bg)
    dr = ImageDraw.Draw(img)
    r = bead * scale / 2
    moves, prev = [], None
    for L in (layers[::-1] if reverse else layers):
        col = hex_to_rgb(L.colour)
        for s in L.strokes:
            pts = [(float(x) * scale, float(y) * scale) for x, y in s.points]
            dr.line(pts, fill=col, width=max(1, int(round(bead * scale))), joint="curve")
            for x, y in (pts[0], pts[-1]):
                dr.ellipse([x - r, y - r, x + r, y + r], fill=col)
            if prev is not None:
                moves.append((prev, pts[0]))
            prev = pts[-1]
    if travel:
        for a, b in moves:
            dr.line([a, b], fill=(120, 170, 255), width=ss)
    return img.resize(out_size, Image.LANCZOS)


def write_preview(path, original, labels, layers, w_mm, h_mm, bead, batter_rgb, mirror):
    size = 420
    scale = size / max(w_mm, h_mm)
    pal = np.array(list(batter_rgb) + [(60, 60, 60)], dtype=np.uint8)
    q = pal[np.where(labels < 0, 3, labels)]
    quant = Image.fromarray(q).resize((int(w_mm * scale), int(h_mm * scale)), Image.NEAREST)
    griddle = render(layers, w_mm, h_mm, bead, scale, travel=True)
    flipped = render(layers, w_mm, h_mm, bead, scale, travel=False, reverse=True)
    flipped = ImageOps.mirror(flipped) if mirror else flipped
    quant_seen = ImageOps.mirror(quant) if mirror else quant
    orig = original.copy()
    orig.thumbnail((size, size))
    panels = [("photo", orig), ("3 colours", quant_seen),
              ("on the griddle, blue = travel", griddle), ("after flipping", flipped)]
    pad, top = 10, 24
    W = sum(p.size[0] for _, p in panels) + pad * (len(panels) + 1)
    H = max(p.size[1] for _, p in panels) + top + pad
    sheet = Image.new("RGB", (W, H), (255, 255, 255))
    dr = ImageDraw.Draw(sheet)
    x = pad
    for title, p in panels:
        sheet.paste(p, (x, top))
        dr.text((x, 6), title, fill=(0, 0, 0))
        x += p.size[0] + pad
    sheet.save(path)
    return sheet


# --------------------------------------------------------------------------- main


def make_pancake(args):
    batter = [c.strip() for c in args.batter.split(",")]
    if len(batter) != 3:
        raise SystemExit("--batter needs exactly 3 colours, one per syringe (nozzle 0,1,2)")
    batter_rgb = [hex_to_rgb(c) for c in batter]
    batter_L = rgb_to_lab(np.array(batter_rgb, dtype=float))[:, 0]
    dark = int(np.argmin(batter_L))
    minf = args.min_feature / args.px

    rgb, inside, alpha, img = load_raster(Path(args.image), args.width, args.px, args.shape)
    h_px, w_px = inside.shape
    w_mm, h_mm = w_px * args.px, h_px * args.px

    # 1. subject mask
    if args.background == "remove":
        fg, how = foreground_mask(img, rgb, inside, alpha, args.px)
        fg = ndimage.binary_fill_holes(opening(fg, minf / 2)) & inside
        print(f"background removed with {how}")
    else:
        fg = inside & (alpha if alpha is not None else True)
    if not fg.any():
        raise SystemExit("nothing left after background removal; try --background keep")
    if not args.no_mirror:  # the pancake is flipped: print the mirror image
        rgb, inside, fg = rgb[:, ::-1], inside[:, ::-1], fg[:, ::-1]

    # 2. colours
    line_strokes = []
    if args.style == "lineart":
        fill_nozzles = [n for n in range(3) if n != dark]
        labels = clean_labels(split_colours(rgb, fg, fill_nozzles, batter_rgb, args.match), fg, minf)
        tones = split_colours(rgb, fg, [0, 1, 2], batter_rgb, "lightness")
        dark_mask = tones == dark  # darkest of 3 tones = dark features
        line_strokes = line_art_strokes(fg, dark_mask, args.px, args.bead, args.simplify)
        fill_region = erode(fg, 0.8 * args.bead / args.px)  # fill stays inside the outline
        design = labels.copy()
        design[fg & (dark_mask | ~erode(fg, args.bead / args.px))] = dark
    else:
        labels = clean_labels(split_colours(rgb, fg, [0, 1, 2], batter_rgb, args.match), fg, minf)
        fill_region, design = fg, labels

    # 3. toolpaths, in print order (default: darkest batter first)
    order = [int(o) for o in args.order.split(",")] if args.order else \
        [int(i) for i in np.argsort(batter_L)]
    layers, pos = [], np.array([0.0, h_mm])  # start near machine origin (lower left)
    for nz in order:
        layer = ColourLayer(nozzle=nz, colour=batter[nz], mask=labels == nz)
        if args.style == "lineart" and nz == dark:
            layer.strokes, pos = order_strokes(line_strokes, pos)
        else:
            mask = (labels == nz) & fill_region
            if mask.any():
                outl = [] if args.no_outline else outline_strokes(mask, args.px, args.bead,
                                                                  args.simplify)
                # hatch ends overlap the loop a little, batter needs to merge
                inset = 0.8 * args.bead if outl else 0.5 * args.bead
                hat = hatch_strokes(mask, args.px, args.bead, args.bead * args.spacing,
                                    args.angle, inset, max_link=3 * args.bead)
                outl, pos = order_strokes(outl, pos)
                hat, pos = order_strokes(hat, pos)
                layer.strokes = outl + hat
        layers.append(layer)

    # stats: batter volume and plunger travel per syringe
    bead_area = math.pi / 4 * args.bead * args.bead_height  # elliptic bead cross section
    stats = {"pancake_mm": [round(w_mm, 1), round(h_mm, 1)], "print_order": order,
             "bead_mm": args.bead, "bead_height_mm": args.bead_height, "syringes": {}}
    total_t = 0.0
    for L in layers:
        vol = L.length * bead_area
        stats["syringes"][str(L.nozzle)] = {
            "colour": L.colour, "strokes": len(L.strokes), "path_mm": round(L.length, 1),
            "batter_ml": round(vol / 1000, 2),
            "plunger_mm": round(vol / args.syringe_mm3_per_mm, 2)}
        total_t += L.length / args.speed
    stats["extrude_time_s"] = round(total_t + args.dwell * max(0, len(layers) - 1), 0)
    stats["plunger_mm_per_path_mm"] = round(bead_area / args.syringe_mm3_per_mm, 5)

    out = Path(args.output)
    out.mkdir(parents=True, exist_ok=True)
    stem = Path(args.image).stem
    note = (f"made by image_to_pancake.py from {Path(args.image).name}: {w_mm:.0f}x{h_mm:.0f} mm, "
            f"bead {args.bead} mm, style {args.style}, mirrored={not args.no_mirror}, "
            f"print order {order}. Print with design.fit_to_print_area: false")
    svg_path = out / f"{stem}.svg"
    write_svg(svg_path, layers, w_mm, h_mm, args.bead, note)
    write_events(out / f"{stem}.events.json", layers, h_mm, args.origin, args.dwell, stats)
    sheet = write_preview(out / f"{stem}_preview.png", img, design, layers, w_mm, h_mm,
                          args.bead, batter_rgb, not args.no_mirror)

    print(f"{svg_path}  ({w_mm:.0f} x {h_mm:.0f} mm, print order {order})")
    for nz, st in stats["syringes"].items():
        role = "line art" if args.style == "lineart" and int(nz) == dark else "fill"
        print(f"  syringe {nz} {st['colour']} ({role}): {st['strokes']:3d} strokes, "
              f"{st['path_mm']:6.0f} mm path, {st['batter_ml']:5.1f} ml, "
              f"{st['plunger_mm']:5.2f} mm plunger")
    print(f"  about {stats['extrude_time_s']:.0f} s of extrusion at {args.speed} mm/s "
          f"(incl. {args.dwell} s per colour change)")
    if args.show:
        sheet.show()
    return svg_path, layers, stats


def build_parser():
    p = argparse.ArgumentParser(description=__doc__.split("\n\n")[0],
                                formatter_class=argparse.ArgumentDefaultsHelpFormatter)
    p.add_argument("image", help="photo or drawing (jpg, png, ...)")
    p.add_argument("-o", "--output", default="out", help="output folder")
    p.add_argument("--width", type=float, default=100.0, help="pancake width in mm")
    p.add_argument("--shape", choices=["circle", "rect"], default="rect",
                   help="circle crops the centre square to a round pancake")
    p.add_argument("--style", choices=["lineart", "tones"], default="lineart",
                   help="lineart: darkest batter draws outline and dark features, the other two "
                        "fill. tones: all three batters fill")
    p.add_argument("--background", choices=["remove", "keep"], default="remove")
    p.add_argument("--batter", default=",".join(DEFAULT_BATTER),
                   help="batter colour in syringe 0,1,2; keep equal to the nozzle colours "
                        "in the machine config")
    p.add_argument("--match", choices=["lightness", "color"], default="lightness",
                   help="lightness: dark tone to dark batter. color: nearest batter colour")
    p.add_argument("--order", default="", help="print order, e.g. 0,1,2 (default darkest first)")
    p.add_argument("--no-mirror", action="store_true",
                   help="do not mirror (the pancake is flipped, so mirroring is normally right)")
    p.add_argument("--bead", type=float, default=3.0, help="bead width in mm")
    p.add_argument("--bead-height", type=float, default=1.5, help="bead height in mm")
    p.add_argument("--spacing", type=float, default=0.9,
                   help="hatch line spacing in bead widths (<1 overlaps the beads)")
    p.add_argument("--angle", type=float, default=0.0, help="hatch angle in degrees")
    p.add_argument("--no-outline", action="store_true", help="fill colours: hatch only, no loop")
    p.add_argument("--min-feature", type=float, default=3.0,
                   help="drop features thinner than this (mm)")
    p.add_argument("--simplify", type=float, default=0.3, help="simplify tolerance (mm)")
    p.add_argument("--px", type=float, default=0.25, help="raster resolution (mm per pixel)")
    p.add_argument("--dwell", type=float, default=20.0, help="seconds between colours")
    p.add_argument("--speed", type=float, default=15.0, help="print speed for the time estimate")
    p.add_argument("--origin", type=float, nargs=2, default=[0.0, 0.0], metavar=("X", "Y"),
                   help="machine position (mm) of the pancake's lower left corner")
    p.add_argument("--syringe-mm3-per-mm", type=float, default=DEFAULT_SYRINGE_MM3_PER_MM,
                   help="batter volume per mm of plunger travel")
    p.add_argument("--seed", type=int, default=0)
    p.add_argument("--show", action="store_true", help="open the preview")
    return p


def main(argv=None):
    make_pancake(build_parser().parse_args(argv))


if __name__ == "__main__":
    main()
