File size: 36,151 Bytes
dec006b
 
 
 
103a492
 
dec006b
103a492
dec006b
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
103a492
 
 
 
 
 
 
dec006b
 
 
103a492
dec006b
103a492
 
 
 
 
 
 
 
 
 
 
 
 
dec006b
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
103a492
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
dec006b
103a492
 
 
dec006b
 
 
 
 
 
 
103a492
 
 
 
 
 
 
dec006b
 
 
 
 
 
 
 
 
 
 
 
103a492
 
dec006b
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
103a492
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
07a68d0
103a492
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
"""Chart and Catalog App rules for the writer, without reading records."""
from __future__ import annotations

import copy
from functools import lru_cache
import json
import math
from pathlib import Path
import re


# Mirror viz/chartData.ts, not sheet/ChartDialog.tsx.
CHART_KINDS = ("bar", "line", "area", "donut", "kpi", "table")
CHART_AGGS = ("sum", "avg", "count", "min", "max")
CHART_PALETTES = ("brand", "categorical", "sequential", "diverging")
CHART_FORMATS = ("auto", "number", "currency", "percent", "compact")
MAX_CHARTS = 12
MAX_TITLE = 60
MAX_DONUT_OPTIONS = 6
_CHART_KEYS = {"id", "kind", "agg", "x", "y", "title", "splitBy", "stacked",
               "palette", "axis", "size", "bucket", "span", "compare"}
_WORDS = re.compile(r"[^\W\d_]+", re.UNICODE)
_EMOJI = re.compile(
    "[\U0001f000-\U0001faff\u2600-\u27bf\u2300-\u23ff"
    "\u00a9\u00ae\u203c\u2049\u2122\u2139\u2b05-\u2b07\u2b1b\u2b1c"
    "\u2b50\u2b55\u3030\u303d\u3297\u3299\ufe0f\u20e3]"
)
MUST_RULES = {
    "text_required": "Text rule: give {label} a nonempty text value.",
    "text_length": "Text length rule: shorten {label} to at most 60 characters.",
    "text_caps": "Capital word rule: rewrite {label} without an all-capital word.",
    "text_case": "Sentence case rule: capitalize the first letter of {label} and use lowercase for the remaining letters.",
    "text_emoji": "Emoji rule: remove emoji from {label}.",
    "text_dash": "Dash rule: replace the em or en dash in {label} with plain words or punctuation.",
    "chart_spec": "Chart spec rule: use the charts list in display with supported keys, kinds and aggregates and unique nonempty card ids.",
    "card_limit": "Card count rule: keep at most 12 cards on the page.",
    "kpi_first": "Card order rule: move every kpi card before the other cards.",
    "palette": "Palette rule: choose brand, categorical, sequential or diverging instead of a literal colour.",
    "bound_number": "Bound number rule: remove literal card values and bind x, y and splitBy to readable fields in every compatible database.",
    "currency": "Currency rule: use auto or currency for a currency field's axis format.",
    "donut_options": "Donut option rule: use a bar chart or bind a select field with at most 6 declared options.",
    "axis": "Axis rule: use only x and y, labels of at most 40 characters and a named format.",
    "size": "Card size rule: use a width from 1 to 12 and a height from 120 to 800.",
    "series": "Series rule: use splitBy distinct from x and stack only a bar or area with splitBy.",
    "period": "Period rule: bind y to a metric field and use a bar, line or area with a supported bucket and span.",
    "compare": "Comparison rule: use prior_year beside a period or on a sum of metric kpi card.",
}
SHOULD_RULES = {
    "time_chart": "Time chart rule: use a line or area chart for a time field.",
    "donut_free": "Donut category rule: use a bar chart for a free field.",
}
CATALOG_RULES = {
    "catalog_spec": "Catalog spec rule: use a list of Catalog records with brand objects in catalogs.",
    "catalog_hex": "Catalog colour rule: set {label} to a hex colour with 3 or 6 digits, such as #234.",
    "catalog_contrast": "Catalog contrast rule: {label} has contrast {ratio:.6f}:1 against white. Darken this colour to reach at least 4.5:1.",
    "catalog_page": "Catalog page rule: {label} must be an object with an id, kind, template and bindings. Use only declared page fields.",
    "catalog_kind": "Catalog kind rule: choose a valid kind from {valid}. Legacy intro reads as section and gallery reads as grid.",
    "catalog_template": "Catalog template rule: choose a valid template for {kind} from {valid}.",
    "catalog_bindings": "Catalog binding rule: {label} must use optional title and body text and products as a list of source key strings. Use no expression or code fields.",
    "catalog_text": "Catalog text rule: {label} must be plain text of at most {limit} characters, with no long dashes or control characters.",
    "catalog_design": "Catalog design rule: {label} must use only {keys}. Choose a declared layout, alignment, image fit and font family, and 1 to 4 columns.",
    "catalog_pair_contrast": "Catalog contrast rule: {label}.color against {label}.background has contrast {ratio:.6f}:1. Change color or background to reach at least 4.5:1.",
}
_HEX_COLOUR = re.compile(r"#[0-9a-fA-F]{3}(?:[0-9a-fA-F]{3})?")
CATALOG_MIN_CONTRAST = 4.5
# Legacy pages paint brand ink on white. Template pages use their effective design.
CATALOG_TEXT_GROUND = "#fff"
CATALOG_KINDS = ("cover", "toc", "product", "grid", "section", "closing")
CATALOG_KIND_ALIASES = {"intro": "section", "gallery": "grid"}
_CATALOG_DESIGN_CHOICES = {
    "layout": ("stacked", "split", "centered"),
    "align": ("left", "center", "right"),
    "imageFit": ("contain", "cover"),
    "fontFamily": ("serif", "sans"),
}
_CATALOG_DESIGN_KEYS = {"background", "color", "accent", "columns", *_CATALOG_DESIGN_CHOICES}
_CATALOG_PAGE_KEYS = {"id", "kind", "template", "bindings", "design"}
_CATALOG_CONTENT_KEYS = {"title", "body", "products"}
_CATALOG_LEGACY_KEYS = {"title", "body", "products", "codes", "imageCode", "layout"}
_CATALOG_CODE_KEYS = {"expr", "expression", "formula", "signal", "fn", "code", "script", "html", "css"}


