"""Chart geometry (spec/scene-additions.md §1a): resolved data -> a flat list of drawing operations.

Pure and font-independent: text width is an estimate, so the plot area does not depend on metrics. The editor
has a line-by-line twin in ``frontend/src/editor/canvas/chartGeometry.ts``; both are held to the same output by
``spec/fixtures/chart.fixtures.json``. Keep them in step and regenerate with
``python -m snapfile_render.tools.chart_fixtures --update``.

Operations (pt, y down, origin = node top left), in drawing order:

- ``{"op":"rect","x","y","w","h","fill"}``
- ``{"op":"line","pts":[x0,y0,x1,y1,...],"stroke","width"}``
- ``{"op":"path","d":[["M",x,y],["L",x,y],["C",x1,y1,x2,y2,x,y],["Z"]],"fill","fillOpacity","stroke","width"}``
- ``{"op":"circle","cx","cy","r","fill","stroke","width"}``
- ``{"op":"arc","cx","cy","outer","inner","start","end","full","fill"}``, degrees clockwise from 12 o'clock
- ``{"op":"text","text","x","y","anchor","color","size","weight"}``, ``y`` is the baseline
"""

from __future__ import annotations

import math
from typing import Any

CHART_TYPES = frozenset(
    {"donut", "pie", "bar", "barStacked", "barHorizontal", "barHorizontalStacked", "line", "area", "scatter", "radar"}
)
ROUND_TYPES = frozenset({"donut", "pie"})
PALETTE = ["#002C61", "#FFBB00", "#6BA460", "#00878E"]
VALUE_LIMIT = 1e15
ELLIPSIS = "…"
NBSP = " "

GRID_COLOR = "#E5E7EB"
AXIS_COLOR = "#9CA3AF"
AXIS_TEXT = "#6B7280"
LEGEND_TEXT = "#374151"
MIN_W = 60.0
MIN_H = 40.0
AXIS_WEIGHT = 400


def r3(value: float) -> float:
    return math.floor(value * 1000 + 0.5) / 1000


def clamp(value: float, lo: float, hi: float) -> float:
    return max(lo, min(hi, value))


# ---------------------------------------------------------------------- text estimate
_NARROW = set("iljI.,:;'|!` ")
_MEDIUM = set('ftr()[]{}-/\\"*')
_WIDE = set("mwMW@%ЖМФШЩЫЮ")
_WIDE_LOWER = set("жмфшщыю")


def _char_width(ch: str) -> float:
    c = ord(ch)
    if ch in _NARROW:
        return 0.32
    if ch in _MEDIUM:
        return 0.42
    if ch in _WIDE:
        return 0.98
    if ch in _WIDE_LOWER:
        return 0.82
    if c > 0xFFFF or 0x2E80 <= c <= 0x9FFF or 0xAC00 <= c <= 0xD7AF or 0xF900 <= c <= 0xFAFF or 0xFF00 <= c <= 0xFFEF:
        return 1.05
    if 65 <= c <= 90 or 0x410 <= c <= 0x42F or c == 0x401:
        return 0.76
    return 0.62


def text_width(text: str, size: float) -> float:
    return sum(_char_width(ch) for ch in text) * size


def truncate(text: str, size: float, limit: float) -> str:
    """Cut with an ellipsis to fit ``limit``; empty when even the ellipsis does not fit."""
    if text_width(text, size) <= limit:
        return text
    room = limit - text_width(ELLIPSIS, size)
    if room < 0:
        return ""
    used = 0.0
    out = ""
    for ch in text:
        used += _char_width(ch) * size
        if used > room:
            break
        out += ch
    return out.rstrip() + ELLIPSIS


def format_number(value: float, decimals: int | None, locale: str) -> str:
    """Grouped number. ``decimals`` None: up to two, trailing zeros dropped."""
    ru = str(locale or "").lower().startswith("ru")
    places = 2 if decimals is None else int(clamp(float(decimals), 0, 6))
    power = 10.0**places
    scaled = float(math.floor(abs(value) * power + 0.5))
    whole = float(math.floor(scaled / power))
    frac = int(scaled - whole * power)
    groups: list[str] = []
    while whole >= 1000:
        groups.insert(0, str(int(whole % 1000)).rjust(3, "0"))
        whole = float(math.floor(whole / 1000))
    groups.insert(0, str(int(whole)))
    text = (NBSP if ru else ",").join(groups)
    if places:
        tail = str(frac).rjust(places, "0")
        if decimals is None:
            tail = tail.rstrip("0")
        if tail:
            text += ("," if ru else ".") + tail
    return ("-" if value < 0 and scaled > 0 else "") + text


# ---------------------------------------------------------------------- options
def _dict(value: Any) -> dict[str, Any]:
    return value if isinstance(value, dict) else {}


def _number(value: Any) -> float | None:
    if isinstance(value, bool) or not isinstance(value, (int, float)):
        return None
    return float(value) if math.isfinite(value) else None


def _number_or(value: Any, default: float) -> float:
    parsed = _number(value)
    return parsed if parsed is not None else default


def _pos(value: Any, default: float) -> float:
    parsed = _number(value)
    return parsed if parsed is not None and parsed > 0 else default


def _color(value: Any, default: str) -> str:
    return value if isinstance(value, str) and value else default


