plushie 0.7.1

Desktop GUI framework for Rust
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
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
1205
1206
1207
1208
1209
1210
1211
1212
1213
1214
1215
1216
1217
1218
1219
1220
1221
1222
1223
1224
1225
1226
1227
1228
1229
1230
1231
1232
1233
1234
1235
1236
1237
1238
1239
1240
1241
1242
1243
1244
1245
1246
1247
1248
1249
1250
1251
1252
1253
1254
1255
1256
1257
1258
1259
1260
1261
1262
1263
1264
1265
1266
1267
1268
1269
1270
1271
1272
1273
1274
1275
1276
1277
1278
1279
1280
1281
1282
1283
1284
1285
1286
1287
1288
1289
1290
1291
1292
1293
1294
1295
1296
1297
1298
1299
1300
1301
1302
1303
1304
1305
1306
1307
1308
1309
1310
1311
1312
1313
1314
1315
1316
1317
1318
1319
1320
1321
1322
1323
1324
1325
1326
1327
1328
1329
1330
1331
1332
1333
1334
1335
1336
1337
1338
1339
1340
1341
1342
1343
1344
1345
1346
1347
1348
1349
1350
1351
1352
1353
1354
1355
1356
1357
1358
1359
1360
1361
1362
1363
1364
1365
1366
1367
1368
1369
1370
1371
1372
1373
1374
1375
1376
1377
1378
1379
1380
1381
1382
1383
1384
1385
1386
1387
1388
1389
1390
1391
1392
1393
1394
1395
1396
1397
1398
1399
1400
1401
1402
1403
1404
1405
1406
1407
1408
1409
1410
1411
1412
1413
1414
1415
1416
1417
1418
1419
1420
1421
1422
1423
1424
1425
1426
1427
1428
1429
1430
1431
1432
1433
1434
1435
1436
1437
1438
1439
1440
1441
1442
1443
1444
1445
1446
1447
1448
1449
1450
1451
1452
1453
1454
1455
1456
1457
1458
1459
1460
1461
1462
1463
1464
1465
1466
1467
1468
1469
1470
1471
1472
1473
1474
1475
1476
1477
1478
1479
1480
1481
1482
1483
1484
1485
1486
1487
1488
1489
1490
1491
1492
1493
1494
1495
1496
1497
1498
1499
1500
1501
1502
1503
1504
1505
1506
1507
1508
1509
1510
1511
1512
1513
1514
1515
1516
1517
1518
1519
1520
1521
1522
1523
1524
1525
1526
1527
1528
1529
1530
1531
1532
1533
1534
1535
1536
1537
1538
1539
1540
1541
1542
1543
1544
1545
1546
1547
1548
1549
1550
1551
1552
1553
1554
1555
1556
1557
1558
1559
1560
1561
1562
1563
1564
1565
1566
1567
1568
1569
1570
1571
1572
1573
1574
1575
1576
1577
1578
1579
1580
1581
1582
1583
1584
1585
1586
1587
1588
1589
1590
1591
1592
1593
1594
1595
1596
1597
1598
1599
1600
1601
1602
1603
1604
1605
1606
1607
1608
1609
1610
1611
1612
1613
1614
1615
1616
1617
1618
1619
1620
1621
1622
1623
1624
1625
1626
1627
1628
1629
1630
1631
1632
1633
1634
1635
1636
1637
1638
1639
1640
1641
1642
1643
1644
1645
1646
1647
1648
1649
1650
1651
1652
1653
1654
1655
1656
1657
1658
1659
1660
1661
1662
1663
1664
1665
1666
1667
1668
1669
1670
1671
1672
1673
1674
1675
1676
1677
1678
1679
1680
1681
1682
1683
1684
1685
1686
1687
1688
1689
1690
1691
1692
1693
1694
1695
1696
1697
1698
1699
1700
1701
1702
1703
1704
1705
1706
1707
1708
1709
1710
1711
1712
1713
1714
1715
1716
1717
1718
1719
1720
1721
1722
1723
1724
1725
1726
1727
1728
1729
1730
1731
1732
1733
1734
1735
1736
1737
1738
1739
1740
1741
1742
1743
1744
1745
1746
1747
1748
1749
1750
1751
1752
1753
1754
1755
1756
1757
1758
1759
1760
1761
1762
1763
1764
1765
1766
1767
1768
1769
1770
1771
1772
1773
1774
1775
1776
1777
1778
1779
1780
1781
1782
1783
1784
1785
1786
1787
1788
1789
1790
1791
1792
1793
1794
1795
1796
1797
1798
1799
1800
1801
1802
1803
1804
1805
1806
1807
1808
1809
1810
1811
1812
1813
1814
1815
1816
1817
1818
1819
1820
1821
1822
1823
1824
1825
1826
1827
1828
1829
1830
1831
1832
1833
1834
1835
1836
1837
1838
1839
1840
1841
1842
1843
1844
1845
1846
1847
1848
1849
1850
1851
1852
1853
1854
1855
1856
1857
1858
1859
1860
1861
1862
1863
1864
1865
1866
1867
1868
1869
1870
1871
1872
1873
1874
1875
1876
1877
1878
1879
1880
1881
1882
1883
1884
1885
1886
1887
1888
1889
1890
1891
1892
1893
1894
1895
1896
1897
1898
1899
1900
1901
1902
1903
1904
1905
1906
1907
1908
1909
1910
1911
1912
1913
1914
1915
1916
1917
1918
1919
1920
1921
1922
1923
1924
1925
1926
1927
1928
1929
1930
1931
1932
1933
1934
1935
1936
1937
1938
1939
1940
1941
1942
1943
1944
1945
1946
1947
1948
1949
1950
1951
1952
1953
1954
1955
1956
1957
1958
1959
1960
1961
1962
1963
1964
1965
1966
1967
1968
1969
1970
1971
1972
1973
1974
1975
1976
1977
1978
//! Tree normalization: scope prefixing, ID validation, a11y rewrites.
//!
//! After `App::view()` returns a `View`, normalization
//! walks the tree to apply scoped ID prefixes and validate ID
//! constraints. A second pass rewrites cross-widget accessibility
//! references (`labelled_by`, `described_by`, `error_message`,
//! `active_descendant`, `radio_group`) through the same scope-
//! prefix logic, populates implicit radio groups from the shared
//! `group` prop on radios, and exposes the currently selected radio
//! as the group's active descendant.
//!
//! ## Scoping rules
//!
//! Containers with explicit (non-auto) IDs create a scope. Their
//! children's IDs are prefixed with the scope chain joined by `/`.
//! Two node types are exempt:
//!
//! - **Auto IDs** (prefixed `auto:`): generated by the DSL, not
//!   user-chosen. They don't participate in scoping and bypass
//!   duplicate detection (the same call site in a loop produces
//!   identical auto IDs).
//! - **Window nodes** (`type_name == "window"`): top-level layout
//!   containers that don't scope their children.
//!
//! ## ID constraints
//!
//! - `/` is reserved as the scope separator and rejected in
//!   user-provided IDs.
//! - Duplicate explicit IDs within a tree produce a warning.
//!
//! ## Depth cap
//!
//! Recursion is capped at
//! [`plushie_widget_sdk::shared_state::MAX_TREE_DEPTH`]. Beyond the
//! cap the subtree is truncated (the returned node has no children)
//! and a `tree_too_deep` diagnostic is appended. Render and
//! prepare_walk apply the same cap so defence-in-depth holds even
//! if the host sends a pathologically nested tree.
//!
//! ## A11y rewrites
//!
//! Cross-widget references inside the `a11y` prop are scope-rewritten
//! the same way widget IDs are: a reference to `heading` inside a
//! scoped `form` container becomes `main#form/heading`. References
//! that cannot be resolved to any declared ID in the normalized
//! tree produce an `a11y_ref_unresolved` diagnostic.
//!
//! Radio widgets sharing the same `group` prop value are collected
//! into an implicit radio group: each member's `a11y.radio_group` is
//! populated with the scoped IDs of its peers. This mirrors the
//! HTML `<input type="radio" name="x">` model where grouping is by
//! name, not DOM position.
//!
//! `automation::Element::inferred_role` falls back to the widget type
//! for selector matching without writing those roles back into the tree.

use std::collections::{BTreeMap, HashSet};

use plushie_core::diagnostic::Diagnostic;
use plushie_core::protocol::{PropValue, TreeNode};
#[cfg(any(test, feature = "wire"))]
use plushie_core::tree_walk::walk;
use plushie_core::tree_walk::{MAX_TREE_DEPTH, TreeTransform, WalkCtx};

