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
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
"""Structured deterministic renderers (``docs/02`` §9, ``docs/07`` §8 P6).

A renderer turns a structured :class:`World` into four byte-addressed assets —
``rgba.png``, ``node_map.uint32.png``, ``render_manifest.json``,
``text_manifest.json`` — by **drawing fresh from the world**, never by editing an
input raster. Two hard P6 gates shape this module:

  * **Byte-identical replay** — the same ``(world, renderer_id, seed, size)`` in
    the same clean process must reproduce the PNG bytes and the node-map hash
    exactly. So nothing time-dependent ever enters a manifest or a canvas: the
    backend is the fixed matplotlib ``Agg`` backend, the font is a pinned TTF
    (its SHA-256 recorded), and iteration order is sorted.
  * **No pixel-edit / inpainting code path** — REDACT_SOLID_V1 (§10.1) hides a
    node by *drawing a fixed, content-independent patch* over its would-be
    pixels. The hidden node is excluded from the canvas and the node map; the
    patch carries no node id. There is no code path that inpaints or otherwise
    edits the pixels of an existing raster.

The node map encodes, per pixel, the index of the semantic node that owns it
(``0`` = background / no node) as a little-endian ``uint32`` packed into the RGBA
channels — a standard, lossless PNG. Anti-alias boundaries are resolved by an
alpha-aware ownership mask (the node with the highest drawn alpha wins; ties
break to the lower node index), produced in the same draw pass as the RGBA.
"""

from __future__ import annotations

import hashlib
from collections.abc import Callable, Sequence
from dataclasses import dataclass, field
from typing import Any, Literal, Protocol

import matplotlib

matplotlib.use("Agg")  # fixed, headless, deterministic backend

from ..hashing import sha256_bytes
from ..ingest.base import IngestError
from ..sources.base import World
from ..sources.world_ops import hidden_nodes

# A draw command: ``node_id`` owns every pixel the callable paints onto ``ax``
# (``None`` for a content-independent patch — e.g. a REDACT_SOLID cover — which
# owns no node). The callable must be deterministic and depend only on the world
# layout, never on wall-clock state.
DrawCommand = tuple[str | None, Callable[[Any], None]]

RendererKind = Literal["plot", "geometry", "table", "clevr"]

#: Node-map pixel value for background / unowned pixels (also a real index is
#: offset by 1, so node 0 in the table is never ambiguous with background).
_BACKGROUND = 0


class RenderError(IngestError):
    """A world cannot be rendered (unsupported kind/predicate, infeasible layout).

    Raised rather than emitting a partial or faked render — P6 never silently
    coerces an unrenderable world into assets.
    """


@dataclass(frozen=True)
class RendererFamily:
    """One train/held-out rendering family (``docs/02`` §9.3).

    Train and held-out families are **disjoint**: different font file, different
    palette, different layout parameters, so an asset rendered under one family
    cannot leak into a pipeline bound to the other (gate: "train/held-out assets
    disjoint"). The font SHA-256 is recorded in every manifest for replay.
    """

    name: str
    kind: RendererKind
    font_name: str  # matplotlib font family name (resolved to a pinned TTF)
    palette: dict[str, str]  # named colors, disjoint across families
    layout: dict[str, Any] = field(default_factory=dict)


@dataclass(frozen=True)
class GlyphRecord:
    """One text glyph cluster linked to the semantic node it labels (§9 gate)."""

    node_id: str
    text: str
    x0: float
    y0: float
    x1: float
    y1: float
    font_sha256: str


@dataclass(frozen=True)
class RenderedAssets:
    """The four byte-addressed assets one ``render`` call produces."""

    rgba_png: bytes
    node_map_png: bytes
    render_manifest: dict[str, Any]
    text_manifest: dict[str, Any]

    @property
    def rgba_sha256(self) -> str:
        return sha256_bytes(self.rgba_png)

    @property
    def node_map_sha256(self) -> str:
        return sha256_bytes(self.node_map_png)


class Renderer(Protocol):
    """One deterministic renderer for one world kind (``docs/02`` §9.1)."""

    name: str
    version: str
    kind: RendererKind

    def render(
        self,
        world: World,
        *,
        renderer_id: str,
        seed: int,
        width: int,
        height: int,
        family: RendererFamily | None = ...,
    ) -> RenderedAssets:
        """Render ``world`` to four byte-addressed assets; never edits a raster.

        ``family`` overrides the renderer's default train family (used to render
        under a held-out family — §9.3); ``None``/default keeps the train family.
        """
        ...


# --- common pipeline: commands + glyphs → RGBA + node map -------------------


