gts 0.10.0

Global Type System (GTS) library for Rust
Documentation
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
//! OP#13 – Schema Traits Validation (`x-gts-traits-schema` / `x-gts-traits`)
//!
//! Validates that trait values provided in derived schemas conform to the
//! effective trait schema built from the entire inheritance chain.
//!
//! **Algorithm:**
//! 1. Walk the chain from leftmost (base) to rightmost (leaf) segment.
//! 2. For each schema in the chain, collect:
//!    - `x-gts-traits-schema` subschemas (object | `true` | `false`) → compose
//!      via `allOf` into the *effective trait schema*.
//!    - `x-gts-traits` objects → merge per RFC 7396 JSON Merge Patch into the
//!      *effective traits object*.
//! 3. Apply defaults from the effective trait schema to fill unresolved trait
//!    properties (materialization step).
//! 4. Validate the effective traits object against the effective trait schema
//!    (completeness check runs only when the type is non-abstract — see
//!    `store.rs::validate_schema_traits`).
//!
//! **Override semantics (RFC 7396 JSON Merge Patch):**
//! - Scalars: descendant value wins (last-wins).
//! - Objects: deep-merge recursively (keys not restated by the descendant are
//!   preserved from the ancestor).
//! - Arrays: replace wholesale (no element-wise merge).
//! - `null` at any depth deletes the key, after which `apply_defaults` may
//!   re-substitute a default.
//! - Locking publisher-controlled values is done via JSON Schema `const` in
//!   `x-gts-traits-schema`; the registry carries no GTS-specific immutability
//!   rule.
//!
//! **Empty trait schemas:** If a schema in the chain declares
//! `x-gts-traits-schema: {}` or `true`, it contributes an unconstrained
//! sub-schema. `false` contributes a sub-schema that rejects all values; a
//! type whose effective schema is `false` and which carries no traits passes
//! (nothing is validated), but any non-empty trait value fails.
//!
//! **Construction side.** This module also owns the Rust-side helpers that
//! *build* the `x-gts-traits-schema` value the validation logic above consumes:
//! the [`GtsTraitsSchema`] opt-in marker and [`inline_traits_schema_of`] (see
//! the "Inline trait-schema construction" section). Keeping construction and
//! validation together — alongside the [`X_GTS_TRAITS_SCHEMA`] / [`X_GTS_TRAITS`]
//! keyword constants — means there is one home for everything `x-gts-traits-*`.

use serde_json::Value;

/// JSON Schema annotation keyword that defines the *shape* of trait properties
/// available to a GTS type and its descendants. Schema-only — MUST NOT appear
/// in instances (see GTS spec § 9.7.1).
pub const X_GTS_TRAITS_SCHEMA: &str = "x-gts-traits-schema";

/// JSON Schema annotation keyword that supplies concrete *values* for trait
/// properties declared via [`X_GTS_TRAITS_SCHEMA`]. Schema-only — MUST NOT
/// appear in instances (see GTS spec § 9.7.1).
pub const X_GTS_TRAITS: &str = "x-gts-traits";

/// Maximum recursion depth for traversing `allOf` nesting.
/// Prevents stack overflow on deeply nested or maliciously crafted schemas.
const MAX_RECURSION_DEPTH: usize = 64;

// ---------------------------------------------------------------------------
// Inline trait-schema construction
// ---------------------------------------------------------------------------
//
// A trait shape can be supplied two ways:
//
// - **inline** — a private object subschema embedded directly under
//   `x-gts-traits-schema`. Produced from any `#[derive(schemars::JsonSchema)]`
//   struct via [`inline_traits_schema_of`] (the macro emits
//   `traits_schema = inline(MyStruct)`).
// - **referenced** — a reusable trait-schema registered as an ordinary GTS
//   type, pulled in via `$ref`. The macro emits this for `traits_schema = T`
//   where `T` is a `#[struct_to_gts_schema]` type, as
//   `{ "type": "object", "allOf": [{ "$ref": "gts://<TYPE_ID>" }] }`.
//
// `const`, `default` and `x-gts-ref` on trait properties are expressed with
// standard schemars/serde attributes (`#[schemars(extend("const" = ...))]`,
// `#[serde(default = "...")]`, `#[schemars(extend("x-gts-ref" = "..."))]`), so
// no GTS-specific field attributes are needed.

/// Opt-in marker for a struct that backs an inline `x-gts-traits-schema`.
///
/// Implement it by adding `GtsTraitsSchema` to a struct's `#[derive(...)]` list
/// (the derive macro lives in `gts_macros`), alongside `schemars::JsonSchema`.
/// It is the bound `#[struct_to_gts_schema(..., traits_schema = inline(T))]`
/// requires of `T`, so a struct used in `inline(...)` without the derive fails
/// to compile — the same opt-in gate the `$ref` form already gets from
/// [`crate::GtsSchema`].
///
/// `JsonSchema` is a supertrait because the inline subschema is generated from
/// `T`'s `JsonSchema` impl at runtime (see [`inline_traits_schema_of`]); this
/// also means deriving `GtsTraitsSchema` without `JsonSchema` is a compile
/// error, mirroring `Eq: PartialEq`.
pub trait GtsTraitsSchema: schemars::JsonSchema {}

/// Build the inline `x-gts-traits-schema` object subschema for a `JsonSchema` type.
///
/// Returns the type's own JSON Schema with the root-only `$schema` annotation
/// stripped (meaningless inside an embedded subschema), so the fragment is
/// self-contained when embedded into a host document.
///
/// All subschemas are inlined via `inline_subschemas`: any `$ref` schemars
/// would otherwise emit points at `#/$defs/<Name>`, a JSON pointer resolved
/// against the *host document* root rather than this fragment — and the
/// fragment carries no `$defs` of its own, so such a ref would be structurally
/// broken. Inlining expands every named subschema in place, including
/// `GtsInstanceId` / `GtsTypeId` (whose `JsonSchema` impls already emit the
/// canonical inline body) and arbitrary user enums / nested structs used as
/// trait-schema fields.
///
/// The one shape that cannot be inlined is a genuinely *recursive* type, for
/// which schemars must keep a `$ref` to break the cycle; such a type is not a
/// valid inline trait-schema field.
///
/// # Panics
/// Panics only if serializing `T`'s generated `schemars::Schema` to a
/// `serde_json::Value` fails, which is infallible for a valid `JsonSchema`
/// impl (a schema carries no non-string map keys or non-finite floats). The
/// panic is preferred over silently degrading to an accept-anything `{}`.
#[must_use]
// `serde_json::to_value` on a `schemars::Schema` is infallible (no non-string
// map keys, no NaN/Inf floats in a generated schema), so the only way to reach
// the panic is a schemars bug. For a spec reference implementation, failing
// loudly is correct: silently degrading to `{ "type": "object" }` would yield
// an accept-anything trait schema that validates nothing.
#[allow(clippy::expect_used)]
pub fn inline_traits_schema_of<T: schemars::JsonSchema>() -> Value {
    let mut generator = schemars::generate::SchemaSettings::default()
        .with(|s| s.inline_subschemas = true)
        .into_generator();
    let schema = <T as schemars::JsonSchema>::json_schema(&mut generator);
    let mut value = serde_json::to_value(&schema)
        .expect("schemars JsonSchema serialization to a JSON value is infallible for valid types");

    if let Some(obj) = value.as_object_mut() {
        obj.remove("$schema");
    }
    value
}

// ---------------------------------------------------------------------------
// Public API
// ---------------------------------------------------------------------------

