#!/usr/bin/env python3
"""Build a Mosaic page from a declarative design spec, through the public write path.

    python build_page.py --config sweep.json --spec myspec.json

This is the skill eating its own cooking. Nothing here knows anything about Mosaic
that is not written down in ../data and ../references: node types come from
node-types.csv, the placement check comes from placement-rules.csv and
node-verification.csv, style keys come from style-properties.csv and
style-states.csv, and the commit sequence is the one in references/write-protocol.md.

## Spec format

    {
      "page_id": 12,                  WordPress post the template is bound to
      "title": "Brutalist",
      "master": "Brutalist master",
      "tree": { ...node... }
    }

A node is:

    {"type": "div",
     "text": "hello",                  shorthand: adds a wysiwyg-text child (inside an
                                       Inherited text `text` node unless the type
                                       holds runs itself - see wrap_text_runs)
     "data": {"tagName": "h1"},        merged into the node's data
     "style": {"_": {...}, "_m": {...}},          base state, per breakpoint
     "hover": {"_": {...}},                       any state name works as a key
     "children": [ ...nodes... ]}

Style keys are camelCase properties from style-properties.csv; the shorthand expands
to data.style.states[<state>][<breakpoint>][<property>], the shape confirmed in
references/styling.md.

## Safety

Before committing, every parent/child pair is checked against placement-rules.csv, and
every type against node-verification.csv. A type measured BROKE_PAGE or COMMIT_5xx is
refused outright unless --force, because committing one is how you get a 200-response
page that serves a 54-byte error string. After committing, the page is fetched and its
size checked - the only reliable signal that the write actually worked.
"""
import mosaic_config
import argparse
import csv
import json
import os
import re
import sys
import uuid

sys.path.insert(0, os.path.dirname(os.path.abspath(__file__)))
from sweep_node_types import (  # noqa: E402
    MIN_HEALTHY_BYTES,
    Client,
    envelopes,
    exceptions_of,
    unwrap,
)

DATA = os.path.join(os.path.dirname(os.path.abspath(__file__)), "..", "data")
RESERVED = {"type", "text", "data", "children", "style"}


def load_csv(name):
    with open(os.path.join(DATA, name), encoding="utf-8") as fh:
        return list(csv.DictReader(fh))


# Any tag inside wysiwyg-text. Since 1.0.11 the run's `<` and `>` are escaped on
# output (WysiwygTextNodeMResource::getEscapedText, NEXT-5875), so `<strong>` or
# `<br>` prints as those characters on the page. Inline formatting is written as
# nodes instead: wysiwyg-span, wysiwyg-linebreak, wysiwyg-link.
PROSE_TAG = re.compile(r"</?[a-zA-Z][a-zA-Z0-9-]*\s*[^>]*>")
DYNAMIC_CALL = re.compile(r"@[A-Za-z_][A-Za-z0-9_]*\s*\(")
# types whose own content is parsed as code from a plain string
RAW_CODE_TYPES = {"code", "wpShortcode", "wysiwyg-variable", "wysiwyg-text"}
# data keys whose plain string is evaluated (loop source; form action settings;
# a condition's variable subject)
RAW_CODE_KEYS = {"localContextOptions", "actions", "dynamicCode"}


def plain_code_paths(value, path="data"):
    """Paths of plain strings holding @fn( code where only {"v": ...} is computed."""
    if isinstance(value, str):
        return [path] if DYNAMIC_CALL.search(value) else []
    if isinstance(value, dict):
        if isinstance(value.get("v"), str):
            return []
        return [p for k, v in value.items() if k not in RAW_CODE_KEYS
                for p in plain_code_paths(v, "%s.%s" % (path, k))]
    if isinstance(value, list):
        return [p for i, v in enumerate(value) for p in plain_code_paths(v, "%s[%d]" % (path, i))]
    return []
AT_RULE_GLUED = re.compile(
    r"@(media|supports|container|layer|scope|import|page|starting-style|"
    r"font-feature-values|counter-style|property|document)\(")