class _Options:
    def __init__(self, inp: dict[str, Any]) -> None:
        kind = inp["chartType"]
        self.kind = kind
        self.w = float(inp["w"])
        self.h = float(inp["h"])
        self.locale = str(inp.get("locale") or "en")
        labels = _dict(inp.get("labels"))
        self.labels = labels
        self.show_labels = labels.get("show") is not False if kind in ROUND_TYPES else labels.get("show") is True
        self.size = _pos(labels.get("fontSize"), clamp(min(self.w, self.h) / 26, 7.0, 11.0))
        self.weight = int(_pos(labels.get("fontWeight"), 800 if kind in ROUND_TYPES else 600))
        self.decimals = _number(labels.get("decimals"))
        self.prefix = str(labels.get("prefix") or "")
        self.suffix = str(labels.get("suffix") or "")
        self.outside_color = _color(labels.get("outsideColor"), "#374151")
        self.inside_color = _color(labels.get("insideColor"), "#FFFFFF")
        fits = self.w >= MIN_W and self.h >= MIN_H
        legend = _dict(inp.get("legend"))
        self.legend_show = fits and legend.get("show") is True
        self.legend_pos = legend.get("position") if legend.get("position") in ("top", "right", "left") else "bottom"
        self.legend_color = _color(legend.get("color"), LEGEND_TEXT)
        axes = _dict(inp.get("axes"))
        self.axes = axes
        self.axes_show = fits and axes.get("show") is not False
        self.axis_color = _color(axes.get("color"), AXIS_COLOR)
        self.axis_text = _color(axes.get("labelColor"), AXIS_TEXT)
        grid = _dict(inp.get("grid"))
        self.grid_show = grid.get("show") is not False
        self.grid_color = _color(grid.get("color"), GRID_COLOR)
        self.grid_width = _pos(grid.get("width"), 0.5)
        self.bar_gap = clamp(_number_or(inp.get("barGap"), 0.3), 0.0, 0.95)
        self.line_width = _pos(inp.get("lineWidth"), 2.0)
        self.smooth = inp.get("smooth") is True
        self.fill_opacity = clamp(_number_or(inp.get("fillOpacity"), 0.3), 0.0, 1.0)
        markers = _dict(inp.get("markers"))
        if kind in ("line", "radar"):
            self.markers = markers.get("show") is not False
        else:
            self.markers = kind == "scatter" or (kind == "area" and markers.get("show") is True)
        self.marker_r = _pos(markers.get("size"), 8.0 if kind == "scatter" else 6.0) / 2

    def value_text(self, value: float, decimals: int | None = None) -> str:
        places = int(self.decimals) if self.decimals is not None else decimals
        return self.prefix + format_number(value, places, self.locale) + self.suffix


class _Out:
    """Collects operations; text is kept inside the node box or dropped."""

    def __init__(self, w: float, h: float) -> None:
        self.w = w
        self.h = h
        self.ops: list[dict[str, Any]] = []

    def rect(self, x: float, y: float, w: float, h: float, fill: str) -> None:
        self.ops.append({"op": "rect", "x": r3(x), "y": r3(y), "w": r3(w), "h": r3(h), "fill": fill})

    def line(self, pts: list[float], stroke: str, width: float) -> None:
        self.ops.append({"op": "line", "pts": [r3(p) for p in pts], "stroke": stroke, "width": r3(width)})

    def path(self, d: list[list[Any]], fill: str | None, fill_opacity: float, stroke: str | None, width: float) -> None:
        self.ops.append(
            {
                "op": "path",
                "d": [[seg[0], *[r3(v) for v in seg[1:]]] for seg in d],
                "fill": fill,
                "fillOpacity": r3(fill_opacity),
                "stroke": stroke,
                "width": r3(width),
            }
        )

    def circle(self, cx: float, cy: float, r: float, fill: str | None, stroke: str | None, width: float) -> None:
        self.ops.append(
            {"op": "circle", "cx": r3(cx), "cy": r3(cy), "r": r3(r), "fill": fill, "stroke": stroke, "width": r3(width)}
        )

    def arc(
        self, cx: float, cy: float, outer: float, inner: float, start: float, end: float, full: bool, fill: str
    ) -> None:
        self.ops.append(
            {
                "op": "arc",
                "cx": r3(cx),
                "cy": r3(cy),
                "outer": r3(outer),
                "inner": r3(inner),
                "start": r3(start),
                "end": r3(end),
                "full": full,
                "fill": fill,
            }
        )

    def text(self, text: str, x: float, y: float, anchor: str, color: str, size: float, weight: int) -> None:
        tw = text_width(text, size)
        if not text or size > self.h or tw > self.w:
            return
        left = x if anchor == "start" else (x - tw if anchor == "end" else x - tw / 2)
        x += clamp(left, 0.0, self.w - tw) - left
        y = clamp(y, size * 0.85, self.h - size * 0.25)
        self.ops.append(
            {
                "op": "text",
                "text": text,
                "x": r3(x),
                "y": r3(y),
                "anchor": anchor,
                "color": color,
                "size": r3(size),
                "weight": weight,
            }
        )


