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
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
2
3
4
5
6
7
8
9
10
11
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
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
"""Deterministic, information-complete plot rendering.

``PlotRenderer`` draws directly from ``plot_world_v1`` with Pillow.  Unlike the
initial marker-only prototype, the image contains the information a solver needs:
numeric or categorical x ticks, numeric y ticks, title/axis labels, a
series-coloured legend, and line or grouped-bar geometry.

Redacted points are never placed at their hidden y coordinate.  A fixed vertical
strip at the point's observed x spans the complete data region, and the hidden
point breaks its line.  Axis scaling uses ``world["render_domain"]`` when present;
otherwise it is derived from visible points only.  Consequently completion worlds
that differ only in a hidden y value produce byte-identical pixel assets.
"""

from __future__ import annotations

import io
from collections.abc import Iterable, Mapping, Sequence
from dataclasses import dataclass
from fractions import Fraction
from math import ceil, floor
from typing import Any

from ..dsl.ast import canonical_number_str, parse_number
from ..sources.base import World
from ..sources.world_ops import hidden_nodes
from .base import (
    GlyphRecord,
    RenderedAssets,
    RendererFamily,
    RendererKind,
    RenderError,
    _encode_uint32_png,
    build_render_manifest,
    build_text_manifest,
    font_sha256,
    validate_rendered_assets,
)

_NAME = "plot_renderer"
_VERSION = "3"
_KIND: RendererKind = "plot"
_MIN_WIDTH = 320
_MIN_HEIGHT = 220
_Y_TICKS = 5
_MAX_X_TICKS = 16


@dataclass(frozen=True)
class _Point:
    node_id: str
    x_label: str
    x_value: Fraction | None
    y: Fraction | None
    y_label: str
    hidden: bool


@dataclass(frozen=True)
class _Series:
    node_id: str
    label: str
    points: tuple[_Point, ...]
    hidden: bool


@dataclass(frozen=True)
class _Domain:
    numeric_x: bool
    x_min: Fraction
    x_max: Fraction
    y_min: Fraction
    y_max: Fraction
    x_labels: tuple[str, ...]

    def manifest_record(self) -> dict[str, Any]:
        return {
            "numeric_x": self.numeric_x,
            "x_min": canonical_number_str(self.x_min) if self.numeric_x else None,
            "x_max": canonical_number_str(self.x_max) if self.numeric_x else None,
            "y_min": canonical_number_str(self.y_min),
            "y_max": canonical_number_str(self.y_max),
            "x_labels": list(self.x_labels),
        }