/// Validates schema traits for a full inheritance chain.
///
/// `chain_schemas` is an ordered list of `(schema_id, raw_schema_content)` pairs
/// from base (index 0) to leaf (last index).  The content should be **raw**
/// (not allOf-flattened) so that `x-gts-*` extension keys are preserved.
///
/// This is the self-contained entry point used by unit tests.  The store
/// integration uses [`validate_effective_traits`] directly after collecting
/// and resolving trait schemas itself.
///
/// # Errors
/// Returns `Vec<String>` of error messages if trait values don't conform to the
/// effective trait schema or if traits are provided without trait schema.
#[cfg(test)]
pub fn validate_traits_chain(chain_schemas: &[(String, Value)]) -> Result<(), Vec<String>> {
    let mut trait_schemas = Vec::new();
    let mut merged = serde_json::Map::new();
    for (_id, content) in chain_schemas {
        collect_trait_schema_from_value(content, &mut trait_schemas);
        collect_traits_from_value(content, &mut merged);
    }
    // Dialect comes from the leaf document's `$schema`, mirroring the store path.
    // Absent (synthetic fixtures without `$schema`) falls back to the validator's
    // default draft, exactly like the rest of the crate.
    let dialect = chain_schemas
        .last()
        .and_then(|(_, content)| content.get("$schema").and_then(Value::as_str));
    validate_effective_traits(&trait_schemas, &Value::Object(merged), true, dialect)
}

/// Validates trait values against the effective trait schema built from the
/// given list of resolved trait schemas.
///
/// `resolved_trait_schemas` – `x-gts-traits-schema` values collected from the
/// chain, with any `$ref` inside them already resolved.
///
/// `merged_traits` – shallow-merged `x-gts-traits` values (rightmost wins).
///
/// When `check_unresolved` is `true`, every *required* trait-schema property
/// without a default must have a value in `merged_traits` (optional properties
/// may be left unresolved, per README §9.7.5 / OP#13); set to `false` for
/// intermediate schema validation where descendants may still supply values.
///
/// `dialect` is the host document's `$schema` URI (e.g.
/// `http://json-schema.org/draft-07/schema#`). When `Some`, it pins the JSON
/// Schema draft used to validate trait values so they are interpreted under the
/// same dialect as the rest of the type schema — necessary because the inline
/// trait fragment had its root-only `$schema` stripped when
/// embedded. When `None`, validation falls back to the validator's automatic
/// draft detection (Draft 2020-12 when no `$schema` is present), matching how
/// instance and schema validation behave elsewhere in this crate. A GTS Type
/// Schema always declares `$schema`, so the store path always passes `Some`.
///
/// # Errors
/// Returns `Vec<String>` of error messages if trait values don't conform to the
/// effective trait schema, if required traits are missing, or if traits exist
/// without a trait schema in the chain.
pub fn validate_effective_traits(
    resolved_trait_schemas: &[Value],
    merged_traits: &Value,
    check_unresolved: bool,
    dialect: Option<&str>,
) -> Result<(), Vec<String>> {
    let has_trait_values = merged_traits.as_object().is_some_and(|m| !m.is_empty());

    if resolved_trait_schemas.is_empty() {
        if has_trait_values {
            return Err(vec![format!(
                "{X_GTS_TRAITS} values provided but no {X_GTS_TRAITS_SCHEMA} is defined in the \
                 inheritance chain"
            )]);
        }
        return Ok(());
    }

    // Each x-gts-traits-schema is a JSON Schema subschema. Accepted forms are
    // an object subschema, `true`, or `false`. Validate JSON Schema integrity
    // only for object-form subschemas; the boolean forms have well-defined
    // JSON Schema semantics (true = accept anything, false = reject anything)
    // and need no further checks here.
    //
    // Note on x-gts-* keys inside an object subschema: any GTS type may be
    // referenced from another host's `x-gts-traits-schema` via `$ref`, in
    // which case the inlined body of the referenced type will contain its own
    // `x-gts-traits-schema` / `x-gts-traits` keys as ordinary JSON members.
    // To a standard JSON Schema validator these are unknown keywords (JSON
    // Schema treats unknown keys as annotations and ignores them for
    // validation), so they are inert here. This module deliberately does not
    // reject their presence — doing so would prevent the legitimate authoring
    // pattern where an existing GTS type is reused as a trait-schema source.
    for (i, ts) in resolved_trait_schemas.iter().enumerate() {
        match ts {
            Value::Bool(_) => {}
            Value::Object(_) => {
                if let Err(e) = jsonschema::validator_for(ts) {
                    return Err(vec![format!(
                        "x-gts-traits-schema[{i}] is not a valid JSON Schema: {e}"
                    )]);
                }
            }
            _ => {
                return Err(vec![format!(
                    "x-gts-traits-schema[{i}] must be an object subschema or a boolean; got {ts}"
                )]);
            }
        }
    }

    let mut effective_trait_schema = build_effective_trait_schema(resolved_trait_schemas);

    // If any subschema in the chain is the boolean `false`, the effective
    // schema is unsatisfiable. A type that carries no traits at all is still
    // valid (`false` prohibits traits, not the existence of typed descendants).
    // A type carrying any traits fails.
    if effective_schema_is_false(&effective_trait_schema) {
        if has_trait_values {
            return Err(vec![format!(
                "{X_GTS_TRAITS_SCHEMA} resolves to `false` in the chain — \
                 {X_GTS_TRAITS} values are prohibited"
            )]);
        }
        return Ok(());
    }

    // Pin the JSON Schema dialect to the host document's `$schema` so trait
    // values validate under the same draft as the rest of the type schema
    // (the dialect is set by `$schema`). The inline trait fragment had its
    // root-only `$schema` stripped when embedded, so we (re)set it from
    // the host here. When the caller supplies no dialect, we leave the schema as
    // is and let the validator detect/default the draft (Draft 2020-12), matching
    // instance/schema validation elsewhere in this crate.
    if let Some(dialect) = dialect
        && let Some(obj) = effective_trait_schema.as_object_mut()
    {
        obj.insert("$schema".to_owned(), Value::String(dialect.to_owned()));
    }

    let effective_traits = apply_defaults(&effective_trait_schema, merged_traits);

    let mut errors = match validate_traits_against_schema(
        &effective_trait_schema,
        &effective_traits,
        check_unresolved,
    ) {
        Ok(()) => Vec::new(),
        Err(e) => e,
    };

    // Enforce `x-gts-ref` on trait values. The standard
    // `jsonschema` validator ignores `x-gts-ref` as an unknown keyword, so a
    // trait value that violates the declared GTS-prefix would otherwise slip
    // through. Treat the effective trait-schema as the schema and the
    // materialized effective traits as the instance.
    let xref = crate::x_gts_ref::XGtsRefValidator::new();
    for err in xref.validate_instance(&effective_traits, &effective_trait_schema, "") {
        errors.push(format!("trait x-gts-ref: {err}"));
    }

    if errors.is_empty() {
        Ok(())
    } else {
        Err(errors)
    }
}

/// Returns true when at least one subschema along the chain is the JSON
/// boolean `false`. Under JSON Schema `allOf` semantics, `false` makes the
/// composed schema unsatisfiable; treat it as the "traits prohibited" signal.
///
/// Recursion is bounded by [`MAX_RECURSION_DEPTH`] to prevent stack overflow.
fn effective_schema_is_false(schema: &Value) -> bool {
    effective_schema_is_false_recursive(schema, 0)
}