@dataclass(frozen=True)
class _Layout:
    """The deterministic draw plan a kind-specific renderer produces.

    ``owner_ids`` is every non-background owner the canvas may paint — semantic
    world nodes **plus** synthetic display nodes (axes/ticks) — so the node map
    fully segments the image. ``visible_node_ids`` is the semantic subset (world
    nodes that are not hidden) the manifest reports and the coverage gate checks.
    """

    commands: tuple[DrawCommand, ...]
    glyphs: tuple[GlyphRecord, ...]
    owner_ids: tuple[str, ...]
    visible_node_ids: tuple[str, ...]
    family: RendererFamily


def rasterize(
    layout: _Layout,
    *,
    width: int,
    height: int,
    seed: int,
) -> tuple[bytes, bytes, dict[str, int]]:
    """Turn a layout into ``(rgba_png, node_map_png, node_pixel_counts)``.

    The RGBA canvas runs every command; the node map runs each owner's commands
    alone into an alpha mask, then takes the alpha-aware argmax (highest alpha
    wins; ties to the lower node index) so anti-alias boundaries have one owner.
    Returns the per-owner pixel count; the manifest filters coverage to the
    semantic ``visible_node_ids`` subset.
    """
    import io

    import matplotlib.pyplot as plt
    import numpy as np
    from PIL import Image

    dpi = 100
    fig_w, fig_h = width / dpi, height / dpi

    def _new_fig() -> tuple[Any, Any]:
        fig = plt.figure(figsize=(fig_w, fig_h), dpi=dpi)
        ax = fig.add_axes((0.0, 0.0, 1.0, 1.0))
        ax.set_xlim(0.0, 1.0)
        ax.set_ylim(0.0, 1.0)
        ax.set_axis_off()
        return fig, ax

    # --- RGBA canvas: every command, in order ---
    fig, ax = _new_fig()
    _paint_background(ax, layout.family)
    for _nid, draw in layout.commands:
        draw(ax)
    rgba_buf = io.BytesIO()
    fig.savefig(rgba_buf, format="png", dpi=dpi)
    plt.close(fig)
    rgba_png = rgba_buf.getvalue()

    # --- node map: per-owner alpha masks → alpha-aware ownership ---
    # Ownership is measured by *paint coverage* (the alpha channel), not
    # luminance: a black text label on a black ground is still opaque paint and
    # must own its pixels. So each mask is rendered on a *transparent* canvas
    # (no background rect) and we read the alpha channel; only the node's own
    # drawn artists produce non-zero alpha. This keeps black-label nodes (a plot
    # series, a geometry entity label) covered, not just colored markers.
    owner_ids = layout.owner_ids
    masks: list[np.ndarray] = []
    for nid in owner_ids:
        fig, ax = _new_fig()
        fig.patch.set_alpha(0.0)  # transparent figure; nothing else is painted
        for cmd_nid, draw in layout.commands:
            if cmd_nid == nid:
                draw(ax)
        buf = io.BytesIO()
        fig.savefig(buf, format="png", dpi=dpi, transparent=True)
        plt.close(fig)
        rgba = np.asarray(Image.open(buf).convert("RGBA"), dtype=np.float32)
        masks.append(rgba[..., 3])  # alpha channel = this node's painted coverage
    counts: dict[str, int] = {}
    if masks:
        stack = np.stack(masks, axis=0)  # (N, H, W)
        top_alpha = stack.max(axis=0)
        owners = np.argmax(stack, axis=0)  # ties → lowest index (np.argmax rule)
        owned = top_alpha > _MASK_ALPHA  # any non-zero alpha on an owner mask claims it
        idx = np.where(owned, owners.astype("<u4") + 1, np.uint32(_BACKGROUND))
        node_map_png = _encode_uint32_png(idx)
        for i, nid in enumerate(owner_ids):
            counts[nid] = int(np.count_nonzero(owned & (owners == i)))
    else:
        idx = np.zeros((height, width), dtype="<u4")
        node_map_png = _encode_uint32_png(idx)

    return rgba_png, node_map_png, counts


# Any non-zero alpha on a per-node mask claims the pixel (anti-alias edges
# included); the highest-alpha node wins, ties break to the lower node index.
_MASK_ALPHA = 1.0


def _paint_background(ax: Any, family: RendererFamily) -> None:
    # The RGBA canvas gets the family background. (Per-node masks render on a
    # transparent figure instead — see :func:`rasterize` — so nothing is painted
    # here for the mask pass.)
    color = family.palette.get("background", "#FFFFFF")
    ax.add_patch(_mpl_patch_rect(0.0, 0.0, 1.0, 1.0, facecolor=color, edgecolor="none", zorder=-10))