class Surface:
    """Everything the builder is allowed to know, loaded from the skill's own tables."""

    def __init__(self):
        self.types = {r["type"]: r for r in load_csv("node-types.csv")}
        self.rules = {r["type"]: r for r in load_csv("placement-rules.csv")}
        self.outcome = {r["type"]: r["outcome"] for r in load_csv("node-verification.csv")}
        style_rows = load_csv("style-properties.csv")
        self.style_props = {r["property"] for r in style_rows}
        # 24 of the 101 style properties are restricted to an enum. A value outside it
        # is accepted by the API, stored, and silently never compiled - white-space
        # takes pre-wrap but not pre-line, and the difference is invisible until you
        # look at the delivered CSS. Refuse it here instead.
        self.style_enums = {r["property"]: set(r["accepted_values"].split("|"))
                            for r in style_rows if r.get("accepted_values")}
        self.states = {r["state"] for r in load_csv("style-states.csv")}
        # what a composite type needs INSIDE it, which canBeParentFor does not describe
        self.default_children = {r["type"]: r["default_children"].split("|")
                                 for r in load_csv("default-children.csv")}

    def check(self, parent_type, node, force, ancestors=()):
        t = node["type"]
        problems = []
        if t not in self.types:
            problems.append("unknown node type %r" % t)
            return problems
        # A `code` node's content is parsed as a Mosaic template at render time,
        # and a CSS at-rule glued to its parenthesis - `@media(`, the way every
        # minifier writes it - is read as a function call whose arguments cannot
        # be parsed. The commit succeeds; the public page becomes an HTTP 500.
        # Measured both ways on the demo site (`@media (` renders, `@media(`
        # does not). Refused here for the same reason an unsafe type is: the
        # failure is silent at the only point this tool can still stop it.
        # A tag in `wysiwyg-text` is wrong on every version, in opposite ways.
        # Through 1.0.10 the run was raw HTML: "a real <dialog>" opened an element
        # and the rest of the paragraph vanished. Since 1.0.11 `<` and `>` are
        # escaped on output, so `<strong>` and `<br>` print literally (measured on
        # the demo site). Either way the commit succeeds and only the page is wrong.
        # An entity (`&lt;dialog&gt;`, `&amp;`) prints as its character on both;
        # emphasis, breaks and links are their own nodes.
        if t == "wysiwyg-text" and not force:
            text = (node.get("data") or {}).get("text") or ""
            hit = PROSE_TAG.search(text)
            if hit:
                problems.append("wysiwyg-text contains `%s` - since 1.0.11 a tag in a text "
                                "run prints as literal characters. Use a wysiwyg-span / "
                                "wysiwyg-linebreak / wysiwyg-link node for formatting, or "
                                "write a literal tag name as &lt;%s&gt;"
                                % (hit.group(0), hit.group(0).strip("<>/")))
        if t == "code" and not force:
            content = (node.get("data") or {}).get("content") or ""
            hit = AT_RULE_GLUED.search(content)
            if hit:
                problems.append("code content contains `%s` - Mosaic's template parser reads "
                                "it as a function call and the page renders as HTTP 500; "
                                "write `%s (`" % (hit.group(0), hit.group(0)[:-1]))
        # Node data is computed only in the {"v": "..."} object form
        # (DynamicCodeHelper::isDynamicCode); evaluateText hands a plain string back
        # verbatim. So `"entryName": "@VAR('form/field_name')"` stores and shows the
        # code itself - measured on a live form's submission list. Raw strings that ARE
        # evaluated: code content, wpShortcode, wysiwyg-variable dynamicCode, a loop
        # source, and form action settings (getSetting takes either form).
        if not force and t not in RAW_CODE_TYPES:
            for path in plain_code_paths(node.get("data") or {}):
                problems.append("%s holds dynamic code as a plain string - it is stored "
                                "and shown literally; write it as {\"v\": \"...\"}" % path)
        # A local-context loop's source written as `@LOOP('post/x')` renders on the
        # front end - LoopEvaluator.php reads the loop name out of any function call -
        # and throws in the editor, whose evaluateLoop only resolves `@VAR`
        # ("this._loopEvaluatorFunction is not a function", canvas never finishes).
        # The page is 200 and complete, so nothing downstream of this can see it.
        if not force:
            opts = (node.get("data") or {}).get("localContextOptions") or {}
            src = opts.get("loopSource")
            code = src.get("v") if isinstance(src, dict) else src
            if isinstance(code, str) and code.lstrip().upper().startswith("@LOOP("):
                problems.append("loopSource %r breaks the Mosaic editor (front end renders, "
                                "editor throws _loopEvaluatorFunction is not a function); "
                                "write it as %r" % (code, "@VAR(" + code.lstrip()[6:]))
        # node-verification.csv measured every type UNDER A PLAIN DIV. A type that broke
        # there is not broken in general - most of them are family members that simply
        # need their own parent. So the measured verdict only applies when the parent is
        # not the one the type is declared to belong under.
        parent_rule = self.rules.get(parent_type or "", {})
        parent_defaults = self.default_children.get(parent_type or "", [])
        declared_child = (t in (parent_rule.get("allowed_children") or "").split("|")
                          or t in parent_defaults
                          # the wysiwyg family is one interchangeable content model: a
                          # parent that seeds itself with wysiwyg-text takes any of
                          # them, and wysiwyg-variable inside a text node is verified
                          # to render (references/dynamic-content.md)
                          or (t.startswith("wysiwyg-")
                              and any(d.startswith("wysiwyg-") for d in parent_defaults))
                          # A family member under its own family head. The table
                          # cannot say this when the head's rule is `any` and its
                          # allowed_children column is therefore empty - `slider`
                          # accepts anything, so nothing records that
                          # `slider-slides` is exactly where it belongs.
                          or (parent_type and t.startswith(parent_type + "-")))
        # The comment above covers types that need their own PARENT. The other half
        # of the same story is a family HEAD, which needs its own CHILDREN: a bare
        # `slider` is measured COMMIT_500 because it has no `slider-slides`, not
        # because a div cannot hold it. So a node whose type prefixes other
        # registered types - slider/slider-slides, accordion/accordion-item,
        # form/form-input - and which actually carries one of them is not the thing
        # that was measured, and the verdict does not apply to it.
        rule_for_t = self.rules.get(t, {})
        family = [x for x in self.types if x.startswith(t + "-")]
        kids = [c.get("type") for c in (node.get("children") or []) if isinstance(c, dict)]
        nested_as_family = bool(family) and any(k in family for k in kids)

        # `nested_under` is what `canBeNestedChildFor()` walks the parent chain
        # looking for: `radio-input` needs a `choice` above it, `label` needs a
        # `field`, `loop-pagination` needs a `loop`. The names often share no
        # prefix, so this is the only way to tell a correct placement from the
        # bare one that was measured.
        needs = (rule_for_t.get("nested_under") or "").split("|") if rule_for_t else []
        nested_ok = bool(needs and needs != [""] and
                         any(x in needs for x in (ancestors + ((parent_type,)
                                                               if parent_type else ()))))

        # ...and the same question the `allow` branch asks below: is this type
        # part of the required internal structure of something we are inside?
        in_ancestor_structure = any(t in self.default_children.get(x, [])
                                    for x in ancestors)

        outcome = self.outcome.get(t)
        if (not declared_child and not nested_as_family and not nested_ok
                and not in_ancestor_structure
                and (outcome == "BROKE_PAGE" or (outcome or "").startswith("COMMIT_5"))):
            problems.append("%s is measured %s under a plain container, and %s is not its declared parent"
                            % (t, outcome, parent_type or "<root>"))
        # The wysiwyg family is inline CONTENT, not a child in the placement sense, and
        # canBeParentFor does not govern it. `text` inherits canBeParentFor -> false yet
        # TextElementTypeFactory::getTextElementDefaultData() seeds itself with a
        # wysiwyg-text child, and that combination renders. Checking these against the
        # parent rule would refuse every piece of text on the page.
        if parent_type and not t.startswith("wysiwyg-"):
            rule = self.rules.get(parent_type, {})
            # `rule == "none"` means canBeParentFor() was never overridden, which
            # is the editor's drop rule and not the same question as "can this
            # hold children". `takes_children` records the factory signature, and
            # a type whose getDefaultData takes `$children` is a container
            # whatever the drop rule says - `dropdown-wrapper` is exactly that.
            if (rule.get("rule") == "none"
                    and not rule.get("takes_children")
                    and t not in self.default_children.get(parent_type, [])):
                problems.append("%s is a leaf and accepts no children (tried %s)" % (parent_type, t))
            elif rule.get("rule") == "allow":
                allowed = rule["allowed_children"].split("|") + self.default_children.get(parent_type, [])
                # A loop container stands in for its parent's children: a
                # `slider-loop-slides` sits inside `slider-slides` and repeats a
                # `slider-slide`, so what it accepts is what `slider-slides`
                # accepts. The plugin's own canBeParentFor says `slider-slides`
                # here, which would nest the track inside its own loop - and the
                # factory's default children say `slider-slide`, which is the
                # structure the editor builds. Rather than hard-code the
                # disagreement, take the rule from the grandparent, which is both
                # types' actual authority.
                # ancestors[-1] IS the parent; the grandparent is one further up
                # A type that is part of the required internal structure of
                # something we are INSIDE is legal wherever that structure puts
                # it. `multi-steps-forms` declares `canBeParentFor` ->
                # `form-multi-steps`, which is its own parent; the real child,
                # `multi-steps-form-step`, is in `form-multi-steps`'s healed
                # default children. Same disagreement as the loop containers.
                if t not in allowed:
                    for anc in ancestors:
                        if t in self.default_children.get(anc, []):
                            allowed = allowed + [t]
                            break
                if t not in allowed and "-loop-" in parent_type and len(ancestors) > 1:
                    gp = self.rules.get(ancestors[-2], {})
                    allowed = allowed + (gp.get("allowed_children") or "").split("|")
                if t not in allowed:
                    problems.append("%s accepts only %s, not %s" % (parent_type, "/".join(allowed), t))
        # customStyles is the pre-1.0.8 name of customDeclarations; expand_shorthands maps it
        shorthands = {"radius", "shadow", "transitionAll", "move", "border", "gridCols", "customStyles"}
        for state, per_bp in node.get("style", {}).items():
            if state not in self.states:
                problems.append("unknown style state %r on %s" % (state, t))
            for _bp, props in per_bp.items():
                for p, value in props.items():
                    if p not in self.style_props and p not in shorthands:
                        problems.append("%r is not a supported style property (on %s)" % (p, t))
                    if (p == "fontFamily" and isinstance(value, str)
                            and not FONT_FAMILY_LIST.match(value.strip(" \t\n\r\f"))):
                        problems.append("fontFamily=%r is not a plain family list - Mosaic "
                                        "drops it without a rule (NEXT-5841); use a font "
                                        "variable {\"var\": id}, or customDeclarations for "
                                        "var(--x) (on %s)" % (value, t))
                    allowed = self.style_enums.get(p)
                    if allowed and isinstance(value, str) and value not in allowed:
                        problems.append("%s=%r is not one of %s (on %s)"
                                        % (p, value, "/".join(sorted(allowed)), t))
        return [] if force else problems