fn effective_schema_is_false_recursive(schema: &Value, depth: usize) -> bool {
    if depth >= MAX_RECURSION_DEPTH {
        return false;
    }
    match schema {
        Value::Bool(false) => true,
        Value::Object(obj) => {
            if let Some(Value::Array(items)) = obj.get("allOf") {
                items
                    .iter()
                    .any(|item| effective_schema_is_false_recursive(item, depth + 1))
            } else {
                false
            }
        }
        _ => false,
    }
}

// ---------------------------------------------------------------------------
// Collection helpers (pub(crate) so the store can call them)
// ---------------------------------------------------------------------------

/// Recursively search a schema value for `x-gts-traits-schema` entries.
///
/// Handles both top-level and `allOf`-nested occurrences.
/// Recursion is bounded by [`MAX_RECURSION_DEPTH`] to prevent stack overflow.
pub(crate) fn collect_trait_schema_from_value(value: &Value, out: &mut Vec<Value>) {
    collect_trait_schema_recursive(value, out, 0);
}

fn collect_trait_schema_recursive(value: &Value, out: &mut Vec<Value>, depth: usize) {
    if depth >= MAX_RECURSION_DEPTH {
        return;
    }

    let Some(obj) = value.as_object() else {
        return;
    };

    if let Some(ts) = obj.get(X_GTS_TRAITS_SCHEMA) {
        out.push(ts.clone());
    }

    // Also check inside allOf items (e.g. a derived schema that is an allOf overlay)
    if let Some(Value::Array(all_of)) = obj.get("allOf") {
        for item in all_of {
            collect_trait_schema_recursive(item, out, depth + 1);
        }
    }
}

/// Recursively search a schema value for `x-gts-traits` entries and union
/// them into a single per-level trait patch.
///
/// `null` values are preserved verbatim — they carry RFC 7396 "delete this
/// key" semantics and must reach the cross-level merge step (in
/// `store::validate_schema_traits`) intact. Within a single level, multiple
/// `x-gts-traits` blocks (e.g. one inline + ones nested in `allOf` overlays)
/// are unioned with later-occurring entries winning per key. The cross-level
/// step then applies these per-level patches in chain order via RFC 7396.
///
/// Recursion is bounded by [`MAX_RECURSION_DEPTH`] to prevent stack overflow.
pub(crate) fn collect_traits_from_value(
    value: &Value,
    merged: &mut serde_json::Map<String, Value>,
) {
    collect_traits_recursive(value, merged, 0);
}

fn collect_traits_recursive(
    value: &Value,
    merged: &mut serde_json::Map<String, Value>,
    depth: usize,
) {
    if depth >= MAX_RECURSION_DEPTH {
        return;
    }

    let Some(obj) = value.as_object() else {
        return;
    };

    if let Some(Value::Object(traits)) = obj.get(X_GTS_TRAITS) {
        for (k, v) in traits {
            merged.insert(k.clone(), v.clone());
        }
    }

    if let Some(Value::Array(all_of)) = obj.get("allOf") {
        for item in all_of {
            collect_traits_recursive(item, merged, depth + 1);
        }
    }
}

/// Merge `patch` into `target` per RFC 7396 JSON Merge Patch.
///
/// Semantics:
/// - Scalar / array values replace the existing value wholesale.
/// - Objects merge recursively (keys not restated by `patch` are preserved).
/// - `null` values **delete** the corresponding key from `target`; if the
///   target had no such key the null is a no-op (the key remains absent so
///   `apply_defaults` can later substitute a `default` from the trait schema).
///
/// This is the trait-merge primitive used to compose `x-gts-traits` along the
/// `$id` chain (root → leaf).
///
/// Recursion over nested objects is bounded by [`MAX_RECURSION_DEPTH`] to
/// prevent stack overflow on deeply-nested (or maliciously crafted) trait
/// values.
pub(crate) fn merge_rfc7396_into(
    target: &mut serde_json::Map<String, Value>,
    patch: &serde_json::Map<String, Value>,
) {
    merge_rfc7396_recursive(target, patch, 0);
}

fn merge_rfc7396_recursive(
    target: &mut serde_json::Map<String, Value>,
    patch: &serde_json::Map<String, Value>,
    depth: usize,
) {
    if depth >= MAX_RECURSION_DEPTH {
        return;
    }
    for (k, v) in patch {
        match v {
            Value::Null => {
                target.remove(k);
            }
            Value::Object(patch_obj) => {
                if let Some(Value::Object(existing)) = target.get_mut(k) {
                    merge_rfc7396_recursive(existing, patch_obj, depth + 1);
                } else {
                    // Either target lacks the key or holds a non-object —
                    // RFC 7396: a new object value replaces wholesale, but
                    // inner `null`s in the patch still mean "no such key".
                    let mut fresh = serde_json::Map::new();
                    merge_rfc7396_recursive(&mut fresh, patch_obj, depth + 1);
                    target.insert(k.clone(), Value::Object(fresh));
                }
            }
            other => {
                target.insert(k.clone(), other.clone());
            }
        }
    }
}

/// Build a single effective trait schema by composing all collected trait schemas
/// using `allOf`.  When there is only one schema, return it directly.
///
/// **Note on `additionalProperties`:** When multiple trait schemas are composed
/// via `allOf`, standard JSON Schema semantics apply.  If one sub-schema sets
/// `additionalProperties: false`, properties introduced by *other* sub-schemas
/// in the same `allOf` may fail validation.  This is correct per the JSON Schema
/// specification — authors should use `additionalProperties: false` only in the
/// outermost (single) trait schema, or omit it in favour of explicit property
/// lists.
fn build_effective_trait_schema(schemas: &[Value]) -> Value {
    match schemas.len() {
        0 => Value::Object(serde_json::Map::new()),
        1 => schemas[0].clone(),
        _ => {
            let mut wrapper = serde_json::Map::new();
            wrapper.insert("type".to_owned(), Value::String("object".to_owned()));
            wrapper.insert("allOf".to_owned(), Value::Array(schemas.to_vec()));
            Value::Object(wrapper)
        }
    }
}

/// Apply JSON Schema `default` values from the effective trait schema to the
/// merged traits object for any properties that are not yet present.
///
/// Handles nested object properties recursively: if a trait property is an object
/// type with its own `properties` and `default` values, those are applied to the
/// corresponding nested object in the traits.
fn apply_defaults(trait_schema: &Value, traits: &Value) -> Value {
    apply_defaults_recursive(trait_schema, traits, 0)
}

fn apply_defaults_recursive(trait_schema: &Value, traits: &Value, depth: usize) -> Value {
    if depth >= MAX_RECURSION_DEPTH {
        return traits.clone();
    }

    let mut result = match traits {
        Value::Object(m) => m.clone(),
        _ => serde_json::Map::new(),
    };

    // Collect properties from the trait schema (may be in top-level or allOf)
    let props = collect_all_properties(trait_schema);

    for (prop_name, prop_schema) in &props {
        if let Some(prop_obj) = prop_schema.as_object() {
            if !result.contains_key(prop_name.as_str()) {
                // Property is absent — apply top-level default if present
                if let Some(default_val) = prop_obj.get("default") {
                    result.insert(prop_name.clone(), default_val.clone());
                }
            } else if prop_obj.get("type") == Some(&Value::String("object".to_owned()))
                && prop_obj.contains_key("properties")
            {
                // Property is present and is an object type with sub-properties —
                // recurse to apply nested defaults.  If the input value is a
                // non-object (e.g. a string where the schema expects an object),
                // the recursion will produce a defaulted object that replaces the
                // original value; JSON Schema validation will catch the type
                // mismatch later, so this is intentional.
                let nested = apply_defaults_recursive(
                    prop_schema,
                    result.get(prop_name.as_str()).unwrap_or(&Value::Null),
                    depth + 1,
                );
                result.insert(prop_name.clone(), nested);
            }
        }
    }

    Value::Object(result)
}