class RuleError(ValueError):
    """A must rule refused the proposed App before a write."""
    code = "app_rule"

    def __init__(self, rule, **values):
        self.rule = rule
        message = (CATALOG_RULES if rule in CATALOG_RULES else MUST_RULES)[rule]
        super().__init__(message.format(**values))


def _fail(rule, **values):
    raise RuleError(rule, **values)


def _relative_luminance(colour):
    digits = colour[1:]
    if len(digits) == 3:
        digits = "".join(channel * 2 for channel in digits)
    channels = [int(digits[offset:offset + 2], 16) / 255 for offset in (0, 2, 4)]
    linear = [channel / 12.92 if channel <= 0.04045
              else ((channel + 0.055) / 1.055) ** 2.4 for channel in channels]
    return sum(channel * weight for channel, weight in zip(linear, (0.2126, 0.7152, 0.0722)))


@lru_cache(maxsize=1)
def _catalog_templates():
    # Root-level platform JSON is in the deploy set; platform/model JSON is not.
    path = Path(__file__).resolve().parents[2] / "platform" / "catalog_templates.json"
    if not path.is_file():
        # The Space serves api/ beside platform/, where core is a namespace package (no __file__).
        import core
        path = Path(next(iter(core.__path__))).resolve().parent / "catalog_templates.json"
    with path.open(encoding="utf-8") as handle:
        return json.load(handle)


def catalog_templates():
    """Return the shared data library without exposing the cached object to callers."""
    return copy.deepcopy(_catalog_templates())


def catalog_page_template(page):
    """Resolve legacy kind aliases and the same default template as catalog_store."""
    if not isinstance(page, dict):
        _fail("catalog_page", label="Each page")
    kind = page.get("kind")
    if not isinstance(kind, str):
        _fail("catalog_kind", valid=", ".join(CATALOG_KINDS))
    kind = CATALOG_KIND_ALIASES.get(kind, kind)
    kinds = {row["kind"]: row["templates"] for row in _catalog_templates()["kinds"]}
    if kind not in kinds:
        _fail("catalog_kind", valid=", ".join(kinds))
    templates = {row["id"]: row for row in kinds[kind]}
    template = page.get("template", kind + "-stacked")
    if not isinstance(template, str) or template not in templates:
        _fail("catalog_template", kind=kind, valid=", ".join(templates))
    return copy.deepcopy(templates[template])