# Five style properties take a structured value rather than a CSS string. Writing a
# string to them is accepted and then silently produces `transform:none`, `box-shadow:none`
# or no rule at all - so these shorthands exist to make the correct shape unavoidable.
# Each was confirmed against the compiled CSS; see references/styling.md.

# A fixed namespace, so a design token's row ID is a function of its name alone and
# a rebuild rebinds the same row instead of adding a second one.
# ValidatorStyleFontFamily.php (NEXT-5841): quoted names and unquoted identifier
# runs, joined by commas with spaces only. Anything else - var(), a function, a tab
# or newline between names - is dropped at compile time with no error.
_FF_UNQUOTED = r"[\w-]+(?: +[\w-]+)*"
_FF_NAME = (r"(?:\"[^\"\\<;{}\x00-\x1f\x7f]+\"|'[^'\\<;{}\x00-\x1f\x7f]+'|"
            + _FF_UNQUOTED + ")")
FONT_FAMILY_LIST = re.compile(r"^" + _FF_NAME + r"(?: *, *" + _FF_NAME + r")*$")

VAR_NAMESPACE = uuid.UUID("6d6f7361-6963-4865-6164-6c657373ff01")
VAR_IDS = {}


def expand_shorthands(props):
    out = {}
    extra_css = []
    for key, value in props.items():
        if key == "gridCols":
            # gridTemplateColumns is a CSSGridTemplateStylePropertyFactory property: a
            # plain "repeat(3, 1fr)" string is accepted and then compiles to nothing at
            # all, so a grid silently collapses to one column. Until that structured
            # shape is pinned down, route it through the customDeclarations escape hatch.
            extra_css.append("grid-template-columns:%s;" % value)
        elif key == "radius" and isinstance(value, str):
            out["borderRadius"] = {"type": "all", "allOptions": {"borderRadiusValue": value}}
        elif key == "shadow" and isinstance(value, dict):
            out["boxShadow"] = [dict({"blur": "0px", "spread": "0px", "type": "outside",
                                      "uuid": str(uuid.uuid4())}, **value)]
        elif key == "transitionAll" and isinstance(value, str):
            duration, _, easing = value.partition(" ")
            out["transition"] = [{"transitionProperty": "all", "transitionDuration": duration,
                                  "transitionDelay": "0ms", "transitionTimingFunction": easing or "ease",
                                  "uuid": str(uuid.uuid4())}]
        elif key == "move" and isinstance(value, dict):
            # {"translateY": "-8px"} -> the transform array entry for that transform type
            out["transform"] = [{"type": t, "%sOptions" % t: {"value": v}, "uuid": str(uuid.uuid4())}
                                for t, v in value.items()]
        elif key == "border" and isinstance(value, dict):
            width, style, color = value.get("width", "1px"), value.get("style", "solid"), value.get("color", "#000")
            out["borderStyle"] = {"border%s%s" % (side, part): val
                                  for side in ("Top", "Right", "Bottom", "Left")
                                  for part, val in (("Width", width), ("Style", style), ("Color", color))}
        elif isinstance(value, dict) and "token" in value:
            # {"token": "--brand"} -> the {"var": <uuid>} reference the compiler wants
            vid = VAR_IDS.get(value["token"])
            if not vid:
                sys.exit("style references token %r before it is declared in theme.variables"
                         % value["token"])
            out[key] = {"var": vid}
        else:
            out[key] = value
    if extra_css:
        # merge with any customDeclarations the spec set itself rather than clobbering it
        out["customDeclarations"] = (out.get("customDeclarations", "") + "".join(extra_css))
    if "customStyles" in out:
        # the 1.0.7 spelling; 1.0.8 renamed the raw-CSS escape hatch and the validator
        # drops the old key silently, so specs written before the rename still build
        out["customDeclarations"] = out.pop("customStyles") + out.get("customDeclarations", "")
    return out