/// Collect all property definitions from a schema, handling `allOf` composition.
///
/// When the same property name appears in multiple `allOf` sub-schemas (e.g.
/// base defines `priority: {type: string}` and mid narrows to an enum), the
/// *last-seen* definition wins.  This matches the rightmost-wins semantics of
/// JSON Schema `allOf` merge and avoids duplicate "unresolved" errors.
fn collect_all_properties(schema: &Value) -> Vec<(String, Value)> {
    let mut props = Vec::new();
    collect_props_recursive(schema, &mut props, 0);
    // Deduplicate: keep last occurrence of each property name (rightmost wins)
    let mut seen = std::collections::HashSet::new();
    let mut deduped = Vec::with_capacity(props.len());
    for (name, schema) in props.into_iter().rev() {
        if seen.insert(name.clone()) {
            deduped.push((name, schema));
        }
    }
    deduped.reverse();
    deduped
}

fn collect_props_recursive(schema: &Value, props: &mut Vec<(String, Value)>, depth: usize) {
    if depth >= MAX_RECURSION_DEPTH {
        return;
    }

    let Some(obj) = schema.as_object() else {
        return;
    };

    if let Some(Value::Object(p)) = obj.get("properties") {
        for (k, v) in p {
            props.push((k.clone(), v.clone()));
        }
    }

    if let Some(Value::Array(all_of)) = obj.get("allOf") {
        for item in all_of {
            collect_props_recursive(item, props, depth + 1);
        }
    }
}

/// Collect the union of `required` property names declared at the top level or
/// within any `allOf` branch of the (effective) trait schema. Mirrors
/// [`collect_all_properties`] so completeness enforcement matches JSON Schema's
/// own `required` aggregation across the composed chain.
fn collect_all_required(schema: &Value) -> std::collections::HashSet<String> {
    let mut req = std::collections::HashSet::new();
    collect_required_recursive(schema, &mut req, 0);
    req
}

fn collect_required_recursive(
    schema: &Value,
    req: &mut std::collections::HashSet<String>,
    depth: usize,
) {
    if depth >= MAX_RECURSION_DEPTH {
        return;
    }

    let Some(obj) = schema.as_object() else {
        return;
    };

    if let Some(Value::Array(required)) = obj.get("required") {
        for item in required {
            if let Some(name) = item.as_str() {
                req.insert(name.to_owned());
            }
        }
    }

    if let Some(Value::Array(all_of)) = obj.get("allOf") {
        for item in all_of {
            collect_required_recursive(item, req, depth + 1);
        }
    }
}

/// Validate the effective traits object against the effective trait schema.
///
/// Uses the `jsonschema` crate for standard JSON Schema validation.  This
/// catches type mismatches, enum violations, `additionalProperties` errors,
/// and any other constraint issues.
///
/// Additionally checks that every *required* property defined in the trait
/// schema is resolved (has a value or default) — i.e. there are no required
/// "holes" left after applying defaults. Optional properties may be unresolved.
fn validate_traits_against_schema(
    trait_schema: &Value,
    effective_traits: &Value,
    check_unresolved: bool,
) -> Result<(), Vec<String>> {
    let mut errors = Vec::new();

    // Standard JSON Schema validation of the traits object
    match jsonschema::validator_for(trait_schema) {
        Ok(validator) => {
            for error in validator.iter_errors(effective_traits) {
                errors.push(format!("trait validation: {error}"));
            }
        }
        Err(e) => {
            errors.push(format!("failed to compile trait schema: {e}"));
        }
    }

    // Check for unresolved (missing) trait properties that have no default.
    // A property is "unresolved" if:
    // - It exists in the trait schema `properties`
    // - It has no `default`
    // - It is absent from the effective traits object
    // Skipped when check_unresolved is false (intermediate schema validation).
    if !check_unresolved {
        return if errors.is_empty() {
            Ok(())
        } else {
            Err(errors)
        };
    }

    let all_props = collect_all_properties(trait_schema);
    let required = collect_all_required(trait_schema);
    let traits_obj = effective_traits.as_object();

    for (prop_name, prop_schema) in &all_props {
        // Only *required* trait properties must be resolved. An optional
        // property left unresolved is spec-valid: the GTS spec keys completeness
        // on standard JSON Schema validation (README §9.7.5) and OP#13 requires
        // resolution of "all required trait properties" — not every declared one.
        // (Standard JSON Schema validation above already reports missing required
        // members; this loop adds a type-annotated, trait-specific message.)
        if !required.contains(prop_name.as_str()) {
            continue;
        }

        let has_value = traits_obj.is_some_and(|m| m.contains_key(prop_name.as_str()));

        let has_default = prop_schema
            .as_object()
            .is_some_and(|m| m.contains_key("default"));

        if !has_value && !has_default {
            let expected_type = prop_schema
                .as_object()
                .and_then(|m| m.get("type"))
                .and_then(Value::as_str)
                .unwrap_or("any");
            errors.push(format!(
                "trait property '{prop_name}' (type: {expected_type}) is not resolved: \
                 no value provided and no default defined in the trait schema. \
                 All traits must be resolved (via a {X_GTS_TRAITS} value in the chain \
                 or a `default` in the trait schema) on non-abstract types; otherwise \
                 mark the type abstract (x-gts-abstract: true)"
            ));
        }
    }

    if errors.is_empty() {
        Ok(())
    } else {
        Err(errors)
    }
}

// ---------------------------------------------------------------------------
// Tests
// ---------------------------------------------------------------------------

#[cfg(test)]
#[allow(clippy::unwrap_used, clippy::expect_used)]
mod tests {
    use super::*;
    use serde_json::json;

    #[test]
    fn test_no_traits_schema_passes() {
        let chain = vec![(
            "gts.x.test.base.v1~".to_owned(),
            json!({"$schema": "http://json-schema.org/draft-07/schema#", "type": "object", "properties": {"id": {"type": "string"}}}),
        )];
        assert!(validate_traits_chain(&chain).is_ok());
    }

    #[test]
    fn test_traits_without_schema_in_derived_fails() {
        let chain = vec![
            (
                "base~".to_owned(),
                json!({"$schema": "http://json-schema.org/draft-07/schema#", "type": "object", "properties": {"id": {"type": "string"}}}),
            ),
            (
                "derived~".to_owned(),
                json!({"$schema": "http://json-schema.org/draft-07/schema#",
                    "type": "object",
                    "x-gts-traits": {"retention": "P30D"}
                }),
            ),
        ];
        let err = validate_traits_chain(&chain).unwrap_err();
        assert!(
            err.iter().any(|e| e.contains("no x-gts-traits-schema")),
            "should fail when traits provided without schema: {err:?}"
        );
    }

    #[test]
    fn test_traits_without_schema_in_base_fails() {
        let chain = vec![(
            "base~".to_owned(),
            json!({"$schema": "http://json-schema.org/draft-07/schema#",
                "type": "object",
                "x-gts-traits": {"retention": "P30D"},
                "properties": {"id": {"type": "string"}}
            }),
        )];
        let err = validate_traits_chain(&chain).unwrap_err();
        assert!(
            err.iter().any(|e| e.contains("no x-gts-traits-schema")),
            "should fail when base has traits but no schema: {err:?}"
        );
    }