def _mpl_patch_rect(x: float, y: float, w: float, h: float, **kw: Any) -> Any:
    from matplotlib.patches import Rectangle

    return Rectangle((x, y), w, h, **kw)


def paint_text(text: str, x: float, y: float, font_name: str, *, size: int = 11) -> Any:
    """A draw callable painting ``text`` at ``(x, y)`` in the pinned ``font_name``.

    Used so a label-bearing semantic node (a plot series, a geometry entity)
    owns the pixels of its label text — giving it node-map coverage (§9.4 step 5:
    "glyph를 그리며 각 draw call에 semantic node ID를 붙인다") in addition to its
    :class:`GlyphRecord` entry in the text manifest.
    """

    def draw(ax: Any) -> None:
        ax.text(
            x,
            y,
            text,
            fontfamily=font_name,
            fontsize=size,
            color="#000000",
            va="bottom",
            ha="left",
            clip_on=False,
        )

    return draw


def glyph_command(glyph: GlyphRecord, font_name: str) -> DrawCommand:
    """The owned draw command that paints a glyph's label text (for node coverage)."""
    return (glyph.node_id, paint_text(glyph.text, glyph.x0, glyph.y0, font_name))


def _encode_uint32_png(idx: Any) -> bytes:
    """Pack a ``uint32`` index array into an RGBA PNG (little-endian per pixel)."""
    import io

    import numpy as np
    from PIL import Image

    idx = np.asarray(idx, dtype="<u4")
    rgba = np.zeros((*idx.shape, 4), dtype="uint8")
    rgba[..., 0] = (idx & 0xFF).astype("uint8")
    rgba[..., 1] = ((idx >> 8) & 0xFF).astype("uint8")
    rgba[..., 2] = ((idx >> 16) & 0xFF).astype("uint8")
    rgba[..., 3] = ((idx >> 24) & 0xFF).astype("uint8")
    buf = io.BytesIO()
    Image.fromarray(rgba, mode="RGBA").save(buf, format="png")
    return buf.getvalue()


def decode_uint32_png(png: bytes) -> Any:
    """Inverse of :func:`_encode_uint32_png` — read the node-index array back."""
    import io

    import numpy as np
    from PIL import Image

    rgba = np.asarray(Image.open(io.BytesIO(png)).convert("RGBA"), dtype="uint8")
    return (
        rgba[..., 0].astype("<u4")
        | (rgba[..., 1].astype("<u4") << 8)
        | (rgba[..., 2].astype("<u4") << 16)
        | (rgba[..., 3].astype("<u4") << 24)
    )


# --- manifest builder -------------------------------------------------------


def font_sha256(font_name: str) -> str:
    """SHA-256 of the pinned TTF matplotlib resolves ``font_name`` to."""
    from matplotlib.font_manager import findfont

    path = findfont(font_name, fallback_to_default=False)
    with open(path, "rb") as fh:
        return hashlib.sha256(fh.read()).hexdigest()


def build_render_manifest(
    *,
    renderer_id: str,
    renderer_name: str,
    renderer_version: str,
    family: RendererFamily,
    world: World,
    seed: int,
    width: int,
    height: int,
    rgba_png: bytes,
    node_map_png: bytes,
    visible_node_ids: Sequence[str],
    owner_ids: Sequence[str],
    node_pixel_counts: dict[str, int],
    glyph_count: int,
    backend: str = "matplotlib_agg",
    backend_version: str | None = None,
) -> dict[str, Any]:
    """The deterministic ``render_manifest.json`` content (no time fields)."""
    hidden = sorted(hidden_nodes(world))
    import matplotlib

    if backend_version is None:
        backend_version = matplotlib.__version__
    coverage = {nid: node_pixel_counts.get(nid, 0) for nid in sorted(visible_node_ids)}
    return {
        "renderer_id": renderer_id,
        "renderer_name": renderer_name,
        "renderer_version": renderer_version,
        "backend": backend,
        "backend_version": backend_version,
        "font_name": family.font_name,
        "font_sha256": font_sha256(family.font_name),
        "locale": "C",
        "seed": seed,
        "width": width,
        "height": height,
        "world_sha256": _world_sha(world),
        "rgba_sha256": sha256_bytes(rgba_png),
        "node_map_sha256": sha256_bytes(node_map_png),
        "node_table": ["__background__", *owner_ids],
        "visible_node_ids": sorted(visible_node_ids),
        "hidden_node_ids": hidden,
        "node_map_coverage": coverage,
        "text_glyph_count": glyph_count,
    }