/// Normalize a view tree: apply scope prefixes, validate IDs,
/// rewrite cross-widget a11y references, and populate implicit
/// radio relationships.
///
/// Returns the normalized tree and any validation warnings
/// (duplicate IDs, reserved characters, unresolved a11y refs).
///
/// Thin wrapper around the `NormalizeTransform`: drives it through
/// `walk()` over a clone of the input, then runs the cross-widget
/// a11y passes. Call sites that already own a mutable tree can
/// compose [`NormalizeTransform`] with other transforms through
/// `walk()` directly and then invoke [`finalize_a11y`].
#[cfg(any(test, feature = "wire"))]
pub fn normalize(tree: &TreeNode) -> (TreeNode, Vec<Diagnostic>) {
    let mut result = tree.clone();
    let mut transform = NormalizeTransform::new();
    let mut ctx = WalkCtx::default();

    walk(&mut result, &mut [&mut transform], &mut ctx);
    let (warnings, _ctx) = finalize_a11y(&mut result, ctx);
    (result, warnings)
}

/// Maximum length (in bytes) for a widget ID. Matches the canonical
/// rule the Elixir / Python / Ruby / TypeScript SDKs already enforce.
/// 1024 bytes leaves plenty of room for scope prefixes while keeping
/// diagnostic text manageable.
const MAX_WIDGET_ID_LEN: usize = 1024;

/// Check a user-authored widget ID against the canonical ruleset and
/// push a `widget_id_invalid` diagnostic for each violation.
///
/// Reasons surfaced (each a separate diagnostic so callers can match
/// on the specific failure):
/// - `too_long`: > 1024 bytes
/// - `reserved_char`: contains `/` or `#`
fn validate_widget_id(id: &str, type_name: &str, warnings: &mut Vec<Diagnostic>) {
    // Invariant: auto-generated IDs (prefixed `auto:`) never contain
    // `/` or `#`. `NormalizeTransform::enter` only calls this helper
    // for user-authored IDs; if that ever changes, the reserved-char
    // checks below would fire on every auto ID in the tree.
    //
    // Empty IDs are treated the same as auto-generated ones: they
    // represent "not authored" state and skip the full ruleset. The
    // duplicate-detection and reference-resolution passes downstream
    // treat them as unrecognised anyway.
    if id.is_empty() {
        return;
    }
    if id.len() > MAX_WIDGET_ID_LEN {
        let detail = format!(
            "{type_name} ID is {} bytes, exceeds {} (reason=too_long)",
            id.len(),
            MAX_WIDGET_ID_LEN,
        );
        warnings.push(Diagnostic::WidgetIdInvalid {
            reason: "too_long".to_string(),
            type_name: type_name.to_string(),
            id: id.to_string(),
            detail,
        });
        return;
    }
    if id.contains('/') {
        let detail = format!(
            "ID \"{id}\" contains reserved character '/'. Use container \
             scoping instead. (reason=reserved_char)"
        );
        warnings.push(Diagnostic::WidgetIdInvalid {
            reason: "reserved_char".to_string(),
            type_name: type_name.to_string(),
            id: id.to_string(),
            detail,
        });
    }
    if id.contains('#') {
        let detail = format!(
            "ID \"{id}\" contains reserved character '#'. '#' is reserved \
             for window-qualified paths. (reason=reserved_char)"
        );
        warnings.push(Diagnostic::WidgetIdInvalid {
            reason: "reserved_char".to_string(),
            type_name: type_name.to_string(),
            id: id.to_string(),
            detail,
        });
    }
}

/// Run the a11y-ref rewrite and missing-accessible-name passes over a
/// tree whose IDs are already scope-normalized. Continues accumulating
/// warnings into the supplied [`WalkCtx`].
///
/// Split from `normalize_in_place` so callers that compose
/// normalization with other transforms in a single traversal can still
/// reuse the cross-widget a11y logic, which has to run *after* the
/// full set of declared IDs is known.
pub(crate) fn finalize_a11y(tree: &mut TreeNode, mut ctx: WalkCtx) -> (Vec<Diagnostic>, WalkCtx) {
    let declared_ids = collect_ids(tree);
    let radio_groups = collect_radio_groups(tree);
    rewrite_a11y_in_place(tree, "", &declared_ids, &radio_groups, &mut ctx.warnings, 0);
    check_missing_accessible_name(tree, &mut ctx.warnings);

    let warnings = std::mem::take(&mut ctx.warnings);
    (warnings, ctx)
}

/// First-pass transform: scope-rewrite IDs, detect duplicates and
/// reserved characters, cap recursion depth.
///
/// Uses `WalkCtx::scope` as a stack: `enter` extends it with this
/// node's contribution; `exit` truncates back to the pre-enter length.
/// Normalize-specific state (duplicate-ID set, depth counter) stays
/// inside the transform so `WalkCtx` can remain scope-only.
pub(crate) struct NormalizeTransform<'a> {
    seen_ids: HashSet<String>,
    /// Length to truncate `ctx.scope` to on `exit` for each node on
    /// the stack. Mirrors the recursion frames.
    scope_stack: Vec<usize>,
    /// Per-node truncation flag. Non-empty at a cache hit so `exit`
    /// knows not to store back into the memo cache when the subtree
    /// was served from the cache rather than freshly walked.
    truncate_children: Vec<bool>,
    /// Per-node memo state: if the node was a memo hit we suppress
    /// descent and skip writing back to the cache; if it was a miss
    /// we stash the (scoped_id, deps_hash) so `exit` can store the
    /// freshly-normalized children. `None` for non-memo nodes.
    memo_stack: Vec<Option<MemoFrame>>,
    /// Optional memo cache. `None` disables memoization entirely.
    memo_cache: Option<&'a mut super::memo_cache::MemoCache>,
}

/// Per-memo-node state pushed onto `memo_stack`. On cache hit, the
/// `was_hit` flag keeps `exit` from re-storing the (unchanged)
/// subtree; on miss, `deps_hash` is stored alongside the scoped id
/// so the new normalized children can be cached.
struct MemoFrame {
    scoped_id: String,
    deps_hash: u64,
    was_hit: bool,
}

impl<'a> NormalizeTransform<'a> {
    #[cfg(any(test, feature = "wire"))]
    pub(crate) fn new() -> Self {
        Self::with_memo_cache(None)
    }

    pub(crate) fn with_memo_cache(
        memo_cache: Option<&'a mut super::memo_cache::MemoCache>,
    ) -> Self {
        Self {
            seen_ids: HashSet::new(),
            scope_stack: Vec::new(),
            truncate_children: Vec::new(),
            memo_stack: Vec::new(),
            memo_cache,
        }
    }
}