    #[test]
    fn test_all_traits_resolved() {
        let chain = vec![
            (
                "gts.x.test.base.v1~".to_owned(),
                json!({"$schema": "http://json-schema.org/draft-07/schema#",
                    "type": "object",
                    "x-gts-traits-schema": {
                        "type": "object",
                        "properties": {
                            "retention": {"type": "string"},
                            "topicRef": {"type": "string"}
                        }
                    }
                }),
            ),
            (
                "gts.x.test.base.v1~x.test._.derived.v1~".to_owned(),
                json!({"$schema": "http://json-schema.org/draft-07/schema#",
                    "type": "object",
                    "x-gts-traits": {
                        "retention": "P90D",
                        "topicRef": "gts.x.core.events.topic.v1~x.test._.orders.v1"
                    }
                }),
            ),
        ];
        assert!(validate_traits_chain(&chain).is_ok());
    }

    #[test]
    fn test_defaults_fill_traits() {
        let chain = vec![
            (
                "base~".to_owned(),
                json!({"$schema": "http://json-schema.org/draft-07/schema#",
                    "type": "object",
                    "x-gts-traits-schema": {
                        "type": "object",
                        "properties": {
                            "retention": {"type": "string", "default": "P30D"},
                            "topicRef": {"type": "string", "default": "default_topic"}
                        }
                    }
                }),
            ),
            (
                "derived~".to_owned(),
                json!({"$schema": "http://json-schema.org/draft-07/schema#", "type": "object"}),
            ),
        ];
        assert!(validate_traits_chain(&chain).is_ok());
    }

    #[test]
    fn test_missing_required_trait_fails() {
        let chain = vec![
            (
                "base~".to_owned(),
                json!({"$schema": "http://json-schema.org/draft-07/schema#",
                    "type": "object",
                    "x-gts-traits-schema": {
                        "type": "object",
                        "properties": {
                            "topicRef": {"type": "string"},
                            "retention": {"type": "string", "default": "P30D"}
                        },
                        "required": ["topicRef"]
                    }
                }),
            ),
            (
                "derived~".to_owned(),
                json!({"$schema": "http://json-schema.org/draft-07/schema#",
                    "type": "object",
                    "x-gts-traits": {
                        "retention": "P90D"
                    }
                }),
            ),
        ];
        let err = validate_traits_chain(&chain).unwrap_err();
        assert!(
            err.iter().any(|e| e.contains("topicRef")),
            "should mention missing topicRef: {err:?}"
        );
    }

    #[test]
    fn test_optional_unresolved_trait_passes() {
        // Spec (README §9.7.5 / OP#13): only *required* trait properties must be
        // resolved. An optional declared property left unresolved is valid — it
        // simply stays absent and standard JSON Schema validation accepts it.
        let chain = vec![(
            "base~".to_owned(),
            json!({"$schema": "http://json-schema.org/draft-07/schema#",
                "type": "object",
                "x-gts-traits-schema": {
                    "type": "object",
                    "properties": {
                        "topicRef": {"type": "string"},
                        "note": {"type": "string"}
                    },
                    "required": ["topicRef"]
                },
                "x-gts-traits": {"topicRef": "events.orders"}
            }),
        )];
        assert!(
            validate_traits_chain(&chain).is_ok(),
            "optional unresolved trait property must not fail completeness"
        );
    }

    #[test]
    fn test_wrong_type_fails() {
        let chain = vec![
            (
                "base~".to_owned(),
                json!({"$schema": "http://json-schema.org/draft-07/schema#",
                    "type": "object",
                    "x-gts-traits-schema": {
                        "type": "object",
                        "properties": {
                            "maxRetries": {"type": "integer", "minimum": 0, "default": 3}
                        }
                    }
                }),
            ),
            (
                "derived~".to_owned(),
                json!({"$schema": "http://json-schema.org/draft-07/schema#",
                    "type": "object",
                    "x-gts-traits": {
                        "maxRetries": "not_a_number"
                    }
                }),
            ),
        ];
        let err = validate_traits_chain(&chain).unwrap_err();
        assert!(!err.is_empty(), "wrong type should fail");
    }

    #[test]
    fn test_unknown_property_fails() {
        let chain = vec![
            (
                "base~".to_owned(),
                json!({"$schema": "http://json-schema.org/draft-07/schema#",
                    "type": "object",
                    "x-gts-traits-schema": {
                        "type": "object",
                        "additionalProperties": false,
                        "properties": {
                            "retention": {"type": "string", "default": "P30D"}
                        }
                    }
                }),
            ),
            (
                "derived~".to_owned(),
                json!({"$schema": "http://json-schema.org/draft-07/schema#",
                    "type": "object",
                    "x-gts-traits": {
                        "retention": "P90D",
                        "unknownTrait": "some_value"
                    }
                }),
            ),
        ];
        let err = validate_traits_chain(&chain).unwrap_err();
        assert!(
            err.iter()
                .any(|e| e.contains("additional") || e.contains("unknownTrait")),
            "unknown property should fail: {err:?}"
        );
    }

    #[test]
    fn test_override_in_chain() {
        let chain = vec![
            (
                "base~".to_owned(),
                json!({"$schema": "http://json-schema.org/draft-07/schema#",
                    "type": "object",
                    "x-gts-traits-schema": {
                        "type": "object",
                        "properties": {
                            "retention": {"type": "string"}
                        }
                    }
                }),
            ),
            (
                "mid~".to_owned(),
                json!({"$schema": "http://json-schema.org/draft-07/schema#",
                    "type": "object",
                    "x-gts-traits": {"retention": "P30D"}
                }),
            ),
            (
                "leaf~".to_owned(),
                json!({"$schema": "http://json-schema.org/draft-07/schema#",
                    "type": "object",
                    "x-gts-traits": {"retention": "P365D"}
                }),
            ),
        ];
        assert!(validate_traits_chain(&chain).is_ok());
    }

    #[test]
    fn test_both_keywords_in_same_schema() {
        let chain = vec![
            (
                "base~".to_owned(),
                json!({"$schema": "http://json-schema.org/draft-07/schema#",
                    "type": "object",
                    "x-gts-traits-schema": {
                        "type": "object",
                        "properties": {
                            "topicRef": {"type": "string"},
                            "retention": {"type": "string", "default": "P30D"}
                        }
                    }
                }),
            ),
            (
                "mid~".to_owned(),
                json!({"$schema": "http://json-schema.org/draft-07/schema#",
                    "type": "object",
                    "x-gts-traits-schema": {
                        "type": "object",
                        "properties": {
                            "auditRetention": {"type": "string", "default": "P365D"}
                        }
                    },
                    "x-gts-traits": {
                        "topicRef": "gts.x.core.events.topic.v1~x.test._.audit.v1"
                    }
                }),
            ),
        ];
        assert!(validate_traits_chain(&chain).is_ok());
    }

    #[test]
    fn test_three_level_chain_missing_in_leaf() {
        let chain = vec![
            (
                "base~".to_owned(),
                json!({"$schema": "http://json-schema.org/draft-07/schema#",
                    "type": "object",
                    "x-gts-traits-schema": {
                        "type": "object",
                        "properties": {
                            "retention": {"type": "string", "default": "P30D"}
                        }
                    }
                }),
            ),
            (
                "mid~".to_owned(),
                json!({"$schema": "http://json-schema.org/draft-07/schema#",
                    "type": "object",
                    "x-gts-traits-schema": {
                        "type": "object",
                        "properties": {
                            "priority": {"type": "string"}
                        },
                        "required": ["priority"]
                    }
                }),
            ),
            (
                "leaf~".to_owned(),
                json!({"$schema": "http://json-schema.org/draft-07/schema#",
                    "type": "object",
                    "x-gts-traits": {"retention": "P90D"}
                }),
            ),
        ];
        let err = validate_traits_chain(&chain).unwrap_err();
        assert!(
            err.iter().any(|e| e.contains("priority")),
            "should mention missing priority: {err:?}"
        );
    }