def to_style(spec_style):
    """{state: {breakpoint: {prop: value}}} -> the data.style shape."""
    if not spec_style:
        return None
    return {"states": {state: {bp: expand_shorthands(props) for bp, props in per_bp.items()}
                       for state, per_bp in spec_style.items()}}


# Every component instance flatten() emits, so the override pass can find them
# again after the commit. Cleared by build_site before each page.
COMPONENT_USES = []



def refresh_node_ids(tree):
    """Give every pinned `nodeID` in a tree a fresh uuid, and carry the rename
    through every reference to it.

    A pin exists so that two nodes written in the SAME pass can agree on an id -
    a `modalOpen` action names the modal's node id, and neither exists yet. It is
    not a claim that this exact uuid must be the one in the database, and treating
    it as one makes the spec single-use: `wp_mosaic_nodes`' primary key is
    (ID, themeID), so the second build of the same spec into the same theme dies
    on a duplicate key, with the page already half written.

    Rewriting at build time keeps the agreement (both halves move together) and
    drops the false claim. Done on the serialized tree because a reference can sit
    anywhere - `settings.target.uuid` today, somewhere else tomorrow - and a
    structural walk would have to know every one of them.
    """
    ids = []

    def collect(node):
        if isinstance(node, dict):
            if isinstance(node.get("nodeID"), str):
                ids.append(node["nodeID"])
            for v in node.values():
                collect(v)
        elif isinstance(node, list):
            for v in node:
                collect(v)

    collect(tree)
    if not ids:
        return tree
    blob = json.dumps(tree, ensure_ascii=False)
    for old in dict.fromkeys(ids):
        blob = blob.replace(old, str(uuid.uuid4()))
    return json.loads(blob)