# ---------------------------------------------------------------------- legend
def _legend(out: _Out, opt: _Options, items: list[dict[str, str]]) -> tuple[float, float, float, float]:
    """Draw the legend and return the box left for the chart (x, y, w, h)."""
    w, h = opt.w, opt.h
    items = [it for it in items if it["name"]]
    if not opt.legend_show or not items:
        return 0.0, 0.0, w, h
    size = opt.size
    mark = size * 0.8
    gap = size * 0.4
    item_gap = size * 1.2
    row_h = size * 1.5
    pos = opt.legend_pos
    if pos in ("top", "bottom"):
        rows: list[list[tuple[str, str, float]]] = [[]]
        used = 0.0
        for it in items:
            name = truncate(it["name"], size, max(0.0, w - mark - gap))
            iw = mark + gap + text_width(name, size)
            if rows[-1] and used + item_gap + iw > w:
                rows.append([])
                used = 0.0
            used += iw + (item_gap if len(rows[-1]) else 0.0)
            rows[-1].append((name, it["color"], iw))
        max_rows = max(1, math.floor(h * 0.3 / row_h))
        rows = rows[:max_rows]
        total = len(rows) * row_h
        top = 0.0 if pos == "top" else h - total
        for ri, row in enumerate(rows):
            row_w = sum(c[2] for c in row) + item_gap * (len(row) - 1)
            x = (w - row_w) / 2
            y = top + ri * row_h
            for name, color, iw in row:
                out.rect(x, y + (row_h - mark) / 2, mark, mark, color)
                out.text(
                    name, x + mark + gap, y + row_h / 2 + size * 0.35, "start", opt.legend_color, size, AXIS_WEIGHT
                )
                x += iw + item_gap
        reserve = total + size * 0.5
        return (0.0, reserve, w, h - reserve) if pos == "top" else (0.0, 0.0, w, h - reserve)
    col = min(max(text_width(it["name"], size) for it in items) + mark + gap, w * 0.35)
    limit = max(0.0, col - mark - gap)
    max_rows = max(1, math.floor(h / row_h))
    shown = items[:max_rows]
    y = (h - len(shown) * row_h) / 2
    x = 0.0 if pos == "left" else w - col
    for it in shown:
        out.rect(x, y + (row_h - mark) / 2, mark, mark, it["color"])
        out.text(
            truncate(it["name"], size, limit),
            x + mark + gap,
            y + row_h / 2 + size * 0.35,
            "start",
            opt.legend_color,
            size,
            AXIS_WEIGHT,
        )
        y += row_h
    reserve = col + size * 0.5
    return (reserve, 0.0, w - reserve, h) if pos == "left" else (0.0, 0.0, w - reserve, h)


# ---------------------------------------------------------------------- scales
class _Scale:
    def __init__(self, lo: float, hi: float, ticks: list[float], decimals: int | None) -> None:
        self.lo = lo
        self.hi = hi
        self.ticks = ticks
        self.decimals = decimals

    def at(self, value: float, a: float, b: float) -> float:
        return a + (clamp(value, self.lo, self.hi) - self.lo) / (self.hi - self.lo) * (b - a)


def _round_to(value: float, places: int) -> float:
    power = 10.0**places
    return math.floor(value * power + 0.5) / power


def _scale(lo: float, hi: float, min_v: float | None, max_v: float | None, nice: bool, count: float | None) -> _Scale:
    if lo > hi:
        lo, hi = 0.0, 1.0
    if lo == hi:
        if lo == 0:
            hi = 1.0
        elif lo > 0:
            lo = 0.0
        else:
            hi = 0.0
    use_min, use_max = min_v is not None, max_v is not None
    a = min_v if min_v is not None else lo
    b = max_v if max_v is not None else hi
    if a >= b:
        a, b, use_min, use_max = lo, hi, False, False
    n = int(clamp(count if count is not None else 5.0, 2.0, 20.0))
    if not nice:
        ticks = [a + (b - a) * i / (n - 1) for i in range(n)]
        return _Scale(a, b, ticks, None)
    raw = (b - a) / (n - 1)
    exp = math.floor(math.log10(raw))
    base = 10.0**exp
    f = raw / base
    mult = 1.0 if f <= 1 else (2.0 if f <= 2 else (5.0 if f <= 5 else 10.0))
    step = mult * base
    places = max(0, -(exp + 1 if mult == 10 else exp))
    if not use_min:
        a = math.floor(a / step + 1e-9) * step
    if not use_max:
        b = math.ceil(b / step - 1e-9) * step
    first = math.ceil(a / step - 1e-9)
    ticks = []
    i = 0
    while i < 200:
        t = (first + i) * step
        if t > b + step * 1e-9:
            break
        ticks.append(_round_to(t, places) if places < 12 else t)
        i += 1
    return _Scale(a, b, ticks, places)


def _value_scale(opt: _Options, lo: float, hi: float) -> _Scale:
    axes = opt.axes
    return _scale(
        lo,
        hi,
        _number(axes.get("min")),
        _number(axes.get("max")),
        axes.get("nice") is not False,
        _number(axes.get("tickCount")),
    )


def _x_scale(opt: _Options, lo: float, hi: float) -> _Scale:
    axes = opt.axes
    return _scale(
        lo,
        hi,
        _number(axes.get("xMin")),
        _number(axes.get("xMax")),
        axes.get("nice") is not False,
        _number(axes.get("tickCount")),
    )