class _Canvas:
    """Pillow RGBA canvas plus a same-pass integer owner canvas."""

    def __init__(self, width: int, height: int, family: RendererFamily) -> None:
        import numpy as np
        from matplotlib.font_manager import findfont
        from PIL import Image, ImageDraw

        self.width = width
        self.height = height
        self.family = family
        self.image = Image.new("RGBA", (width, height), family.palette.get("background", "#FFFFFF"))
        self.owner_image = Image.new("I", (width, height), 0)
        self.draw = ImageDraw.Draw(self.image)
        self.owner_draw = ImageDraw.Draw(self.owner_image)
        self.owner_ids: list[str] = []
        self.owner_index: dict[str, int] = {}
        self.glyphs: list[GlyphRecord] = []
        self._font_path = findfont(family.font_name, fallback_to_default=False)
        self._font_sha256 = font_sha256(family.font_name)
        self._font_cache: dict[int, Any] = {}
        self._np = np

    def _owner(self, node_id: str) -> int:
        index = self.owner_index.get(node_id)
        if index is None:
            self.owner_ids.append(node_id)
            index = len(self.owner_ids)
            self.owner_index[node_id] = index
        return index

    def reserve(self, node_id: str) -> None:
        self._owner(node_id)

    def font(self, size: int) -> Any:
        from PIL import ImageFont

        size = max(7, int(size))
        font = self._font_cache.get(size)
        if font is None:
            font = ImageFont.truetype(self._font_path, size=size)
            self._font_cache[size] = font
        return font

    def line(
        self,
        node_id: str,
        xy: Sequence[tuple[float, float]],
        *,
        fill: str,
        width: int,
    ) -> None:
        index = self._owner(node_id)
        self.draw.line(xy, fill=fill, width=width, joint="curve")
        self.owner_draw.line(xy, fill=index, width=max(1, width))

    def rectangle(
        self,
        node_id: str | None,
        box: tuple[float, float, float, float],
        *,
        fill: str,
        outline: str | None = None,
        width: int = 1,
    ) -> None:
        self.draw.rectangle(box, fill=fill, outline=outline, width=width)
        index = 0 if node_id is None else self._owner(node_id)
        self.owner_draw.rectangle(box, fill=index)

    def ellipse(
        self,
        node_id: str,
        box: tuple[float, float, float, float],
        *,
        fill: str,
        outline: str,
        width: int = 1,
    ) -> None:
        index = self._owner(node_id)
        self.draw.ellipse(box, fill=fill, outline=outline, width=width)
        self.owner_draw.ellipse(box, fill=index)

    def text(
        self,
        node_id: str,
        text: str,
        xy: tuple[float, float],
        *,
        size: int,
        fill: str,
        anchor: str,
        max_width: float | None = None,
    ) -> tuple[int, int, int, int] | None:
        if not text:
            return None
        index = self._owner(node_id)
        x, y, font, bbox = self._text_layout(
            text,
            xy,
            size=size,
            anchor=anchor,
            max_width=max_width,
        )
        self.draw.text((x, y), text, font=font, fill=fill, anchor=anchor)
        self.owner_draw.text((x, y), text, font=font, fill=index, anchor=anchor)
        self.glyphs.append(
            GlyphRecord(
                node_id=node_id,
                text=text,
                x0=bbox[0] / self.width,
                y0=(self.height - bbox[3]) / self.height,
                x1=bbox[2] / self.width,
                y1=(self.height - bbox[1]) / self.height,
                font_sha256=self._font_sha256,
            )
        )
        return bbox

    def text_bbox(
        self,
        text: str,
        xy: tuple[float, float],
        *,
        size: int,
        anchor: str,
        max_width: float | None = None,
    ) -> tuple[int, int, int, int]:
        """Measure text exactly as :meth:`text` will draw it, without painting."""
        _, _, _, bbox = self._text_layout(
            text,
            xy,
            size=size,
            anchor=anchor,
            max_width=max_width,
        )
        return bbox

    def _text_layout(
        self,
        text: str,
        xy: tuple[float, float],
        *,
        size: int,
        anchor: str,
        max_width: float | None,
    ) -> tuple[float, float, Any, tuple[int, int, int, int]]:
        font_size = size
        font = self.font(font_size)
        if max_width is not None:
            while font_size > 7:
                probe = self.draw.textbbox(xy, text, font=font, anchor=anchor)
                if probe[2] - probe[0] <= max_width:
                    break
                font_size -= 1
                font = self.font(font_size)

        x, y = xy
        bbox = self.draw.textbbox((x, y), text, font=font, anchor=anchor)
        if max_width is not None and bbox[2] - bbox[0] > max_width + 1:
            raise RenderError(f"plot text does not fit its allotted width: {text!r}")

        # Keep the complete glyph box within the raster while preserving its
        # requested alignment as closely as possible.
        if bbox[0] < 2:
            x += 2 - bbox[0]
        if bbox[2] > self.width - 2:
            x -= bbox[2] - (self.width - 2)
        if bbox[1] < 2:
            y += 2 - bbox[1]
        if bbox[3] > self.height - 2:
            y -= bbox[3] - (self.height - 2)
        raw_bbox = self.draw.textbbox((x, y), text, font=font, anchor=anchor)
        bbox = (
            floor(raw_bbox[0]),
            floor(raw_bbox[1]),
            ceil(raw_bbox[2]),
            ceil(raw_bbox[3]),
        )
        if bbox[0] < 0 or bbox[1] < 0 or bbox[2] > self.width or bbox[3] > self.height:
            raise RenderError(f"plot glyph is outside the canvas: {text!r}, bbox={bbox!r}")
        return x, y, font, bbox

    def finish(self) -> tuple[bytes, bytes, dict[str, int]]:
        owner_array = self._np.asarray(self.owner_image, dtype="<u4")
        rgba_buf = io.BytesIO()
        self.image.save(rgba_buf, format="PNG", compress_level=9, optimize=False)
        counts = {
            node_id: int(self._np.count_nonzero(owner_array == index))
            for node_id, index in self.owner_index.items()
        }
        return rgba_buf.getvalue(), _encode_uint32_png(owner_array), counts