def flatten(node, parent_id, master_id, surface, force, ordering="a0",
            parent_type=None, out=None, ancestors=()):
    """Depth-first walk producing revision records, checking placement as it goes."""
    out = out if out is not None else []
    if node.get("component"):
        node = dict(node, type="div")     # placement is checked as a plain element
    problems = surface.check(parent_type, node, force, ancestors)
    if problems:
        raise SystemExit("refusing to build:\n  " + "\n  ".join(problems))

    # `nodeID` pins the node's own id instead of minting one. An interaction that
    # targets another element stores that element's NODE id (`settings.target =
    # {"type": "element", "uuid": <nodeID>}`), not its attrID, so the two have to be
    # written in the same pass - there is no way to point at a node whose id the
    # spec never sees. The id must be unique in the THEME, not the document:
    # wp_mosaic_nodes' primary key is (ID, themeID), so a hard-coded one collides
    # with whatever a previous build left behind and the commit 500s on a duplicate
    # key. Mint it per run.
    nid = node.get("nodeID") or str(uuid.uuid4())
    data = dict(node.get("data") or {})
    style = to_style(node.get("style"))
    if style:
        # merge, not replace: data.style may already carry universalClasses or a
        # variant, which the states from node["style"] must not wipe out
        data["style"] = dict(data.get("style") or {}, **style)
    # A node that names a component becomes an INSTANCE of it, and an instance's
    # type carries the component's id after a slash - the factory splits on it, and
    # a bare `component-instance` has no id to read and fatals. `overrides` is not
    # written here: Mosaic materialises one override node per component node per
    # instance, and those are updated in a second pass once they exist.
    node_type = node["type"]
    if node.get("component"):
        node_type = "component-instance/%s" % node["component"]
        data.pop("overrides", None)
    out.append({
        "ID": nid, "parentType": "node", "parentID": parent_id, "ordering": ordering,
        "status": "publish", "revision": "", "version": "", "type": node_type,
        "data": data, "documentType": "master", "documentID": master_id,
    })
    if node.get("component"):
        # remembered by attrID so the override pass can find this instance again
        COMPONENT_USES.append({"instance_attr": data.get("attrID"),
                               "componentID": node["component"],
                               "component_name": node.get("_component_name"),
                               "overrides": node.get("overrides") or {}})
        return out

    children = list(node.get("children") or [])
    if node.get("text") is not None:
        children.insert(0, {"type": "wysiwyg-text", "data": {"text": node["text"]}})
    children = wrap_text_runs(node["type"], children)
    for i, child in enumerate(children):
        flatten(child, nid, master_id, surface, force, ordering_for(i),
                node["type"], out, ancestors + (node["type"],))
    return out