    #[test]
    fn test_enum_constraint_violation() {
        let chain = vec![
            (
                "base~".to_owned(),
                json!({"$schema": "http://json-schema.org/draft-07/schema#",
                    "type": "object",
                    "x-gts-traits-schema": {
                        "type": "object",
                        "properties": {
                            "priority": {
                                "type": "string",
                                "enum": ["low", "medium", "high", "critical"],
                                "default": "medium"
                            }
                        }
                    }
                }),
            ),
            (
                "derived~".to_owned(),
                json!({"$schema": "http://json-schema.org/draft-07/schema#",
                    "type": "object",
                    "x-gts-traits": {"priority": "ultra_high"}
                }),
            ),
        ];
        let err = validate_traits_chain(&chain).unwrap_err();
        assert!(!err.is_empty(), "enum violation should fail");
    }

    #[test]
    fn test_minimum_violation() {
        let chain = vec![
            (
                "base~".to_owned(),
                json!({"$schema": "http://json-schema.org/draft-07/schema#",
                    "type": "object",
                    "x-gts-traits-schema": {
                        "type": "object",
                        "properties": {
                            "maxRetries": {
                                "type": "integer",
                                "minimum": 0,
                                "maximum": 10,
                                "default": 3
                            }
                        }
                    }
                }),
            ),
            (
                "derived~".to_owned(),
                json!({"$schema": "http://json-schema.org/draft-07/schema#",
                    "type": "object",
                    "x-gts-traits": {"maxRetries": -1}
                }),
            ),
        ];
        let err = validate_traits_chain(&chain).unwrap_err();
        assert!(!err.is_empty(), "minimum violation should fail");
    }

    #[test]
    fn test_narrowing_valid() {
        // Base: priority is open string
        // Mid: narrows to enum, provides valid value
        let chain = vec![
            (
                "base~".to_owned(),
                json!({"$schema": "http://json-schema.org/draft-07/schema#",
                    "type": "object",
                    "x-gts-traits-schema": {
                        "type": "object",
                        "properties": {
                            "priority": {"type": "string"},
                            "retention": {"type": "string", "default": "P30D"}
                        }
                    }
                }),
            ),
            (
                "mid~".to_owned(),
                json!({"$schema": "http://json-schema.org/draft-07/schema#",
                    "type": "object",
                    "x-gts-traits-schema": {
                        "type": "object",
                        "properties": {
                            "priority": {
                                "type": "string",
                                "enum": ["low", "medium", "high", "critical"]
                            }
                        }
                    },
                    "x-gts-traits": {"priority": "high"}
                }),
            ),
        ];
        assert!(validate_traits_chain(&chain).is_ok());
    }

    #[test]
    fn test_narrowing_violation() {
        let chain = vec![
            (
                "base~".to_owned(),
                json!({"$schema": "http://json-schema.org/draft-07/schema#",
                    "type": "object",
                    "x-gts-traits-schema": {
                        "type": "object",
                        "properties": {
                            "priority": {"type": "string"},
                            "retention": {"type": "string", "default": "P30D"}
                        }
                    }
                }),
            ),
            (
                "mid~".to_owned(),
                json!({"$schema": "http://json-schema.org/draft-07/schema#",
                    "type": "object",
                    "x-gts-traits-schema": {
                        "type": "object",
                        "properties": {
                            "priority": {
                                "type": "string",
                                "enum": ["low", "medium", "high", "critical"]
                            }
                        }
                    },
                    "x-gts-traits": {"priority": "high"}
                }),
            ),
            (
                "leaf~".to_owned(),
                json!({"$schema": "http://json-schema.org/draft-07/schema#",
                    "type": "object",
                    "x-gts-traits": {"priority": "ultra_high"}
                }),
            ),
        ];
        let err = validate_traits_chain(&chain).unwrap_err();
        assert!(!err.is_empty(), "narrowing violation should fail");
    }

    #[test]
    fn test_deep_inheritance_chain() {
        // Chain near MAX_RECURSION_DEPTH — exercises recursion guard boundary
        let mut chain = vec![(
            "base~".to_owned(),
            json!({"$schema": "http://json-schema.org/draft-07/schema#",
                "type": "object",
                "x-gts-traits-schema": {
                    "type": "object",
                    "properties": {
                        "retention": {"type": "string", "default": "P30D"}
                    }
                }
            }),
        )];
        for i in 1..super::MAX_RECURSION_DEPTH {
            chain.push((
                format!("level{i}~"),
                json!({"$schema": "http://json-schema.org/draft-07/schema#", "type": "object"}),
            ));
        }
        assert!(validate_traits_chain(&chain).is_ok());
    }

    #[test]
    fn test_malformed_trait_schema_not_object() {
        // x-gts-traits-schema is a string, not an object
        let chain = vec![
            (
                "base~".to_owned(),
                json!({"$schema": "http://json-schema.org/draft-07/schema#",
                    "type": "object",
                    "x-gts-traits-schema": "not_an_object"
                }),
            ),
            (
                "derived~".to_owned(),
                json!({"$schema": "http://json-schema.org/draft-07/schema#",
                    "type": "object",
                    "x-gts-traits": {"foo": "bar"}
                }),
            ),
        ];
        // The string value should be collected but fail gracefully at validation
        let result = validate_traits_chain(&chain);
        // The trait schema "not_an_object" has no properties, so "foo" is undeclared.
        // The chain should fail because traits are provided without a valid schema.
        assert!(
            result.is_err(),
            "malformed trait schema should fail: {result:?}"
        );
    }

    #[test]
    fn test_trait_values_as_object() {
        // Trait value is a nested object, not just a primitive
        let chain = vec![
            (
                "base~".to_owned(),
                json!({"$schema": "http://json-schema.org/draft-07/schema#",
                    "type": "object",
                    "x-gts-traits-schema": {
                        "type": "object",
                        "properties": {
                            "retry": {
                                "type": "object",
                                "properties": {
                                    "maxAttempts": {"type": "integer", "default": 3},
                                    "backoff": {"type": "string", "default": "exponential"}
                                }
                            }
                        }
                    }
                }),
            ),
            (
                "derived~".to_owned(),
                json!({"$schema": "http://json-schema.org/draft-07/schema#",
                    "type": "object",
                    "x-gts-traits": {
                        "retry": {"maxAttempts": 5}
                    }
                }),
            ),
        ];
        assert!(
            validate_traits_chain(&chain).is_ok(),
            "object trait values should be accepted"
        );
    }

    #[test]
    fn test_trait_values_as_array() {
        // Trait value is an array
        let chain = vec![
            (
                "base~".to_owned(),
                json!({"$schema": "http://json-schema.org/draft-07/schema#",
                    "type": "object",
                    "x-gts-traits-schema": {
                        "type": "object",
                        "properties": {
                            "tags": {
                                "type": "array",
                                "items": {"type": "string"},
                                "default": []
                            }
                        }
                    }
                }),
            ),
            (
                "derived~".to_owned(),
                json!({"$schema": "http://json-schema.org/draft-07/schema#",
                    "type": "object",
                    "x-gts-traits": {
                        "tags": ["audit", "compliance"]
                    }
                }),
            ),
        ];
        assert!(
            validate_traits_chain(&chain).is_ok(),
            "array trait values should be accepted"
        );
    }

