"""Compile a scene graph document (TZ 2.3) into a render plan (TZ 2.6.3).

The plan is a normalised copy of the document made only of builtin types (dict/list/tuple/str/int/float/
bool/None), so it can be stored with ``marshal``. Compilation:

* fills defaults, sheet sizes from ``format``/``orientation``;
* resolves ``styleRef`` and document defaults into explicit run styles;
* parses ``{{...}}`` templates, ``visibleIf``, ``bind``, ``repeater.source``/``filter``, ``image.src``;
* marks text nodes that reference ``page.*`` (laid out after pagination);
* collects used fonts / assets.
"""

from __future__ import annotations

from typing import Any

from . import ENGINE_VERSION, PLAN_FORMAT
from .charts import AXIS_WEIGHT, CHART_TYPES, ROUND_TYPES
from .errors import RenderError
from .expr.parser import Ast, ExprSyntaxError, collect_paths, parse_expression, parse_template

SHEET_FORMATS: dict[str, tuple[float, float]] = {
    "A3": (841.89, 1190.55),
    "A4": (595.28, 841.89),
    "A5": (419.53, 595.28),
    "Letter": (612.0, 792.0),
    "Legal": (612.0, 1008.0),
}

DEFAULT_TEXT_STYLE: dict[str, Any] = {
    "fontFamily": "Inter",
    "fontId": None,
    "fontSize": 10.0,
    "fontWeight": 400,
    "fontStyle": "normal",
    "color": "#000000",
    "letterSpacing": 0.0,
    "lineHeight": 1.2,
    "underline": False,
    "strike": False,
    "textCase": "none",
}

SUPPORTED_NODES = frozenset({"frame", "group", "rect", "ellipse", "line", "text", "image", "repeater", "chart"})
FOCAL_PRESETS: dict[str, tuple[float, float]] = {
    "center": (0.5, 0.5),
    "left top": (0.0, 0.0),
    "top": (0.5, 0.0),
    "right top": (1.0, 0.0),
    "left": (0.0, 0.5),
    "right": (1.0, 0.5),
    "left bottom": (0.0, 1.0),
    "bottom": (0.5, 1.0),
    "right bottom": (1.0, 1.0),
}
STROKE_SIDES = ("top", "right", "bottom", "left")
STYLE_KEYS = tuple(DEFAULT_TEXT_STYLE)


class CompileContext:
    def __init__(self, strict: bool = False) -> None:
        self.strict = strict
        self.errors: list[dict[str, Any]] = []
        self.warnings: list[dict[str, Any]] = []
        self.fonts: set[str] = set()
        self.families: set[tuple[str, int, str]] = set()
        self.assets: set[str] = set()
        self.variables: set[str] = set()
        self.node_ids: set[str] = set()

    def error(self, code: str, message: str, **info: Any) -> None:
        self.errors.append({"code": code, "message": message, **info})

    def warn(self, code: str, **info: Any) -> None:
        self.warnings.append({"code": code, **info})


def _num(value: Any, default: float = 0.0) -> float:
    if value is None or isinstance(value, bool):
        return default
    try:
        return round(float(value), 4)
    except (TypeError, ValueError):
        return default


def _expr(source: Any, ctx: CompileContext, node_id: str, field: str) -> Ast | None:
    if source is None or source == "":
        return None
    if not isinstance(source, str):
        return ("const", source)
    try:
        ast = parse_expression(source)
    except ExprSyntaxError as exc:
        ctx.error("SCENE_EXPRESSION_INVALID", str(exc), node=node_id, field=field)
        return None
    ctx.variables.update(collect_paths(ast))
    return ast


def _template(text: str, ctx: CompileContext, node_id: str) -> tuple[Any, ...]:
    try:
        parts = parse_template(text)
    except ExprSyntaxError as exc:
        ctx.error("SCENE_EXPRESSION_INVALID", str(exc), node=node_id, field="text")
        return (text,)
    for part in parts:
        if not isinstance(part, str):
            ctx.variables.update(collect_paths(part[1]))
    return parts


def _uses_page(parts: tuple[Any, ...]) -> bool:
    for part in parts:
        if not isinstance(part, str) and any(p == "page" or p.startswith("page.") for p in collect_paths(part[1])):
            return True
    return False


def _merge_style(base: dict[str, Any], extra: dict[str, Any] | None) -> dict[str, Any]:
    if not extra:
        return base
    merged = dict(base)
    for k, v in extra.items():
        if v is not None:
            merged[k] = v
    return merged