# Types the editor lets hold text runs directly (its own defaults put
# wysiwyg-text straight under these). Everything else - button, menu-link,
# dropdown-toggle, tab, submit-label... - gets its runs inside a `text` node on
# the Inherited text variant, and a run placed directly under one renders fine
# but cannot be edited in the editor: the navigator shows no child and a
# double-click opens only the link settings.
DIRECT_TEXT_HOSTS = {"text", "label", "choice-label", "choice-legend", "fieldset-legend",
                     "wysiwyg-span", "wysiwyg-link"}
INHERITED_TEXT_VARIANT = "6381b2f3-7a23-05db-87b9-c808a98a292b"


def wrap_text_runs(node_type, children):
    """Group consecutive wysiwyg-* children of a non-text host into one
    `text` node on the Inherited text variant, the shape the editor builds."""
    if node_type in DIRECT_TEXT_HOSTS:
        return children
    out, run = [], []
    for child in children:
        if str(child.get("type", "")).startswith("wysiwyg-"):
            run.append(child)
            continue
        if run:
            out.append({"type": "text", "data": {"style": {"variant": INHERITED_TEXT_VARIANT}},
                        "children": run})
            run = []
        out.append(child)
    if run:
        out.append({"type": "text", "data": {"style": {"variant": INHERITED_TEXT_VARIANT}},
                    "children": run})
    return out