    #[test]
    fn test_x_gts_keys_inside_trait_schema_are_tolerated() {
        // A trait-schema may contain GTS-extension keys as ordinary members —
        // this happens when an existing GTS type (which carries its own
        // `x-gts-traits-schema` / `x-gts-traits`) is reused as a trait-schema
        // source via $ref. Standard JSON Schema treats unknown keywords as
        // annotations, so these keys are inert at validation time and must
        // not cause registration to fail.
        //
        // To isolate this property from the unrelated completeness check, the
        // trait-schema below declares only optional properties and the chain
        // supplies a matching x-gts-traits value.
        let chain = vec![(
            "base~".to_owned(),
            json!({"$schema": "http://json-schema.org/draft-07/schema#",
                "type": "object",
                "x-gts-traits-schema": {
                    "type": "object",
                    // GTS-extension keys nested here mimic a $ref'd GTS type
                    // body — they are unknown keywords to JSON Schema and
                    // must be ignored.
                    "x-gts-traits-schema": {"type": "object"},
                    "x-gts-traits": {"foo": "bar"},
                    "properties": {
                        "retention": {"type": "string"}
                    }
                },
                "x-gts-traits": {"retention": "P30D"}
            }),
        )];
        assert!(
            validate_traits_chain(&chain).is_ok(),
            "x-gts-traits / x-gts-traits-schema nested inside a trait-schema body \
             should be tolerated as unknown JSON Schema keywords"
        );
    }

    #[test]
    fn test_nested_object_defaults_applied() {
        // Trait schema has nested object with defaults — verify they are applied
        let chain = vec![
            (
                "base~".to_owned(),
                json!({"$schema": "http://json-schema.org/draft-07/schema#",
                    "type": "object",
                    "x-gts-traits-schema": {
                        "type": "object",
                        "properties": {
                            "retry": {
                                "type": "object",
                                "properties": {
                                    "maxAttempts": {"type": "integer", "default": 3},
                                    "backoff": {"type": "string", "default": "exponential"}
                                }
                            }
                        }
                    }
                }),
            ),
            (
                "derived~".to_owned(),
                json!({"$schema": "http://json-schema.org/draft-07/schema#",
                    "type": "object",
                    "x-gts-traits": {
                        "retry": {"maxAttempts": 5}
                    }
                }),
            ),
        ];
        // Should pass because nested defaults fill in the missing "backoff"
        assert!(
            validate_traits_chain(&chain).is_ok(),
            "nested defaults should fill in missing sub-properties"
        );
    }

    #[test]
    fn test_improved_error_message_includes_type() {
        let chain = vec![
            (
                "base~".to_owned(),
                json!({"$schema": "http://json-schema.org/draft-07/schema#",
                    "type": "object",
                    "x-gts-traits-schema": {
                        "type": "object",
                        "properties": {
                            "topicRef": {"type": "string"},
                            "retention": {"type": "string", "default": "P30D"}
                        },
                        "required": ["topicRef"]
                    }
                }),
            ),
            (
                "derived~".to_owned(),
                json!({"$schema": "http://json-schema.org/draft-07/schema#",
                    "type": "object",
                    "x-gts-traits": {"retention": "P90D"}
                }),
            ),
        ];
        let err = validate_traits_chain(&chain).unwrap_err();
        assert!(
            err.iter().any(|e| e.contains("type: string")),
            "error message should include expected type: {err:?}"
        );
    }

    #[test]
    fn test_empty_trait_schema_permits_any_traits() {
        // An empty x-gts-traits-schema: {} is unconstrained — any trait values pass
        let chain = vec![
            (
                "base~".to_owned(),
                json!({"$schema": "http://json-schema.org/draft-07/schema#",
                    "type": "object",
                    "x-gts-traits-schema": {}
                }),
            ),
            (
                "derived~".to_owned(),
                json!({"$schema": "http://json-schema.org/draft-07/schema#",
                    "type": "object",
                    "x-gts-traits": {"anything": "goes", "count": 42}
                }),
            ),
        ];
        assert!(
            validate_traits_chain(&chain).is_ok(),
            "empty trait schema should permit any traits"
        );
    }

    #[test]
    fn test_duplicate_property_dedup_rightmost_wins() {
        // Base defines `priority: string`, mid narrows to enum.
        // The dedup should keep the enum definition (rightmost), not report
        // "priority" as unresolved twice.
        let chain = vec![
            (
                "base~".to_owned(),
                json!({"$schema": "http://json-schema.org/draft-07/schema#",
                    "type": "object",
                    "x-gts-traits-schema": {
                        "type": "object",
                        "properties": {
                            "priority": {"type": "string"},
                            "retention": {"type": "string", "default": "P30D"}
                        }
                    }
                }),
            ),
            (
                "mid~".to_owned(),
                json!({"$schema": "http://json-schema.org/draft-07/schema#",
                    "type": "object",
                    "x-gts-traits-schema": {
                        "type": "object",
                        "properties": {
                            "priority": {
                                "type": "string",
                                "enum": ["low", "medium", "high"]
                            }
                        }
                    }
                }),
            ),
            (
                "leaf~".to_owned(),
                json!({"$schema": "http://json-schema.org/draft-07/schema#",
                    "type": "object",
                    "x-gts-traits": {"priority": "high"}
                }),
            ),
        ];
        // Should pass: priority is provided, retention has default
        assert!(
            validate_traits_chain(&chain).is_ok(),
            "dedup should keep rightmost definition"
        );

        // Verify the unresolved-property check dedups: priority is declared in
        // two layers but the trait-specific "is not resolved" message must be
        // emitted only once (not per declaration). priority is required here so
        // the completeness check fires.
        let chain_missing = vec![
            (
                "base~".to_owned(),
                json!({"$schema": "http://json-schema.org/draft-07/schema#",
                    "type": "object",
                    "x-gts-traits-schema": {
                        "type": "object",
                        "properties": {
                            "priority": {"type": "string"},
                            "retention": {"type": "string", "default": "P30D"}
                        },
                        "required": ["priority"]
                    }
                }),
            ),
            (
                "mid~".to_owned(),
                json!({"$schema": "http://json-schema.org/draft-07/schema#",
                    "type": "object",
                    "x-gts-traits-schema": {
                        "type": "object",
                        "properties": {
                            "priority": {
                                "type": "string",
                                "enum": ["low", "medium", "high"]
                            }
                        }
                    }
                }),
            ),
            (
                "leaf~".to_owned(),
                json!({"$schema": "http://json-schema.org/draft-07/schema#", "type": "object"}),
            ),
        ];
        let err = validate_traits_chain(&chain_missing).unwrap_err();
        // Isolate the manual completeness message (the standard JSON Schema
        // validator separately reports the missing `required` member).
        let unresolved_priority: Vec<_> = err
            .iter()
            .filter(|e| e.contains("priority") && e.contains("is not resolved"))
            .collect();
        assert_eq!(
            unresolved_priority.len(),
            1,
            "priority should be reported as unresolved exactly once, got: {unresolved_priority:?}"
        );
    }

    #[test]
    fn test_invalid_trait_schema_caught_early() {
        // x-gts-traits-schema with an invalid "type" value should fail early
        // with a clear message about being an invalid JSON Schema
        let chain = vec![(
            "base~".to_owned(),
            json!({"$schema": "http://json-schema.org/draft-07/schema#",
                "type": "object",
                "x-gts-traits-schema": {
                    "type": "invalid_type_value"
                }
            }),
        )];
        let err = validate_traits_chain(&chain).unwrap_err();
        assert!(
            err.iter()
                .any(|e| e.contains("not a valid JSON Schema") || e.contains("failed to compile")),
            "should report invalid JSON Schema early: {err:?}"
        );
    }