class PlotRenderer:
    """Deterministic renderer for ``plot_world_v1``."""

    name = _NAME
    version = _VERSION
    kind = _KIND

    def render(
        self,
        world: World,
        *,
        renderer_id: str,
        seed: int,
        width: int,
        height: int,
        family: RendererFamily | None = None,
    ) -> RenderedAssets:
        if world.get("world_schema") != "plot_world_v1":
            raise RenderError(
                f"plot renderer expects plot_world_v1, got {world.get('world_schema')!r}"
            )
        family = family or _PLOT_TRAIN_FAMILY
        if family.kind != self.kind:
            raise RenderError(
                f"renderer family {family.name!r} has kind {family.kind!r}, expected {self.kind!r}"
            )
        if renderer_id != family.name:
            raise RenderError(f"renderer_id {renderer_id!r} does not match family {family.name!r}")
        if width < _MIN_WIDTH or height < _MIN_HEIGHT:
            raise RenderError(
                f"plot canvas must be at least {_MIN_WIDTH}x{_MIN_HEIGHT}, got {width}x{height}"
            )

        series = _parse_series(world)
        domain = _build_domain(world, series)
        canvas = _Canvas(width, height, family)
        visible = _draw_plot(canvas, world, series, domain, family)
        rgba_png, node_map_png, counts = canvas.finish()

        manifest = build_render_manifest(
            renderer_id=renderer_id,
            renderer_name=self.name,
            renderer_version=self.version,
            family=family,
            world=world,
            seed=seed,
            width=width,
            height=height,
            rgba_png=rgba_png,
            node_map_png=node_map_png,
            visible_node_ids=visible,
            owner_ids=canvas.owner_ids,
            node_pixel_counts=counts,
            glyph_count=len(canvas.glyphs),
            backend="pillow",
            backend_version=_pillow_version(),
        )
        manifest["render_domain"] = domain.manifest_record()
        manifest["plot_type"] = _plot_type(world)
        assets = RenderedAssets(
            rgba_png=rgba_png,
            node_map_png=node_map_png,
            render_manifest=manifest,
            text_manifest=build_text_manifest(canvas.glyphs, world=world),
        )
        validate_rendered_assets(assets)
        return assets


def _parse_series(world: World) -> tuple[_Series, ...]:
    hidden = hidden_nodes(world)
    raw_series = world.get("series", []) or []
    if not isinstance(raw_series, list) or not raw_series:
        raise RenderError("plot world has no series")
    output: list[_Series] = []
    seen: set[str] = set()
    for raw in raw_series:
        if not isinstance(raw, Mapping):
            raise RenderError("plot series is not an object")
        sid = str(raw.get("id", ""))
        if not sid or sid in seen:
            raise RenderError(f"plot series has a missing/duplicate id: {sid!r}")
        seen.add(sid)
        is_series_hidden = sid in hidden
        points: list[_Point] = []
        raw_points = raw.get("points", []) or []
        if not isinstance(raw_points, list):
            raise RenderError(f"plot series {sid!r} points are not a list")
        for raw_point in raw_points:
            if not isinstance(raw_point, Mapping):
                raise RenderError(f"plot series {sid!r} contains a non-object point")
            pid = str(raw_point.get("id", ""))
            if not pid or pid in seen:
                raise RenderError(f"plot point has a missing/duplicate id: {pid!r}")
            seen.add(pid)
            x_label = str(raw_point.get("x", ""))
            if not x_label:
                raise RenderError(f"plot point {pid!r} has no x value")
            try:
                x_value: Fraction | None = parse_number(x_label)
            except (TypeError, ValueError, ZeroDivisionError):
                x_value = None
            is_hidden = is_series_hidden or pid in hidden
            if is_hidden:
                # A redacted point's content is deliberately opaque to layout.
                # In particular, ``None`` and alternate completion values must
                # produce the same observed raster.
                y: Fraction | None = None
                y_label = ""
            else:
                try:
                    y = parse_number(raw_point.get("y", ""))
                except (TypeError, ValueError, ZeroDivisionError) as exc:
                    raise RenderError(f"plot point {pid!r} has an invalid y value") from exc
                y_label = _exact_value_label(y)
            points.append(
                _Point(
                    node_id=pid,
                    x_label=x_label,
                    x_value=x_value,
                    y=y,
                    y_label=y_label,
                    hidden=is_hidden,
                )
            )
        output.append(
            _Series(
                node_id=sid,
                label=str(raw.get("label", sid)),
                points=tuple(points),
                hidden=is_series_hidden,
            )
        )
    if not any(s.points for s in output):
        raise RenderError("plot world has no points")
    return tuple(output)