def ordering_for(index):
    """Siblings order by a fractional-index STRING, never by number."""
    alphabet = "0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz"
    return "a" + (alphabet[index] if index < len(alphabet) else alphabet[-1] + alphabet[index % len(alphabet)])


def theme_records(spec, doc, surface):
    """Turn the spec's `theme` block into collectionVariable + variant records.

    Both are theme-scoped rather than per-node, and both are how a real Mosaic site is
    meant to be styled: variables are the tokens, variants (the theme-global element
    classes - `elementClasses` before 1.0.8) apply them to every element of a kind.
    See references/design-system.md.
    """
    theme = spec.get("theme") or {}
    out = {}

    variables = theme.get("variables") or {}
    if variables:
        collection = (doc.get("collection") or [{}])[0].get("ID")
        mode = (doc.get("collectionMode") or [{}])[0].get("ID")
        skin = (doc.get("collectionSkin") or [{}])[0].get("ID")
        if not (collection and mode and skin):
            sys.exit("theme.variables needs a healed collection/mode/skin")
        recs = []
        # The ID is DERIVED from the token name, not minted.
        #
        # It used to be a fresh `uuid4()` per run, and `_varIDs` starts empty every
        # time, so each build wrote a NEW collectionVariable row and left the old one
        # in place. The rows are parented to the theme's collection, which survives
        # `build_site.py` making a fresh master, so they accumulate - and both end up
        # in `:root`, where the later one wins. Measured: after changing `--mk-faint`
        # from rgb(160,162,168) to rgb(107,109,113), the delivered stylesheet carried
        #
        #     --mk-faint: rgb(107, 109, 113)
        #     --mk-faint: rgb(160, 162, 168)
        #
        # and the page kept rendering the old grey. Every server-side check passed:
        # the commit succeeded, the new variable existed, its value was correct. Only
        # `verify_browser.py`, reading the computed colour off the element, saw it.
        #
        # A UUIDv5 over the custom property is stable across runs and across machines
        # with no state to carry, so a rebuild REBINDS the row instead of adding one.
        for custom_property, value in variables.items():
            vid = str(uuid.uuid5(VAR_NAMESPACE, custom_property))
            spec.setdefault("_varIDs", {})[custom_property] = vid
            recs.append({"newRevisionRecord": {
                "ID": vid, "parentType": "collection", "parentID": collection,
                "ordering": "a0", "status": "publish", "revision": "", "version": "",
                "data": {"name": custom_property.lstrip("-"),
                         "type": value.get("type", "color"),
                         "customProperty": custom_property,
                         "skinsData": {skin: {mode: {"value": value["value"]}}}}},
                "originalRevisionRecord": None})
        # Reap strays from before the ID became derivable. Anything on this
        # collection that claims a custom property we manage, under an ID we did not
        # derive, is a leftover that can still win the cascade.
        managed = {v["ID"] for v in (r["newRevisionRecord"] for r in recs)}
        for row in (doc.get("collectionVariable") or []):
            cp = (row.get("data") or {}).get("customProperty")
            if cp in variables and row["ID"] not in managed:
                print("  reaping stale variable %s (%s)" % (cp, row["ID"][:8]))
                recs.append({"newRevisionRecord": dict(row, status="delete"),
                             "originalRevisionRecord": row})
        out["collectionVariable"] = recs
        # register the IDs before element-class styles are expanded - those cite
        # tokens too, and expand_shorthands resolves {"token": ...} from this map
        VAR_IDS.update(spec["_varIDs"])

    classes = theme.get("variants") or theme.get("elementClasses") or {}
    if classes:
        catalog = load_csv("variants.csv")
        recs = []
        for name, states in classes.items():
            # a catalog id, a class_name (m-loop-item) or a name. Names repeat -
            # `Item` is the accordion, loop AND list item, all three with a parent -
            # so a name only resolves when it is the sole row, or the sole
            # parent-less one, carrying it
            matches = ([m for m in catalog if m["id"] == name]
                       or [m for m in catalog if m["class_name"] == name]
                       or [m for m in catalog if m["name"] == name])
            if not matches:
                sys.exit("no variant %r; see data/variants.csv" % name)
            roots = [m for m in matches if not m["parent"]]
            if len(matches) > 1 and len(roots) != 1:
                sys.exit("variant name %r is ambiguous; use one of: %s" % (
                    name, ", ".join(m["class_name"] for m in matches)))
            # a fresh UUID here is accepted and then silently dropped, so the meta ID
            # is the only thing that works
            top = roots[0] if len(matches) > 1 else matches[0]
            recs.append({"newRevisionRecord": {
                "ID": top["id"], "parentType": "", "parentID": "", "ordering": "a0",
                "status": "publish", "revision": "", "version": "",
                "data": {"states": {st: {bp: expand_shorthands(props)
                                         for bp, props in per_bp.items()}
                                    for st, per_bp in states.items()}}},
                "originalRevisionRecord": None})
        out["variant"] = recs
    return out


