"""Resolve + layout + paginate (TZ 2.6.2 stages 2-4).

Turns a render plan and input data into a list of :class:`Page` objects with positioned
:class:`DrawNode` trees. Handles ``visibleIf``, ``bind``, text substitution and measurement,
``pushDown``/``anchorTo``, horizontal constraints in repeater cells, repeaters (vertical / horizontal /
grid, clip and hug), the flow repeater with ``overflow: nextPage`` (continuation sheets, repeated header,
footer, ``showOn``), sheet repeat, conditional sheets and page numbering (``page.number``/``page.total``
are resolved after pagination: texts referencing ``page.*`` are laid out in a second pass).
"""

from __future__ import annotations

import copy
import math
import re
import time
from collections.abc import Callable
from decimal import Decimal
from typing import Any

from .charts import PALETTE as CHART_PALETTE
from .charts import ROUND_TYPES, VALUE_LIMIT, chart_ops, normalize_segments
from .errors import RenderError, RenderTimeout, Warnings
from .expr.evaluator import MISSING, EvalEnv, Scope, evaluate, render_template, to_float, truthy
from .expr.filters import _sort_number
from .model import DrawNode, Page
from .providers import AssetResolver, FontProvider, ImageRef
from .text.layout import layout_text

EPS = 0.01


def _chart_field(item: Any, path: str | None) -> Any:
    """A chart field of a source item; dots and brackets reach into nested values."""
    if not path:
        return None
    if isinstance(item, dict) and path in item:
        return item[path]
    cur = item
    for seg in re.findall(r"[^.\[\]]+", path):
        if isinstance(cur, dict):
            cur = cur.get(seg)
        elif isinstance(cur, list) and seg.isdigit() and int(seg) < len(cur):
            cur = cur[int(seg)]
        else:
            return None
    return cur


def _chart_text(raw: Any) -> str:
    if raw is None or raw is MISSING:
        return ""
    if isinstance(raw, Decimal):
        raw = float(raw)
    if isinstance(raw, float) and raw.is_integer():
        return str(int(raw))
    return str(raw)


def _chart_value(raw: Any) -> float | None:
    """A plotted number; missing or non-numeric values are None (a gap, never a zero)."""
    if raw is None or raw is MISSING or isinstance(raw, bool) or raw == "":
        return None
    if isinstance(raw, dict) and "amount" in raw:
        raw = raw["amount"]
    parsed = _sort_number(raw)
    if parsed is None:
        return None
    value = float(parsed)
    return max(-VALUE_LIMIT, min(VALUE_LIMIT, value)) if math.isfinite(value) else None


class LayoutOptions:
    def __init__(
        self,
        *,
        locale: str = "ru",
        kerning: bool = True,
        missing_placeholder: bool = False,
        max_pages: int = 200,
        deadline: float | None = None,
        check: Callable[[], None] | None = None,
        doc_vars: dict[str, Any] | None = None,
        tz_offset_minutes: int | None = None,
    ) -> None:
        self.locale = locale
        self.kerning = kerning
        self.missing_placeholder = missing_placeholder
        self.max_pages = max_pages
        self.deadline = deadline
        self.check = check
        self.doc_vars = doc_vars or {}
        self.tz_offset_minutes = tz_offset_minutes


def _set_path(target: dict[str, Any], path: str, value: Any) -> None:
    parts = path.split(".")
    cur: Any = target
    for i, part in enumerate(parts):
        last = i == len(parts) - 1
        key: Any = int(part) if part.isdigit() and isinstance(cur, list) else part
        if last:
            if isinstance(cur, list) and isinstance(key, int):
                if key < len(cur):
                    cur[key] = value
            elif isinstance(cur, dict):
                cur[key] = value
            return
        nxt = (
            cur[key]
            if isinstance(cur, list) and isinstance(key, int) and key < len(cur)
            else (cur.get(key) if isinstance(cur, dict) else None)
        )
        if nxt is None:
            return
        cur = nxt


_NUMERIC_PROPS = {
    "x",
    "y",
    "w",
    "h",
    "rotation",
    "opacity",
    "cornerRadius",
    "gap",
    "padding",
    "top",
    "right",
    "bottom",
    "left",
}
_TEXT_STYLE_BINDS = {"color", "fontSize", "fontWeight", "letterSpacing", "lineHeight"}


def _bound_value(prop: str, value: Any) -> Any:
    if value is MISSING:
        return None
    if isinstance(value, Decimal):
        return float(value)
    if prop.split(".")[-1] in _NUMERIC_PROPS | {"width", "offset", "fontSize", "fontWeight", "letterSpacing"}:
        return to_float(value)
    return value