def _catalog_text(value, label, limit, *, required=False):
    if (not isinstance(value, str) or len(value) > limit
            or required and not value.strip()
            or isinstance(value, str) and ("\u2013" in value or "\u2014" in value
                or any(ord(char) < 32 and char not in "\n\r\t" for char in value))):
        _fail("catalog_text", label=label, limit=limit)


def _catalog_design(design, label):
    keys = ", ".join(sorted(_CATALOG_DESIGN_KEYS))
    if not isinstance(design, dict) or set(design) - _CATALOG_DESIGN_KEYS:
        _fail("catalog_design", label=label, keys=keys)
    for key in ("background", "color", "accent"):
        if key in design and (not isinstance(design[key], str) or not _HEX_COLOUR.fullmatch(design[key])):
            _fail("catalog_hex", label=label + "." + key)
    for key, choices in _CATALOG_DESIGN_CHOICES.items():
        if key in design and design[key] not in choices:
            _fail("catalog_design", label=label + "." + key, keys=keys)
    if "columns" in design and (type(design["columns"]) is not int or not 1 <= design["columns"] <= 4):
        _fail("catalog_design", label=label + ".columns", keys=keys)


def catalog_page_design(page, *, label="Page design"):
    """Return validated template defaults with page overrides and measured text contrast."""
    template = catalog_page_template(page)
    overrides = page.get("design", {})
    _catalog_design(overrides, label)
    design = {**template["design"], **overrides}
    _catalog_design(design, label)
    ink, ground = (_relative_luminance(design[key]) for key in ("color", "background"))
    ratio = (max(ink, ground) + 0.05) / (min(ink, ground) + 0.05)
    # Accent is decorative in the shared renderer, so only color is text ink.
    if ratio < CATALOG_MIN_CONTRAST:
        _fail("catalog_pair_contrast", label=label, ratio=ratio)
    return design


def _validate_catalog_page(page, label):
    catalog_page_template(page)
    _catalog_text(page.get("id"), label + ".id", 256, required=True)
    bindings = page.get("bindings", {})
    if not isinstance(bindings, dict):
        _fail("catalog_bindings", label=label + ".bindings")
    legacy = bindings.get("legacy", {})
    if not isinstance(legacy, dict):
        _fail("catalog_bindings", label=label + ".bindings.legacy")
    # T03 archives authored data and mirrors its fields. The carrier is never executable.
    for mapping, allowed in ((page, _CATALOG_PAGE_KEYS | _CATALOG_LEGACY_KEYS),
                             (bindings, _CATALOG_CONTENT_KEYS | _CATALOG_LEGACY_KEYS | {"legacy"})):
        if any(key in _CATALOG_CODE_KEYS or key not in allowed and (key not in legacy or value != legacy[key])
               for key, value in mapping.items()):
            _fail("catalog_bindings", label=label)
    for content in (page, bindings):
        for key, limit in (("title", 120), ("body", 2000), ("imageCode", 256)):
            if key in content:
                _catalog_text(content[key], label + "." + key, limit)
        for key in ("products", "codes"):
            if key in content:
                products = content[key]
                if not isinstance(products, list):
                    _fail("catalog_bindings", label=label + "." + key)
                for code in products:
                    _catalog_text(code, label + "." + key, 256, required=True)
        if "layout" in content:
            layout = content["layout"]
            if (not isinstance(layout, dict) or set(layout) - {"cols", "showPack", "showColor", "showPrice"}
                    or "cols" in layout and (type(layout["cols"]) is not int or not 1 <= layout["cols"] <= 4)
                    or any(key in layout and type(layout[key]) is not bool
                           for key in ("showPack", "showColor", "showPrice"))):
                _fail("catalog_bindings", label=label + ".layout")
    catalog_page_design(page, label=label + ".design")


def validate_catalog_display(display):
    """Validate catalog pages on every writer while keeping legacy reads lossless."""
    if not isinstance(display, dict):
        _fail("catalog_spec")
    catalogs = display.get("catalogs", [])
    if not isinstance(catalogs, list):
        _fail("catalog_spec")
    ground = _relative_luminance(CATALOG_TEXT_GROUND)
    for index, catalog in enumerate(catalogs):
        if not isinstance(catalog, dict):
            _fail("catalog_spec")
        pages = catalog.get("pages", [])
        if not isinstance(pages, list):
            _fail("catalog_page", label=f"Catalog {index + 1} pages")
        for page_index, page in enumerate(pages):
            _validate_catalog_page(page, f"Catalog {index + 1} page {page_index + 1}")
        legacy_ink = not pages or any(not any(key in page for key in ("template", "bindings", "design"))
                                     for page in pages)
        if "brand" not in catalog:
            continue
        brand = catalog["brand"]
        if not isinstance(brand, dict):
            _fail("catalog_spec")
        for role in ("primary", "accent"):
            if role not in brand:
                continue
            colour = brand[role]
            label = f"Catalog {index + 1} brand.{role}"
            if not isinstance(colour, str) or not _HEX_COLOUR.fullmatch(colour):
                _fail("catalog_hex", label=label)
            if not legacy_ink:
                continue
            luminance = _relative_luminance(colour)
            ratio = (max(luminance, ground) + 0.05) / (min(luminance, ground) + 0.05)
            if ratio < CATALOG_MIN_CONTRAST:
                _fail("catalog_contrast", label=label, ratio=ratio)