def create_master(client, name):
    inst = unwrap(client.get("adminMasterEditorInstance"), "adminMasterEditorInstance")
    mid = str(uuid.uuid4())
    resp = client.commit("adminMasterEditorInstance", envelopes(inst), {"master": [{
        "newRevisionRecord": {"ID": mid, "parentType": "", "parentID": "", "ordering": "a0",
                              "status": "publish", "revision": "", "version": "", "name": name},
        "originalRevisionRecord": None}]})
    err = exceptions_of(resp)
    if err:
        sys.exit("master commit failed: %s" % err)
    return mid


def bind_template(client, cfg, master_id, page_id):
    """Attach the master to one WordPress post via a manual template assignment."""
    url = "%s/templateAssign/createManualTemplate" % client.api
    resp = client._call(url, {"resourceQuery": "post/%d" % page_id, "masterID": master_id})
    if "_httperror" in resp:
        sys.exit("template assign failed: %s %s" % (resp["_httperror"], resp["_body"][:200]))
    return resp


def build(client, cfg, spec, force):
    surface = Surface()
    master_id = create_master(client, spec.get("master") or spec["title"])
    doc = unwrap(client.get("masterDocumentInstance/%s" % master_id), "masterDocumentInstance")
    key = "node/master/%s" % master_id
    nodes = doc[key]
    body = next((n for n in nodes if n["type"] == "body"), None)
    if not body:
        sys.exit("healed master has no body")
    # the healed skeleton puts three empty divs in the body; clear them so the design
    # is the only thing on the page
    doomed = [n for n in nodes if n["parentID"] == body["ID"]]
    if doomed:
        client.commit("masterDocumentInstance/%s" % master_id, envelopes(doc), {key: [
            {"newRevisionRecord": dict(n, status="delete"), "originalRevisionRecord": n} for n in doomed]})
        doc = unwrap(client.get("masterDocumentInstance/%s" % master_id), "masterDocumentInstance")

    # theme records first: the variable IDs have to exist before a node can cite one
    VAR_IDS.clear()
    extra = theme_records(spec, doc, surface)

    records = flatten(refresh_node_ids(spec["tree"]), body["ID"], master_id, surface,
                      force, parent_type="body")
    payload = dict(extra)
    payload[key] = [{"newRevisionRecord": r, "originalRevisionRecord": None} for r in records]
    resp = client.commit("masterDocumentInstance/%s" % master_id, envelopes(doc), payload)
    err = exceptions_of(resp)
    if err:
        sys.exit("node commit failed: %s" % err)

    bind_template(client, cfg, master_id, spec["page_id"])
    print("master=%s  nodes=%d  page_id=%s" % (master_id, len(records), spec["page_id"]))
    return master_id, len(records)


if __name__ == "__main__":
    ap = argparse.ArgumentParser()
    ap.add_argument("--config",
                    help="JSON with base/cookie/nonce; omit it and the MOSAIC_SITE_URL / MOSAIC_REST_COOKIE / MOSAIC_REST_NONCE environment variables supply them instead")
    ap.add_argument("--spec", required=True)
    ap.add_argument("--force", action="store_true", help="skip the placement/outcome checks")
    a = ap.parse_args()
    cfg = mosaic_config.load(a.config)
    spec = json.load(open(a.spec, encoding="utf-8"))
    client = Client(cfg)
    build(client, cfg, spec, a.force)