impl TreeTransform for NormalizeTransform<'_> {
    fn enter(&mut self, node: &mut TreeNode, ctx: &mut WalkCtx) {
        // Depth enforcement lives in `plushie_core::tree_walk::walk`,
        // which halts descent at MAX_TREE_DEPTH and pushes a
        // `tree_depth_exceeded` warning. We still run scope/memo
        // bookkeeping here so `exit` restores state symmetrically.

        // Snapshot where the enclosing scope ended so `exit` can
        // restore `ctx.scope` to exactly this length.
        let prev_scope_len = ctx.scope.len();
        let type_name = &node.type_name;
        let is_auto = node.id.starts_with("auto:");
        let is_window = type_name == "window";

        // ID validation (user IDs only). Auto-generated IDs bypass
        // every check here. Canonical rules (match Elixir / Python /
        // Ruby / TypeScript):
        //
        // - non-empty
        // - no `/` (reserved as scope separator)
        // - no `#` (reserved for window-qualified paths)
        // - length <= 1024 bytes
        if !is_auto {
            validate_widget_id(&node.id, &node.type_name, &mut ctx.warnings);
            // Explicit empty IDs are treated as "not authored" elsewhere
            // but still worth flagging as a structured diagnostic: a
            // widget declared with `.id("")` has no addressable handle
            // for downstream scope references or test selectors.
            //
            // Skip placeholder-internal types (`__widget__`, `__memo__`)
            // and the `__noop__` test harness wrapper: those carry empty
            // IDs by construction while the containing widget is still
            // being configured, and flagging them would produce a false
            // positive before the owning expander fills the slot in.
            if node.id.is_empty()
                && !matches!(
                    node.type_name.as_str(),
                    "__widget__" | "__memo__" | "__noop__"
                )
            {
                ctx.warnings.push(Diagnostic::EmptyId {
                    type_name: node.type_name.clone(),
                });
            }
        }

        // Build the scoped ID directly into `ctx.scope`. The shared
        // buffer is our single scratch allocation for scope paths; we
        // grow it on enter and truncate on exit, so nested levels
        // don't each allocate their own path string.
        //
        // After this block `ctx.scope` equals the child-scope that
        // descendants should see (with the window suffix applied for
        // window nodes).
        let scoped_id = if is_auto || node.id.is_empty() {
            // Auto-IDs and empty IDs never scope-prefix and never
            // contribute to the child-scope path. Leave `ctx.scope`
            // untouched.
            node.id.clone()
        } else if ctx.scope.is_empty() {
            // Top-level node: its ID becomes the root of the scope.
            ctx.scope.push_str(&node.id);
            node.id.clone()
        } else {
            // Nested user-ID: append "/id" unless we're directly under
            // a window boundary ("name#"), in which case the '#' is
            // the separator.
            if !ctx.scope.ends_with('#') {
                ctx.scope.push('/');
            }
            ctx.scope.push_str(&node.id);
            ctx.scope.clone()
        };

        // Duplicate detection (non-auto only). One clone for the
        // HashSet entry.
        if !is_auto && !scoped_id.is_empty() && !self.seen_ids.insert(scoped_id.clone()) {
            ctx.warnings.push(Diagnostic::DuplicateId {
                id: scoped_id.clone(),
                window_id: None,
            });
        }

        // Windows append a trailing '#' so their children slot in
        // after the window-qualified path (e.g. "main#form").
        if is_window {
            ctx.scope.push('#');
        }

        node.id = scoped_id;

        // Memoization: if this is a __memo__ node and the deps hash
        // matches the cached entry for this scoped id, swap in the
        // cached normalized children and skip descent entirely. On a
        // miss, remember enough state to cache the result on exit.
        let memo_frame = self.consult_memo(node);
        let truncate = memo_frame.as_ref().is_some_and(|f| f.was_hit);

        self.scope_stack.push(prev_scope_len);
        self.truncate_children.push(truncate);
        self.memo_stack.push(memo_frame);
    }

    fn exit(&mut self, node: &mut TreeNode, ctx: &mut WalkCtx) {
        // Pop memo frame first so we know whether to cache on the way
        // out; then restore scope.
        if let Some(Some(frame)) = self.memo_stack.pop() {
            self.finish_memo(node, frame);
        }
        if let Some(prev_len) = self.scope_stack.pop() {
            ctx.scope.truncate(prev_len);
        }
        self.truncate_children.pop();
    }

    fn skip_children(&self, _node: &TreeNode, _ctx: &WalkCtx) -> bool {
        self.truncate_children.last().copied().unwrap_or(false)
    }
}

impl NormalizeTransform<'_> {
    /// Pre-descend memo lookup. Mutates `node.children` in place when
    /// a cache hit installs the previously-normalized subtree. The
    /// returned frame tells `exit` whether to cache the freshly-
    /// walked children.
    fn consult_memo(&mut self, node: &mut TreeNode) -> Option<MemoFrame> {
        if node.type_name != "__memo__" {
            return None;
        }
        let cache = self.memo_cache.as_deref_mut()?;
        // Accept both Typed and Wire props: `get_value` normalises to
        // serde_json::Value so the memo marker works regardless of
        // how the caller built the view tree.
        let deps_hash = node
            .props
            .get_value("__memo_deps__")
            .and_then(|v| v.as_u64())?;

        cache.mark_live(&node.id);

        if let Some(cached) = cache.get(&node.id, deps_hash) {
            node.children = cached.to_vec();
            return Some(MemoFrame {
                scoped_id: node.id.clone(),
                deps_hash,
                was_hit: true,
            });
        }

        Some(MemoFrame {
            scoped_id: node.id.clone(),
            deps_hash,
            was_hit: false,
        })
    }

    /// Post-descend memo cache write. On a miss, stash the freshly-
    /// normalized children. On a hit we have nothing to do - the
    /// cached entry is already what's in `node.children`.
    fn finish_memo(&mut self, node: &TreeNode, frame: MemoFrame) {
        if frame.was_hit {
            return;
        }
        if let Some(cache) = self.memo_cache.as_deref_mut() {
            cache.insert(frame.scoped_id, frame.deps_hash, node.children.clone());
        }
    }
}

// ---------------------------------------------------------------------------
// Pass 2: a11y rewrites
// ---------------------------------------------------------------------------

/// Collect every declared scoped ID in the normalized tree.
fn collect_ids(node: &TreeNode) -> HashSet<String> {
    fn walk(node: &TreeNode, out: &mut HashSet<String>) {
        if !node.id.is_empty() && !node.id.starts_with("auto:") {
            out.insert(node.id.clone());
        }
        for child in &node.children {
            walk(child, out);
        }
    }
    let mut ids = HashSet::new();
    walk(node, &mut ids);
    ids
}

/// Key used to collect radios into a shared group: (enclosing scope, group name).
///
/// Scope is the same scope string we use for IDs; it keeps two radio
/// sets with the same `group` name in separate scoped containers from
/// being lumped together. Window qualifiers are baked into the scope
/// string.
type RadioGroupKey = (String, String);

#[derive(Clone, Default)]
struct RadioGroupInfo {
    ids: Vec<String>,
    active_descendant: Option<String>,
}

/// Collect radio widgets sharing the same `group` prop value within
/// the same enclosing scope. Returns a map from `(scope, group_name)`
/// to the ordered scoped IDs and the currently selected radio, when
/// one can be inferred from matching `value` and `selected` props.
fn collect_radio_groups(root: &TreeNode) -> BTreeMap<RadioGroupKey, RadioGroupInfo> {
    fn walk(node: &TreeNode, scope: &str, groups: &mut BTreeMap<RadioGroupKey, RadioGroupInfo>) {
        let next_scope = child_scope_of(node, scope);
        if node.type_name == "radio"
            && let Some(group) = node.props.get_str("group")
        {
            let key = (scope.to_string(), group.to_string());
            let info = groups.entry(key).or_default();
            info.ids.push(node.id.clone());
            if let (Some(value), Some(selected)) =
                (node.props.get_str("value"), node.props.get_str("selected"))
                && value == selected
            {
                info.active_descendant = Some(node.id.clone());
            }
        }
        for child in &node.children {
            walk(child, &next_scope, groups);
        }
    }
    let mut groups = BTreeMap::new();
    walk(root, "", &mut groups);
    groups
}

/// Scope string under which this node's children live after
/// normalization. Mirrors `normalize_node`'s child-scope computation
/// but operates on already-scoped node IDs.
fn child_scope_of(node: &TreeNode, scope: &str) -> String {
    let is_auto = node.id.starts_with("auto:");
    let is_window = node.type_name == "window";
    if is_window {
        format!("{}#", node.id)
    } else if is_auto || node.id.is_empty() {
        scope.to_string()
    } else {
        node.id.clone()
    }
}

/// Walk the normalized tree and rewrite a11y refs + populate defaults
/// in place.
fn rewrite_a11y_in_place(
    node: &mut TreeNode,
    scope: &str,
    declared: &HashSet<String>,
    radio_groups: &BTreeMap<RadioGroupKey, RadioGroupInfo>,
    warnings: &mut Vec<Diagnostic>,
    depth: usize,
) {
    if depth > MAX_TREE_DEPTH {
        return;
    }

    let next_scope = child_scope_of(node, scope);
    node.props = apply_a11y_rewrites(node, scope, declared, radio_groups, warnings);
    for child in &mut node.children {
        rewrite_a11y_in_place(
            child,
            &next_scope,
            declared,
            radio_groups,
            warnings,
            depth + 1,
        );
    }
}

/// Widget types that accept `required` / `validation` props and project
/// them onto the `a11y` sub-object. Mirrors Elixir, Python, Ruby,
/// TypeScript, Gleam.
const VALIDATABLE_WIDGETS: &[&str] = &[
    "text_input",
    "text_editor",
    "checkbox",
    "pick_list",
    "combo_box",
];

/// Extract a `required` prop, guarded to validatable widget types.
fn required_from_props(type_name: &str, props: &plushie_core::protocol::Props) -> Option<bool> {
    if !VALIDATABLE_WIDGETS.contains(&type_name) {
        return None;
    }
    props.get_value("required").and_then(|v| v.as_bool())
}