def chart_rule_guide():
    """Return the writer's vocabulary, limits, must rules and advice as guide data."""
    return copy.deepcopy({
        "kinds": CHART_KINDS, "aggregates": CHART_AGGS, "palettes": CHART_PALETTES,
        "formats": CHART_FORMATS, "maxCards": MAX_CHARTS, "maxTitle": MAX_TITLE,
        "maxDonutOptions": MAX_DONUT_OPTIONS, "must": MUST_RULES, "should": SHOULD_RULES,
        "cards": "config.display.charts", "series": "splitBy",
        "rowCount": "Omit y to count database rows.",
    })


def validate_text(value, label):
    """Check authored names and titles before the browser can truncate them."""
    if not isinstance(value, str) or not value.strip():
        _fail("text_required", label=label)
    if len(value) > MAX_TITLE:
        _fail("text_length", label=label)
    if _EMOJI.search(value):
        _fail("text_emoji", label=label)
    if "\u2013" in value or "\u2014" in value:
        _fail("text_dash", label=label)
    words = _WORDS.findall(value)
    if any(len(word) > 1 and word.isupper() for word in words):
        _fail("text_caps", label=label)
    letters = [letter for letter in value if letter.lower() != letter.upper()]
    if letters and (not letters[0].isupper() or any(not letter.islower() for letter in letters[1:])):
        _fail("text_case", label=label)


def _number(value, low, high):
    return type(value) in (int, float) and low <= value <= high and math.isfinite(value)


def validate_chart_display(display):
    """Validate the exact browser card shape while preserving trusted layouts without cards."""
    if "cards" in display:
        _fail("chart_spec")
    if "title" in display:
        validate_text(display["title"], "the page title")
    if "charts" not in display:
        return
    charts = display["charts"]
    if not isinstance(charts, list):
        _fail("chart_spec")
    if len(charts) > MAX_CHARTS:
        _fail("card_limit")
    non_kpi = False
    ids = set()
    for card in charts:
        if not isinstance(card, dict):
            _fail("chart_spec")
        if set(card) - _CHART_KEYS:
            _fail("bound_number")
        ident, kind, agg = card.get("id"), card.get("kind"), card.get("agg")
        if (not isinstance(ident, str) or not ident.strip() or ident in ids
                or kind not in CHART_KINDS or agg not in CHART_AGGS):
            _fail("chart_spec")
        ids.add(ident)
        if kind == "kpi" and non_kpi:
            _fail("kpi_first")
        non_kpi = non_kpi or kind != "kpi"
        if "title" in card:
            validate_text(card["title"], "the card title")
        for key in ("x", "y", "splitBy"):
            if key in card and (not isinstance(card[key], str) or not card[key].strip()):
                _fail("bound_number")
        if "palette" in card and card["palette"] not in CHART_PALETTES:
            _fail("palette")
        if (card.get("splitBy") and card["splitBy"] == card.get("x")
                or "stacked" in card and type(card["stacked"]) is not bool
                or card.get("stacked") and (not card.get("splitBy") or kind not in ("bar", "area"))):
            _fail("series")
        if "axis" in card:
            axis = card["axis"]
            if not isinstance(axis, dict) or set(axis) - {"x", "y"}:
                _fail("axis")
            for side in axis.values():
                if not isinstance(side, dict) or set(side) - {"label", "format"}:
                    _fail("axis")
                if "label" in side and (not isinstance(side["label"], str) or len(side["label"]) > 40):
                    _fail("axis")
                if "format" in side and side["format"] not in CHART_FORMATS:
                    _fail("axis")
        if "size" in card:
            size = card["size"]
            if not isinstance(size, dict) or set(size) - {"w", "h"}:
                _fail("size")
            if ("w" in size and not _number(size["w"], 1, 12)
                    or "h" in size and not _number(size["h"], 120, 800)):
                _fail("size")
        metric = str(card.get("y") or "").startswith("measure_")
        if "bucket" in card:
            if not metric or kind not in ("bar", "line", "area") or card["bucket"] not in (
                    "week", "month", "quarter", "year"):
                _fail("period")
        if "span" in card:
            span = card["span"]
            if (not card.get("bucket") or not isinstance(span, dict) or set(span) != {"lastN"}
                    or type(span["lastN"]) is not int or not 1 <= span["lastN"] <= 120):
                _fail("period")
        if "compare" in card and (card["compare"] != "prior_year" or not (
                card.get("bucket") or kind == "kpi" and agg == "sum" and metric)):
            _fail("compare")