def _stride(longest: float, slot: float) -> int:
    return max(1, math.ceil((longest + 4) / slot)) if slot > 0 else 1


def _monotone(pts: list[tuple[float, float]]) -> list[list[Any]]:
    """Cubic segments through the points that never overshoot them, so the curve stays inside the plot."""
    n = len(pts)
    slopes = []
    for i in range(n - 1):
        dx = pts[i + 1][0] - pts[i][0]
        slopes.append((pts[i + 1][1] - pts[i][1]) / dx if dx != 0 else 0.0)
    tang = [slopes[0]] + [0.0] * (n - 2) + [slopes[-1]]
    for i in range(1, n - 1):
        a, b = slopes[i - 1], slopes[i]
        tang[i] = 0.0 if a * b <= 0 else 2 * a * b / (a + b)
    d: list[list[Any]] = []
    for i in range(n - 1):
        (x0, y0), (x1, y1) = pts[i], pts[i + 1]
        third = (x1 - x0) / 3
        d.append(["C", x0 + third, y0 + tang[i] * third, x1 - third, y1 - tang[i + 1] * third, x1, y1])
    return d


def _trace(pts: list[tuple[float, float]], smooth: bool) -> list[list[Any]]:
    if smooth and len(pts) > 2:
        return _monotone(pts)
    return [["L", p[0], p[1]] for p in pts[1:]]


def _runs(points: list[tuple[float, float] | None]) -> list[list[tuple[float, float]]]:
    """Runs of consecutive present points: a missing value breaks the line."""
    runs: list[list[tuple[float, float]]] = [[]]
    for p in points:
        if p is None:
            if runs[-1]:
                runs.append([])
        else:
            runs[-1].append(p)
    return [r for r in runs if r]


# ---------------------------------------------------------------------- cartesian
def _shape_data(inp: dict[str, Any]) -> tuple[list[str], list[dict[str, Any]], int, bool]:
    series = [s for s in (inp.get("series") or []) if isinstance(s, dict)]
    categories = [str(c) for c in (inp.get("categories") or [])]
    n = max([len(categories)] + [len(s.get("values") or []) for s in series])
    categories = categories + [""] * (n - len(categories))
    shaped = []
    has_value = False
    for i, s in enumerate(series):
        values = list(s.get("values") or [])
        values = [v if isinstance(v, (int, float)) and not isinstance(v, bool) else None for v in values]
        values += [None] * (n - len(values))
        has_value = has_value or any(v is not None for v in values)
        shaped.append(
            {
                "name": str(s.get("name") or ""),
                "color": s.get("color") or _palette(inp)[i % len(_palette(inp))],
                "values": values,
                "colors": s.get("colors"),
                "xs": s.get("xs"),
            }
        )
    return categories, shaped, n, has_value


def _palette(inp: dict[str, Any]) -> list[str]:
    return inp.get("palette") or PALETTE