/// Parse a `validation` prop onto `(invalid, error_message)`. Guarded to
/// validatable widget types.
///
/// Accepted shapes (mirrors the permissive matcher the other SDKs use):
///
/// - `"valid"`                                    -> `(Some(false), None)`
/// - `"pending"`                                  -> `(None, None)`
/// - `["invalid", message]`                       -> `(Some(true), Some(message))`
/// - `{"state": "invalid", "message": m}`         -> `(Some(true), Some(m))`
/// - `{"state": "valid"}`                         -> `(Some(false), None)`
/// - `{"state": "pending"}`                       -> `(None, None)`
fn invalid_from_props(
    type_name: &str,
    props: &plushie_core::protocol::Props,
) -> (Option<bool>, Option<String>) {
    if !VALIDATABLE_WIDGETS.contains(&type_name) {
        return (None, None);
    }
    let Some(v) = props.get_value("validation") else {
        return (None, None);
    };

    if let Some(s) = v.as_str() {
        return match s {
            "valid" => (Some(false), None),
            "pending" => (None, None),
            _ => (None, None),
        };
    }

    if let Some(arr) = v.as_array()
        && arr.len() == 2
        && arr[0].as_str() == Some("invalid")
    {
        let msg = arr[1].as_str().map(str::to_string);
        return (Some(true), msg);
    }

    if let Some(obj) = v.as_object() {
        let state = obj.get("state").and_then(|s| s.as_str());
        let message = obj
            .get("message")
            .and_then(|s| s.as_str())
            .map(str::to_string);
        return match state {
            Some("valid") => (Some(false), None),
            Some("pending") => (None, None),
            Some("invalid") => (Some(true), message),
            _ => (None, None),
        };
    }

    (None, None)
}

/// Build a new Props for `node` with its a11y sub-object rewritten.
///
/// Returns the input node's props unchanged if there is nothing to do.
fn apply_a11y_rewrites(
    node: &TreeNode,
    scope: &str,
    declared: &HashSet<String>,
    radio_groups: &BTreeMap<RadioGroupKey, RadioGroupInfo>,
    warnings: &mut Vec<Diagnostic>,
) -> plushie_core::protocol::Props {
    let radio_info = if node.type_name == "radio" {
        node.props.get_str("group").and_then(|g| {
            radio_groups
                .get(&(scope.to_string(), g.to_string()))
                .cloned()
        })
    } else {
        None
    };

    let required_prop = required_from_props(&node.type_name, &node.props);
    let (invalid_prop, error_text) = invalid_from_props(&node.type_name, &node.props);

    let a11y_obj = node
        .props
        .get_value("a11y")
        .and_then(|v| v.as_object().cloned());

    // If the existing a11y is absent AND we have nothing to inject,
    // leave props alone. This keeps untouched nodes bit-identical.
    if a11y_obj.is_none()
        && radio_info.is_none()
        && required_prop.is_none()
        && invalid_prop.is_none()
        && error_text.is_none()
    {
        return node.props.clone();
    }

    let mut obj = a11y_obj.unwrap_or_default();

    // Rewrite single-ID refs.
    for key in [
        "labelled_by",
        "described_by",
        "error_message",
        "active_descendant",
    ] {
        if let Some(v) = obj.get(key).cloned()
            && let Some(s) = v.as_str()
        {
            let rewritten = resolve_ref(s, scope);
            if !declared.contains(&rewritten) && !s.is_empty() {
                warnings.push(Diagnostic::A11yRefUnresolved {
                    id: node.id.clone(),
                    key: key.to_string(),
                    value: s.to_string(),
                    is_member: false,
                });
            }
            obj.insert(key.to_string(), serde_json::Value::String(rewritten));
        }
    }

    // Rewrite each element of `radio_group`.
    if let Some(v) = obj.get("radio_group").cloned()
        && let Some(arr) = v.as_array()
    {
        let rewritten: Vec<serde_json::Value> = arr
            .iter()
            .filter_map(|item| item.as_str())
            .map(|s| {
                let r = resolve_ref(s, scope);
                if !declared.contains(&r) && !s.is_empty() {
                    warnings.push(Diagnostic::A11yRefUnresolved {
                        id: node.id.clone(),
                        key: "radio_group".to_string(),
                        value: s.to_string(),
                        is_member: true,
                    });
                }
                serde_json::Value::String(r)
            })
            .collect();
        obj.insert(
            "radio_group".to_string(),
            serde_json::Value::Array(rewritten),
        );
    }

    // Populate implicit radio relationships from the shared `group`
    // prop. Explicit author-provided fields win independently.
    if let Some(info) = radio_info {
        if !obj.contains_key("radio_group") {
            let arr: Vec<serde_json::Value> = info
                .ids
                .into_iter()
                .map(serde_json::Value::String)
                .collect();
            obj.insert("radio_group".to_string(), serde_json::Value::Array(arr));
        }
        if !obj.contains_key("active_descendant")
            && let Some(active_descendant) = info.active_descendant
        {
            obj.insert(
                "active_descendant".to_string(),
                serde_json::Value::String(active_descendant),
            );
        }
    }

    // Project `required: true` onto `a11y.required`. Explicit a11y
    // override (from the author) wins. `false` is not projected: the
    // absence of the key carries the same semantic weight as `false`.
    if required_prop == Some(true) && !obj.contains_key("required") {
        obj.insert("required".to_string(), serde_json::Value::Bool(true));
    }

    // Project `validation` onto `a11y.invalid` and `a11y.error_message`.
    // Only `invalid` gets a boolean either way; `valid` -> `false` so
    // assistive tech can announce "no error".
    if let Some(inv) = invalid_prop
        && !obj.contains_key("invalid")
    {
        obj.insert("invalid".to_string(), serde_json::Value::Bool(inv));
    }
    if let Some(msg) = error_text
        && !obj.contains_key("error_message")
    {
        obj.insert("error_message".to_string(), serde_json::Value::String(msg));
    }

    // Reassemble props with the updated a11y object.
    install_a11y(&node.props, obj)
}

/// Produce a new `Props` value with `a11y` replaced by the given map.
fn install_a11y(
    base: &plushie_core::protocol::Props,
    obj: serde_json::Map<String, serde_json::Value>,
) -> plushie_core::protocol::Props {
    let mut map = base.as_prop_map().clone();
    map.remove("a11y");
    map.insert("a11y", PropValue::from(serde_json::Value::Object(obj)));
    plushie_core::protocol::Props::from(map)
}

/// Rewrite a cross-widget ID reference through the scope-prefix logic.
///
/// The reference shapes recognized (mirrors the ID-prefix rules):
/// - Already-scoped refs (`"window#path"` or `"scope/leaf"`) pass
///   through unchanged.
/// - Bare refs gain the enclosing scope as a prefix.
/// - Empty refs pass through (nothing to resolve).
fn resolve_ref(raw: &str, scope: &str) -> String {
    if raw.is_empty() || scope.is_empty() {
        return raw.to_string();
    }
    if raw.contains('#') || raw.contains('/') {
        // Author provided a pre-scoped ref; leave it alone.
        return raw.to_string();
    }
    if scope.ends_with('#') {
        format!("{scope}{raw}")
    } else {
        format!("{scope}/{raw}")
    }
}

/// Walk the tree, emit `missing_accessible_name` diagnostics for
/// interactive or visual widgets that would render without any name a
/// screen reader can announce.
///
/// Checked widget types:
///
/// - `button`, `pointer_area`: need either a text child, a `label`
///   prop, `a11y.label`, or `a11y.labelled_by`.
/// - `toggler`, `checkbox`: same as above (their native role is
///   announced, but the *name* still needs to come from somewhere).
/// - `image`, `svg`: need `alt`, `a11y.label`, or `a11y.labelled_by`.
///   Skipped when `decorative: true` (the author has explicitly
///   marked it ignorable for AT).
/// - `qr_code`: needs `alt`, `description`, or an `a11y.label` /
///   `a11y.description` override.
///
/// Canvas interactive elements have their own diagnostic in
/// `canvas/interaction.rs`; this check skips them.
fn check_missing_accessible_name(node: &TreeNode, warnings: &mut Vec<Diagnostic>) {
    fn walk(node: &TreeNode, warnings: &mut Vec<Diagnostic>) {
        if widget_requires_accessible_name(&node.type_name) && !has_accessible_name(node) {
            warnings.push(Diagnostic::MissingAccessibleName {
                type_name: node.type_name.clone(),
                id: node.id.clone(),
            });
        }
        for child in &node.children {
            walk(child, warnings);
        }
    }
    walk(node, warnings);
}

fn widget_requires_accessible_name(type_name: &str) -> bool {
    matches!(
        type_name,
        "button" | "toggler" | "checkbox" | "pointer_area" | "image" | "svg" | "qr_code"
    )
}