def validate_chart_bindings(display, fields_by_database):
    """Check fields and declared select options, then return advice without reading values."""
    advice = []
    for card in display.get("charts", []):
        refs = {key: card[key] for key in ("x", "y", "splitBy") if key in card}
        if not fields_by_database:
            _fail("bound_number")
        for fields in fields_by_database.values():
            if any(field not in fields for field in refs.values()):
                _fail("bound_number")
            for side in ("x", "y"):
                field = fields.get(refs.get(side), {})
                field_type = field.get("type") or field.get("dataType")
                fmt = ((card.get("axis") or {}).get(side) or {}).get("format", "auto")
                if field_type == "currency" and fmt not in ("auto", "currency"):
                    _fail("currency")
            category = fields.get(card.get("x"), {})
            field_type = category.get("type") or category.get("dataType")
            if field_type in ("date", "datetime", "created_time", "modified_time") and card["kind"] not in ("line", "area"):
                advice.append(SHOULD_RULES["time_chart"])
            if card["kind"] == "donut" and category:
                if field_type in ("select", "selection", "single_select", "multi_select"):
                    options = category.get("options", category.get("choices"))
                    if not isinstance(options, (list, tuple)):
                        _fail("donut_options")
                    if len(options) > MAX_DONUT_OPTIONS:
                        _fail("donut_options")
                else:
                    advice.append(SHOULD_RULES["donut_free"])
    return list(dict.fromkeys(advice))