def _focal(raw: Any) -> tuple[float, float]:
    if isinstance(raw, str):
        return FOCAL_PRESETS.get(raw.strip().lower(), (0.5, 0.5))
    if isinstance(raw, dict):
        return (_num(raw.get("x"), 0.5), _num(raw.get("y"), 0.5))
    return (0.5, 0.5)


def _edges(raw: Any) -> dict[str, float]:
    if isinstance(raw, dict):
        return {k: _num(raw.get(k)) for k in STROKE_SIDES}
    return dict.fromkeys(STROKE_SIDES, _num(raw))


def _paints(raw: Any, ctx: CompileContext) -> list[dict[str, Any]]:
    out: list[dict[str, Any]] = []
    for p in raw or []:
        if not isinstance(p, dict) or p.get("visible") is False:
            continue
        paint = dict(p)
        paint.setdefault("type", "solid")
        paint["opacity"] = _num(p.get("opacity"), 1.0)
        if paint["type"] == "image":
            paint["focal"] = _focal(p.get("focal"))
            if p.get("assetId"):
                ctx.assets.add(str(p["assetId"]))
        out.append(paint)
    return out


def _strokes(raw: Any) -> list[dict[str, Any]]:
    out: list[dict[str, Any]] = []
    for s in raw or []:
        if not isinstance(s, dict) or s.get("visible") is False:
            continue
        out.append(
            {
                "color": s.get("color", "#000000"),
                "width": _num(s.get("width"), 1.0),
                "align": s.get("align", "center"),
                "dash": [float(d) for d in (s.get("dash") or [])],
                "cap": s.get("cap", "butt"),
                "join": s.get("join", "miter"),
                "miterLimit": _num(s.get("miterLimit"), 4.0),
                "opacity": _num(s.get("opacity"), 1.0),
            }
        )
    return out