    #[test]
    fn test_chain_default_leaf_wins_over_ancestor() {
        // Three-level chain — base, mid, leaf — each redeclares the same trait
        // property's `default` to a different value. No x-gts-traits is supplied
        // anywhere in the chain. Materialization must pick the LEAF-most default,
        // because (a) defaults are JSON Schema annotations that don't participate
        // in narrowing and (b) `collect_all_properties` dedup keeps the last
        // occurrence along the root→leaf-ordered `allOf`.
        let base_ts = json!({"$schema": "http://json-schema.org/draft-07/schema#",
            "type": "object",
            "properties": {
                "retention": {"type": "string", "default": "P30D"}
            }
        });
        let mid_ts = json!({"$schema": "http://json-schema.org/draft-07/schema#",
            "type": "object",
            "properties": {
                "retention": {"type": "string", "default": "P90D"}
            }
        });
        let leaf_ts = json!({"$schema": "http://json-schema.org/draft-07/schema#",
            "type": "object",
            "properties": {
                "retention": {"type": "string", "default": "P365D"}
            }
        });

        let effective = build_effective_trait_schema(&[base_ts, mid_ts, leaf_ts]);
        let materialized = apply_defaults(&effective, &Value::Object(serde_json::Map::new()));

        let retention = materialized
            .as_object()
            .and_then(|m| m.get("retention"))
            .and_then(Value::as_str)
            .expect("retention should be present after materialization");
        assert_eq!(
            retention, "P365D",
            "leaf-most default must win; got {retention}"
        );
    }

    #[test]
    fn test_chain_default_explicit_value_wins_over_defaults() {
        // Same 3-level chain as above, but mid supplies an explicit value via
        // x-gts-traits. After RFC 7396 chain merge, retention is set; the
        // materialization step must NOT clobber it with the leaf's default.
        let base_ts = json!({"$schema": "http://json-schema.org/draft-07/schema#",
            "type": "object",
            "properties": {
                "retention": {"type": "string", "default": "P30D"}
            }
        });
        let mid_ts = json!({"$schema": "http://json-schema.org/draft-07/schema#",
            "type": "object",
            "properties": {
                "retention": {"type": "string", "default": "P90D"}
            }
        });
        let leaf_ts = json!({"$schema": "http://json-schema.org/draft-07/schema#",
            "type": "object",
            "properties": {
                "retention": {"type": "string", "default": "P365D"}
            }
        });

        let effective = build_effective_trait_schema(&[base_ts, mid_ts, leaf_ts]);
        let mut merged = serde_json::Map::new();
        merged.insert("retention".to_owned(), Value::String("P42D".to_owned()));
        let materialized = apply_defaults(&effective, &Value::Object(merged));

        let retention = materialized
            .as_object()
            .and_then(|m| m.get("retention"))
            .and_then(Value::as_str)
            .expect("retention should be present after materialization");
        assert_eq!(
            retention, "P42D",
            "explicit chain-merged value must override all defaults; got {retention}"
        );
    }

    #[test]
    fn test_chain_default_null_delete_restores_leaf_default() {
        // Chain where ancestor sets the value and descendant deletes it via
        // RFC 7396 null. After the cross-level merge the key is absent;
        // materialization should fill it from the leaf-most default declaration.
        // This is the "null reverts to the schema default" path documented for
        // the merge strategy.
        let base_ts = json!({"$schema": "http://json-schema.org/draft-07/schema#",
            "type": "object",
            "properties": {
                "retention": {"type": "string", "default": "P30D"}
            }
        });
        let leaf_ts = json!({"$schema": "http://json-schema.org/draft-07/schema#",
            "type": "object",
            "properties": {
                "retention": {"type": "string", "default": "P365D"}
            }
        });

        // Simulate chain merge: base sets retention=P7D, leaf deletes via null
        // → merged is empty. The patches are `x-gts-traits` value objects, which
        // never carry `$schema`.
        let mut merged = serde_json::Map::new();
        merge_rfc7396_into(
            &mut merged,
            json!({"retention": "P7D"}).as_object().unwrap(),
        );
        merge_rfc7396_into(&mut merged, json!({"retention": null}).as_object().unwrap());
        assert!(
            !merged.contains_key("retention"),
            "null patch should remove the key from merged"
        );

        let effective = build_effective_trait_schema(&[base_ts, leaf_ts]);
        let materialized = apply_defaults(&effective, &Value::Object(merged));

        let retention = materialized
            .as_object()
            .and_then(|m| m.get("retention"))
            .and_then(Value::as_str)
            .expect("retention should be restored from the leaf default");
        assert_eq!(
            retention, "P365D",
            "after null delete, materialization must use the leaf-most default; got {retention}"
        );
    }
}

#[cfg(test)]
#[allow(clippy::unwrap_used, clippy::expect_used)]
mod inline_traits_schema_tests {
    use super::*;
    use crate::gts::GtsInstanceId;
    use schemars::JsonSchema;

    /// Recursively collect every `$ref` string found anywhere in the value.
    fn collect_refs(v: &Value, out: &mut Vec<String>) {
        match v {
            Value::Object(map) => {
                if let Some(Value::String(r)) = map.get("$ref") {
                    out.push(r.clone());
                }
                for val in map.values() {
                    collect_refs(val, out);
                }
            }
            Value::Array(arr) => {
                for val in arr {
                    collect_refs(val, out);
                }
            }
            _ => {}
        }
    }

    #[derive(JsonSchema)]
    #[allow(dead_code)]
    enum SeverityLevel {
        Low,
        High,
    }

    #[derive(JsonSchema)]
    #[allow(dead_code)]
    struct EnumFieldTraits {
        level: SeverityLevel,
    }

    /// A non-primitive field (here an enum) must be inlined into the embedded
    /// fragment, not left as a `$ref` into a `$defs` block that the fragment
    /// does not carry. Otherwise `x-gts-traits-schema` is structurally broken
    /// and fails when a JSON Schema validator tries to resolve the dangling ref.
    #[test]
    fn enum_field_is_inlined_with_no_dangling_refs() {
        let schema = inline_traits_schema_of::<EnumFieldTraits>();

        // The embedded fragment must be self-contained: no $defs block...
        assert!(
            schema.get("$defs").is_none(),
            "embedded fragment must not carry a $defs block: {schema}"
        );
        // ...and therefore no $ref anywhere pointing into one.
        let mut refs = Vec::new();
        collect_refs(&schema, &mut refs);
        assert!(
            refs.is_empty(),
            "embedded fragment has dangling refs: {refs:?} in {schema}"
        );

        // The enum's variants must actually be present inline.
        let serialized = schema.to_string();
        assert!(
            serialized.contains("Low") && serialized.contains("High"),
            "enum variants should be inlined into the fragment: {schema}"
        );
    }

    #[derive(JsonSchema)]
    #[allow(dead_code)]
    struct InstanceIdTraits {
        topic_ref: GtsInstanceId,
    }

    /// Regression: the canonical `GtsInstanceId` representation (its inline
    /// `x-gts-ref` body) must survive, with no dangling ref left behind.
    #[test]
    fn gts_instance_id_field_keeps_canonical_inline_form() {
        let schema = inline_traits_schema_of::<InstanceIdTraits>();

        let mut refs = Vec::new();
        collect_refs(&schema, &mut refs);
        assert!(
            refs.is_empty(),
            "unexpected dangling refs: {refs:?} in {schema}"
        );

        let prop = &schema["properties"]["topic_ref"];
        assert_eq!(prop["type"], "string");
        assert_eq!(prop["format"], "gts-instance-id");
        assert_eq!(prop["x-gts-ref"], "gts.*");
    }
}