class DocumentLayout:
    def __init__(
        self,
        plan: dict[str, Any],
        data: dict[str, Any],
        fonts: FontProvider,
        assets: AssetResolver,
        options: LayoutOptions,
        warnings: Warnings,
    ) -> None:
        self.plan = plan
        self.data = data
        self.fonts = fonts
        self.assets = assets
        self.opt = options
        self.warnings = warnings
        self.env = EvalEnv(
            locale=options.locale,
            warnings=warnings,
            missing_placeholder=options.missing_placeholder,
            tz_offset_minutes=options.tz_offset_minutes,
        )
        self.sheets_by_id = {s["id"]: s for s in plan["sheets"]}
        self._ops = 0
        self._image_cache: dict[str, ImageRef | None] = {}

    # ------------------------------------------------------------------ helpers
    def _tick(self) -> None:
        self._ops += 1
        if self._ops % 200 == 0:
            if self.opt.deadline is not None and time.monotonic() > self.opt.deadline:
                raise RenderTimeout()
            if self.opt.check is not None:
                self.opt.check()

    def _eval(self, ast: Any, scope: Scope, node_id: str | None) -> Any:
        self.env.node_id = node_id
        return evaluate(ast, scope, self.env)

    # ------------------------------------------------------------------ document
    def run(self) -> list[Page]:
        system = Scope({"now": self.opt.doc_vars.get("generatedAt")})
        root = Scope({"doc": self.opt.doc_vars}, Scope(self.data, system))
        pages: list[Page] = []
        for si, sheet in enumerate(self.plan["sheets"]):
            if sheet.get("continuationOnly"):
                continue
            copies: list[Scope] = []
            if sheet["repeat"]:
                rep = sheet["repeat"]
                arr = self._eval(rep["source"], root, sheet["id"]) if rep["source"] else MISSING
                if not isinstance(arr, list):
                    arr = []
                n = len(arr)
                for i, item in enumerate(arr[: rep["maxPages"]]):
                    loop = {"index": i + 1, "index0": i, "first": i == 0, "last": i == n - 1, "count": n}
                    copies.append(root.child({rep["as"]: item, rep["indexAs"]: i, "loop": loop}))
            else:
                copies.append(root)
            for scope in copies:
                sheet_scope = scope.child({"sheet": {"index": si, "name": sheet["name"], "id": sheet["id"]}})
                if sheet["visibleIf"] is not None and not truthy(
                    self._eval(sheet["visibleIf"], sheet_scope, sheet["id"])
                ):
                    continue
                section = len(pages)
                for page in self._build_sheet(sheet, sheet_scope):
                    page.section = section
                    pages.append(page)
                if len(pages) > self.opt.max_pages:
                    raise RenderError("PAGINATION_LIMIT", f"Document exceeds {self.opt.max_pages} pages")
        self._number_pages(pages)
        for page in pages:
            for item in page.items:
                self._finalize(item)
        return pages

    def _number_pages(self, pages: list[Page]) -> None:
        total = len(pages)
        number = 0
        sections: dict[int, list[Page]] = {}
        for p in pages:
            sections.setdefault(p.section, []).append(p)
        for p in pages:
            number = int(p.restart) if p.restart else number + 1
            sec = sections[p.section]
            p.vars.update(
                {
                    "number": number,
                    "total": total,
                    "sheetName": p.sheet_name,
                    "sectionNumber": sec.index(p) + 1,
                    "sectionTotal": len(sec),
                    "skip": p.skip_numbering,
                }
            )

    def _finalize(self, node: DrawNode) -> None:
        if node.deferred is not None:
            plan_node, scope = node.deferred
            node.deferred = None
            self._fill_text(node, plan_node, scope)
        for child in node.children:
            self._finalize(child)

    # ------------------------------------------------------------------ sheets & pagination
    def _new_page(self, sheet: dict[str, Any]) -> Page:
        background = sheet["background"]
        if background and background.get("type") == "image":
            background = dict(background, _ref=self._image(str(background.get("assetId") or "")))
        return Page(
            sheet_id=sheet["id"],
            sheet_name=sheet["name"],
            w=sheet["w"],
            h=sheet["h"],
            bleed=sheet["bleed"],
            background=background,
            skip_numbering=sheet["pageNumbering"]["skip"],
            restart=sheet["pageNumbering"]["restart"],
            raster=sheet["raster"],
        )

    def _build_sheet(self, sheet: dict[str, Any], scope: Scope) -> list[Page]:
        flow = next((c for c in sheet["children"] if c["type"] == "repeater" and c["overflow"] == "nextPage"), None)
        if flow is None:
            page = self._new_page(sheet)
            page_scope = scope.child({"page": page.vars})
            page.items = self._layout_children(sheet["children"], page_scope, sheet["w"], sheet["h"])
            return [page]
        return self._paginate_flow(sheet, flow, scope)

    def _paginate_flow(self, sheet: dict[str, Any], flow: dict[str, Any], scope: Scope) -> list[Page]:
        flow_scope = scope.child({"page": {}})
        if flow["visibleIf"] is not None and not truthy(self._eval(flow["visibleIf"], flow_scope, flow["id"])):
            page = self._new_page(sheet)
            others = [c for c in sheet["children"] if c is not flow]
            page.items = self._layout_children(others, scope.child({"page": page.vars}), sheet["w"], sheet["h"])
            return [page]
        items = self._repeater_items(flow, flow_scope)
        cell_w = flow["item"]["w"] or flow["w"]
        cells = [self._build_cell(flow["item"], s, cell_w, flow["w"]) for s in items]
        rows = self._rows(flow, cells)
        plans: list[tuple[dict[str, Any], list[DrawNode]]] = []
        cur_sheet = sheet
        idx = 0
        first = True
        max_pages = sheet["overflow"]["maxPages"]
        while True:
            area = next((c for c in cur_sheet["children"] if c["id"] == flow["id"]), flow)
            placed_nodes: list[DrawNode] = []
            y = 0.0
            header = flow["header"]
            if header and (first or header["repeat"]):
                hdr = self._build_cell(header, flow_scope, area["w"], area["w"])
                hdr.y = y
                placed_nodes.append(hdr)
                y += hdr.h
            footer = flow["footer"]
            footer_h = footer["h"] if footer else 0.0
            avail = area["h"] - footer_h
            placed = 0
            while idx < len(rows):
                row = rows[idx]
                row_h = max(c.h for c in row)
                if y + row_h <= avail + EPS or placed == 0:
                    if y + row_h > avail + EPS:
                        self.warnings.add("ITEM_TOO_TALL", node=flow["id"], index=idx)
                    self._place_row(flow, row, y, area["w"], placed_nodes)
                    y += row_h + flow["gapRow"]
                    idx += 1
                    placed += 1
                else:
                    break
            if not rows and flow["emptyState"]:
                empty = self._build_cell(flow["emptyState"], flow_scope, area["w"], area["w"])
                empty.y = y
                placed_nodes.append(empty)
            if footer and (footer["repeat"] or idx >= len(rows)):
                ftr = self._build_cell(footer, flow_scope, area["w"], area["w"])
                ftr.y = (y - flow["gapRow"]) if placed else y
                placed_nodes.append(ftr)
            plans.append((cur_sheet, placed_nodes))
            if idx >= len(rows):
                break
            if len(plans) >= max_pages:
                raise RenderError(
                    "PAGINATION_LIMIT",
                    f"Sheet {sheet['name']!r} exceeds overflow.maxPages={max_pages}",
                    [{"sheet": sheet["id"]}],
                )
            first = False
            cont_id = cur_sheet["overflow"].get("continuationSheetId") or sheet["overflow"].get("continuationSheetId")
            cur_sheet = self.sheets_by_id.get(cont_id, sheet) if cont_id else sheet
        pages: list[Page] = []
        for pi, (psheet, nodes) in enumerate(plans):
            page = self._new_page(psheet)
            page_scope = scope.child({"page": page.vars})
            is_first, is_last = pi == 0, pi == len(plans) - 1
            visible_children = []
            for child in psheet["children"]:
                show = child.get("showOn", "all")
                if show == "first" and not is_first:
                    continue
                if show == "continuation" and is_first:
                    continue
                if show == "last" and not is_last:
                    continue
                visible_children.append(child)
            laid = self._layout_children(
                visible_children, page_scope, psheet["w"], psheet["h"], replace={flow["id"]: nodes}
            )
            page.items = laid
            pages.append(page)
        return pages

    # ------------------------------------------------------------------ repeaters
    def _repeater_items(self, rep: dict[str, Any], scope: Scope) -> list[Scope]:
        arr = self._eval(rep["source"], scope, rep["id"]) if rep["source"] else MISSING
        if arr is MISSING or arr is None:
            arr = []
        if not isinstance(arr, list):
            self.warnings.add("REPEATER_SOURCE_NOT_ARRAY", node=rep["id"])
            arr = []
        if rep["filter"] is not None:
            arr = [it for it in arr if truthy(self._eval(rep["filter"], scope.child({rep["as"]: it}), rep["id"]))]
        if rep["sort"]:
            by, order = rep["sort"]

            def sort_key(it: Any) -> tuple[int, Any]:
                v = it.get(by) if isinstance(it, dict) else None
                f = to_float(v)
                return (0, f) if f is not None else (1, str(v or ""))

            arr = sorted(arr, key=sort_key, reverse=order == "desc")
        if rep["maxItems"]:
            arr = arr[: int(rep["maxItems"])]
        parent_loop = scope.lookup("loop")
        n = len(arr)
        scopes = []
        for i, it in enumerate(arr):
            loop = {
                "index": i + 1,
                "index0": i,
                "first": i == 0,
                "last": i == n - 1,
                "count": n,
                "parent": None if parent_loop is MISSING else parent_loop,
            }
            scopes.append(scope.child({rep["as"]: it, rep["indexAs"]: i, "loop": loop}))
        return scopes

    def _build_cell(self, cell: dict[str, Any], scope: Scope, w: float, design_w: float) -> DrawNode:
        base_w = cell["w"] or design_w
        node = DrawNode("group", "cell", 0.0, 0.0, w, cell["h"])
        node.children = self._layout_children(cell["children"], scope, w, cell["h"], design_w=base_w)
        if cell["hug"]:
            bottom = max((c.y + c.h for c in node.children), default=0.0)
            node.h = bottom
        return node

    def _rows(self, rep: dict[str, Any], cells: list[DrawNode]) -> list[list[DrawNode]]:
        if rep["direction"] == "grid":
            n = rep["columns"]
            return [cells[i : i + n] for i in range(0, len(cells), n)]
        return [[c] for c in cells]

    def _place_row(
        self, rep: dict[str, Any], row: list[DrawNode], y: float, area_w: float, out: list[DrawNode]
    ) -> None:
        if rep["direction"] == "grid":
            n = rep["columns"]
            cw = (area_w - rep["gapCol"] * (n - 1)) / n
            for ci, cell in enumerate(row):
                cell.x = ci * (cw + rep["gapCol"])
                cell.y = y
                out.append(cell)
        else:
            row[0].y = y
            out.append(row[0])

    def _layout_repeater(self, node: dict[str, Any], dn: DrawNode, scope: Scope) -> None:
        items = self._repeater_items(node, scope)
        direction = node["direction"]
        if direction == "grid":
            n = node["columns"]
            cell_w = (dn.w - node["gapCol"] * (n - 1)) / n
        elif direction == "horizontal":
            cell_w = node["item"]["w"] or node["w"]
        else:
            cell_w = node["item"]["w"] or dn.w
        cells = [self._build_cell(node["item"], s, cell_w, node["item"]["w"] or cell_w) for s in items]
        children: list[DrawNode] = []
        y = 0.0
        if node["header"]:
            hdr = self._build_cell(node["header"], scope, dn.w, dn.w)
            children.append(hdr)
            y = hdr.h
        if not cells and node["emptyState"]:
            empty = self._build_cell(node["emptyState"], scope, dn.w, dn.w)
            empty.y = y
            children.append(empty)
        if direction == "horizontal":
            x = 0.0
            for c in cells:
                c.x, c.y = x, y
                x += c.w + node["gapCol"]
                children.append(c)
            content_h = y + max((c.h for c in cells), default=0.0)
        else:
            for row in self._rows(node, cells):
                self._place_row(node, row, y, dn.w, children)
                y += max(c.h for c in row) + node["gapRow"]
            content_h = y - (node["gapRow"] if cells else 0.0)
        if node["footer"]:
            ftr = self._build_cell(node["footer"], scope, dn.w, dn.w)
            ftr.y = content_h
            children.append(ftr)
            content_h += ftr.h
        if direction == "horizontal" and node["sizing"][0] == "hug" and cells:
            dn.w = x - node["gapCol"]
        if node["sizing"][1] == "hug":
            dn.h = content_h
        elif content_h > dn.h + EPS and node["overflow"] == "error":
            raise RenderError("REPEATER_OVERFLOW", "Repeater content does not fit", [{"node": node["id"]}])
        elif content_h > dn.h + EPS:
            self.warnings.add("REPEATER_CLIPPED", node=node["id"])
        dn.children = children

    # ------------------------------------------------------------------ children & nodes
    def _layout_children(
        self,
        children: list[dict[str, Any]],
        scope: Scope,
        parent_w: float,
        parent_h: float,
        *,
        design_w: float | None = None,
        replace: dict[str, list[DrawNode]] | None = None,
    ) -> list[DrawNode]:
        results: list[tuple[dict[str, Any], DrawNode | None]] = []
        for child in children:
            self._tick()
            if replace and child["id"] in replace:
                dn = DrawNode("group", child["id"], child["x"], child["y"], child["w"], child["h"])
                dn.children = replace[child["id"]]
                results.append((child, dn))
                continue
            dn = self._layout_node(child, scope)
            if dn is not None and design_w is not None and abs(design_w - parent_w) > EPS:
                self._apply_h_constraint(child, dn, design_w, parent_w)
            results.append((child, dn))
        self._apply_push_down(results)
        return [dn for _, dn in results if dn is not None]

    @staticmethod
    def _apply_h_constraint(plan: dict[str, Any], dn: DrawNode, w0: float, w1: float) -> None:
        mode = plan["constraints"][0]
        dw = w1 - w0
        if mode == "right":
            dn.x += dw
        elif mode == "center":
            dn.x += dw / 2
        elif mode == "leftRight":
            dn.w += dw
        elif mode == "scale" and w0 > 0:
            r = w1 / w0
            dn.x *= r
            dn.w *= r

    @staticmethod
    def _apply_push_down(results: list[tuple[dict[str, Any], DrawNode | None]]) -> None:
        if not any(p["pushDown"] or p["anchorTo"] for p, _ in results):
            return
        order = sorted(range(len(results)), key=lambda i: results[i][0]["y"])
        shift: dict[int, float] = {}
        growth: dict[int, float] = {}
        by_id = {results[i][0]["id"]: i for i in range(len(results))}
        for i in order:
            plan, dn = results[i]
            g = (dn.h - plan["h"]) if dn is not None else -plan["h"]
            growth[i] = g
            s = 0.0
            if plan["anchorTo"] and plan["anchorTo"].get("nodeId") in by_id:
                j = by_id[plan["anchorTo"]["nodeId"]]
                tp, tdn = results[j]
                if j in shift:
                    bottom = tp["y"] + shift[j] + (tdn.h if tdn is not None else 0.0)
                    s = bottom + float(plan["anchorTo"].get("gap", 0)) - plan["y"]
            elif plan["pushDown"]:
                best: float | None = None
                for j in order:
                    if j == i:
                        break
                    pj = results[j][0]
                    if (
                        pj["y"] + pj["h"] <= plan["y"] + EPS
                        and pj["x"] < plan["x"] + plan["w"]
                        and plan["x"] < pj["x"] + pj["w"]
                    ):
                        cand = shift.get(j, 0.0) + growth[j]
                        best = cand if best is None else max(best, cand)
                s = best or 0.0
            shift[i] = s
            if dn is not None and s:
                dn.y += s

    def _apply_bind(self, node: dict[str, Any], scope: Scope) -> dict[str, Any]:
        out = dict(node)
        for key in ("fills", "strokes", "layout"):
            if key in node:
                out[key] = copy.deepcopy(node[key])
        for prop, ast in node["bind"]:
            value = _bound_value(prop, self._eval(ast, scope, node["id"]))
            if value is None:
                continue
            if prop in _TEXT_STYLE_BINDS and node["type"] == "text":
                self._bind_text_style(out, prop, value)
            elif prop == "color" and node["type"] != "text":
                paint = next((f for f in out["fills"] if f.get("type") == "solid"), None)
                if paint is None:
                    out["fills"] = [{"type": "solid", "color": value, "opacity": 1.0}, *out["fills"]]
                else:
                    paint["color"] = value
            elif prop == "padding" and out.get("layout"):
                out["layout"]["padding"] = dict.fromkeys(("top", "right", "bottom", "left"), float(value))
            elif prop == "gap" and out.get("layout"):
                out["layout"]["gap"] = float(value)
            elif prop == "gap" and node["type"] == "repeater":
                out["gapRow"] = out["gapCol"] = float(value)
            elif "." in prop:
                _set_path(out, prop, value)
            else:
                out[prop] = value
        return out

    @staticmethod
    def _bind_text_style(node: dict[str, Any], prop: str, value: Any) -> None:
        if prop == "fontWeight":
            value = int(value)
        node["paragraphs"] = [
            {**para, "runs": [{**run, "style": {**run["style"], prop: value}} for run in para["runs"]]}
            for para in node["paragraphs"]
        ]

    def _layout_node(self, node: dict[str, Any], scope: Scope) -> DrawNode | None:
        if node["visibleIf"] is not None and not truthy(self._eval(node["visibleIf"], scope, node["id"])):
            return None
        if node["bind"]:
            node = self._apply_bind(node, scope)
        dn = DrawNode(node["type"], node["id"], node["x"], node["y"], max(0.0, node["w"]), max(0.0, node["h"]))
        dn.rotation = node["rotation"]
        dn.origin = node["origin"]
        dn.opacity = max(0.0, min(1.0, node["opacity"]))
        dn.blend = node["blendMode"]
        dn.fills = node["fills"]
        if any(f.get("type") == "image" for f in dn.fills):
            dn.fills = [
                dict(f, _ref=self._image(str(f.get("assetId") or ""))) if f.get("type") == "image" else f
                for f in dn.fills
            ]
        dn.strokes = node["strokes"]
        dn.stroke_sides = node["strokeSides"]
        dn.radius = node["cornerRadius"]
        dn.clip = node["clip"]
        kind = node["type"]
        if kind == "frame" and node.get("layout"):
            self._layout_auto(node, dn, scope)
        elif kind in ("frame", "group"):
            dn.children = self._layout_children(node["children"], scope, dn.w, dn.h)
            if node["sizing"][1] == "hug":
                dn.h = max((c.y + c.h for c in dn.children), default=0.0)
            if node["sizing"][0] == "hug":
                dn.w = max((c.x + c.w for c in dn.children), default=0.0)
        elif kind == "text":
            if node["pageRef"]:
                dn.deferred = (node, scope)
            else:
                self._fill_text(dn, node, scope)
        elif kind == "image":
            if not self._fill_image(dn, node, scope):
                return None
        elif kind == "ellipse":
            dn.arc = node.get("arc")
        elif kind == "line":
            dn.points = node["points"]
        elif kind == "repeater":
            dn.kind = "group"
            self._layout_repeater(node, dn, scope)
        elif kind == "chart":
            dn.kind = "group"
            self._layout_chart(node, dn, scope)
        return dn

    # ------------------------------------------------------------------ auto layout
    def _sized(self, child: dict[str, Any], scope: Scope, w: float | None, h: float | None) -> DrawNode | None:
        """Lay a child out with sizes imposed by the parent's auto layout."""
        plan = dict(child)
        sw, sh = child["sizing"]
        if w is not None:
            plan["w"] = w
        if h is not None:
            plan["h"] = h
        if child["type"] == "text":
            if sw == "hug":
                plan["autoSize"] = "width"
            elif sh == "hug" or (sh == "fill" and h is None):
                plan["autoSize"] = "height"
        if w is not None and sw != "hug":
            sw = "fixed"
        if h is not None and sh != "hug":
            sh = "fixed"
        elif sh == "fill":
            sh = "hug"
        if sw == "fill":
            sw = "hug"
        plan["sizing"] = (sw, sh)
        return self._layout_node(plan, scope)

    def _layout_auto(self, node: dict[str, Any], dn: DrawNode, scope: Scope) -> None:
        lay = node["layout"]
        vertical = lay["mode"] == "vertical"
        pad = lay["padding"]
        gap = lay["gap"]
        pad_main = (pad["top"] + pad["bottom"]) if vertical else (pad["left"] + pad["right"])
        pad_cross = (pad["left"] + pad["right"]) if vertical else (pad["top"] + pad["bottom"])
        hug_main = node["sizing"][1 if vertical else 0] == "hug"
        hug_cross = node["sizing"][0 if vertical else 1] == "hug"
        size_main = dn.h if vertical else dn.w
        size_cross = dn.w if vertical else dn.h
        content_main = max(0.0, size_main - pad_main)
        content_cross = max(0.0, size_cross - pad_cross)
        align = lay["align"]

        def main_sizing(child: dict[str, Any]) -> str:
            return child["sizing"][1 if vertical else 0]

        def cross_sizing(child: dict[str, Any]) -> str:
            return child["sizing"][0 if vertical else 1]

        def stretches(child: dict[str, Any]) -> bool:
            mode = cross_sizing(child)
            return mode == "fill" or (align == "stretch" and mode == "fixed")

        def place(child: dict[str, Any], main: float | None) -> DrawNode | None:
            self._tick()
            cross = content_cross if stretches(child) and not hug_cross else None
            w, h = (cross, main) if vertical else (main, cross)
            return self._sized(child, scope, w, h)

        visible = [
            c for c in node["children"] if c["visibleIf"] is None or truthy(self._eval(c["visibleIf"], scope, c["id"]))
        ]
        placed: dict[int, DrawNode | None] = {}
        fills: list[int] = []
        for i, child in enumerate(visible):
            if main_sizing(child) == "fill" and not hug_main:
                fills.append(i)
            else:
                placed[i] = place(child, None)
        used = sum((n.h if vertical else n.w) for n in placed.values() if n is not None)
        gaps = gap * max(0, len(visible) - 1)
        if fills:
            share = max(0.0, content_main - used - gaps) / len(fills)
            for i in fills:
                placed[i] = place(visible[i], share)
        nodes = [(visible[i], placed[i]) for i in range(len(visible)) if placed.get(i) is not None]
        if hug_cross:
            content_cross = max(((n.w if vertical else n.h) for _, n in nodes), default=0.0)
            for idx, (child, n) in enumerate(nodes):
                if stretches(child) and (n.w if vertical else n.h) < content_cross - EPS:
                    w, h = (content_cross, n.h) if vertical else (n.w, content_cross)
                    again = self._sized(child, scope, w, h)
                    if again is not None:
                        nodes[idx] = (child, again)
            size_cross = content_cross + pad_cross
        total = sum((n.h if vertical else n.w) for _, n in nodes) + gap * max(0, len(nodes) - 1)
        if hug_main:
            size_main = total + pad_main
            content_main = total
        free = content_main - total
        justify = lay["justify"]
        step = gap
        offset = 0.0
        if justify == "center":
            offset = free / 2
        elif justify == "end":
            offset = free
        elif justify == "spaceBetween" and len(nodes) > 1 and free > 0:
            step = gap + free / (len(nodes) - 1)
        cursor = (pad["top"] if vertical else pad["left"]) + offset
        cross_start = pad["left"] if vertical else pad["top"]
        for _, n in nodes:
            extent = n.w if vertical else n.h
            cross_pos = cross_start
            if align == "center":
                cross_pos += (content_cross - extent) / 2
            elif align == "end":
                cross_pos += content_cross - extent
            if vertical:
                n.x, n.y = cross_pos, cursor
                cursor += n.h + step
            else:
                n.x, n.y = cursor, cross_pos
                cursor += n.w + step
        dn.children = [n for _, n in nodes]
        if vertical:
            dn.w, dn.h = size_cross, size_main
        else:
            dn.w, dn.h = size_main, size_cross

    # ------------------------------------------------------------------ charts
    def _chart_segments(self, node: dict[str, Any], scope: Scope) -> list[dict[str, Any]]:
        out = self._chart_raw_segments(node, scope)
        return normalize_segments(out, node["remainderColor"], node.get("normalize") is True)

    def _chart_raw_segments(self, node: dict[str, Any], scope: Scope) -> list[dict[str, Any]]:
        def number(raw: Any) -> float:
            if isinstance(raw, Decimal):
                return float(raw)
            parsed = _sort_number(raw) if raw is not MISSING else None
            return float(parsed) if parsed is not None else 0.0

        palette = node["palette"]
        out: list[dict[str, Any]] = []
        if node["source"] is not None:
            arr = self._eval(node["source"], scope, node["id"])
            if not isinstance(arr, list):
                if arr is not MISSING and arr is not None:
                    self.warnings.add("REPEATER_SOURCE_NOT_ARRAY", node=node["id"])
                arr = []
            for item in arr:
                if isinstance(item, dict):
                    out.append(
                        {
                            "pct": number(_chart_field(item, node["valueField"])),
                            "label": _chart_text(_chart_field(item, node["labelField"])),
                            "color": _chart_field(item, node["colorField"]),
                        }
                    )
                else:
                    out.append({"pct": number(item), "label": "", "color": None})
        else:
            self.env.node_id = node["id"]
            for seg in node["segments"]:
                value = self._eval(seg["value"], scope, node["id"]) if seg["value"] is not None else 0
                color = seg["color"]
                if isinstance(color, tuple):
                    resolved = self._eval(color, scope, node["id"])
                    color = resolved if isinstance(resolved, str) else None
                out.append(
                    {"pct": number(value), "label": render_template(seg["label"], scope, self.env), "color": color}
                )
        for i, seg in enumerate(out):
            if not seg["color"]:
                seg["color"] = palette[i % len(palette)] if palette else "#000000"
        return out

    def _chart_label(
        self,
        text: str,
        font: str,
        size: float,
        color: str,
        x: float,
        baseline: float,
        anchor: str,
        spacing: float = 0.0,
    ) -> DrawNode:
        """A one-line text positioned by its baseline; ``anchor`` is start, middle or end."""
        run = {"text": text, "font": font, "size": size, "letterSpacing": spacing, "lineHeight": 1.2, "textCase": None}
        para = {"align": "left", "indent": 0.0, "spaceBefore": 0.0, "spaceAfter": 0.0, "runs": [run]}
        box = {
            "w": 0.0,
            "h": 0.0,
            "autoSize": "width",
            "overflowMode": "clip",
            "maxLines": None,
            "ellipsis": False,
            "minFontSize": None,
            "verticalAlign": "top",
            "paragraphSpacing": 0.0,
        }
        result = layout_text(
            [para],
            box,
            self.fonts.metrics,
            kerning=self.opt.kerning,
            fallback_run={"font": font, "size": size, "lineHeight": 1.2},
        )
        width = float(result["width"])
        first = result["lines"][0]["baseline"] if result["lines"] else size
        left = x if anchor == "start" else (x - width if anchor == "end" else x - width / 2)
        dn = DrawNode("text", "chart-label", left, baseline - float(first), width, float(result["height"]))
        dn.text = result
        dn.text_runs = [
            {
                "fontKey": font,
                "fontSize": size,
                "color": color,
                "letterSpacing": spacing,
                "underline": False,
                "strike": False,
            }
        ]
        return dn

    def _chart_geometry(
        self,
        node: dict[str, Any],
        segments: list[dict[str, Any]],
        outer: float,
        inner: float,
        font: str,
        size: float,
        cx: float,
        cy: float,
    ) -> tuple[list[DrawNode], tuple[float, float, float, float]]:
        """Ring, leader lines and labels; returns draw nodes and their bounding box."""
        labels = node["labels"]
        k = outer / 120.0
        rings: list[DrawNode] = []
        leaders: list[DrawNode] = []
        texts: list[DrawNode] = []
        min_x, min_y, max_x, max_y = cx - outer, cy - outer, cx + outer, cy + outer
        ratio = (inner / outer) if outer > 0 else 0.0
        ratio = min(0.999, max(0.0, ratio))
        angle = node["startAngle"] - 90.0

        for i, seg in enumerate(segments):
            pct = seg["pct"]
            sweep = pct / 100 * 360
            full = pct >= 99.99
            ring = DrawNode("ellipse", f"{node['id']}-s{i}", cx - outer, cy - outer, outer * 2, outer * 2)
            ring.fills = [{"type": "solid", "color": seg["color"], "opacity": 1.0}]
            ring.arc = (angle, angle + 360.0, ratio) if full else (angle, angle + sweep, ratio)
            rings.append(ring)
            mid = math.radians(angle + sweep / 2)
            cos_m, sin_m = math.cos(mid), math.sin(mid)
            if labels["show"] and pct >= labels["minPct"]:
                text = f"{round(pct)}%"
                if pct >= labels["outsidePct"]:
                    radius = (outer + inner) / 2 + 5 * k
                    color = labels["remainderLabelColor"] if seg.get("remainder") else labels["insideColor"]
                    texts.append(
                        self._chart_label(
                            text, font, size, color, cx + radius * cos_m, cy + radius * sin_m + size * 0.385, "middle"
                        )
                    )
                else:
                    p1 = (cx + outer * cos_m, cy + outer * sin_m)
                    p2 = (cx + (outer + 18 * k) * cos_m, cy + (outer + 18 * k) * sin_m)
                    right = cos_m >= 0
                    p3 = (p2[0] + (16 * k if right else -16 * k), p2[1])
                    for a, b in ((p1, p2), (p2, p3)):
                        line = DrawNode("line", f"{node['id']}-l{i}", 0.0, 0.0, 0.0, 0.0)
                        line.points = [a, b]
                        line.strokes = [
                            {
                                "color": labels["leaderColor"],
                                "width": labels["leaderWidth"] * max(k, 0.25),
                                "dash": [],
                                "cap": "butt",
                                "join": "miter",
                                "miterLimit": 4.0,
                                "opacity": 1.0,
                            }
                        ]
                        leaders.append(line)
                    tx = p3[0] + (4 * k if right else -4 * k)
                    label = self._chart_label(
                        text, font, size, labels["outsideColor"], tx, p3[1] + size * 0.31, "start" if right else "end"
                    )
                    texts.append(label)
                    min_x, max_x = min(min_x, label.x), max(max_x, label.x + label.w)
                    min_y, max_y = min(min_y, label.y), max(max_y, label.y + label.h)
                    for px, py in (p2, p3):
                        min_x, max_x = min(min_x, px), max(max_x, px)
                        min_y, max_y = min(min_y, py), max(max_y, py)
            angle += sweep
        return rings + leaders + texts, (min_x, min_y, max_x, max_y)

    def _chart_center(
        self, node: dict[str, Any], scope: Scope, outer: float, inner: float, cx: float, cy: float
    ) -> list[DrawNode]:
        center = node["center"]
        if not center:
            return []
        self.env.node_id = node["id"]
        k = outer / 120.0
        out: list[DrawNode] = []
        line_font = self.fonts.resolve(center["fontId"], center["fontFamily"], center["lineFontWeight"], "normal")
        line_size = center["lineFontSize"] or 8 * k
        spacing = center["lineLetterSpacing"] if center["lineLetterSpacing"] >= 0 else 1.5 * k
        baseline = cy - 18 * k
        for key in ("line1", "line2"):
            text = render_template(center[key], scope, self.env)
            if text:
                out.append(
                    self._chart_label(text, line_font, line_size, center["lineColor"], cx, baseline, "middle", spacing)
                )
            baseline += 11 * k
        value = render_template(center["value"], scope, self.env)
        if value:
            font = self.fonts.resolve(center["fontId"], center["fontFamily"], center["valueFontWeight"], "normal")
            size = center["valueFontSize"] or 20 * k
            label = self._chart_label(value, font, size, center["valueColor"], cx, cy + 19 * k, "middle")
            limit = inner * 1.8
            if label.w > limit > 0:
                size = size * limit / label.w
                label = self._chart_label(value, font, size, center["valueColor"], cx, cy + 19 * k, "middle")
            out.append(label)
        return out

    def _chart_series_data(self, node: dict[str, Any], scope: Scope) -> dict[str, Any]:
        """Resolve the data of a cartesian or radar chart (§1a): ``source`` wins over static data."""
        nid = node["id"]
        self.env.node_id = nid
        scatter = node["chartType"] == "scatter"
        defs = node["series"]
        categories: list[str] = []
        series: list[dict[str, Any]] = []

        def color_of(raw: Any) -> Any:
            if isinstance(raw, tuple):
                resolved = self._eval(raw, scope, nid)
                return resolved if isinstance(resolved, str) and resolved else None
            return raw

        if node["source"] is not None:
            arr = self._eval(node["source"], scope, nid)
            if not isinstance(arr, list):
                if arr is not MISSING and arr is not None:
                    self.warnings.add("REPEATER_SOURCE_NOT_ARRAY", node=nid)
                arr = []
            label_field = node["labelField"]
            categories = [_chart_text(_chart_field(it, label_field)) if isinstance(it, dict) else "" for it in arr]
            for d in defs or [{"name": ("",), "color": None, "valueField": node["valueField"]}]:
                y_field = (
                    d.get("yField")
                    or d.get("valueField")
                    or (node["yField"] if scatter else None)
                    or node["valueField"]
                )
                x_field = d.get("xField") or node["xField"]
                entry: dict[str, Any] = {
                    "name": render_template(d["name"], scope, self.env),
                    "color": color_of(d["color"]),
                    "values": [_chart_value(_chart_field(it, y_field) if isinstance(it, dict) else it) for it in arr],
                }
                if scatter:
                    if x_field:
                        entry["xs"] = [
                            _chart_value(_chart_field(it, x_field)) if isinstance(it, dict) else None for it in arr
                        ]
                    else:
                        entry["xs"] = [_chart_value(c) for c in categories]
                if not defs and node["colorField"]:
                    entry["colors"] = [
                        _chart_field(it, node["colorField"]) if isinstance(it, dict) else None for it in arr
                    ]
                series.append(entry)
        elif defs:
            categories = [render_template(c, scope, self.env) for c in node["categories"]]
            for d in defs:
                entry = {
                    "name": render_template(d["name"], scope, self.env),
                    "color": color_of(d["color"]),
                    "values": [_chart_value(self._eval(v, scope, nid)) if v is not None else None for v in d["values"]],
                }
                if scatter:
                    entry["xs"] = [_chart_value(c) for c in categories]
                series.append(entry)
        elif node["segments"]:
            values: list[float | None] = []
            colors: list[Any] = []
            for seg in node["segments"]:
                values.append(_chart_value(self._eval(seg["value"], scope, nid)) if seg["value"] is not None else None)
                categories.append(render_template(seg["label"], scope, self.env))
                colors.append(color_of(seg["color"]))
            entry = {"name": "", "color": None, "values": values, "colors": colors}
            if scatter:
                entry["xs"] = [_chart_value(c) for c in categories]
            series.append(entry)
        return {"categories": categories, "series": series}

    def _chart_input(self, node: dict[str, Any], scope: Scope, w: float, h: float) -> dict[str, Any]:
        inp: dict[str, Any] = {
            "chartType": node["chartType"],
            "w": w,
            "h": h,
            "locale": self.opt.locale,
            "palette": node["palette"],
            "labels": node["labelsRaw"],
            "legend": node["legend"],
            "axes": node["axes"],
            "grid": node["grid"],
            "markers": node["markers"],
            "barGap": node["barGap"],
            "lineWidth": node["lineWidth"],
            "fillOpacity": node["fillOpacity"],
            "smooth": node["smooth"],
            "startAngle": node["startAngle"],
        }
        if node["chartType"] in ROUND_TYPES:
            palette = node["palette"]
            inp.update(
                {
                    "segments": [
                        {"pct": s["pct"], "label": s["label"], "color": s["color"]}
                        for s in self._chart_raw_segments({**node, "palette": palette or list(CHART_PALETTE)}, scope)
                    ],
                    "outerRadius": node["outerRadius"],
                    "innerRadius": node["innerRadius"],
                    "remainderColor": node["remainderColor"],
                    "normalize": node["normalize"],
                }
            )
        else:
            inp.update(self._chart_series_data(node, scope))
        return inp

    def _chart_ops_nodes(self, node: dict[str, Any], ops: list[dict[str, Any]], w: float, h: float) -> list[DrawNode]:
        """Draw nodes for the operations of ``charts.chart_ops``; labels stay inside by their real width."""
        labels = node["labels"]
        nid = node["id"]
        out: list[DrawNode] = []

        def stroke(color: str, width: float) -> dict[str, Any]:
            return {
                "color": color,
                "width": width,
                "dash": [],
                "cap": "round",
                "join": "round",
                "miterLimit": 4.0,
                "opacity": 1.0,
            }

        for i, op in enumerate(ops):
            kind = op["op"]
            if kind == "rect":
                n = DrawNode("rect", f"{nid}-r{i}", op["x"], op["y"], op["w"], op["h"])
                n.fills = [{"type": "solid", "color": op["fill"], "opacity": 1.0}]
            elif kind == "line":
                n = DrawNode("path", f"{nid}-l{i}", 0.0, 0.0, 0.0, 0.0)
                pts = op["pts"]
                n.path = [["M" if k == 0 else "L", pts[k], pts[k + 1]] for k in range(0, len(pts), 2)]
                n.strokes = [stroke(op["stroke"], op["width"])]
            elif kind == "path":
                n = DrawNode("path", f"{nid}-p{i}", 0.0, 0.0, 0.0, 0.0)
                n.path = op["d"]
                if op["fill"]:
                    n.fills = [{"type": "solid", "color": op["fill"], "opacity": op["fillOpacity"]}]
                if op["stroke"]:
                    n.strokes = [stroke(op["stroke"], op["width"])]
            elif kind == "circle":
                r = op["r"]
                n = DrawNode("ellipse", f"{nid}-c{i}", op["cx"] - r, op["cy"] - r, r * 2, r * 2)
                if op["fill"]:
                    n.fills = [{"type": "solid", "color": op["fill"], "opacity": 1.0}]
                if op["stroke"]:
                    n.strokes = [stroke(op["stroke"], op["width"])]
            elif kind == "arc":
                outer = op["outer"]
                n = DrawNode("ellipse", f"{nid}-s{i}", op["cx"] - outer, op["cy"] - outer, outer * 2, outer * 2)
                n.fills = [{"type": "solid", "color": op["fill"], "opacity": 1.0}]
                ratio = min(0.999, max(0.0, op["inner"] / outer)) if outer > 0 else 0.0
                n.arc = (op["start"] - 90.0, op["end"] - 90.0, ratio)
            else:
                font = self.fonts.resolve(labels["fontId"], labels["fontFamily"], op["weight"], "normal")
                n = self._chart_label(op["text"], font, op["size"], op["color"], op["x"], op["y"], op["anchor"])
                n.x = max(0.0, min(n.x, w - n.w))
            out.append(n)
        return out

    def _layout_chart(self, node: dict[str, Any], dn: DrawNode, scope: Scope) -> None:
        if node["chartType"] != "donut" or node["legend"].get("show") is True:
            result = chart_ops(self._chart_input(node, scope, dn.w, dn.h))
            dn.clip = True
            dn.children = self._chart_ops_nodes(node, result["ops"], dn.w, dn.h)
            geo = result.get("center")
            if geo and node["chartType"] == "donut":
                dn.children += self._chart_center(node, scope, geo["outer"], geo["inner"], geo["cx"], geo["cy"])
            return
        segments = self._chart_segments(node, scope)
        half = min(dn.w, dn.h) / 2
        outer = node["outerRadius"] or half
        inner = node["innerRadius"] if node["innerRadius"] >= 0 else outer * 0.5833
        labels = node["labels"]
        font = self.fonts.resolve(labels["fontId"], labels["fontFamily"], labels["fontWeight"], "normal")
        size = labels["fontSize"] or 13 * outer / 120.0
        cx, cy = dn.w / 2, dn.h / 2
        _, (x0, y0, x1, y1) = self._chart_geometry(node, segments, outer, inner, font, size, cx, cy)
        reach_x = max(cx - x0, x1 - cx)
        reach_y = max(cy - y0, y1 - cy)
        scale = min(1.0, (dn.w / 2) / reach_x if reach_x > 0 else 1.0, (dn.h / 2) / reach_y if reach_y > 0 else 1.0)
        if scale < 1.0:
            outer, inner, size = outer * scale, inner * scale, size * scale
        nodes, _ = self._chart_geometry(node, segments, outer, inner, font, size, cx, cy)
        dn.clip = False
        dn.children = nodes + self._chart_center(node, scope, outer, inner, cx, cy)

    # ------------------------------------------------------------------ text
    def _resolve_runs(self, node: dict[str, Any], scope: Scope) -> tuple[list[dict[str, Any]], list[dict[str, Any]]]:
        self.env.node_id = node["id"]
        paragraphs: list[dict[str, Any]] = []
        styles: list[dict[str, Any]] = []
        for para in node["paragraphs"]:
            runs = []
            for run in para["runs"]:
                text = render_template(run["parts"], scope, self.env)
                st = run["style"]
                key = self.fonts.resolve(st["fontId"], st["fontFamily"], st["fontWeight"], st["fontStyle"])
                text_case = st.get("textCase")
                runs.append(
                    {
                        "text": text,
                        "font": key,
                        "size": st["fontSize"],
                        "letterSpacing": st["letterSpacing"],
                        "lineHeight": st["lineHeight"],
                        "textCase": text_case if text_case != "none" else None,
                    }
                )
                styles.append(st | {"fontKey": key})
            if node["collapseEmpty"] and runs and not "".join(r["text"] for r in runs).strip():
                styles = styles[: len(styles) - len(runs)]
                continue
            paragraphs.append({**{k: para[k] for k in ("align", "indent", "spaceBefore", "spaceAfter")}, "runs": runs})
        return paragraphs, styles

    def _fill_text(self, dn: DrawNode, node: dict[str, Any], scope: Scope) -> None:
        paragraphs, styles = self._resolve_runs(node, scope)
        fb = node["fallbackStyle"]
        fb_key = self.fonts.resolve(fb["fontId"], fb["fontFamily"], fb["fontWeight"], fb["fontStyle"])
        auto = node["autoSize"] if not node["pageRef"] else ("width" if node["autoSize"] == "width" else "none")
        box = {
            "w": dn.w,
            "h": dn.h,
            "autoSize": auto,
            "overflowMode": node["overflowMode"],
            "maxLines": node["maxLines"],
            "ellipsis": node["ellipsis"],
            "minFontSize": node["minFontSize"],
            "verticalAlign": node["verticalAlign"],
            "paragraphSpacing": node["paragraphSpacing"],
        }
        result = layout_text(
            paragraphs,
            box,
            self.fonts.metrics,
            kerning=self.opt.kerning,
            fallback_run={"font": fb_key, "size": fb["fontSize"], "lineHeight": fb["lineHeight"]},
        )
        for code in result["warnings"]:
            self.warnings.add(code, node=node["id"])
        if auto == "height":
            dn.h = result["height"]
        elif auto == "width":
            new_w = result["width"]
            align = paragraphs[0]["align"] if paragraphs else "left"
            if align == "center":
                dn.x += (dn.w - new_w) / 2
            elif align == "right":
                dn.x += dn.w - new_w
            dn.w = new_w
            dn.h = max(dn.h, result["height"]) if node["pageRef"] else result["height"]
        dn.text = result
        dn.text_runs = styles

    # ------------------------------------------------------------------ images
    def _fill_image(self, dn: DrawNode, node: dict[str, Any], scope: Scope) -> bool:
        ref: ImageRef | None = None
        candidates: list[str] = []
        if node["src"] is not None:
            value = self._eval(node["src"], scope, node["id"])
            if isinstance(value, str) and value:
                candidates.append(value)
        if node["assetId"]:
            candidates.append(str(node["assetId"]))
        if node["fallbackAssetId"]:
            candidates.append(str(node["fallbackAssetId"]))
        for src in candidates:
            ref = self._image(src)
            if ref is not None:
                break
        if ref is None:
            self.warnings.add("IMAGE_UNAVAILABLE", node=node["id"])
            return False
        dn.image = ref
        dn.fit = node["fit"]
        dn.focal = node["focal"]
        return True

    def _image(self, src: str) -> ImageRef | None:
        if src in self._image_cache:
            return self._image_cache[src]
        ref: ImageRef | None
        if src.startswith(("http://", "https://", "data:")):
            try:
                ref = self.assets.fetch(src)
            except RenderError:
                raise
            except Exception:
                ref = None
            if ref is None and src.startswith("http"):
                self.warnings.add("IMAGE_FETCH_FAILED", url=src[:200])
        else:
            ref = self.assets.image(src)
        self._image_cache[src] = ref
        return ref