def _build_domain(world: World, series: Sequence[_Series]) -> _Domain:
    all_points = [point for item in series for point in item.points]
    numeric_x = all(point.x_value is not None for point in all_points)
    axis_values = _axis_values(world.get("x_axis"))
    x_labels = _dedup([*axis_values, *(point.x_label for point in all_points)])
    if not x_labels:
        raise RenderError("plot world has no x labels")

    render_domain = world.get("render_domain")
    domain_map = render_domain if isinstance(render_domain, Mapping) else {}

    if numeric_x:
        numeric_values = [point.x_value for point in all_points if point.x_value is not None]
        x_min_override = _domain_bound(domain_map, "x", "min")
        x_max_override = _domain_bound(domain_map, "x", "max")
        x_min = x_min_override if x_min_override is not None else min(numeric_values)
        x_max = x_max_override if x_max_override is not None else max(numeric_values)
    else:
        x_min = Fraction(0)
        x_max = Fraction(max(1, len(x_labels) - 1))
    x_min, x_max = _nondegenerate(x_min, x_max)

    visible_y = [
        point.y
        for item in series
        if not item.hidden
        for point in item.points
        if not point.hidden and point.y is not None
    ]
    y_min_override = _domain_bound(domain_map, "y", "min")
    y_max_override = _domain_bound(domain_map, "y", "max")
    if visible_y:
        y_min = y_min_override if y_min_override is not None else min(visible_y)
        y_max = y_max_override if y_max_override is not None else max(visible_y)
    else:
        y_min = y_min_override if y_min_override is not None else Fraction(0)
        y_max = y_max_override if y_max_override is not None else Fraction(1)

    if "bar" in _plot_type(world) and y_min_override is None and y_max_override is None:
        y_min = min(y_min, Fraction(0))
        y_max = max(y_max, Fraction(0))
    y_min, y_max = _nondegenerate(y_min, y_max)
    if y_min_override is None and y_max_override is None:
        padding = (y_max - y_min) / 10
        y_min -= padding
        y_max += padding

    return _Domain(
        numeric_x=numeric_x,
        x_min=x_min,
        x_max=x_max,
        y_min=y_min,
        y_max=y_max,
        x_labels=tuple(x_labels),
    )