def _cartesian(inp: dict[str, Any]) -> dict[str, Any]:
    opt = _Options(inp)
    kind = opt.kind
    horizontal = kind in ("barHorizontal", "barHorizontalStacked")
    stacked = kind in ("barStacked", "barHorizontalStacked")
    is_bar = kind in ("bar", "barStacked", "barHorizontal", "barHorizontalStacked")
    scatter = kind == "scatter"
    categories, series, n, has_value = _shape_data(inp)
    if not has_value:
        categories, series, n = [], [], 0
    out = _Out(opt.w, opt.h)
    size = opt.size
    bx, by, bw, bh = _legend(out, opt, [{"name": s["name"], "color": s["color"]} for s in series])

    # value domain
    lows: list[float] = []
    highs: list[float] = []
    if stacked:
        for i in range(n):
            lows.append(sum(s["values"][i] for s in series if s["values"][i] is not None and s["values"][i] < 0))
            highs.append(sum(s["values"][i] for s in series if s["values"][i] is not None and s["values"][i] > 0))
    else:
        for s in series:
            for v in s["values"]:
                if v is not None:
                    lows.append(v)
                    highs.append(v)
    lo = min(lows) if lows else 0.0
    hi = max(highs) if highs else 1.0
    if is_bar or kind == "area":
        lo, hi = min(lo, 0.0), max(hi, 0.0)
    vs = _value_scale(opt, float(lo), float(hi))
    negative = float(lo) < 0
    xs_data: list[list[float | None]] = []
    xscale = None
    if scatter:
        all_x: list[float] = []
        for s in series:
            raw = s["xs"] if isinstance(s["xs"], list) else []
            xs = [(float(raw[i]) if i < len(raw) and _number(raw[i]) is not None else float(i + 1)) for i in range(n)]
            xs_data.append(list(xs))
            all_x += [x for x, v in zip(xs, s["values"], strict=True) if v is not None]
        xscale = _x_scale(opt, min(all_x) if all_x else 0.0, max(all_x) if all_x else 1.0)

    # margins
    pad = max(opt.marker_r + 0.5 if opt.markers else 0.0, opt.line_width / 2 if not is_bar else 0.0, 1.0)
    val_labels = [opt.value_text(t, vs.decimals) for t in vs.ticks]
    label_room = size + 3 if opt.show_labels and not stacked else 0.0
    max_tick_w = max([text_width(t, size) for t in val_labels], default=0.0)
    if horizontal:
        cat_w = min(max([text_width(c, size) for c in categories], default=0.0), bw * 0.35)
        left = (cat_w + 4 if opt.axes_show and n else 0.0) + pad
        bottom = size * 1.5 if opt.axes_show else pad
        top = max(pad, size * 0.6 if opt.axes_show else 0.0)
        right = max(pad, max_tick_w / 2 if opt.axes_show else 0.0)
        if opt.show_labels and not stacked:
            longest = max(
                [text_width(opt.value_text(v), size) for s in series for v in s["values"] if v is not None], default=0.0
            )
            room = min(longest + 4, bw * 0.25)
            right = max(right, room)
            if negative:
                left += room
    else:
        tick_w = min(max_tick_w, bw * 0.3)
        left = tick_w + 4 + pad if opt.axes_show else pad
        bottom = size * 1.5 if opt.axes_show else pad
        top = max(pad, size * 0.6 if opt.axes_show else 0.0) + label_room
        right = pad
        if scatter and opt.axes_show and xscale is not None:
            right = max(
                pad, max([text_width(opt.value_text(t, xscale.decimals), size) for t in xscale.ticks], default=0.0) / 2
            )
        if negative and opt.show_labels and is_bar and not stacked:
            bottom += label_room
    px, py = bx + left, by + top
    pw, ph = bw - left - right, bh - top - bottom
    axes_show = opt.axes_show
    if pw < 8 or ph < 8:
        axes_show = False
        px, py, pw, ph = bx + pad, by + pad, bw - 2 * pad, bh - 2 * pad
    if pw < 1 or ph < 1:
        return {"ops": out.ops, "empty": not has_value, "plot": None}
    x1, y1 = px + pw, py + ph

    # grid
    if opt.grid_show:
        for t in vs.ticks:
            if horizontal:
                x = vs.at(t, px, x1)
                out.line([x, py, x, y1], opt.grid_color, opt.grid_width)
            else:
                y = vs.at(t, y1, py)
                out.line([px, y, x1, y], opt.grid_color, opt.grid_width)
        if xscale is not None:
            for t in xscale.ticks:
                x = xscale.at(t, px, x1)
                out.line([x, py, x, y1], opt.grid_color, opt.grid_width)

    slot = (ph if horizontal else pw) / n if n else 0.0
    zero = clamp(0.0, vs.lo, vs.hi)
    texts: list[tuple[str, float, float, str, str]] = []

    if is_bar:
        m = len(series) or 1
        group = slot * (1 - opt.bar_gap)
        thick = group if stacked else group / m
        for i in range(n):
            base = (py if horizontal else px) + slot * i + (slot - group) / 2
            pos_sum = 0.0
            neg_sum = 0.0
            for si, s in enumerate(series):
                v = s["values"][i]
                if v is None:
                    continue
                colors = s["colors"]
                color = (colors[i] if isinstance(colors, list) and i < len(colors) and colors[i] else None) or s[
                    "color"
                ]
                if stacked:
                    start = pos_sum if v >= 0 else neg_sum
                    end = start + v
                    if v >= 0:
                        pos_sum = end
                    else:
                        neg_sum = end
                    offset = base
                else:
                    start, end = 0.0, v
                    offset = base + thick * si
                if horizontal:
                    a, b = vs.at(start, px, x1), vs.at(end, px, x1)
                    if abs(b - a) >= 0.01:
                        out.rect(min(a, b), offset, abs(b - a), thick, color)
                    cy = offset + thick / 2
                    label = opt.value_text(v)
                    if stacked:
                        if abs(b - a) >= text_width(label, size) + 2 and thick >= size:
                            texts.append((label, (a + b) / 2, cy + size * 0.35, "middle", opt.inside_color))
                    elif v >= 0:
                        texts.append((label, b + 3, cy + size * 0.35, "start", opt.outside_color))
                    else:
                        texts.append((label, b - 3, cy + size * 0.35, "end", opt.outside_color))
                else:
                    a, b = vs.at(start, y1, py), vs.at(end, y1, py)
                    if abs(b - a) >= 0.01:
                        out.rect(offset, min(a, b), thick, abs(b - a), color)
                    cx = offset + thick / 2
                    label = opt.value_text(v)
                    if stacked:
                        if abs(b - a) >= size * 1.1 and thick >= text_width(label, size) + 2:
                            texts.append((label, cx, (a + b) / 2 + size * 0.35, "middle", opt.inside_color))
                    elif v >= 0:
                        texts.append((label, cx, b - 3, "middle", opt.outside_color))
                    else:
                        texts.append((label, cx, b + size + 2, "middle", opt.outside_color))
    else:
        base_y = vs.at(zero, y1, py)
        for si, s in enumerate(series):
            points: list[tuple[float, float] | None] = []
            for i in range(n):
                v = s["values"][i]
                if v is None:
                    points.append(None)
                    continue
                if scatter:
                    x_val = xs_data[si][i]
                    assert xscale is not None and x_val is not None
                    if not (xscale.lo <= x_val <= xscale.hi and vs.lo <= v <= vs.hi):
                        points.append(None)
                        continue
                    points.append((xscale.at(x_val, px, x1), vs.at(v, y1, py)))
                else:
                    points.append((px + slot * (i + 0.5), vs.at(v, y1, py)))
            runs = _runs(points)
            if kind == "area":
                for run in runs:
                    d = [["M", run[0][0], base_y], ["L", run[0][0], run[0][1]], *_trace(run, opt.smooth)]
                    d += [["L", run[-1][0], base_y], ["Z"]]
                    out.path(d, s["color"], opt.fill_opacity, None, 0.0)
            if not scatter:
                for run in runs:
                    if len(run) > 1:
                        d = [["M", run[0][0], run[0][1]], *_trace(run, opt.smooth)]
                        out.path(d, None, 0.0, s["color"], opt.line_width)
            for i, p in enumerate(points):
                if p is None:
                    continue
                alone = not scatter and (i == 0 or points[i - 1] is None) and (i == n - 1 or points[i + 1] is None)
                if opt.markers or alone:
                    r = opt.marker_r if opt.markers else max(opt.line_width, 1.5)
                    out.circle(
                        p[0], p[1], r, s["color"], "#FFFFFF" if opt.markers else None, 0.75 if opt.markers else 0.0
                    )
                v = s["values"][i]
                texts.append(
                    (
                        opt.value_text(v),
                        p[0],
                        p[1] - (opt.marker_r if opt.markers else 1.0) - 3,
                        "middle",
                        opt.outside_color,
                    )
                )

    # axis lines
    if axes_show:
        if horizontal:
            x = vs.at(zero, px, x1)
            out.line([x, py, x, y1], opt.axis_color, 0.75)
        else:
            y = vs.at(zero, y1, py)
            out.line([px, y, x1, y], opt.axis_color, 0.75)
            if scatter and xscale is not None:
                x = xscale.at(clamp(0.0, xscale.lo, xscale.hi), px, x1)
                out.line([x, py, x, y1], opt.axis_color, 0.75)

    # axis text
    if axes_show and has_value:
        axis = opt.axis_text
        if horizontal:
            thin = _stride(max_tick_w, pw / max(1, len(vs.ticks) - 1))
            for j, t in enumerate(vs.ticks):
                if j % thin == 0:
                    out.text(val_labels[j], vs.at(t, px, x1), y1 + size * 1.2, "middle", axis, size, AXIS_WEIGHT)
            rows = _stride(size * 1.1 - 4, slot) if n else 1
            for i, c in enumerate(categories):
                if i % rows == 0:
                    out.text(
                        truncate(c, size, cat_w),
                        bx + cat_w,
                        py + slot * (i + 0.5) + size * 0.35,
                        "end",
                        axis,
                        size,
                        AXIS_WEIGHT,
                    )
        else:
            tick_limit = min(max_tick_w, bw * 0.3)
            for j, t in enumerate(vs.ticks):
                out.text(
                    truncate(val_labels[j], size, tick_limit),
                    px - 4 - pad,
                    vs.at(t, y1, py) + size * 0.35,
                    "end",
                    axis,
                    size,
                    AXIS_WEIGHT,
                )
            base = y1 + size * 1.2 + (label_room if negative and opt.show_labels and is_bar and not stacked else 0.0)
            if xscale is not None:
                x_labels = [opt.value_text(t, xscale.decimals) for t in xscale.ticks]
                longest = max([text_width(t, size) for t in x_labels], default=0.0)
                thin = _stride(longest, pw / max(1, len(xscale.ticks) - 1))
                for j, t in enumerate(xscale.ticks):
                    if j % thin == 0:
                        out.text(x_labels[j], xscale.at(t, px, x1), base, "middle", axis, size, AXIS_WEIGHT)
            elif n:
                longest = min(max(text_width(c, size) for c in categories), pw / 3)
                thin = _stride(longest, slot)
                limit = slot * thin - 4
                for i, c in enumerate(categories):
                    if i % thin == 0:
                        out.text(
                            truncate(c, size, limit), px + slot * (i + 0.5), base, "middle", axis, size, AXIS_WEIGHT
                        )

    if opt.show_labels:
        for text, x, y, anchor, color in texts:
            out.text(text, x, y, anchor, color, size, opt.weight)
    return {"ops": out.ops, "empty": not has_value, "plot": {"x": r3(px), "y": r3(py), "w": r3(pw), "h": r3(ph)}}