/// Returns true if the node carries any source of accessible name.
fn has_accessible_name(node: &TreeNode) -> bool {
    // A widget marked `decorative: true` opts out of the check; the
    // author has stated AT should ignore it. Only meaningful for
    // image / svg today; the prop is ignored on widget types that
    // don't honour it.
    if matches!(node.type_name.as_str(), "image" | "svg")
        && node
            .props
            .get_value("decorative")
            .and_then(|v| v.as_bool())
            .unwrap_or(false)
    {
        return true;
    }
    // A `label` prop (checkbox / toggler carry their text here).
    if node.props.get_str("label").is_some_and(|s| !s.is_empty()) {
        return true;
    }
    // image / svg use `alt`; qr_code accepts `alt` or `description`.
    if matches!(node.type_name.as_str(), "image" | "svg" | "qr_code")
        && node.props.get_str("alt").is_some_and(|s| !s.is_empty())
    {
        return true;
    }
    if node.type_name == "qr_code"
        && node
            .props
            .get_str("description")
            .is_some_and(|s| !s.is_empty())
    {
        return true;
    }
    // An a11y override with label or labelled_by.
    if let Some(a11y) = node.props.get_value("a11y") {
        if a11y
            .get("label")
            .and_then(|v| v.as_str())
            .is_some_and(|s| !s.is_empty())
        {
            return true;
        }
        if a11y
            .get("labelled_by")
            .and_then(|v| v.as_str())
            .is_some_and(|s| !s.is_empty())
        {
            return true;
        }
        // qr_code also accepts an `a11y.description` since its
        // payload is data, not a textual name.
        if node.type_name == "qr_code"
            && a11y
                .get("description")
                .and_then(|v| v.as_str())
                .is_some_and(|s| !s.is_empty())
        {
            return true;
        }
    }
    // A non-empty text child anywhere in the subtree.
    fn has_text_child(n: &TreeNode) -> bool {
        for child in &n.children {
            if child.type_name == "text"
                && child
                    .props
                    .get_str("content")
                    .is_some_and(|s| !s.is_empty())
            {
                return true;
            }
            if has_text_child(child) {
                return true;
            }
        }
        false
    }
    has_text_child(node)
}

#[cfg(test)]
mod tests {
    use super::*;
    use serde_json::json;

    /// Normalize a tree through both the scope-rewrite transform and
    /// the memo cache, so tests can assert memo-hit behaviour.
    fn normalize_with_memo(
        tree: &TreeNode,
        cache: &mut super::super::memo_cache::MemoCache,
    ) -> (TreeNode, Vec<Diagnostic>) {
        cache.begin_cycle();
        let mut result = tree.clone();
        let mut transform = NormalizeTransform::with_memo_cache(Some(cache));
        let mut ctx = WalkCtx::default();
        walk(&mut result, &mut [&mut transform], &mut ctx);
        drop(transform);
        cache.finish_cycle();
        let (warnings, _ctx) = finalize_a11y(&mut result, ctx);
        (result, warnings)
    }

    fn memo_node(key: &str, deps_hash: u64, inner: TreeNode) -> TreeNode {
        let mut props = plushie_core::protocol::PropMap::new();
        props.insert("__memo_deps__", deps_hash);
        TreeNode {
            id: format!("memo:{key}"),
            type_name: "__memo__".to_string(),
            props: plushie_core::protocol::Props::from(props),
            children: vec![inner],
        }
    }

    #[test]
    fn memo_hit_reuses_cached_subtree() {
        use super::super::memo_cache::MemoCache;
        let mut cache = MemoCache::new();

        // First render: miss, populates the cache.
        let tree1 = node(
            "root",
            "column",
            vec![memo_node(
                "hdr",
                42,
                node("inner", "text", vec![node("leaf", "text", vec![])]),
            )],
        );
        let (out1, _warn1) = normalize_with_memo(&tree1, &mut cache);
        let memo1 = &out1.children[0];
        // memo id got scope-prefixed into root's scope.
        assert_eq!(memo1.id, "root/memo:hdr");
        assert_eq!(memo1.children[0].id, "root/memo:hdr/inner");
        assert_eq!(memo1.children[0].children[0].id, "root/memo:hdr/inner/leaf");

        // Second render: same deps hash, different inner contents.
        // The hit should restore the cached inner, ignoring the
        // freshly-authored tree.
        let tree2 = node(
            "root",
            "column",
            vec![memo_node(
                "hdr",
                42,
                node("different", "text", vec![node("leaf2", "text", vec![])]),
            )],
        );
        let (out2, _warn2) = normalize_with_memo(&tree2, &mut cache);
        let memo2 = &out2.children[0];
        assert_eq!(memo2.id, "root/memo:hdr");
        // Cache hit restored the earlier "inner" subtree.
        assert_eq!(memo2.children[0].id, "root/memo:hdr/inner");
    }

    #[test]
    fn memo_miss_on_deps_change_renormalizes() {
        use super::super::memo_cache::MemoCache;
        let mut cache = MemoCache::new();

        let tree1 = node(
            "root",
            "column",
            vec![memo_node("hdr", 1, node("inner_a", "text", vec![]))],
        );
        let (_out1, _w1) = normalize_with_memo(&tree1, &mut cache);

        // Deps change: the freshly-authored subtree should appear,
        // not the cached one.
        let tree2 = node(
            "root",
            "column",
            vec![memo_node("hdr", 2, node("inner_b", "text", vec![]))],
        );
        let (out2, _w2) = normalize_with_memo(&tree2, &mut cache);
        assert_eq!(out2.children[0].children[0].id, "root/memo:hdr/inner_b");
    }

    #[test]
    fn nested_memos_each_memoize_independently() {
        use super::super::memo_cache::MemoCache;
        let mut cache = MemoCache::new();

        let inner_memo = memo_node("inner", 10, node("leaf", "text", vec![]));
        let outer_memo = memo_node("outer", 20, inner_memo);
        let tree1 = node("root", "column", vec![outer_memo]);
        let (out1, _w1) = normalize_with_memo(&tree1, &mut cache);
        let outer1 = &out1.children[0];
        assert_eq!(outer1.id, "root/memo:outer");
        let inner1 = &outer1.children[0];
        assert_eq!(inner1.id, "root/memo:outer/memo:inner");
        assert_eq!(inner1.children[0].id, "root/memo:outer/memo:inner/leaf");

        // Second render: both hit.
        let inner_memo2 = memo_node("inner", 10, node("other_leaf", "text", vec![]));
        let outer_memo2 = memo_node("outer", 20, inner_memo2);
        let tree2 = node("root", "column", vec![outer_memo2]);
        let (out2, _w2) = normalize_with_memo(&tree2, &mut cache);
        let outer2 = &out2.children[0];
        let inner2 = &outer2.children[0];
        // The cached outer returns the cached inner subtree with
        // `leaf`, not `other_leaf`.
        assert_eq!(inner2.children[0].id, "root/memo:outer/memo:inner/leaf");
    }

    fn node(id: &str, type_name: &str, children: Vec<TreeNode>) -> TreeNode {
        TreeNode {
            id: id.to_string(),
            type_name: type_name.to_string(),
            props: plushie_core::protocol::Props::from_json(json!({})),
            children,
        }
    }

    fn node_with_props(id: &str, type_name: &str, props: serde_json::Value) -> TreeNode {
        TreeNode {
            id: id.to_string(),
            type_name: type_name.to_string(),
            props: plushie_core::protocol::Props::from_json(props),
            children: vec![],
        }
    }

    fn a11y_role(node: &TreeNode) -> Option<String> {
        node.props
            .get_value("a11y")
            .and_then(|v| v.get("role").and_then(|r| r.as_str()).map(str::to_string))
    }

    #[test]
    fn scope_buffer_survives_deep_nesting() {
        // Regression: the scope-string buffer threaded through
        // normalize_node's walk must grow on enter and shrink on
        // exit so siblings at the same depth see the same scope
        // regardless of traversal order.
        let tree = node(
            "main",
            "window",
            vec![
                node(
                    "form",
                    "container",
                    vec![
                        node("a", "text_input", vec![]),
                        node(
                            "row",
                            "row",
                            vec![
                                node("b", "text_input", vec![]),
                                node("c", "text_input", vec![]),
                            ],
                        ),
                        node("d", "text_input", vec![]),
                    ],
                ),
                node("footer", "container", vec![node("e", "text", vec![])]),
            ],
        );
        let (result, warnings) = normalize(&tree);
        assert!(warnings.is_empty(), "got {warnings:?}");
        let form = &result.children[0];
        assert_eq!(form.id, "main#form");
        assert_eq!(form.children[0].id, "main#form/a");
        let row = &form.children[1];
        assert_eq!(row.id, "main#form/row");
        assert_eq!(row.children[0].id, "main#form/row/b");
        assert_eq!(row.children[1].id, "main#form/row/c");
        // `d` at the same depth as `row` must see the scope restored
        // after `row`'s exit - not leak "/row".
        assert_eq!(form.children[2].id, "main#form/d");
        let footer = &result.children[1];
        assert_eq!(footer.id, "main#footer");
        assert_eq!(footer.children[0].id, "main#footer/e");
    }