class Compiler:
    def __init__(self, ctx: CompileContext | None = None) -> None:
        self.ctx = ctx or CompileContext()
        self.styles: dict[str, Any] = {}
        self.defaults: dict[str, Any] = dict(DEFAULT_TEXT_STYLE)

    # ------------------------------------------------------------------ document
    def compile(self, doc: dict[str, Any]) -> dict[str, Any]:
        ctx = self.ctx
        if not isinstance(doc, dict):
            raise RenderError("SCENE_INVALID", "Document must be an object")
        fv = doc.get("formatVersion", 1)
        if fv != 1:
            raise RenderError("SCENE_FORMAT_UNSUPPORTED", f"formatVersion {fv} is not supported")
        defaults = doc.get("defaults") or {}
        self.defaults = _merge_style(DEFAULT_TEXT_STYLE, {k: defaults.get(k) for k in STYLE_KEYS})
        self.styles = doc.get("styles") or {}
        meta_raw = doc.get("meta") or {}
        meta = {
            k: _template(str(v), ctx, "meta")
            for k, v in meta_raw.items()
            if k in ("title", "author", "subject", "keywords") and v
        }
        sheets_raw = doc.get("sheets")
        if not isinstance(sheets_raw, list) or not sheets_raw:
            raise RenderError("SCENE_INVALID", "Document must contain at least one sheet")
        sheets = [self.sheet(s, i) for i, s in enumerate(sheets_raw)]
        continuation_targets = {
            s["overflow"].get("continuationSheetId") for s in sheets if s["overflow"].get("continuationSheetId")
        }
        for s in sheets:
            s["continuationOnly"] = s["id"] in continuation_targets and not any(
                o["id"] == s["id"] and o["overflow"].get("continuationSheetId") == s["id"] for o in sheets
            )
        if ctx.strict and ctx.errors:
            raise RenderError("SCENE_INVALID", "Scene graph has errors", ctx.errors[:100])
        return {
            "format": PLAN_FORMAT,
            "engine": ENGINE_VERSION,
            "meta": meta,
            "locale": defaults.get("locale"),
            "defaults": self.defaults,
            "sheets": sheets,
            "fonts": sorted(ctx.fonts),
            "families": sorted([list(f) for f in ctx.families]),
            "assets": sorted(ctx.assets),
            "variables": sorted(ctx.variables),
        }

    # ------------------------------------------------------------------ sheets
    def sheet(self, raw: dict[str, Any], index: int) -> dict[str, Any]:
        ctx = self.ctx
        sid = str(raw.get("id") or f"sheet{index}")
        fmt = raw.get("format", "A4")
        orientation = raw.get("orientation", "portrait")
        size = raw.get("size") or {}
        if size.get("w") and size.get("h"):
            w, h = _num(size["w"]), _num(size["h"])
        else:
            w, h = SHEET_FORMATS.get(fmt, SHEET_FORMATS["A4"])
            if orientation == "landscape":
                w, h = h, w
        bleed = raw.get("bleed") or 0
        bleed_v = _num(bleed) if not isinstance(bleed, dict) else max(_num(v) for v in bleed.values())
        repeat = raw.get("repeat")
        repeat_c = None
        if isinstance(repeat, dict) and repeat.get("source"):
            repeat_c = {
                "source": _expr(repeat["source"], ctx, sid, "repeat.source"),
                "as": repeat.get("as", "item"),
                "indexAs": repeat.get("indexAs", "index"),
                "maxPages": int(repeat.get("maxPages") or 200),
            }
        background = raw.get("background")
        overflow = raw.get("overflow") or {}
        return {
            "id": sid,
            "name": str(raw.get("name") or sid),
            "w": w,
            "h": h,
            "bleed": bleed_v,
            "background": _paints([background], ctx)[0] if isinstance(background, dict) else None,
            "children": self.children(raw.get("children"), sid),
            "repeat": repeat_c,
            "visibleIf": _expr(raw.get("visibleIf"), ctx, sid, "visibleIf"),
            "overflow": {
                "continuationSheetId": overflow.get("continuationSheetId"),
                "maxPages": int(overflow.get("maxPages") or 50),
            },
            "pageNumbering": {
                "skip": bool((raw.get("pageNumbering") or {}).get("skip")),
                "restart": (raw.get("pageNumbering") or {}).get("restart"),
            },
            "raster": (raw.get("export") or {}).get("raster", True) is not False,
        }

    # ------------------------------------------------------------------ nodes
    def children(self, raw: Any, parent: str) -> list[dict[str, Any]]:
        out: list[dict[str, Any]] = []
        for i, child in enumerate(raw or []):
            if not isinstance(child, dict):
                continue
            node = self.node(child, f"{parent}/{i}")
            if node is not None:
                out.append(node)
        return out

    def node(self, raw: dict[str, Any], fallback_id: str) -> dict[str, Any] | None:
        ctx = self.ctx
        nid = str(raw.get("id") or fallback_id)
        ntype = raw.get("type")
        if raw.get("visible") is False:
            return None
        if ntype not in SUPPORTED_NODES:
            ctx.warn("NODE_UNSUPPORTED", node=nid, type=ntype)
            return None
        origin = raw.get("origin") or {}
        constraints = raw.get("constraints") or {}
        sizing = raw.get("sizing") or {}
        node: dict[str, Any] = {
            "id": nid,
            "type": ntype,
            "x": _num(raw.get("x")),
            "y": _num(raw.get("y")),
            "w": _num(raw.get("w")),
            "h": _num(raw.get("h")),
            "rotation": _num(raw.get("rotation")),
            "origin": (_num(origin.get("x"), 0.5), _num(origin.get("y"), 0.5)),
            "opacity": _num(raw.get("opacity"), 1.0),
            "blendMode": raw.get("blendMode", "normal"),
            "visibleIf": _expr(raw.get("visibleIf"), ctx, nid, "visibleIf"),
            "constraints": (constraints.get("horizontal", "left"), constraints.get("vertical", "top")),
            "fills": _paints(raw.get("fills"), ctx),
            "strokes": _strokes(raw.get("strokes")),
            "strokeSides": tuple(s for s in STROKE_SIDES if s in (raw.get("strokeSides") or ()))
            if raw.get("strokeSides") is not None
            else None,
            "cornerRadius": raw.get("cornerRadius") or 0,
            "clip": bool(raw.get("clip", ntype == "frame")),
            "sizing": (sizing.get("w", "fixed"), sizing.get("h", "fixed")),
            "pushDown": bool(raw.get("pushDown")),
            "anchorTo": raw.get("anchorTo") if isinstance(raw.get("anchorTo"), dict) else None,
            "showOn": raw.get("showOn", "all"),
            "bind": [],
        }
        for prop, src in (raw.get("bind") or {}).items():
            ast = _expr(src, ctx, nid, f"bind.{prop}")
            if ast is not None:
                node["bind"].append((str(prop), ast))
        handler = getattr(self, f"_node_{ntype}")
        handler(node, raw)
        return node

    def _node_rect(self, node: dict[str, Any], raw: dict[str, Any]) -> None:
        pass

    def _node_ellipse(self, node: dict[str, Any], raw: dict[str, Any]) -> None:
        arc = raw.get("arc")
        node["arc"] = (
            (_num(arc.get("start")), _num(arc.get("end"), 360.0), _num(arc.get("innerRatio")))
            if isinstance(arc, dict)
            else None
        )

    def _node_line(self, node: dict[str, Any], raw: dict[str, Any]) -> None:
        pts = raw.get("points") or [{"x": 0, "y": 0}, {"x": node["w"], "y": node["h"]}]
        node["points"] = [(_num(p.get("x")), _num(p.get("y"))) for p in pts[:2]]
        if not node["strokes"]:
            node["strokes"] = _strokes([{"color": "#000000", "width": 1}])

    def _node_frame(self, node: dict[str, Any], raw: dict[str, Any]) -> None:
        node["children"] = self.children(raw.get("children"), node["id"])
        layout = raw.get("layout") if isinstance(raw.get("layout"), dict) else {}
        mode = layout.get("mode", "none")
        node["layout"] = (
            {
                "mode": mode,
                "gap": _num(layout.get("gap")),
                "padding": _edges(layout.get("padding")),
                "align": layout.get("align", "start"),
                "justify": layout.get("justify", "start"),
            }
            if mode in ("vertical", "horizontal")
            else None
        )

    def _node_group(self, node: dict[str, Any], raw: dict[str, Any]) -> None:
        node["children"] = self.children(raw.get("children"), node["id"])
        node["clip"] = False

    def _node_image(self, node: dict[str, Any], raw: dict[str, Any]) -> None:
        if raw.get("assetId"):
            self.ctx.assets.add(str(raw["assetId"]))
        if raw.get("fallbackAssetId"):
            self.ctx.assets.add(str(raw["fallbackAssetId"]))
        node["assetId"] = raw.get("assetId")
        node["src"] = _expr(raw.get("src"), self.ctx, node["id"], "src")
        node["fit"] = raw.get("fit", "cover")
        node["focal"] = _focal(raw.get("focal"))
        node["fallbackAssetId"] = raw.get("fallbackAssetId")

    def _run_style(self, run: dict[str, Any]) -> dict[str, Any]:
        style = dict(self.defaults)
        ref = run.get("styleRef")
        if ref and isinstance(self.styles.get(ref), dict):
            style = _merge_style(style, self.styles[ref])
        style = _merge_style(style, run.get("style"))
        out = {k: style.get(k) for k in STYLE_KEYS}
        out["fontSize"] = _num(out["fontSize"], 10.0)
        out["fontWeight"] = int(out["fontWeight"] or 400)
        out["letterSpacing"] = _num(out["letterSpacing"])
        if out["fontId"]:
            self.ctx.fonts.add(str(out["fontId"]))
        else:
            self.ctx.families.add((str(out["fontFamily"]), out["fontWeight"], str(out["fontStyle"])))
        return out

    def _node_text(self, node: dict[str, Any], raw: dict[str, Any]) -> None:
        paragraphs: list[dict[str, Any]] = []
        uses_page = False
        dynamic = False
        content = raw.get("content")
        if isinstance(content, str):
            content = [{"runs": [{"text": content}]}]
        for para in content or []:
            runs = []
            for run in para.get("runs") or []:
                parts = _template(str(run.get("text", "")), self.ctx, node["id"])
                uses_page = uses_page or _uses_page(parts)
                dynamic = dynamic or any(not isinstance(p, str) for p in parts)
                runs.append({"parts": parts, "style": self._run_style(run)})
            paragraphs.append(
                {
                    "align": para.get("align", "left"),
                    "indent": _num(para.get("indent")),
                    "spaceBefore": _num(para.get("spaceBefore")),
                    "spaceAfter": _num(para.get("spaceAfter")),
                    "runs": runs,
                }
            )
        node["paragraphs"] = paragraphs
        node["autoSize"] = raw.get("autoSize", "none")
        node["overflowMode"] = raw.get("overflowMode", "clip")
        node["maxLines"] = raw.get("maxLines")
        node["ellipsis"] = bool(raw.get("ellipsis"))
        node["minFontSize"] = raw.get("minFontSize")
        node["verticalAlign"] = raw.get("verticalAlign", "top")
        node["paragraphSpacing"] = _num(raw.get("paragraphSpacing"))
        node["collapseEmpty"] = bool(raw.get("collapseEmpty"))
        node["pageRef"] = uses_page
        node["dynamic"] = dynamic or bool(node["bind"]) or node["visibleIf"] is not None
        node["fallbackStyle"] = dict(self.defaults)

    def _cell(self, raw: Any, owner: str, part: str) -> dict[str, Any] | None:
        if not isinstance(raw, dict):
            return None
        sizing = raw.get("sizing") or {}
        return {
            "w": _num(raw.get("w")) or None,
            "h": _num(raw.get("h", raw.get("height"))),
            "hug": sizing.get("h") == "hug",
            "repeat": raw.get("repeat", True) is not False,
            "children": self.children(raw.get("children"), f"{owner}/{part}"),
        }

    def _node_repeater(self, node: dict[str, Any], raw: dict[str, Any]) -> None:
        ctx = self.ctx
        gap = raw.get("gap", 0)
        if isinstance(gap, dict):
            gap_row, gap_col = _num(gap.get("row")), _num(gap.get("col"))
        else:
            gap_row = gap_col = _num(gap)
        sort = raw.get("sort") if isinstance(raw.get("sort"), dict) else None
        node.update(
            {
                "source": _expr(raw.get("source"), ctx, node["id"], "source"),
                "as": raw.get("as", "item"),
                "indexAs": raw.get("indexAs", "index"),
                "direction": raw.get("direction", "vertical"),
                "gapRow": gap_row,
                "gapCol": gap_col,
                "columns": max(1, int(raw.get("columns") or 1)),
                "item": self._cell(raw.get("item"), node["id"], "item")
                or {"w": None, "h": 20.0, "hug": False, "repeat": True, "children": []},
                "header": self._cell(raw.get("header"), node["id"], "header"),
                "footer": self._cell(raw.get("footer"), node["id"], "footer"),
                "emptyState": self._cell(raw.get("emptyState"), node["id"], "empty"),
                "overflow": raw.get("overflow", "clip"),
                "keepTogether": raw.get("keepTogether", True) is not False,
                "maxItems": raw.get("maxItems"),
                "sort": (sort.get("by"), sort.get("order", "asc")) if sort else None,
                "filter": _expr(raw.get("filter"), ctx, node["id"], "filter"),
            }
        )
        node["clip"] = bool(raw.get("clip", node["overflow"] != "nextPage"))

    def _chart_font(self, raw: dict[str, Any], weight: int) -> None:
        if raw.get("fontId"):
            self.ctx.fonts.add(str(raw["fontId"]))
        else:
            self.ctx.families.add((str(raw.get("fontFamily") or self.defaults["fontFamily"]), weight, "normal"))

    def _node_chart(self, node: dict[str, Any], raw: dict[str, Any]) -> None:
        ctx = self.ctx
        nid = node["id"]
        segments = []
        for i, seg in enumerate(raw.get("segments") or []):
            if not isinstance(seg, dict):
                continue
            color = seg.get("color")
            segments.append(
                {
                    "value": _expr(seg.get("value"), ctx, nid, f"segments.{i}.value"),
                    "label": _template(str(seg.get("label") or ""), ctx, nid),
                    "color": color
                    if not isinstance(color, str) or color.startswith("#")
                    else _expr(color, ctx, nid, f"segments.{i}.color"),
                }
            )
        categories = [_template(str(c if c is not None else ""), ctx, nid) for c in (raw.get("categories") or [])]
        series = []
        for i, item in enumerate(raw.get("series") or []):
            if not isinstance(item, dict):
                continue
            color = item.get("color")
            series.append(
                {
                    "name": _template(str(item.get("name") or ""), ctx, nid),
                    "color": color
                    if not isinstance(color, str) or color.startswith("#")
                    else _expr(color, ctx, nid, f"series.{i}.color"),
                    "valueField": item.get("valueField"),
                    "xField": item.get("xField"),
                    "yField": item.get("yField"),
                    "values": [
                        _expr(v, ctx, nid, f"series.{i}.values.{k}") for k, v in enumerate(item.get("values") or [])
                    ],
                }
            )
        chart_type = raw.get("chartType", "donut")
        if chart_type not in CHART_TYPES:
            chart_type = "donut"
        round_chart = chart_type in ROUND_TYPES
        if round_chart and series:
            # a pie or donut shows one series: the first, when there are no segments of its own
            first = series[0]
            if not segments and not raw.get("source"):
                labels_of = categories + [("",)] * (len(first["values"]) - len(categories))
                segments = [{"value": v, "label": labels_of[k], "color": None} for k, v in enumerate(first["values"])]
        labels = raw.get("labels") if isinstance(raw.get("labels"), dict) else {}
        center = raw.get("center") if isinstance(raw.get("center"), dict) else None
        label_weight = int(labels.get("fontWeight") or (800 if round_chart else 600))
        self._chart_font(labels, label_weight)
        if not round_chart or (isinstance(raw.get("legend"), dict) and raw["legend"].get("show")):
            self._chart_font(labels, AXIS_WEIGHT)
        node.update(
            {
                "chartType": chart_type,
                "categories": categories,
                "series": series,
                "xField": raw.get("xField"),
                "yField": raw.get("yField"),
                "normalize": raw.get("normalize") is True,
                "legend": raw.get("legend") if isinstance(raw.get("legend"), dict) else {},
                "axes": raw.get("axes") if isinstance(raw.get("axes"), dict) else {},
                "grid": raw.get("grid") if isinstance(raw.get("grid"), dict) else {},
                "markers": raw.get("markers") if isinstance(raw.get("markers"), dict) else {},
                "barGap": raw.get("barGap"),
                "lineWidth": raw.get("lineWidth"),
                "fillOpacity": raw.get("fillOpacity"),
                "smooth": raw.get("smooth") is True,
                "labelsRaw": labels,
                "source": _expr(raw.get("source"), ctx, nid, "source"),
                "valueField": raw.get("valueField") or (series[0]["valueField"] if round_chart and series else None),
                "labelField": raw.get("labelField"),
                "colorField": raw.get("colorField"),
                "segments": segments,
                "palette": list(raw.get("palette") or []),
                "remainderColor": raw.get("remainderColor") or "#B0BEC5",
                "outerRadius": _num(raw.get("outerRadius")) or None,
                "innerRadius": _num(raw.get("innerRadius"), -1.0),
                "startAngle": _num(raw.get("startAngle")),
                "labels": {
                    "show": labels.get("show", True) is not False,
                    "minPct": _num(labels.get("minPct"), 5.0),
                    "outsidePct": _num(labels.get("outsidePct"), 12.0),
                    "fontId": labels.get("fontId"),
                    "fontFamily": labels.get("fontFamily") or self.defaults["fontFamily"],
                    "fontSize": _num(labels.get("fontSize")) or None,
                    "fontWeight": label_weight,
                    "insideColor": labels.get("insideColor") or "#FFFFFF",
                    "outsideColor": labels.get("outsideColor") or "#374151",
                    "remainderLabelColor": labels.get("remainderLabelColor") or "#666666",
                    "leaderColor": labels.get("leaderColor") or "#9CA3AF",
                    "leaderWidth": _num(labels.get("leaderWidth"), 1.0),
                },
                "center": None,
            }
        )
        if center is not None:
            line_weight = int(center.get("lineFontWeight") or 700)
            value_weight = int(center.get("valueFontWeight") or 800)
            self._chart_font(center, line_weight)
            self._chart_font(center, value_weight)
            node["center"] = {
                "line1": _template(str(center.get("line1") or ""), ctx, nid),
                "line2": _template(str(center.get("line2") or ""), ctx, nid),
                "value": _template(str(center.get("value") or ""), ctx, nid),
                "fontId": center.get("fontId"),
                "fontFamily": center.get("fontFamily") or self.defaults["fontFamily"],
                "lineFontSize": _num(center.get("lineFontSize")) or None,
                "lineFontWeight": line_weight,
                "lineColor": center.get("lineColor") or "#6B7280",
                "lineLetterSpacing": _num(center.get("lineLetterSpacing"), -1.0),
                "valueFontSize": _num(center.get("valueFontSize")) or None,
                "valueFontWeight": value_weight,
                "valueColor": center.get("valueColor") or "#1B2A4A",
            }


def compile_document(doc: dict[str, Any], strict: bool = False) -> tuple[dict[str, Any], CompileContext]:
    ctx = CompileContext(strict=strict)
    plan = Compiler(ctx).compile(doc)
    return plan, ctx