def _catalog_selftest():
    """Exercise C2 and actual catalog writers with an offline tenant and no network."""
    from contextlib import ExitStack
    import os
    import socket
    import sys
    import threading
    from types import SimpleNamespace
    from unittest.mock import patch

    root = Path(__file__).resolve().parents[2]
    sys.dont_write_bytecode = True
    sys.path[:0] = [str(root / "aios-web" / "api"), str(root / "platform")]
    sys.modules.setdefault("app_rules", sys.modules[__name__])
    os.environ.update(HF_TOKEN="", DATABASE_URL="", STORE_BACKEND="hf", AIOS_PREWARM="0",
                      AIOS_AUTOMATIONS="0", AIOS_SESSION_SECRET="s76-t04-offline-fixture")
    passed = []

    def check(label, value):
        assert value, label
        passed.append(label)
        print("PASS " + label)

    with ExitStack() as stack:
        stack.enter_context(patch.object(socket.socket, "connect", side_effect=AssertionError("Network forbidden")))
        with patch.object(threading.Thread, "start", side_effect=AssertionError("Background workers forbidden")):
            import application_registry as registry
            import catalog_store
            import deps
            import routes_catalogs
            from _fake_store import FakeStore, installed
            from core import odoo, perm_scope, users
            from fastapi import FastAPI
            from fastapi.testclient import TestClient
            from harness.runtime import TenantRuntime
        fake = FakeStore()
        stack.enter_context(installed(fake))
        stack.enter_context(patch.object(odoo, "get_odoo", side_effect=AssertionError("Odoo forbidden")))
        tenant = "s76-t04-offline"
        rt = TenantRuntime(tenant, SimpleNamespace(key=tenant, config={"modules": "all"}),
                           store_namespace="t/" + tenant + "/", store_handle=fake)
        user = {"username": "member", "tenant": tenant, "role": "user", "active": True,
                "bus": "all", "modules": "all", "perms_v": perm_scope.PERMS_VERSION,
                "perms": {"product_data": {"access": True}, "ai_apps": {"access": True}}}
        accounts = {"member": user, "other": {**copy.deepcopy(user), "username": "other"}}
        stack.enter_context(patch.object(users, "registry", return_value=accounts))
        session = deps.Session(tenant, copy.deepcopy(user), {}, rt)
        photo = {"key": "catalog_photo", "label": "Catalog photo", "type": "image",
                 "source": "overlay", "shared": True, "createdBy": "member"}
        rt.put("product_table_workspace__shared", {"fields": {photo["key"]: photo},
                                                 "cells": {"SKU-1": {"catalog_photo": "rec:fixture"}}})
        source = rt.get("product_table_workspace__shared")
        contracts = registry.chart_field_contracts(session, ["product_data"])
        app = registry.create(rt, tenant, "member", {
            "name": "Template fixture", "templateKind": "catalog",
            "navPlacement": {"section": "app", "order": 0}},
            allowed_databases={"product_data"}, field_contracts=contracts)
        api = FastAPI()
        api.include_router(routes_catalogs.router)
        client = stack.enter_context(TestClient(api))
        before = fake.snapshot()
        response = client.get("/api/v1/catalogs/templates")
        check("templates require authentication without reading a tenant", response.status_code == 401
              and fake.snapshot() == before)
        person = [session]
        api.dependency_overrides[deps.require_session] = lambda: person[0]

        def request(method, path, payload=None, status=200):
            kwargs = {"json": payload} if payload is not None else {}
            response = client.request(method, "/api/v1/" + path, **kwargs)
            assert response.status_code == status, (method, path, response.status_code, response.text)
            return response.json()

        library = "apps/" + app["id"] + "/catalogs"
        wire = request("GET", "catalogs/templates")
        check("GET serves the JSON library unchanged", wire == catalog_templates())
        check("C2 serves all six kinds in contract order", [row["kind"] for row in wire["kinds"]] == list(CATALOG_KINDS))
        pages = []
        for row in wire["kinds"]:
            kind, templates = row["kind"], row["templates"]
            check(kind + " has 3 to 5 unique templates and its stable default",
                  3 <= len(templates) <= 5 and len({item["id"] for item in templates}) == len(templates)
                  and kind + "-stacked" in {item["id"] for item in templates})
            check(kind + " variants have distinct complete design defaults",
                  len({json.dumps(item["design"], sort_keys=True) for item in templates}) == len(templates)
                  and all(set(item["design"]) == _CATALOG_DESIGN_KEYS for item in templates))
            for template in templates:
                check(template["id"] + " declares a label and string slots", isinstance(template["label"], str)
                      and bool(template["label"]) and isinstance(template["slots"], list)
                      and bool(template["slots"]) and all(slot in _CATALOG_CONTENT_KEYS for slot in template["slots"]))
                pages.append({"id": template["id"], "kind": kind, "template": template["id"],
                              "bindings": {"title": "Collection", "body": "Authored copy", "products": ["SKU-1"]}})
        check("library copy cannot change subsequent responses", wire is not _catalog_templates())
        wire["kinds"][0]["templates"][0]["design"]["color"] = "#fff"
        check("nested library copies protect cached defaults", request("GET", "catalogs/templates") == catalog_templates())
        saved = request("POST", library, {"name": "All variants", "pages": pages}, 201)["catalog"]
        check("actual store create accepts every template", saved["pages"] == pages)
        check("actual store read retains every template", request("GET", "catalogs/" + saved["id"])["catalog"] == saved)
        copied = request("POST", "catalogs/" + saved["id"] + "/duplicate", status=201)["catalog"]
        check("actual duplicate retains each design and binding", copied["pages"] == pages and copied["id"] != saved["id"])
        defaults = [{"id": kind, "kind": kind, "bindings": {}} for kind in CATALOG_KINDS]
        normalized = request("POST", library, {"pages": defaults}, 201)["catalog"]
        check("T03 normalization selects the six published defaults", all(page["template"] == page["kind"] + "-stacked"
              for page in normalized["pages"]))
        base = {"id": "custom", "kind": "section", "template": "section-stacked", "bindings": {}}
        for design in ({"background": "#000", "color": "#fff", "accent": "#fff"},
                       {"background": "#fff", "color": "#767676", "accent": "#fff"},
                       {"background": "#fff", "color": "#000", "columns": 4, "fontFamily": "sans"}):
            page = {**copy.deepcopy(base), "design": design}
            validate_catalog_display({"catalogs": [{"pages": [page]}]})
            changed = request("PATCH", "catalogs/" + normalized["id"], {"pages": [page]})["catalog"]
            check("agent design passes direct validation and actual PATCH " + json.dumps(design, sort_keys=True),
                  changed["pages"] == [page])
        dark = {**base, "template": "section-centered", "design": {"accent": "#fff"}}
        check("effective design inherits the template ground and ink", catalog_page_design(dark)["background"] == "#1f4e78"
              and catalog_page_design(dark)["color"] == "#ffffff")
        branded = request("POST", library, {"pages": [dark], "brand": {"primary": "#fff", "accent": "#c8a24b"}}, 201)["catalog"]
        check("template contrast uses effective design instead of unused legacy inks", branded["pages"] == [dark])
        before = fake.snapshot()
        error = request("POST", library, {"pages": [], "brand": {"primary": "#fff"}}, 400)["detail"]["error"]
        check("legacy brand inks retain the white ground rule", error["details"]["rule"] == "catalog_contrast"
              and before == fake.snapshot())
        bad_pages = [
            ("unknown kind", {**base, "kind": "unknown"}, list(CATALOG_KINDS)),
            ("unknown template", {**base, "template": "unknown"}, ["section-stacked", "section-split", "section-centered"]),
            ("template belongs to another kind", {**base, "template": "grid-stacked"}, ["section-stacked"]),
            ("bindings must be an object", {**base, "bindings": []}, []),
            ("product bindings must be a list", {**base, "bindings": {"products": "SKU-1"}}, []),
            ("product keys must be strings", {**base, "bindings": {"products": [1]}}, []),
            ("product keys must be nonempty", {**base, "bindings": {"products": [""]}}, []),
            ("title must be text", {**base, "bindings": {"title": 1}}, []),
            ("title is bounded", {**base, "bindings": {"title": "x" * 121}}, []),
            ("body is bounded", {**base, "bindings": {"body": "x" * 2001}}, []),
            ("product keys are bounded", {**base, "bindings": {"products": ["x" * 257]}}, []),
            ("long dashes are refused", {**base, "bindings": {"body": "Bad" + chr(0x2014) + "copy"}}, []),
            ("control characters are refused", {**base, "bindings": {"body": "Bad\x00copy"}}, []),
            ("binding expressions are refused", {**base, "bindings": {"expr": "1+1"}}, []),
            ("carrier cannot enable expressions", {**base, "bindings": {"expr": "1+1", "legacy": {"expr": "1+1"}}}, []),
            ("page scripts are refused", {**base, "script": "alert(1)"}, []),
            ("legacy layout code is refused", {**base, "bindings": {"layout": {"expr": "1+1"}}}, []),
            ("design is an object", {**base, "design": None}, []),
            ("design expressions are refused", {**base, "design": {"formula": "1+1"}}, []),
            ("layout is an enum", {**base, "design": {"layout": "absolute"}}, []),
            ("alignment is an enum", {**base, "design": {"align": []}}, []),
            ("font is an enum", {**base, "design": {"fontFamily": "url(remote)"}}, []),
            ("image fit is an enum", {**base, "design": {"imageFit": "stretch"}}, []),
            ("columns cannot be zero", {**base, "design": {"columns": 0}}, []),
            ("columns cannot exceed four", {**base, "design": {"columns": 5}}, []),
            ("columns cannot be boolean", {**base, "design": {"columns": True}}, []),
            ("columns cannot be fractional", {**base, "design": {"columns": 1.5}}, []),
            ("colour must be hex", {**base, "design": {"color": "red"}}, []),
            ("transparent ground is refused", {**base, "design": {"background": "#0000"}}, []),
            ("accent must be hex", {**base, "design": {"accent": []}}, []),
            ("contrast below 4.5 is refused", {**base, "design": {"color": "#777", "background": "#fff"}},
             ["design.color", "design.background", "4.478089:1", "4.5:1"]),
            ("inherited ink uses overridden ground", {**dark, "design": {"background": "#fff"}},
             ["design.color", "design.background", "1.000000:1"]),
            ("inherited ground uses overridden ink", {**dark, "design": {"color": "#1f4e78"}},
             ["design.color", "design.background", "1.000000:1"]),
        ]
        for label, bad, fragments in bad_pages:
            before = fake.snapshot()
            for method, path in (("POST", library), ("PATCH", "catalogs/" + saved["id"])):
                refused = request(method, path, {"pages": [bad]}, 400)["detail"]["error"]
                assert all(fragment in refused["message"] for fragment in fragments), (label, refused)
                assert fake.snapshot() == before, (label, "mutated storage")
            check(label + " on create and PATCH without mutation", True)
        for payload in ({"pages": {}}, {"pages": [None]}, {"pages": [1]}, {"pages": [base, base]}):
            before = fake.snapshot()
            request("POST", library, payload, 400)
            check("malformed page collection refused without mutation " + json.dumps(payload), before == fake.snapshot())
        before = fake.snapshot()
        person[0] = deps.Session(tenant, accounts["other"], {}, rt)
        request("POST", library, {"pages": [base]}, 403)
        check("non-owner cannot write catalogs", before == fake.snapshot())
        person[0] = deps.Session("another-workspace", copy.deepcopy(user), {}, rt)
        request("POST", library, {"pages": [base]}, 403)
        check("mismatched workspace cannot write catalogs", before == fake.snapshot())
        person[0] = session
        original = copy.deepcopy(catalog_store._load(rt))

        def corrupt(doc):
            doc["catalogs"][saved["id"]]["pages"][0]["design"] = {"color": "#fff", "background": "#fff"}
            return doc

        rt.update(catalog_store.STORE_KEY, corrupt)
        before = fake.snapshot()
        error = request("POST", "catalogs/" + saved["id"] + "/duplicate", status=400)["detail"]["error"]
        check("duplicate validates retained designs before saving", "design.color" in error["message"]
              and "design.background" in error["message"] and before == fake.snapshot())
        rt.put(catalog_store.STORE_KEY, original)
        legacy_pages = [{"id": "intro-old", "kind": "intro", "title": "Welcome", "body": "Authored text",
                         "codes": ["SKU-1"], "order": 7, "metadata": {"author": "original"}},
                        {"id": "gallery-old", "kind": "gallery", "imageCode": "SKU-1",
                         "products": ["SKU-1"], "layout": {"cols": 3, "showPrice": True}}]
        legacy_app = copy.deepcopy(app)
        legacy_app["id"] = "fixture-legacy-app"
        legacy_app["config"]["display"]["catalogs"] = [{"id": "legacy-fixture", "name": "Authored catalog", "pages": legacy_pages}]

        def attach(doc):
            doc["applications"][legacy_app["id"]] = legacy_app
            return doc

        registry._update_document(rt, attach)
        migrated = request("GET", "apps/" + legacy_app["id"] + "/catalogs")["catalogs"][0]
        check("legacy aliases agree with T03 and preserve archived authorship", [page["kind"] for page in migrated["pages"]]
              == ["section", "grid"] and all(page["bindings"]["legacy"] == raw for page, raw in zip(migrated["pages"], legacy_pages)))
        edited = request("PATCH", "catalogs/legacy-fixture", {"name": "Authored catalog renamed"})["catalog"]
        check("valid migration carriers survive actual edits", edited["pages"] == migrated["pages"])
        before = fake.snapshot()
        catalog_store.migrate_legacy(rt, legacy_app)
        check("template validation keeps repeated migration unchanged", before == fake.snapshot())
        aliases = [{"id": "a", "kind": "intro", "bindings": {}}, {"id": "b", "kind": "gallery", "bindings": {}}]
        created = request("POST", library, {"pages": aliases}, 201)["catalog"]
        check("write aliases normalize to stable C2 templates", [(page["kind"], page["template"]) for page in created["pages"]]
              == [("section", "section-stacked"), ("grid", "grid-stacked")])
        for malformed in (None, [], {"catalogs": None}, {"catalogs": [None]}):
            try:
                validate_catalog_display(malformed)
            except RuleError:
                check("direct validator refuses malformed display " + repr(malformed), True)
            else:
                raise AssertionError("Malformed display passed")
        check("source rows remain unchanged", rt.get("product_table_workspace__shared") == source)
        check("public library has no long dashes", not re.search("[" + chr(0x2013) + chr(0x2014) + "]", json.dumps(catalog_templates(), ensure_ascii=False)))
        print(json.dumps({"kinds": len(CATALOG_KINDS), "templates": len(pages),
                          "checks": len(passed), "failed": 0, "tenant": "offline fake store"}, sort_keys=True))


if __name__ == "__main__":
    import sys
    if sys.argv[1:] != ["--catalog-selftest"]:
        raise SystemExit("Usage: python app_rules.py --catalog-selftest")
    _catalog_selftest()