    #[test]
    fn normalize_is_deterministic_across_runs() {
        // Same input tree twice through normalize must yield the same
        // normalized ID shape. Guards the scope buffer against leaking
        // state across calls.
        let build = || {
            node(
                "main",
                "window",
                vec![node(
                    "form",
                    "container",
                    vec![
                        node("a", "text_input", vec![]),
                        node("b", "text_input", vec![]),
                    ],
                )],
            )
        };
        let (a, _) = normalize(&build());
        let (b, _) = normalize(&build());
        let collect_ids = |n: &TreeNode, out: &mut Vec<String>| {
            fn walk(n: &TreeNode, out: &mut Vec<String>) {
                out.push(n.id.clone());
                for c in &n.children {
                    walk(c, out);
                }
            }
            walk(n, out);
        };
        let mut a_ids = Vec::new();
        let mut b_ids = Vec::new();
        collect_ids(&a, &mut a_ids);
        collect_ids(&b, &mut b_ids);
        assert_eq!(a_ids, b_ids);
    }

    #[test]
    fn flat_tree_preserves_ids() {
        let tree = node(
            "root",
            "column",
            vec![node("a", "text", vec![]), node("b", "text", vec![])],
        );
        let (result, warnings) = normalize(&tree);
        assert!(warnings.is_empty());
        assert_eq!(result.children[0].id, "root/a");
        assert_eq!(result.children[1].id, "root/b");
    }

    #[test]
    fn auto_ids_are_not_scoped() {
        let tree = node(
            "auto:col:1:1",
            "column",
            vec![node("btn", "button", vec![])],
        );
        let (result, warnings) = normalize(&tree);
        // The unnamed button triggers missing_accessible_name; that's
        // expected given no label/text child, and is the only warning.
        assert_eq!(warnings.len(), 1);
        assert!(matches!(
            warnings[0].kind(),
            plushie_core::DiagnosticKind::MissingAccessibleName
        ));
        assert_eq!(result.children[0].id, "btn");
    }

    #[test]
    fn nested_scoping() {
        let tree = node(
            "form",
            "container",
            vec![node(
                "section",
                "column",
                vec![node("field", "text_input", vec![])],
            )],
        );
        let (result, warnings) = normalize(&tree);
        assert!(warnings.is_empty());
        assert_eq!(result.children[0].id, "form/section");
        assert_eq!(result.children[0].children[0].id, "form/section/field");
    }

    #[test]
    fn window_scopes_children_with_hash() {
        let tree = node("main", "window", vec![node("col", "column", vec![])]);
        let (result, warnings) = normalize(&tree);
        assert!(warnings.is_empty());
        assert_eq!(result.id, "main");
        assert_eq!(result.children[0].id, "main#col");
    }

    #[test]
    fn window_nested_children_use_slash_after_hash() {
        let tree = node(
            "main",
            "window",
            vec![node(
                "form",
                "container",
                vec![node("email", "text_input", vec![])],
            )],
        );
        let (result, warnings) = normalize(&tree);
        assert!(warnings.is_empty());
        assert_eq!(result.children[0].id, "main#form");
        assert_eq!(result.children[0].children[0].id, "main#form/email");
    }

    #[test]
    fn hash_in_id_produces_warning() {
        let tree = node("bad#id", "text", vec![]);
        let (_, warnings) = normalize(&tree);
        assert_eq!(warnings.len(), 1);
        match &warnings[0] {
            Diagnostic::WidgetIdInvalid { reason, detail, .. } => {
                assert_eq!(reason, "reserved_char");
                assert!(detail.contains("reserved character '#'"));
            }
            other => panic!("unexpected diagnostic: {other:?}"),
        }
    }

    #[test]
    fn non_ascii_id_is_accepted() {
        let tree = node("caf\u{00e9}", "text", vec![]);
        let (result, warnings) = normalize(&tree);
        assert!(
            !warnings
                .iter()
                .any(|w| matches!(w, Diagnostic::WidgetIdInvalid { .. })),
            "expected no widget_id_invalid diagnostic, got {warnings:?}"
        );
        assert_eq!(result.id, "caf\u{00e9}");
    }

    #[test]
    fn control_character_id_is_accepted() {
        let tree = node("has\tctrl", "text", vec![]);
        let (result, warnings) = normalize(&tree);
        assert!(
            !warnings
                .iter()
                .any(|w| matches!(w, Diagnostic::WidgetIdInvalid { .. })),
            "expected no widget_id_invalid diagnostic, got {warnings:?}"
        );
        assert_eq!(result.id, "has\tctrl");
    }

    #[test]
    fn oversize_id_produces_warning() {
        let huge = "a".repeat(2000);
        let tree = node(&huge, "text", vec![]);
        let (_, warnings) = normalize(&tree);
        assert!(
            warnings.iter().any(|w| matches!(
                w,
                Diagnostic::WidgetIdInvalid { reason, .. } if reason == "too_long"
            )),
            "expected too_long diagnostic, got {warnings:?}"
        );
    }

    #[test]
    fn auto_ids_bypass_all_id_validation() {
        // Auto IDs start with "auto:" so they skip the canonical rules.
        let tree = node("auto:col:\u{00e9}", "column", vec![]);
        let (_, warnings) = normalize(&tree);
        assert!(
            !warnings
                .iter()
                .any(|w| matches!(w, Diagnostic::WidgetIdInvalid { .. })),
            "auto IDs must not raise widget_id_invalid, got {warnings:?}"
        );
    }

    #[test]
    fn duplicate_ids_produce_warning() {
        let tree = node(
            "root",
            "column",
            vec![node("btn", "button", vec![]), node("btn", "button", vec![])],
        );
        let (_, warnings) = normalize(&tree);
        // Two unnamed buttons also trigger missing_accessible_name.
        assert!(
            warnings
                .iter()
                .any(|w| matches!(w, Diagnostic::DuplicateId { .. }))
        );
    }

    #[test]
    fn reserved_slash_in_id_produces_warning() {
        let tree = node("form/field", "text_input", vec![]);
        let (_, warnings) = normalize(&tree);
        assert_eq!(warnings.len(), 1);
        match &warnings[0] {
            Diagnostic::WidgetIdInvalid { reason, detail, .. } => {
                assert_eq!(reason, "reserved_char");
                assert!(detail.contains("reserved character"));
            }
            other => panic!("unexpected diagnostic: {other:?}"),
        }
    }

    #[test]
    fn excessive_depth_is_truncated_with_diagnostic() {
        // Build a tree deeper than MAX_TREE_DEPTH. The walker enforces
        // the cap and emits tree_depth_exceeded at the boundary; the
        // normalize pass must not stack-overflow in the process.
        let mut tree = node("leaf", "text", vec![]);
        for i in 0..(MAX_TREE_DEPTH + 20) {
            tree = node(&format!("n{i}"), "container", vec![tree]);
        }

        let (_result, warnings) = normalize(&tree);
        assert!(
            warnings
                .iter()
                .any(|w| matches!(w, Diagnostic::TreeDepthExceeded { .. })),
            "expected tree_depth_exceeded diagnostic; got {warnings:?}"
        );
    }

    #[test]
    fn auto_ids_skip_duplicate_check() {
        let tree = node(
            "root",
            "column",
            vec![
                node("auto:text:1:1", "text", vec![]),
                node("auto:text:1:1", "text", vec![]),
            ],
        );
        let (_, warnings) = normalize(&tree);
        assert!(warnings.is_empty());
    }

    // -- A11y rewrite tests -------------------------------------------------

    #[test]
    fn a11y_role_not_populated_from_widget_type() {
        let tree = node(
            "root",
            "column",
            vec![node_with_props("save", "button", json!({}))],
        );
        let (result, _warnings) = normalize(&tree);
        let btn = &result.children[0];
        assert!(
            a11y_role(btn).is_none(),
            "native widgets should keep their native accessible roles"
        );
    }

    #[test]
    fn a11y_role_explicit_is_preserved() {
        let tree = node(
            "root",
            "column",
            vec![node_with_props(
                "save",
                "button",
                json!({"a11y": {"role": "link"}}),
            )],
        );
        let (result, _warnings) = normalize(&tree);
        let btn = &result.children[0];
        assert_eq!(a11y_role(btn).as_deref(), Some("link"));
    }