def build_text_manifest(glyphs: Sequence[GlyphRecord], *, world: World) -> dict[str, Any]:
    """The ``text_manifest.json`` content — every glyph linked to a node."""
    return {
        "world_sha256": _world_sha(world),
        "glyphs": [
            {
                "node_id": g.node_id,
                "text": g.text,
                "bbox": [g.x0, g.y0, g.x1, g.y1],
                "font_sha256": g.font_sha256,
            }
            for g in sorted(glyphs, key=lambda x: (x.node_id, x.text, x.x0, x.y0))
        ],
    }


def assert_replay_identical(renderer: Renderer, world: World, **kwargs: Any) -> None:
    """Gate helper: render twice in-process and assert byte-identical assets."""
    a = renderer.render(world, **kwargs)
    b = renderer.render(world, **kwargs)
    assert a.rgba_png == b.rgba_png, "rgba.png not byte-identical on replay"
    assert a.node_map_png == b.node_map_png, "node_map not byte-identical on replay"
    assert a.render_manifest == b.render_manifest, "render_manifest differs on replay"
    assert a.text_manifest == b.text_manifest, "text_manifest differs on replay"


def assert_node_coverage(assets: RenderedAssets) -> None:
    """Gate helper: every visible semantic node has verified node-map pixels."""
    import numpy as np

    manifest = assets.render_manifest
    node_table = manifest["node_table"]
    visible = manifest["visible_node_ids"]
    hidden = set(manifest["hidden_node_ids"])
    coverage = manifest["node_map_coverage"]
    if len(node_table) != len(set(node_table)):
        raise RenderError("node table contains duplicate ids")
    leaked = hidden.intersection(node_table)
    if leaked:
        raise RenderError(f"hidden nodes appear in the node table: {sorted(leaked)}")

    owners = decode_uint32_png(assets.node_map_png)
    expected_shape = (manifest["height"], manifest["width"])
    if owners.shape != expected_shape:
        raise RenderError(
            f"node-map dimensions differ from manifest: {owners.shape!r} != {expected_shape!r}"
        )
    if owners.size and int(owners.max()) >= len(node_table):
        raise RenderError("node map references an index absent from the node table")

    missing: list[str] = []
    for node_id in visible:
        if node_id not in node_table:
            missing.append(node_id)
            continue
        actual = int(np.count_nonzero(owners == node_table.index(node_id)))
        if coverage.get(node_id) != actual:
            raise RenderError(
                f"node-map coverage for {node_id!r} differs from pixels: "
                f"{coverage.get(node_id)!r} != {actual}"
            )
        if actual <= 0:
            missing.append(node_id)
    if missing:
        raise RenderError(f"visible nodes without node-map coverage: {missing}")


def assert_glyphs_linked(assets: RenderedAssets) -> None:
    """Gate helper: every glyph is linked, family-font-matched, and in-canvas."""
    node_table = set(assets.render_manifest["node_table"][1:])
    expected_font = assets.render_manifest["font_sha256"]
    glyphs = assets.text_manifest["glyphs"]
    if len(glyphs) != assets.render_manifest["text_glyph_count"]:
        raise RenderError(
            "text glyph count differs from render manifest: "
            f"{len(glyphs)} != {assets.render_manifest['text_glyph_count']}"
        )
    for g in glyphs:
        node_id = g.get("node_id")
        if not node_id:
            raise RenderError(f"glyph without a node link: {g!r}")
        if node_id not in node_table:
            raise RenderError(f"glyph links to a node absent from the node table: {g!r}")
        if g.get("font_sha256") != expected_font:
            raise RenderError(
                f"glyph font hash differs from render family font: "
                f"{g.get('font_sha256')!r} != {expected_font!r}"
            )
        bbox = g.get("bbox")
        if (
            not isinstance(bbox, list)
            or len(bbox) != 4
            or not all(isinstance(value, (int, float)) for value in bbox)
        ):
            raise RenderError(f"glyph has an invalid bbox: {g!r}")
        x0, y0, x1, y1 = bbox
        if not (0.0 <= x0 <= x1 <= 1.0 and 0.0 <= y0 <= y1 <= 1.0):
            raise RenderError(f"glyph is outside the canvas: {g!r}")


def validate_rendered_assets(assets: RenderedAssets) -> None:
    """Apply the mandatory structural gates before any renderer returns assets."""
    manifest = assets.render_manifest
    if manifest["rgba_sha256"] != assets.rgba_sha256:
        raise RenderError("rgba hash differs from render manifest")
    if manifest["node_map_sha256"] != assets.node_map_sha256:
        raise RenderError("node-map hash differs from render manifest")
    assert_node_coverage(assets)
    assert_glyphs_linked(assets)


def _world_sha(world: World) -> str:
    from ..sources.world_ops import world_sha256

    return world_sha256(world)