# ---------------------------------------------------------------------- radar
def _radar(inp: dict[str, Any]) -> dict[str, Any]:
    opt = _Options(inp)
    categories, series, n, has_value = _shape_data(inp)
    if not has_value:
        categories, series, n = [], [], 0
    out = _Out(opt.w, opt.h)
    size = opt.size
    bx, by, bw, bh = _legend(out, opt, [{"name": s["name"], "color": s["color"]} for s in series])
    values = [v for s in series for v in s["values"] if v is not None]
    vs = _value_scale(opt, float(min([0.0, *values])), float(max(values)) if values else 1.0)
    cx, cy = bx + bw / 2, by + bh / 2
    label_w = min(max([text_width(c, size) for c in categories], default=0.0), bw * 0.25) if opt.axes_show else 0.0
    pad = max(opt.marker_r + 0.5 if opt.markers else 0.0, opt.line_width / 2, 1.0)
    radius = min(bw / 2 - label_w - size * 0.6, bh / 2 - size * 1.6) if opt.axes_show else min(bw, bh) / 2 - pad
    axes_show = opt.axes_show
    if radius < 8:
        axes_show = False
        radius = min(bw, bh) / 2 - pad
    if radius < 1:
        return {"ops": out.ops, "empty": not has_value, "plot": None}
    start = _number(inp.get("startAngle")) or 0.0
    count = n if n else 6

    def spoke(i: int, r: float) -> tuple[float, float]:
        a = math.radians(start + 360.0 * i / count - 90.0)
        return cx + r * math.cos(a), cy + r * math.sin(a)

    def polygon(radii: list[float]) -> list[list[Any]]:
        d: list[list[Any]] = []
        for i in range(count):
            x, y = spoke(i, radii[i])
            d.append(["M" if i == 0 else "L", x, y])
        d.append(["Z"])
        return d

    if opt.grid_show:
        for t in vs.ticks:
            r = vs.at(t, 0.0, radius)
            if r <= 0:
                continue
            if count < 3:
                out.circle(cx, cy, r, None, opt.grid_color, opt.grid_width)
            else:
                out.path(polygon([r] * count), None, 0.0, opt.grid_color, opt.grid_width)
        for i in range(count):
            x, y = spoke(i, radius)
            out.line([cx, cy, x, y], opt.grid_color, opt.grid_width)
    texts: list[tuple[str, float, float, str, str]] = []
    for s in series:
        vals = s["values"]
        radii = [vs.at(v if v is not None else vs.lo, 0.0, radius) for v in vals]
        if count >= 3:
            out.path(polygon(radii), s["color"], opt.fill_opacity, s["color"], opt.line_width)
        elif count == 2:
            ax, ay = spoke(0, radii[0])
            bx2, by2 = spoke(1, radii[1])
            out.line([ax, ay, bx2, by2], s["color"], opt.line_width)
        for i in range(n):
            x, y = spoke(i, radii[i])
            if opt.markers:
                out.circle(x, y, opt.marker_r, s["color"], "#FFFFFF", 0.75)
            if vals[i] is not None:
                texts.append(
                    (
                        opt.value_text(vals[i]),
                        x,
                        y - (opt.marker_r if opt.markers else 1.0) - 3,
                        "middle",
                        opt.outside_color,
                    )
                )
    if axes_show and has_value:
        for t in vs.ticks:
            r = vs.at(t, 0.0, radius)
            if r > 0:
                x, y = spoke(0, r)
                out.text(
                    opt.value_text(t, vs.decimals),
                    x + 3,
                    y + size * 0.35,
                    "start",
                    opt.axis_text,
                    size * 0.85,
                    AXIS_WEIGHT,
                )
        for i, c in enumerate(categories):
            a = math.radians(start + 360.0 * i / count - 90.0)
            cos_a, sin_a = math.cos(a), math.sin(a)
            x, y = cx + (radius + size * 0.5) * cos_a, cy + (radius + size * 0.5) * sin_a
            anchor = "middle" if abs(cos_a) < 0.2 else ("start" if cos_a > 0 else "end")
            out.text(
                truncate(c, size, label_w),
                x,
                y + size * 0.35 + sin_a * size * 0.45,
                anchor,
                opt.axis_text,
                size,
                AXIS_WEIGHT,
            )
    if opt.show_labels:
        for text, x, y, anchor, color in texts:
            out.text(text, x, y, anchor, color, size, opt.weight)
    return {
        "ops": out.ops,
        "empty": not has_value,
        "plot": {"x": r3(cx - radius), "y": r3(cy - radius), "w": r3(radius * 2), "h": r3(radius * 2)},
    }