    #[test]
    fn a11y_role_not_populated_for_builtin_widgets() {
        for type_name in [
            "button",
            "canvas",
            "checkbox",
            "column",
            "combo_box",
            "container",
            "float",
            "floating",
            "grid",
            "image",
            "overlay",
            "pane_grid",
            "pick_list",
            "pin",
            "pointer_area",
            "progress_bar",
            "qr_code",
            "radio",
            "responsive",
            "rich_text",
            "row",
            "rule",
            "scrollable",
            "sensor",
            "slider",
            "stack",
            "svg",
            "table",
            "text",
            "text_editor",
            "text_input",
            "themer",
            "tooltip",
            "toggler",
            "vertical_slider",
            "window",
        ] {
            let tree = node("root", "column", vec![node(type_name, type_name, vec![])]);
            let (result, _warnings) = normalize(&tree);
            let child = &result.children[0];
            assert!(
                a11y_role(child).is_none(),
                "{type_name} should not get a normalizer-injected role"
            );
        }
    }

    #[test]
    fn a11y_ref_rewritten_inside_scoped_container() {
        let tree = node(
            "form",
            "container",
            vec![
                node_with_props("heading", "text", json!({"content": "Log in"})),
                node_with_props(
                    "email",
                    "text_input",
                    json!({"a11y": {"labelled_by": "heading"}}),
                ),
            ],
        );
        let (result, warnings) = normalize(&tree);
        assert!(
            warnings.is_empty(),
            "no diagnostics expected, got {warnings:?}"
        );
        let email = &result.children[1];
        let labelled_by = email.props.get_value("a11y").and_then(|v| {
            v.get("labelled_by")
                .and_then(|r| r.as_str())
                .map(str::to_string)
        });
        assert_eq!(labelled_by.as_deref(), Some("form/heading"));
    }

    #[test]
    fn a11y_ref_unresolved_emits_diagnostic() {
        let tree = node(
            "form",
            "container",
            vec![node_with_props(
                "email",
                "text_input",
                json!({"a11y": {"labelled_by": "missing"}}),
            )],
        );
        let (_result, warnings) = normalize(&tree);
        assert!(
            warnings
                .iter()
                .any(|w| matches!(w, Diagnostic::A11yRefUnresolved { .. })),
            "expected a11y_ref_unresolved diagnostic, got {warnings:?}"
        );
    }

    #[test]
    fn implicit_radio_group_populates_radio_group_a11y() {
        let tree = node(
            "form",
            "container",
            vec![
                node_with_props("r1", "radio", json!({"group": "flavor"})),
                node_with_props("r2", "radio", json!({"group": "flavor"})),
                node_with_props("r3", "radio", json!({"group": "flavor"})),
            ],
        );
        let (result, warnings) = normalize(&tree);
        assert!(warnings.is_empty(), "got {warnings:?}");
        for child in &result.children {
            let group = child
                .props
                .get_value("a11y")
                .and_then(|v| v.get("radio_group").cloned())
                .and_then(|v| v.as_array().cloned());
            let group = group.expect("radio_group should be populated");
            let ids: Vec<String> = group
                .iter()
                .filter_map(|v| v.as_str().map(str::to_string))
                .collect();
            assert_eq!(ids, vec!["form/r1", "form/r2", "form/r3"]);
        }
    }

    #[test]
    fn implicit_radio_group_populates_active_descendant() {
        let tree = node(
            "form",
            "container",
            vec![
                node_with_props(
                    "r1",
                    "radio",
                    json!({"group": "flavor", "value": "vanilla", "selected": "chocolate"}),
                ),
                node_with_props(
                    "r2",
                    "radio",
                    json!({"group": "flavor", "value": "chocolate", "selected": "chocolate"}),
                ),
            ],
        );
        let (result, warnings) = normalize(&tree);
        assert!(warnings.is_empty(), "got {warnings:?}");
        for child in &result.children {
            let active_descendant = child.props.get_value("a11y").and_then(|v| {
                v.get("active_descendant")
                    .and_then(|v| v.as_str())
                    .map(str::to_string)
            });
            assert_eq!(active_descendant.as_deref(), Some("form/r2"));
        }
    }

    #[test]
    fn implicit_radio_group_without_selection_has_no_active_descendant() {
        let tree = node(
            "form",
            "container",
            vec![
                node_with_props("r1", "radio", json!({"group": "flavor"})),
                node_with_props("r2", "radio", json!({"group": "flavor"})),
            ],
        );
        let (result, warnings) = normalize(&tree);
        assert!(warnings.is_empty(), "got {warnings:?}");
        for child in &result.children {
            let active_descendant = child
                .props
                .get_value("a11y")
                .and_then(|v| v.get("active_descendant").cloned());
            assert!(
                active_descendant.is_none(),
                "unselected radio group should not infer active_descendant"
            );
        }
    }

    #[test]
    fn missing_accessible_name_diagnostic_for_icon_only_button() {
        let tree = node("root", "column", vec![node("save", "button", vec![])]);
        let (_result, warnings) = normalize(&tree);
        assert!(
            warnings.iter().any(|w| matches!(
                w,
                Diagnostic::MissingAccessibleName { id, .. } if id == "root/save"
            )),
            "expected missing_accessible_name for icon-only button, got {warnings:?}"
        );
    }

    #[test]
    fn button_with_text_child_does_not_warn() {
        let text_child = TreeNode {
            id: "auto:text:1".to_string(),
            type_name: "text".to_string(),
            props: plushie_core::protocol::Props::from_json(json!({"content": "Save"})),
            children: vec![],
        };
        let button = TreeNode {
            id: "save".to_string(),
            type_name: "button".to_string(),
            props: plushie_core::protocol::Props::from_json(json!({})),
            children: vec![text_child],
        };
        let tree = node("root", "column", vec![button]);
        let (_result, warnings) = normalize(&tree);
        assert!(
            warnings.is_empty(),
            "button with text child should be named; got {warnings:?}"
        );
    }

    #[test]
    fn checkbox_with_label_prop_does_not_warn() {
        let tree = node(
            "root",
            "column",
            vec![node_with_props(
                "agree",
                "checkbox",
                json!({"label": "I agree", "checked": false}),
            )],
        );
        let (_result, warnings) = normalize(&tree);
        assert!(warnings.is_empty(), "got {warnings:?}");
    }

    fn has_missing_name(warnings: &[Diagnostic], scoped_id: &str) -> bool {
        warnings.iter().any(|w| {
            matches!(
                w,
                Diagnostic::MissingAccessibleName { id, .. } if id == scoped_id
            )
        })
    }

    #[test]
    fn image_without_alt_or_decorative_warns() {
        let tree = node(
            "root",
            "column",
            vec![node_with_props(
                "logo",
                "image",
                json!({"source": "/logo.png"}),
            )],
        );
        let (_result, warnings) = normalize(&tree);
        assert!(
            has_missing_name(&warnings, "root/logo"),
            "expected missing_accessible_name for unlabelled image, got {warnings:?}"
        );
    }

    #[test]
    fn image_with_alt_does_not_warn() {
        let tree = node(
            "root",
            "column",
            vec![node_with_props(
                "logo",
                "image",
                json!({"source": "/logo.png", "alt": "Company logo"}),
            )],
        );
        let (_result, warnings) = normalize(&tree);
        assert!(
            !has_missing_name(&warnings, "root/logo"),
            "got {warnings:?}"
        );
    }

    #[test]
    fn decorative_image_does_not_warn() {
        let tree = node(
            "root",
            "column",
            vec![node_with_props(
                "deco",
                "image",
                json!({"source": "/divider.png", "decorative": true}),
            )],
        );
        let (_result, warnings) = normalize(&tree);
        assert!(
            !has_missing_name(&warnings, "root/deco"),
            "got {warnings:?}"
        );
    }

    #[test]
    fn svg_without_alt_or_decorative_warns() {
        let tree = node(
            "root",
            "column",
            vec![node_with_props(
                "icon",
                "svg",
                json!({"source": "/icon.svg"}),
            )],
        );
        let (_result, warnings) = normalize(&tree);
        assert!(
            has_missing_name(&warnings, "root/icon"),
            "expected missing_accessible_name for unlabelled svg, got {warnings:?}"
        );
    }

    #[test]
    fn svg_with_a11y_label_does_not_warn() {
        let tree = node(
            "root",
            "column",
            vec![node_with_props(
                "icon",
                "svg",
                json!({"source": "/icon.svg", "a11y": {"label": "Settings"}}),
            )],
        );
        let (_result, warnings) = normalize(&tree);
        assert!(
            !has_missing_name(&warnings, "root/icon"),
            "got {warnings:?}"
        );
    }