def _draw_plot(
    canvas: _Canvas,
    world: World,
    series: Sequence[_Series],
    domain: _Domain,
    family: RendererFamily,
) -> tuple[str, ...]:
    width, height = canvas.width, canvas.height
    legend_width = max(118, min(210, int(width * 0.24)))
    left = max(62, int(width * 0.11))
    right = width - legend_width
    top = max(54, int(height * 0.12))
    bottom = height - max(58, int(height * 0.15))
    if right - left < 140 or bottom - top < 100:
        raise RenderError("plot canvas leaves insufficient data area after labels/legend")

    text_color = family.palette.get("text", "#202020")
    axis_color = family.palette.get("axis", "#444444")
    grid_color = family.palette.get("grid", "#D8D8D8")
    plot_type = _plot_type(world)
    visible_series_count = sum(not item.hidden for item in series)
    x_padding = 0.0
    if "bar" in plot_type:
        _, bar_width = _bar_dimensions(canvas.width, len(domain.x_labels), visible_series_count)
        x_padding = ((max(1, visible_series_count) - 1) / 2 + 0.42) * bar_width + 2
    x_span = right - left - 2 * x_padding
    if x_span <= 0:
        raise RenderError("plot data area is too narrow for grouped bars")

    # Title and axis captions.
    title = _display_text(world.get("title")) or "Chart"
    x_axis_label = _axis_label(world.get("x_axis")) or "X"
    y_axis_label = _axis_label(world.get("y_axis")) or "Value"
    canvas.text(
        "plot:title",
        title,
        (width / 2, 18),
        size=max(14, min(20, width // 45)),
        fill=text_color,
        anchor="ma",
        max_width=width - 20,
    )
    canvas.text(
        "axis:y:label",
        y_axis_label,
        (left, top - 9),
        size=11,
        fill=text_color,
        anchor="ld",
        max_width=max(80, (right - left) * 0.45),
    )
    canvas.text(
        "axis:x:label",
        x_axis_label,
        ((left + right) / 2, height - 8),
        size=11,
        fill=text_color,
        anchor="md",
        max_width=right - left,
    )

    def x_position(point: _Point) -> float:
        if domain.numeric_x:
            assert point.x_value is not None
            ratio = float((point.x_value - domain.x_min) / (domain.x_max - domain.x_min))
        else:
            ratio = (
                domain.x_labels.index(point.x_label) / (len(domain.x_labels) - 1)
                if len(domain.x_labels) > 1
                else 0.5
            )
        if ratio < -1e-9 or ratio > 1 + 1e-9:
            raise RenderError(f"x value {point.x_label!r} is outside render_domain")
        return left + x_padding + min(1.0, max(0.0, ratio)) * x_span

    def x_label_position(label: str) -> float:
        if domain.numeric_x:
            value = parse_number(label)
            ratio = float((value - domain.x_min) / (domain.x_max - domain.x_min))
        else:
            ratio = (
                domain.x_labels.index(label) / (len(domain.x_labels) - 1)
                if len(domain.x_labels) > 1
                else 0.5
            )
        return left + x_padding + min(1.0, max(0.0, ratio)) * x_span

    def y_position(value: Fraction) -> float:
        ratio = float((value - domain.y_min) / (domain.y_max - domain.y_min))
        if ratio < -1e-9 or ratio > 1 + 1e-9:
            raise RenderError(f"y value {canonical_number_str(value)!r} is outside render_domain")
        return bottom - min(1.0, max(0.0, ratio)) * (bottom - top)

    # Grid, axes, and numeric y ticks.
    for i in range(_Y_TICKS):
        ratio = Fraction(i, _Y_TICKS - 1)
        value = domain.y_min + ratio * (domain.y_max - domain.y_min)
        y = bottom - float(ratio) * (bottom - top)
        node_id = f"axis:y:tick:{i}"
        canvas.line(node_id, [(left, y), (right, y)], fill=grid_color, width=1)
        canvas.text(
            node_id,
            _format_number(value),
            (left - 7, y),
            size=9,
            fill=text_color,
            anchor="rm",
            max_width=left - 12,
        )
    canvas.line("axis:x", [(left, bottom), (right, bottom)], fill=axis_color, width=2)
    canvas.line("axis:y", [(left, top), (left, bottom)], fill=axis_color, width=2)

    tick_labels = _decimate(domain.x_labels, _MAX_X_TICKS)
    spacing = (right - left) / max(1, len(tick_labels) - 1)
    tick_size = max(7, min(10, int(spacing * 0.28)))
    for i, label in enumerate(tick_labels):
        x = x_label_position(label)
        node_id = f"axis:x:tick:{i}"
        canvas.line(node_id, [(x, bottom), (x, bottom + 5)], fill=axis_color, width=1)
        canvas.text(
            node_id,
            label,
            (x, bottom + 8 + (i % 2) * 10),
            size=tick_size,
            fill=text_color,
            anchor="ma",
            max_width=max(24, spacing * 1.8),
        )

    # The redaction token is anchored only at observed x.  It is painted after
    # the grid (and clears grid ownership) but before visible series, so unrelated
    # visible points at the same x remain readable.
    hidden_x = _dedup(point.x_label for item in series for point in item.points if point.hidden)
    strip_half_width = max(4, min(12, int((right - left) / max(24, len(domain.x_labels) * 8))))
    for label in hidden_x:
        prototype = next(
            point for item in series for point in item.points if point.x_label == label
        )
        x = x_position(prototype)
        canvas.rectangle(
            None,
            (x - strip_half_width, top, x + strip_half_width, bottom),
            fill=family.palette.get("redact", "#111111"),
        )

    colours = _series_colours(family)
    visible: list[str] = []

    # Reserve every visible semantic owner before drawing; this makes node-table
    # order independent of accidental primitive ordering.
    for item in series:
        if item.hidden:
            continue
        visible.append(item.node_id)
        canvas.reserve(item.node_id)
        for point in item.points:
            if not point.hidden:
                visible.append(point.node_id)
                canvas.reserve(point.node_id)

    if "bar" in plot_type:
        _draw_bars(canvas, series, domain, x_position, y_position, colours)
    else:
        _draw_lines(canvas, series, x_position, y_position, colours, scatter="scatter" in plot_type)
    _draw_value_labels(
        canvas,
        series,
        domain,
        x_position,
        y_position,
        colours,
        plot_type=plot_type,
        data_bounds=(left, top, right, bottom),
    )

    # Series-coloured legend.  The swatch and text are both owned by the series,
    # guaranteeing coverage even for a single-point series.
    legend_x = right + 17
    legend_y = top + 8
    visible_series = [item for item in series if not item.hidden]
    row_height = max(18, min(28, (bottom - top) // max(1, len(visible_series))))
    for index, item in enumerate(visible_series):
        y = legend_y + index * row_height
        if y + 13 > bottom:
            raise RenderError("plot legend does not fit within the canvas")
        colour = colours[index % len(colours)]
        canvas.rectangle(
            item.node_id,
            (legend_x, y, legend_x + 18, y + 8),
            fill=colour,
            outline=axis_color,
        )
        canvas.text(
            item.node_id,
            item.label,
            (legend_x + 24, y + 4),
            size=10,
            fill=text_color,
            anchor="lm",
            max_width=width - (legend_x + 28) - 4,
        )

    return tuple(_dedup(visible))


def _draw_lines(
    canvas: _Canvas,
    series: Sequence[_Series],
    x_position: Any,
    y_position: Any,
    colours: Sequence[str],
    *,
    scatter: bool,
) -> None:
    visible_series = [item for item in series if not item.hidden]
    count = len(visible_series)
    for series_index, item in enumerate(visible_series):
        colour = colours[series_index % len(colours)]
        x_offset = (series_index - (count - 1) / 2) * min(4.0, 8.0 / max(1, count))
        run: list[tuple[float, float]] = []
        runs: list[list[tuple[float, float]]] = []
        for point in item.points:
            if point.hidden:
                if len(run) >= 2:
                    runs.append(run)
                run = []
                continue
            assert point.y is not None
            run.append((x_position(point) + x_offset, y_position(point.y)))
        if len(run) >= 2:
            runs.append(run)
        if not scatter:
            for coordinates in runs:
                canvas.line(item.node_id, coordinates, fill=colour, width=3)
        for point_index, point in enumerate(point for point in item.points if not point.hidden):
            assert point.y is not None
            x = x_position(point) + x_offset
            y = y_position(point.y)
            radius = max(3.0, 6.0 - series_index * 0.35 + (point_index % 2) * 0.2)
            canvas.ellipse(
                point.node_id,
                (x - radius, y - radius, x + radius, y + radius),
                fill=colour,
                outline="#202020",
                width=1,
            )


def _draw_bars(
    canvas: _Canvas,
    series: Sequence[_Series],
    domain: _Domain,
    x_position: Any,
    y_position: Any,
    colours: Sequence[str],
) -> None:
    visible_series = [item for item in series if not item.hidden]
    count = max(1, len(visible_series))
    _, bar_width = _bar_dimensions(canvas.width, len(domain.x_labels), count)
    baseline_value = min(max(Fraction(0), domain.y_min), domain.y_max)
    baseline = y_position(baseline_value)
    for series_index, item in enumerate(visible_series):
        colour = colours[series_index % len(colours)]
        offset = (series_index - (count - 1) / 2) * bar_width
        for point in item.points:
            if point.hidden:
                continue
            assert point.y is not None
            x = x_position(point) + offset
            y = y_position(point.y)
            y0, y1 = sorted((baseline, y))
            if y1 - y0 < 1:
                y1 = y0 + 1
            canvas.rectangle(
                point.node_id,
                (x - bar_width * 0.42, y0, x + bar_width * 0.42, y1),
                fill=colour,
                outline="#202020",
            )


def _draw_value_labels(
    canvas: _Canvas,
    series: Sequence[_Series],
    domain: _Domain,
    x_position: Any,
    y_position: Any,
    colours: Sequence[str],
    *,
    plot_type: str,
    data_bounds: tuple[float, float, float, float],
) -> None:
    """Draw every visible point's exact value with deterministic collision avoidance."""
    left, top, right, bottom = data_bounds
    visible_series = [item for item in series if not item.hidden]
    count = max(1, len(visible_series))
    if "bar" in plot_type:
        _, bar_width = _bar_dimensions(canvas.width, len(domain.x_labels), count)
        x_offsets = [(series_index - (count - 1) / 2) * bar_width for series_index in range(count)]
    else:
        x_offsets = [
            (series_index - (count - 1) / 2) * min(4.0, 8.0 / count)
            for series_index in range(count)
        ]

    # Marker boxes are obstacles for line/scatter labels. Bar labels naturally
    # sit beyond the value endpoint and do not need the whole bar as an obstacle.
    occupied: list[tuple[int, int, int, int]] = []
    if "bar" not in plot_type:
        for series_index, item in enumerate(visible_series):
            for point in item.points:
                if point.hidden:
                    continue
                assert point.y is not None
                x = x_position(point) + x_offsets[series_index]
                y = y_position(point.y)
                occupied.append((round(x - 7), round(y - 7), round(x + 7), round(y + 7)))

    background = canvas.family.palette.get("background", "#FFFFFF")
    base_size = max(8, min(10, canvas.width // 72))
    max_width = min(190.0, max(40.0, right - left - 8))
    for series_index, item in enumerate(visible_series):
        colour = colours[series_index % len(colours)]
        for point_index, point in enumerate(point for point in item.points if not point.hidden):
            assert point.y is not None
            if not point.y_label:
                raise RenderError(f"visible point {point.node_id!r} has no exact value label")
            x = x_position(point) + x_offsets[series_index]
            y = y_position(point.y)
            candidates = _value_label_candidates(
                x,
                y,
                data_bounds=data_bounds,
                parity=(series_index + point_index) % 2,
            )

            selected: (
                tuple[
                    tuple[float, float],
                    str,
                    int,
                    tuple[int, int, int, int],
                ]
                | None
            ) = None
            fallback: list[
                tuple[
                    tuple[int, int, int],
                    tuple[float, float],
                    str,
                    int,
                    tuple[int, int, int, int],
                ]
            ] = []
            for font_size in range(base_size, 6, -1):
                for candidate_index, (xy, anchor) in enumerate(candidates):
                    bbox = canvas.text_bbox(
                        point.y_label,
                        xy,
                        size=font_size,
                        anchor=anchor,
                        max_width=max_width,
                    )
                    padded = _expand_bbox(bbox, 2)
                    score = _label_overlap_score(
                        padded,
                        occupied,
                        bounds=(
                            round(left + 1),
                            round(top + 1),
                            round(right - 1),
                            round(bottom - 1),
                        ),
                    )
                    if score == 0:
                        selected = (xy, anchor, font_size, bbox)
                        break
                    fallback.append(
                        (
                            (score, -font_size, candidate_index),
                            xy,
                            anchor,
                            font_size,
                            bbox,
                        )
                    )
                if selected is not None:
                    break

            if selected is None:
                if not fallback:
                    raise RenderError(f"no value-label placement for point {point.node_id!r}")
                _, xy, anchor, font_size, bbox = min(fallback, key=lambda item: item[0])
            else:
                xy, anchor, font_size, bbox = selected

            label_background = _clip_bbox(
                _expand_bbox(bbox, 2),
                width=canvas.width,
                height=canvas.height,
            )
            canvas.rectangle(point.node_id, label_background, fill=background)
            drawn_bbox = canvas.text(
                point.node_id,
                point.y_label,
                xy,
                size=font_size,
                fill=colour,
                anchor=anchor,
                max_width=max_width,
            )
            assert drawn_bbox is not None
            occupied.append(_expand_bbox(drawn_bbox, 2))


def _value_label_candidates(
    x: float,
    y: float,
    *,
    data_bounds: tuple[float, float, float, float],
    parity: int,
) -> tuple[tuple[tuple[float, float], str], ...]:
    left, top, right, bottom = data_bounds
    above = ((x, y - 9), "mb")
    below = ((x, y + 9), "mt")
    right_of = ((x + 10, y), "lm")
    left_of = ((x - 10, y), "rm")
    above_right = ((x + 7, y - 7), "lb")
    above_left = ((x - 7, y - 7), "rb")
    below_right = ((x + 7, y + 7), "lt")
    below_left = ((x - 7, y + 7), "rt")

    inward = right_of if x <= (left + right) / 2 else left_of
    outward = left_of if inward is right_of else right_of
    if y <= top + (bottom - top) * 0.32:
        primary, secondary = below, above
        diagonal_in = below_right if inward is right_of else below_left
        diagonal_out = below_left if inward is right_of else below_right
    elif y >= top + (bottom - top) * 0.68:
        primary, secondary = above, below
        diagonal_in = above_right if inward is right_of else above_left
        diagonal_out = above_left if inward is right_of else above_right
    elif parity:
        primary, secondary = below, above
        diagonal_in = below_right if inward is right_of else below_left
        diagonal_out = above_left if inward is right_of else above_right
    else:
        primary, secondary = above, below
        diagonal_in = above_right if inward is right_of else above_left
        diagonal_out = below_left if inward is right_of else below_right
    return (
        primary,
        diagonal_in,
        inward,
        secondary,
        diagonal_out,
        outward,
        above_right,
        above_left,
        below_right,
        below_left,
    )


def _expand_bbox(bbox: tuple[int, int, int, int], padding: int) -> tuple[int, int, int, int]:
    return (
        bbox[0] - padding,
        bbox[1] - padding,
        bbox[2] + padding,
        bbox[3] + padding,
    )


def _clip_bbox(
    bbox: tuple[int, int, int, int], *, width: int, height: int
) -> tuple[float, float, float, float]:
    return (
        max(0, bbox[0]),
        max(0, bbox[1]),
        min(width - 1, bbox[2]),
        min(height - 1, bbox[3]),
    )


def _label_overlap_score(
    bbox: tuple[int, int, int, int],
    occupied: Sequence[tuple[int, int, int, int]],
    *,
    bounds: tuple[int, int, int, int],
) -> int:
    left, top, right, bottom = bounds
    overflow = (
        max(0, left - bbox[0])
        + max(0, top - bbox[1])
        + max(0, bbox[2] - right)
        + max(0, bbox[3] - bottom)
    )
    overlap = sum(_bbox_overlap_area(bbox, other) for other in occupied)
    return overflow * 1_000_000 + overlap


def _bbox_overlap_area(first: tuple[int, int, int, int], second: tuple[int, int, int, int]) -> int:
    width = max(0, min(first[2], second[2]) - max(first[0], second[0]))
    height = max(0, min(first[3], second[3]) - max(first[1], second[1]))
    return width * height


def _bar_dimensions(
    canvas_width: int, unique_x_count: int, series_count: int
) -> tuple[float, float]:
    group_width = max(12.0, min(56.0, (canvas_width * 0.58) / max(1, unique_x_count)))
    return group_width, max(3.0, group_width / (max(1, series_count) + 0.4))


def _domain_bound(domain: Mapping[str, Any], axis: str, bound: str) -> Fraction | None:
    direct = domain.get(f"{axis}_{bound}")
    nested = domain.get(axis)
    raw = direct
    if raw is None and isinstance(nested, Mapping):
        raw = nested.get(bound)
    if raw is None:
        return None
    try:
        return parse_number(raw)
    except (TypeError, ValueError, ZeroDivisionError) as exc:
        raise RenderError(f"invalid render_domain {axis}_{bound}: {raw!r}") from exc


def _axis_values(axis: Any) -> list[str]:
    if not isinstance(axis, Mapping):
        return []
    values = axis.get("values") or []
    if not isinstance(values, Sequence) or isinstance(values, (str, bytes)):
        return []
    return [str(value) for value in values if str(value)]


def _axis_label(axis: Any) -> str:
    if isinstance(axis, Mapping):
        return _display_text(axis.get("label"))
    return _display_text(axis)


def _display_text(value: Any) -> str:
    if value is None:
        return ""
    if isinstance(value, Mapping):
        for key in ("text", "label", "title", "name"):
            if value.get(key) is not None:
                return str(value[key])
        return ""
    if isinstance(value, Sequence) and not isinstance(value, (str, bytes)):
        return ", ".join(str(item) for item in value)
    return str(value)


def _plot_type(world: World) -> str:
    return str(world.get("plot_type", "line")).strip().lower() or "line"


def _nondegenerate(low: Fraction, high: Fraction) -> tuple[Fraction, Fraction]:
    if high < low:
        raise RenderError(f"render domain is reversed: {low} > {high}")
    if high == low:
        return low - 1, high + 1
    return low, high


def _format_number(value: Fraction) -> str:
    if value.denominator == 1:
        return str(value.numerator)
    decimal = f"{float(value):.2f}".rstrip("0").rstrip(".")
    return decimal if decimal not in {"-0", ""} else "0"


def _exact_value_label(value: Fraction) -> str:
    """An exact human-readable value: terminating decimal when possible."""
    if value.numerator == 0:
        return "0"
    denominator = value.denominator
    powers_of_two = 0
    powers_of_five = 0
    while denominator % 2 == 0:
        denominator //= 2
        powers_of_two += 1
    while denominator % 5 == 0:
        denominator //= 5
        powers_of_five += 1
    if denominator != 1:
        return canonical_number_str(value)

    decimal_places = max(powers_of_two, powers_of_five)
    scaled = abs(value.numerator)
    scaled *= 2 ** (decimal_places - powers_of_two)
    scaled *= 5 ** (decimal_places - powers_of_five)
    sign = "-" if value.numerator < 0 else ""
    if decimal_places == 0:
        return f"{sign}{scaled}"
    digits = str(scaled).rjust(decimal_places + 1, "0")
    integer = digits[:-decimal_places]
    fractional = digits[-decimal_places:].rstrip("0")
    return f"{sign}{integer}.{fractional}" if fractional else f"{sign}{integer}"


def _dedup(values: Iterable[str]) -> list[str]:
    seen: set[str] = set()
    output: list[str] = []
    for value in values:
        if value not in seen:
            seen.add(value)
            output.append(value)
    return output


def _decimate(values: Sequence[str], maximum: int) -> tuple[str, ...]:
    if len(values) <= maximum:
        return tuple(values)
    indices = {round(index * (len(values) - 1) / (maximum - 1)) for index in range(maximum)}
    return tuple(values[index] for index in sorted(indices))


def _series_colours(family: RendererFamily) -> tuple[str, ...]:
    colours = tuple(
        family.palette[key] for key in sorted(family.palette) if key.startswith("series_")
    )
    if colours:
        return colours
    return (family.palette.get("mark", "#1f77b4"),)


def _pillow_version() -> str:
    import PIL

    return str(PIL.__version__)


_PLOT_TRAIN_FAMILY = RendererFamily(
    name="plot_train_v1",
    kind="plot",
    font_name="DejaVu Sans",
    palette={
        "background": "#FFFFFF",
        "text": "#202020",
        "axis": "#444444",
        "grid": "#D9DEE8",
        "redact": "#151515",
        "mark": "#2563EB",
        "series_0": "#2563EB",
        "series_1": "#EA580C",
        "series_2": "#16A34A",
        "series_3": "#DC2626",
        "series_4": "#7C3AED",
        "series_5": "#A16207",
    },
    layout={"engine": "pillow_v3_exact_labels", "y_ticks": _Y_TICKS},
)
_PLOT_HELDOUT_FAMILY = RendererFamily(
    name="plot_heldout_v1",
    kind="plot",
    font_name="DejaVu Serif",
    palette={
        "background": "#F7F7F0",
        "text": "#17212B",
        "axis": "#38434F",
        "grid": "#D5D2C8",
        "redact": "#303030",
        "mark": "#0F766E",
        "series_0": "#0F766E",
        "series_1": "#BE123C",
        "series_2": "#B7791F",
        "series_3": "#4338CA",
        "series_4": "#A21CAF",
        "series_5": "#475569",
    },
    layout={"engine": "pillow_v3_exact_labels_heldout", "y_ticks": _Y_TICKS},
)

PLOT_FAMILIES: dict[str, RendererFamily] = {
    "plot_train_v1": _PLOT_TRAIN_FAMILY,
    "plot_heldout_v1": _PLOT_HELDOUT_FAMILY,
}


__all__ = ["PLOT_FAMILIES", "PlotRenderer"]