# ---------------------------------------------------------------------- pie and donut
def normalize_segments(raw: list[dict[str, Any]], remainder_color: str, normalize: bool) -> list[dict[str, Any]]:
    """Skip values <= 0, scale a sum above 100 (always when ``normalize``), add a remainder below it."""
    out = [dict(s) for s in raw if s["pct"] > 0]
    total = sum(s["pct"] for s in out)
    if total > 100.01 or (normalize and total > 0):
        for s in out:
            s["pct"] = s["pct"] * 100 / total
    elif total < 99.99:
        out.append({"pct": 100 - total, "label": "", "color": remainder_color, "remainder": True})
    return out


def _pie_extent(
    opt: _Options, segments: list[dict[str, Any]], outer: float, inner: float, size: float, start: float
) -> tuple[float, float]:
    """Distance from the centre the drawing needs on each axis (same rule as the donut in the editor)."""
    labels = opt.labels
    min_pct = _pos_or_zero(labels.get("minPct"), 5.0)
    outside = _pos_or_zero(labels.get("outsidePct"), 12.0)
    k = outer / 120
    x = y = outer
    angle = start
    for s in segments:
        sweep = s["pct"] / 100 * 360
        if opt.show_labels and s["pct"] >= min_pct and s["pct"] < outside:
            a = math.radians(angle + sweep / 2 - 90)
            cos_m, sin_m = math.cos(a), math.sin(a)
            px = (outer + 18 * k) * cos_m
            py = (outer + 18 * k) * sin_m
            right = cos_m >= 0
            tx = abs(px + (20 * k if right else -20 * k))
            x = max(x, tx + text_width(_pct_text(s["pct"]), size))
            y = max(y, abs(py + size * 0.31) + size * 0.5)
        angle += sweep
    return x, y