    #[test]
    fn qr_code_without_name_or_description_warns() {
        let tree = node(
            "root",
            "column",
            vec![node_with_props(
                "wifi",
                "qr_code",
                json!({"data": "WIFI:T:WPA;..."}),
            )],
        );
        let (_result, warnings) = normalize(&tree);
        assert!(
            has_missing_name(&warnings, "root/wifi"),
            "expected missing_accessible_name for unlabelled qr_code, got {warnings:?}"
        );
    }

    #[test]
    fn qr_code_with_description_does_not_warn() {
        let tree = node(
            "root",
            "column",
            vec![node_with_props(
                "wifi",
                "qr_code",
                json!({"data": "WIFI:T:WPA;...", "description": "Scan to join wifi"}),
            )],
        );
        let (_result, warnings) = normalize(&tree);
        assert!(
            !has_missing_name(&warnings, "root/wifi"),
            "got {warnings:?}"
        );
    }

    #[test]
    fn qr_code_with_alt_does_not_warn() {
        let tree = node(
            "root",
            "column",
            vec![node_with_props(
                "wifi",
                "qr_code",
                json!({"data": "WIFI:T:WPA;...", "alt": "Wifi"}),
            )],
        );
        let (_result, warnings) = normalize(&tree);
        assert!(
            !has_missing_name(&warnings, "root/wifi"),
            "got {warnings:?}"
        );
    }

    #[test]
    fn empty_id_emits_empty_id_diagnostic() {
        // Use a container type since interactive widgets require IDs at
        // the builder layer; the normalize pass still inspects whatever
        // TreeNode it's handed.
        let tree = TreeNode {
            id: String::new(),
            type_name: "container".to_string(),
            props: plushie_core::protocol::Props::from(plushie_core::protocol::PropMap::new()),
            children: vec![],
        };
        let (_, warnings) = normalize(&tree);
        assert!(
            warnings
                .iter()
                .any(|w| matches!(w, Diagnostic::EmptyId { .. })),
            "expected empty_id diagnostic, got {warnings:?}"
        );
    }

    #[test]
    fn required_prop_projects_to_a11y_required() {
        let tree = node(
            "form",
            "container",
            vec![node_with_props(
                "email",
                "text_input",
                json!({"required": true}),
            )],
        );
        let (result, warnings) = normalize(&tree);
        assert!(warnings.is_empty(), "got {warnings:?}");
        let email = &result.children[0];
        let required = email
            .props
            .get_value("a11y")
            .and_then(|v| v.get("required").and_then(|r| r.as_bool()));
        assert_eq!(required, Some(true));
    }

    #[test]
    fn required_false_does_not_project() {
        let tree = node(
            "form",
            "container",
            vec![node_with_props(
                "email",
                "text_input",
                json!({"required": false}),
            )],
        );
        let (result, _warnings) = normalize(&tree);
        let email = &result.children[0];
        let required = email
            .props
            .get_value("a11y")
            .and_then(|v| v.get("required").cloned());
        assert!(required.is_none(), "required=false should not project");
    }

    #[test]
    fn required_skipped_for_non_validatable_widgets() {
        // Button is not a validatable widget. A `required: true` prop on
        // it should not flow into a11y.required.
        let tree = node(
            "form",
            "container",
            vec![node_with_props(
                "save",
                "button",
                json!({"label": "Save", "required": true}),
            )],
        );
        let (result, _warnings) = normalize(&tree);
        let btn = &result.children[0];
        let required = btn
            .props
            .get_value("a11y")
            .and_then(|v| v.get("required").cloned());
        assert!(
            required.is_none(),
            "required should not project on non-validatable widgets"
        );
    }

    #[test]
    fn required_explicit_a11y_wins() {
        let tree = node(
            "form",
            "container",
            vec![node_with_props(
                "email",
                "text_input",
                json!({"required": true, "a11y": {"required": false}}),
            )],
        );
        let (result, _warnings) = normalize(&tree);
        let email = &result.children[0];
        let required = email
            .props
            .get_value("a11y")
            .and_then(|v| v.get("required").and_then(|r| r.as_bool()));
        assert_eq!(required, Some(false));
    }

    #[test]
    fn validation_invalid_projects_to_a11y_invalid_and_error_message() {
        let tree = node(
            "form",
            "container",
            vec![node_with_props(
                "email",
                "text_input",
                json!({
                    "validation": {"state": "invalid", "message": "Must be an email"},
                }),
            )],
        );
        let (result, _warnings) = normalize(&tree);
        let email = &result.children[0];
        let a11y = email
            .props
            .get_value("a11y")
            .expect("a11y should be populated");
        assert_eq!(a11y.get("invalid").and_then(|v| v.as_bool()), Some(true));
        assert_eq!(
            a11y.get("error_message").and_then(|v| v.as_str()),
            Some("Must be an email")
        );
    }

    #[test]
    fn validation_invalid_array_shape_accepted() {
        // Shape `["invalid", msg]` is the wire form some SDKs emit.
        let tree = node(
            "form",
            "container",
            vec![node_with_props(
                "email",
                "text_input",
                json!({"validation": ["invalid", "Required field"]}),
            )],
        );
        let (result, _warnings) = normalize(&tree);
        let email = &result.children[0];
        let a11y = email
            .props
            .get_value("a11y")
            .expect("a11y should be populated");
        assert_eq!(a11y.get("invalid").and_then(|v| v.as_bool()), Some(true));
        assert_eq!(
            a11y.get("error_message").and_then(|v| v.as_str()),
            Some("Required field")
        );
    }

    #[test]
    fn validation_valid_projects_false() {
        let tree = node(
            "form",
            "container",
            vec![node_with_props(
                "email",
                "text_input",
                json!({"validation": "valid"}),
            )],
        );
        let (result, _warnings) = normalize(&tree);
        let email = &result.children[0];
        let invalid = email
            .props
            .get_value("a11y")
            .and_then(|v| v.get("invalid").and_then(|b| b.as_bool()));
        assert_eq!(invalid, Some(false));
    }

    #[test]
    fn validation_pending_does_not_project() {
        let tree = node(
            "form",
            "container",
            vec![node_with_props(
                "email",
                "text_input",
                json!({"validation": "pending"}),
            )],
        );
        let (result, _warnings) = normalize(&tree);
        let email = &result.children[0];
        let a11y = email.props.get_value("a11y");
        // No invalid projection; if no other a11y field is inferred,
        // pending validation leaves the node's a11y props untouched.
        if let Some(a11y) = a11y {
            assert!(
                a11y.get("invalid").is_none(),
                "pending should not project invalid"
            );
        }
    }

    #[test]
    fn explicit_radio_group_is_not_overwritten_but_rewritten() {
        let tree = node(
            "form",
            "container",
            vec![
                node_with_props("heading", "text", json!({"content": "Pick"})),
                node_with_props(
                    "r1",
                    "radio",
                    json!({
                        "group": "flavor",
                        "a11y": {"radio_group": ["heading"]}
                    }),
                ),
            ],
        );
        let (result, warnings) = normalize(&tree);
        // No diagnostic since `heading` is a real declared ID.
        assert!(warnings.is_empty(), "got {warnings:?}");
        let r1 = &result.children[1];
        let group = r1
            .props
            .get_value("a11y")
            .and_then(|v| v.get("radio_group").cloned())
            .and_then(|v| v.as_array().cloned())
            .unwrap();
        let ids: Vec<String> = group
            .iter()
            .filter_map(|v| v.as_str().map(str::to_string))
            .collect();
        assert_eq!(ids, vec!["form/heading"]);
    }

    #[test]
    fn explicit_radio_group_still_gets_inferred_active_descendant() {
        let tree = node(
            "form",
            "container",
            vec![
                node_with_props("heading", "text", json!({"content": "Pick"})),
                node_with_props(
                    "r1",
                    "radio",
                    json!({
                        "group": "flavor",
                        "value": "vanilla",
                        "selected": "vanilla",
                        "a11y": {"radio_group": ["heading"]}
                    }),
                ),
            ],
        );
        let (result, warnings) = normalize(&tree);
        assert!(warnings.is_empty(), "got {warnings:?}");
        let r1 = &result.children[1];
        let active_descendant = r1.props.get_value("a11y").and_then(|v| {
            v.get("active_descendant")
                .and_then(|v| v.as_str())
                .map(str::to_string)
        });
        assert_eq!(active_descendant.as_deref(), Some("form/r1"));
    }
}