def _pos_or_zero(value: Any, default: float) -> float:
    parsed = _number(value)
    return parsed if parsed is not None and parsed >= 0 else default


def _pct_text(pct: float) -> str:
    return f"{math.floor(pct + 0.5)}%"


def _pie(inp: dict[str, Any]) -> dict[str, Any]:
    opt = _Options(inp)
    labels = opt.labels
    kind = opt.kind
    palette = _palette(inp)
    remainder_color = _color(inp.get("remainderColor"), "#B0BEC5")
    raw: list[dict[str, Any]] = []
    for i, s in enumerate(inp.get("segments") or []):
        raw.append(
            {
                "pct": float(s.get("pct") or 0),
                "label": str(s.get("label") or ""),
                "color": s.get("color") or palette[i % len(palette)],
            }
        )
    has_value = any(s["pct"] > 0 for s in raw)
    segments = normalize_segments(raw, remainder_color, inp.get("normalize") is True)
    out = _Out(opt.w, opt.h)
    bx, by, bw, bh = _legend(
        out, opt, [{"name": s["label"], "color": s["color"]} for s in segments if not s.get("remainder")]
    )
    show = opt.show_labels and has_value
    opt.show_labels = show
    cx, cy = bx + bw / 2, by + bh / 2
    half = max(0.0, min(bw, bh) / 2)
    outer0 = _pos(inp.get("outerRadius"), half)
    inner_raw = _number(inp.get("innerRadius"))
    inner0 = inner_raw if inner_raw is not None and inner_raw >= 0 else (0.0 if kind == "pie" else outer0 * 0.5833)
    font_size = _number(labels.get("fontSize"))
    start = _number(inp.get("startAngle")) or 0.0
    size0 = font_size if font_size else 13 * outer0 / 120
    ex, ey = _pie_extent(opt, segments, outer0, inner0, size0, start)
    f = min(1.0, (bw / 2) / ex if ex > 0 else 1.0, (bh / 2) / ey if ey > 0 else 1.0)
    outer, inner, size = outer0 * f, inner0 * f, size0 * f
    k = outer / 120
    min_pct = _pos_or_zero(labels.get("minPct"), 5.0)
    outside = _pos_or_zero(labels.get("outsidePct"), 12.0)
    angle = start
    leaders: list[list[float]] = []
    texts: list[tuple[str, float, float, str, str]] = []
    for s in segments:
        pct = s["pct"]
        sweep = pct / 100 * 360
        full = pct >= 99.99
        out.arc(cx, cy, outer, inner, angle, angle + (360.0 if full else sweep), full, s["color"])
        a = math.radians(angle + sweep / 2 - 90)
        cos_m, sin_m = math.cos(a), math.sin(a)
        if show and pct >= min_pct:
            text = _pct_text(pct)
            if pct >= outside:
                radius = (outer + inner) / 2 + 5 * k
                color = _color(labels.get("remainderLabelColor"), "#666666") if s.get("remainder") else opt.inside_color
                texts.append((text, cx + radius * cos_m, cy + radius * sin_m + size * 0.385, "middle", color))
            else:
                x2, y2 = cx + (outer + 18 * k) * cos_m, cy + (outer + 18 * k) * sin_m
                right = cos_m >= 0
                x3 = x2 + (16 * k if right else -16 * k)
                leaders.append([cx + outer * cos_m, cy + outer * sin_m, x2, y2, x3, y2])
                texts.append(
                    (
                        text,
                        x3 + (4 * k if right else -4 * k),
                        y2 + size * 0.31,
                        "start" if right else "end",
                        opt.outside_color,
                    )
                )
        angle += sweep
    leader_color = _color(labels.get("leaderColor"), "#9CA3AF")
    leader_width = _pos(labels.get("leaderWidth"), 1.0) * max(k, 0.25)
    for pts in leaders:
        out.line(pts, leader_color, leader_width)
    for text, x, y, anchor, color in texts:
        out.text(text, x, y, anchor, color, size, opt.weight)
    return {
        "ops": out.ops,
        "empty": not has_value,
        "plot": None,
        "center": {"cx": cx, "cy": cy, "outer": outer, "inner": inner},
    }


def chart_ops(inp: dict[str, Any]) -> dict[str, Any]:
    """``inp``: chartType, w, h, locale, palette, labels, legend, axes, grid, barGap, lineWidth, smooth, fillOpacity,
    markers, startAngle; cartesian and radar: categories, series [{name, color, values, colors?, xs?}];
    pie and donut: segments [{pct, label, color}], outerRadius, innerRadius, remainderColor, normalize.
    Returns ``{"ops": [...], "empty": bool, ...}``; ``empty`` means there was nothing to plot."""
    kind = inp["chartType"]
    if kind in ROUND_TYPES:
        return _pie(inp)
    if kind == "radar":
        return _radar(inp)
    return _cartesian(inp)
