delaunay 0.8.0

D-dimensional Delaunay triangulations and convex hulls in Rust, with exact predicates, deterministic degeneracy handling, explicit topology validation, and bistellar flips for finite point sets.
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
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
1979
1980
1981
1982
1983
1984
1985
1986
1987
1988
1989
1990
1991
1992
1993
1994
1995
1996
1997
1998
1999
2000
2001
2002
2003
2004
2005
2006
2007
2008
2009
2010
2011
2012
2013
2014
2015
2016
2017
2018
2019
2020
2021
2022
2023
2024
2025
2026
2027
2028
2029
2030
2031
2032
2033
2034
2035
2036
2037
2038
2039
2040
2041
2042
2043
2044
2045
2046
2047
2048
2049
2050
2051
2052
2053
2054
2055
2056
2057
2058
2059
2060
2061
2062
2063
2064
2065
2066
2067
2068
2069
2070
2071
2072
2073
2074
2075
2076
2077
2078
2079
2080
2081
2082
2083
2084
2085
2086
2087
2088
2089
2090
2091
2092
2093
2094
2095
2096
2097
2098
2099
2100
2101
2102
2103
2104
2105
2106
2107
2108
2109
2110
2111
2112
2113
2114
2115
2116
2117
2118
2119
2120
2121
2122
2123
2124
2125
2126
2127
2128
2129
2130
2131
2132
2133
2134
2135
2136
2137
2138
2139
2140
2141
2142
2143
2144
2145
2146
2147
2148
2149
2150
2151
2152
2153
2154
2155
2156
2157
2158
2159
2160
2161
2162
2163
2164
2165
2166
2167
2168
2169
2170
2171
2172
2173
2174
2175
2176
2177
2178
2179
2180
2181
2182
2183
2184
2185
2186
2187
2188
2189
2190
2191
2192
2193
2194
2195
2196
2197
2198
2199
2200
2201
2202
2203
2204
2205
2206
2207
2208
2209
2210
2211
2212
2213
2214
2215
2216
2217
2218
2219
2220
2221
2222
2223
2224
2225
2226
2227
2228
2229
2230
2231
2232
2233
2234
2235
2236
2237
2238
2239
2240
2241
2242
2243
2244
2245
2246
2247
2248
2249
2250
2251
2252
2253
2254
2255
2256
2257
2258
2259
2260
2261
2262
2263
2264
2265
2266
2267
2268
2269
2270
2271
2272
2273
2274
2275
2276
2277
2278
2279
2280
2281
2282
2283
2284
2285
2286
2287
2288
2289
2290
2291
2292
2293
2294
2295
2296
2297
2298
2299
2300
2301
2302
2303
2304
2305
2306
2307
2308
2309
2310
2311
2312
2313
2314
2315
2316
2317
2318
2319
2320
2321
2322
2323
2324
2325
2326
2327
2328
2329
2330
2331
2332
2333
2334
2335
2336
2337
2338
2339
2340
2341
2342
2343
2344
2345
2346
2347
2348
2349
2350
2351
2352
2353
2354
2355
2356
2357
2358
2359
2360
2361
2362
2363
2364
2365
2366
2367
2368
2369
2370
2371
2372
2373
2374
2375
2376
2377
2378
2379
2380
2381
2382
2383
2384
2385
2386
2387
2388
2389
2390
2391
2392
2393
2394
2395
2396
2397
2398
2399
2400
2401
2402
2403
2404
2405
2406
2407
2408
2409
2410
2411
2412
2413
2414
2415
2416
2417
2418
2419
2420
2421
2422
2423
2424
2425
2426
2427
2428
2429
2430
2431
2432
2433
2434
2435
2436
2437
2438
2439
2440
2441
2442
2443
2444
2445
2446
2447
2448
2449
2450
2451
2452
2453
2454
2455
2456
2457
2458
2459
2460
2461
2462
2463
2464
2465
2466
2467
2468
2469
2470
2471
2472
2473
2474
2475
2476
2477
2478
2479
2480
2481
2482
2483
2484
2485
2486
2487
2488
2489
2490
2491
2492
2493
2494
2495
2496
2497
2498
2499
2500
2501
2502
2503
2504
2505
2506
2507
2508
2509
2510
2511
2512
2513
2514
2515
2516
2517
2518
2519
2520
2521
2522
2523
2524
2525
2526
2527
2528
2529
2530
2531
2532
2533
2534
2535
2536
2537
2538
2539
2540
2541
2542
2543
2544
2545
2546
2547
2548
2549
2550
2551
2552
2553
2554
2555
2556
2557
2558
2559
2560
2561
2562
2563
2564
2565
2566
2567
2568
2569
2570
2571
2572
2573
2574
2575
2576
2577
2578
2579
2580
2581
2582
2583
2584
2585
2586
2587
2588
2589
2590
2591
2592
2593
2594
2595
2596
2597
2598
2599
2600
2601
2602
2603
2604
2605
2606
2607
2608
2609
2610
2611
2612
2613
2614
2615
2616
2617
2618
2619
2620
2621
2622
2623
2624
2625
2626
2627
2628
2629
2630
2631
2632
2633
2634
2635
2636
2637
2638
2639
2640
2641
2642
2643
2644
2645
2646
2647
2648
2649
2650
2651
2652
2653
2654
2655
2656
2657
2658
2659
2660
2661
2662
2663
2664
2665
2666
2667
2668
2669
2670
2671
2672
2673
2674
2675
2676
2677
2678
2679
2680
2681
2682
2683
2684
2685
2686
2687
2688
2689
2690
2691
2692
2693
2694
2695
2696
2697
2698
2699
2700
2701
2702
2703
2704
2705
2706
2707
2708
2709
2710
2711
2712
2713
2714
2715
2716
2717
2718
//! Realized-geometry validation for generic triangulations.
//!
//! This module owns Level 4 validation for generic [`Triangulation`](crate::Triangulation):
//! after the TDS and topology layers have certified a valid oriented simplicial
//! complex, the realization layer verifies that maximal simplices are nondegenerate
//! and intersect only in their shared faces in the topology's active coordinate chart.

#![forbid(unsafe_code)]

use core::ops::ControlFlow;

use crate::core::collections::{
    FastHashSet, MAX_PRACTICAL_DIMENSION_SIZE, SimplexVertexKeyBuffer, SimplexVertexUuidBuffer,
    SmallBuffer,
};
use crate::core::simplex::Simplex;
use crate::core::tds::{InvariantError, InvariantKind, SimplexKey, Tds, TdsError, VertexKey};
use crate::core::traits::data_type::DataType;
use crate::core::triangulation::Triangulation;
use crate::core::validation::TriangulationValidationError;
use crate::geometry::kernel::Kernel;
use crate::geometry::point::Point;
use crate::geometry::predicates::Orientation;
use crate::geometry::realization::{
    LabeledSimplexRealization, LabeledSimplexRealizationError, PeriodicSimplexSpanError,
    SimplexIntersectionFailure, axis_aligned_bounding_boxes_overlap, coordinate_range_for_axis,
    try_periodic_simplex_span, validate_simplex_realizations_intersect_only_in_shared_faces,
};
use crate::geometry::robust_predicates::robust_orientation;
use crate::geometry::traits::coordinate::{
    CoordinateConversionError, CoordinateValidationError, InvalidCoordinateValue,
};
use crate::topology::traits::global_topology_model::{
    GlobalTopologyModel, GlobalTopologyModelError,
};
use crate::topology::traits::topological_space::TopologyKind;
use num_traits::ToPrimitive;
use thiserror::Error;
use uuid::Uuid;

/// Key- and UUID-based snapshot of one realized simplex.
#[derive(Clone, Debug, Eq, PartialEq)]
pub struct TriangulationRealizationSimplexDetail {
    /// Simplex key at validation time.
    pub key: SimplexKey,
    /// Simplex UUID at validation time.
    pub uuid: Uuid,
    /// Vertex keys stored by the simplex at validation time.
    pub vertices: SimplexVertexKeyBuffer,
    /// Vertex UUIDs stored by the simplex at validation time.
    pub vertex_uuids: SimplexVertexUuidBuffer,
}

/// Key- and UUID-based snapshot of one realized simplex pair.
#[derive(Clone, Debug, Eq, PartialEq)]
pub struct TriangulationRealizationSimplexPairDetail {
    /// First simplex in the pair.
    pub first_simplex: TriangulationRealizationSimplexDetail,
    /// Second simplex in the pair.
    pub second_simplex: TriangulationRealizationSimplexDetail,
}

/// Detailed witness for an illegal realized-simplex intersection.
#[derive(Clone, Debug, Eq, PartialEq)]
pub struct TriangulationRealizationIntersectionDetail {
    /// First simplex in the violating pair.
    pub first_simplex: TriangulationRealizationSimplexDetail,
    /// Second simplex in the violating pair.
    pub second_simplex: TriangulationRealizationSimplexDetail,
    /// Vertices shared by both simplices.
    pub shared_vertices: SimplexVertexKeyBuffer,
    /// UUIDs of vertices shared by both simplices.
    pub shared_vertex_uuids: SimplexVertexUuidBuffer,
    /// First-simplex vertices with positive barycentric weight at the witness.
    pub first_only_witness_vertices: SimplexVertexKeyBuffer,
    /// UUIDs of first-simplex vertices with positive barycentric weight at the witness.
    pub first_only_witness_vertex_uuids: SimplexVertexUuidBuffer,
    /// Second-simplex vertices with positive barycentric weight at the witness.
    pub second_only_witness_vertices: SimplexVertexKeyBuffer,
    /// UUIDs of second-simplex vertices with positive barycentric weight at the witness.
    pub second_only_witness_vertex_uuids: SimplexVertexUuidBuffer,
}

/// Invalid periodic-domain period observed during Level 4 realization validation.
#[derive(Clone, Debug, Error, PartialEq)]
#[non_exhaustive]
pub enum PeriodicDomainPeriodError {
    /// A period was NaN or infinite.
    #[error("non-finite periodic domain period at axis {axis}: {period}")]
    NonFinitePeriod {
        /// Periodic axis with the invalid period.
        axis: usize,
        /// Classified invalid period value.
        period: InvalidCoordinateValue,
    },
    /// A finite period was zero or negative.
    #[error("non-positive periodic domain period at axis {axis}: {period}")]
    NonPositivePeriod {
        /// Periodic axis with the invalid period.
        axis: usize,
        /// Raw finite non-positive period.
        period: f64,
    },
}

impl From<PeriodicSimplexSpanError> for PeriodicDomainPeriodError {
    fn from(source: PeriodicSimplexSpanError) -> Self {
        match source {
            PeriodicSimplexSpanError::NonFinitePeriod { axis, period } => {
                Self::NonFinitePeriod { axis, period }
            }
            PeriodicSimplexSpanError::NonPositivePeriod { axis, period } => {
                Self::NonPositivePeriod { axis, period }
            }
        }
    }
}

/// Errors returned by realized-geometry validation (Level 4).
///
/// This error type is independent of the Delaunay empty-circumsphere predicate:
/// it certifies that the generic triangulation has a valid realization
/// in the topology's supported coordinate chart before any Delaunay-specific
/// predicate is evaluated.
#[derive(Clone, Debug, Error, PartialEq)]
#[non_exhaustive]
pub enum TriangulationRealizationValidationError {
    /// Lower-layer element or TDS structural validation failed (Levels 1-2).
    #[error(transparent)]
    Tds(Box<TdsError>),

    /// Lower-layer topology validation failed (Level 3).
    #[error(transparent)]
    Triangulation(Box<TriangulationValidationError>),

    /// Realized-overlap validation is not yet defined for this topology model.
    #[error(
        "realization validation is unsupported for {topology:?} topology in dimension {dimension}"
    )]
    UnsupportedTopology {
        /// Topology kind configured on the triangulation.
        topology: TopologyKind,
        /// Const-generic coordinate dimension.
        dimension: usize,
    },

    /// Topology-specific coordinate lifting failed while preparing a realized simplex.
    #[error(
        "topology-specific lifting failed for simplex {simplex_uuid} (key {simplex_key:?}), vertex {vertex_key:?}: {source}"
    )]
    TopologyLifting {
        /// Simplex whose coordinates were being lifted.
        simplex_key: SimplexKey,
        /// UUID of the simplex whose coordinates were being lifted.
        simplex_uuid: Uuid,
        /// Vertex whose point triggered the lifting failure.
        vertex_key: VertexKey,
        /// UUID of the vertex whose point triggered the lifting failure.
        vertex_uuid: Uuid,
        /// Underlying topology model failure.
        #[source]
        source: GlobalTopologyModelError,
    },

    /// A simplex realization reused a vertex label.
    #[error(
        "simplex {simplex_uuid} (key {simplex_key:?}) has duplicate realization label {vertex_key:?} ({vertex_uuid}) at indices {first_index} and {duplicate_index}"
    )]
    DuplicateSimplexRealizationLabel {
        /// Key of the simplex with duplicate labels.
        simplex_key: SimplexKey,
        /// UUID of the simplex with duplicate labels.
        simplex_uuid: Uuid,
        /// Vertex-level diagnostic details for the malformed simplex.
        detail: Box<TriangulationRealizationSimplexDetail>,
        /// Duplicated vertex key.
        vertex_key: VertexKey,
        /// UUID of the duplicated vertex.
        vertex_uuid: Uuid,
        /// First realization slot containing the label.
        first_index: usize,
        /// Later realization slot containing the same label.
        duplicate_index: usize,
    },

    /// A simplex has exactly zero orientation and therefore zero D-volume.
    #[error("simplex {simplex_uuid} (key {simplex_key:?}) is degenerate in dimension {dimension}")]
    DegenerateSimplex {
        /// Key of the degenerate simplex.
        simplex_key: SimplexKey,
        /// UUID of the degenerate simplex.
        simplex_uuid: Uuid,
        /// Vertex-level diagnostic details for the degenerate simplex.
        detail: Box<TriangulationRealizationSimplexDetail>,
        /// Const-generic coordinate dimension.
        dimension: usize,
    },

    /// A simplex has negative orientation instead of the canonical positive sign.
    #[error(
        "simplex {simplex_uuid} (key {simplex_key:?}) has negative orientation in dimension {dimension}"
    )]
    NegativeSimplexOrientation {
        /// Key of the negatively oriented simplex.
        simplex_key: SimplexKey,
        /// UUID of the negatively oriented simplex.
        simplex_uuid: Uuid,
        /// Vertex-level diagnostic details for the negatively oriented simplex.
        detail: Box<TriangulationRealizationSimplexDetail>,
        /// Const-generic coordinate dimension.
        dimension: usize,
    },

    /// Coordinate validation failed while preparing an exact predicate input.
    #[error(
        "coordinate validation failed for simplex {simplex_uuid} (key {simplex_key:?}), vertex {vertex_key:?}: {source}"
    )]
    CoordinateValidation {
        /// Simplex whose coordinates were being validated.
        simplex_key: SimplexKey,
        /// UUID of the simplex whose coordinates were being validated.
        simplex_uuid: Uuid,
        /// Vertex whose point triggered the validation failure.
        vertex_key: VertexKey,
        /// UUID of the vertex whose point triggered the validation failure.
        vertex_uuid: Uuid,
        /// Underlying coordinate validation failure.
        #[source]
        source: CoordinateValidationError,
    },

    /// The exact orientation predicate failed for a simplex.
    #[error(
        "orientation predicate failed for simplex {simplex_uuid} (key {simplex_key:?}): {source}"
    )]
    PredicateFailed {
        /// Simplex whose orientation predicate failed.
        simplex_key: SimplexKey,
        /// UUID of the simplex whose orientation predicate failed.
        simplex_uuid: Uuid,
        /// Vertex-level diagnostic details for the simplex.
        detail: Box<TriangulationRealizationSimplexDetail>,
        /// Underlying coordinate conversion failure from the predicate boundary.
        #[source]
        source: CoordinateConversionError,
    },

    /// Exact rational barycentric construction found a singular simplex basis.
    #[error(
        "simplex {simplex_uuid} (key {simplex_key:?}) has a singular barycentric basis in dimension {dimension}"
    )]
    SingularBarycentricBasis {
        /// Simplex whose basis was singular.
        simplex_key: SimplexKey,
        /// UUID of the simplex whose basis was singular.
        simplex_uuid: Uuid,
        /// Vertex-level diagnostic details for the singular simplex.
        detail: Box<TriangulationRealizationSimplexDetail>,
        /// Const-generic coordinate dimension.
        dimension: usize,
    },

    /// Two maximal simplices intersect beyond the face spanned by their shared vertices.
    #[error(
        "simplices {first_simplex_uuid} (key {first_simplex_key:?}) and {second_simplex_uuid} (key {second_simplex_key:?}) intersect outside their shared face"
    )]
    SimplexIntersectionOutsideSharedFace {
        /// Key of the first offending simplex.
        first_simplex_key: SimplexKey,
        /// UUID of the first offending simplex.
        first_simplex_uuid: Uuid,
        /// Key of the second offending simplex.
        second_simplex_key: SimplexKey,
        /// UUID of the second offending simplex.
        second_simplex_uuid: Uuid,
        /// Vertex-level diagnostic details for the illegal intersection.
        detail: Box<TriangulationRealizationIntersectionDetail>,
    },

    /// A lifted periodic simplex spans at least one full period along an axis.
    ///
    /// Such a simplex cannot be certified as injective in one affine covering
    /// chart, so the quotient realization is invalid before pairwise overlap
    /// checks run.
    #[error(
        "simplex {simplex_uuid} (key {simplex_key:?}) spans {span} along periodic axis {axis}, but the period is {period}"
    )]
    PeriodicSimplexSpansDomain {
        /// Key of the offending simplex.
        simplex_key: SimplexKey,
        /// UUID of the offending simplex.
        simplex_uuid: Uuid,
        /// Vertex-level diagnostic details for the offending simplex.
        detail: Box<TriangulationRealizationSimplexDetail>,
        /// Periodic axis whose lifted span is too wide.
        axis: usize,
        /// Lifted coordinate span along `axis`.
        span: f64,
        /// Fundamental-domain period along `axis`.
        period: f64,
    },

    /// A periodic domain period was invalid while checking realized geometry.
    #[error(
        "invalid periodic domain period while validating simplex {simplex_uuid} (key {simplex_key:?}): {source}"
    )]
    InvalidPeriodicDomainPeriod {
        /// Key of the simplex being checked.
        simplex_key: SimplexKey,
        /// UUID of the simplex being checked.
        simplex_uuid: Uuid,
        /// Vertex-level diagnostic details for the simplex being checked.
        detail: Box<TriangulationRealizationSimplexDetail>,
        /// Underlying invalid-period error.
        #[source]
        source: PeriodicDomainPeriodError,
    },

    /// Periodic translate enumeration would require shifts outside the supported range.
    #[error(
        "periodic translate range for simplices {first_simplex_uuid} (key {first_simplex_key:?}) and {second_simplex_uuid} (key {second_simplex_key:?}) on axis {axis} exceeds i32 shift bounds: lower {lower_bound}, upper {upper_bound}"
    )]
    PeriodicTranslateRangeOverflow {
        /// Key of the first simplex in the pair.
        first_simplex_key: SimplexKey,
        /// UUID of the first simplex in the pair.
        first_simplex_uuid: Uuid,
        /// Key of the second simplex in the pair.
        second_simplex_key: SimplexKey,
        /// UUID of the second simplex in the pair.
        second_simplex_uuid: Uuid,
        /// Vertex-level diagnostic details for the pair.
        detail: Box<TriangulationRealizationSimplexPairDetail>,
        /// Periodic axis whose shift range overflowed.
        axis: usize,
        /// Lower floating-point shift bound before integer conversion.
        lower_bound: f64,
        /// Upper floating-point shift bound before integer conversion.
        upper_bound: f64,
    },

    /// A higher validation layer unexpectedly surfaced while running Level 4 validation.
    #[error("unexpected {kind:?} validation error while validating Level 4 realization: {source}")]
    UnexpectedValidationLayer {
        /// Validation layer that leaked into the realization boundary.
        kind: InvariantKind,
        /// Original typed validation error.
        #[source]
        source: Box<InvariantError>,
    },
}

impl From<TdsError> for TriangulationRealizationValidationError {
    fn from(source: TdsError) -> Self {
        Self::Tds(Box::new(source))
    }
}

impl From<TriangulationValidationError> for TriangulationRealizationValidationError {
    fn from(source: TriangulationValidationError) -> Self {
        Self::Triangulation(Box::new(source))
    }
}

/// Discriminant for compact Level 4 realized-geometry validation summaries.
#[derive(Clone, Copy, Debug, Eq, PartialEq)]
#[non_exhaustive]
pub enum TriangulationRealizationValidationErrorKind {
    /// Lower-layer TDS validation failed.
    Tds,
    /// Lower-layer topology validation failed.
    Triangulation,
    /// The topology is not currently supported by realization validation.
    UnsupportedTopology,
    /// Topology-specific coordinate lifting failed.
    TopologyLifting,
    /// A simplex realization reused a vertex label.
    DuplicateSimplexRealizationLabel,
    /// A simplex has zero D-volume.
    DegenerateSimplex,
    /// A simplex has negative orientation instead of the canonical positive sign.
    NegativeSimplexOrientation,
    /// Coordinate validation failed at the predicate boundary.
    CoordinateValidation,
    /// The robust orientation predicate failed.
    PredicateFailed,
    /// Exact barycentric coordinates could not be computed.
    SingularBarycentricBasis,
    /// Two simplices overlap outside their shared face.
    SimplexIntersectionOutsideSharedFace,
    /// A periodic simplex spans at least one full domain period.
    PeriodicSimplexSpansDomain,
    /// A periodic domain period was invalid.
    InvalidPeriodicDomainPeriod,
    /// Periodic translate enumeration exceeded supported shift bounds.
    PeriodicTranslateRangeOverflow,
    /// A higher validation layer unexpectedly surfaced during realization validation.
    UnexpectedValidationLayer,
}

impl From<&TriangulationRealizationValidationError>
    for TriangulationRealizationValidationErrorKind
{
    fn from(source: &TriangulationRealizationValidationError) -> Self {
        match source {
            TriangulationRealizationValidationError::Tds(_) => Self::Tds,
            TriangulationRealizationValidationError::Triangulation(_) => Self::Triangulation,
            TriangulationRealizationValidationError::UnsupportedTopology { .. } => {
                Self::UnsupportedTopology
            }
            TriangulationRealizationValidationError::TopologyLifting { .. } => {
                Self::TopologyLifting
            }
            TriangulationRealizationValidationError::DuplicateSimplexRealizationLabel {
                ..
            } => Self::DuplicateSimplexRealizationLabel,
            TriangulationRealizationValidationError::DegenerateSimplex { .. } => {
                Self::DegenerateSimplex
            }
            TriangulationRealizationValidationError::NegativeSimplexOrientation { .. } => {
                Self::NegativeSimplexOrientation
            }
            TriangulationRealizationValidationError::CoordinateValidation { .. } => {
                Self::CoordinateValidation
            }
            TriangulationRealizationValidationError::PredicateFailed { .. } => {
                Self::PredicateFailed
            }
            TriangulationRealizationValidationError::SingularBarycentricBasis { .. } => {
                Self::SingularBarycentricBasis
            }
            TriangulationRealizationValidationError::SimplexIntersectionOutsideSharedFace {
                ..
            } => Self::SimplexIntersectionOutsideSharedFace,
            TriangulationRealizationValidationError::PeriodicSimplexSpansDomain { .. } => {
                Self::PeriodicSimplexSpansDomain
            }
            TriangulationRealizationValidationError::InvalidPeriodicDomainPeriod { .. } => {
                Self::InvalidPeriodicDomainPeriod
            }
            TriangulationRealizationValidationError::PeriodicTranslateRangeOverflow { .. } => {
                Self::PeriodicTranslateRangeOverflow
            }
            TriangulationRealizationValidationError::UnexpectedValidationLayer { .. } => {
                Self::UnexpectedValidationLayer
            }
        }
    }
}

/// Structured Level 4 realization validation report.
///
/// This report is the diagnostic counterpart to
/// [`Triangulation::is_valid_realization`]. The fast-fail method returns the
/// first invalid realization condition, while this report records every
/// simplex-level failure and every pairwise overlap failure that can be checked
/// after invalid simplices are excluded from pairwise intersection work.
#[derive(Clone, Debug, PartialEq)]
#[must_use]
pub struct TriangulationRealizationValidationReport {
    /// Number of vertices in the triangulation when the report was generated.
    pub number_of_vertices: usize,
    /// Number of simplices in the triangulation when the report was generated.
    pub number_of_simplices: usize,
    /// Number of simplex realizations prepared for Level 4 validation.
    pub checked_simplices: usize,
    /// Number of candidate simplex pairs examined by the overlap broad phase.
    ///
    /// For Euclidean charts this counts pairs whose bounding boxes overlap
    /// after the sweep-and-prune broad phase; for periodic charts it counts all
    /// non-degenerate pairs (exhaustive enumeration).
    pub checked_simplex_pairs: usize,
    /// Ordered list of Level 4 realization violations.
    pub violations: Vec<TriangulationRealizationValidationError>,
}

impl TriangulationRealizationValidationReport {
    /// Returns `true` when no Level 4 realization violations were found.
    ///
    /// # Examples
    ///
    /// ```rust
    /// use delaunay::prelude::construction::{
    ///     DelaunayResult, DelaunayTriangulationBuilder, vertex,
    /// };
    ///
    /// # fn main() -> DelaunayResult<()> {
    /// let vertices = [
    ///     vertex![0.0, 0.0]?,
    ///     vertex![1.0, 0.0]?,
    ///     vertex![0.0, 1.0]?,
    /// ];
    /// let dt = DelaunayTriangulationBuilder::new(&vertices).build()?;
    ///
    /// std::assert_matches!(
    ///     dt.as_triangulation().realization_report(),
    ///     Ok(report) if report.is_valid()
    /// );
    /// # Ok(())
    /// # }
    /// ```
    #[must_use]
    pub const fn is_valid(&self) -> bool {
        self.violations.is_empty()
    }
}

#[derive(Debug)]
struct RealizedSimplex<const D: usize> {
    key: SimplexKey,
    uuid: Uuid,
    vertex_keys: SimplexVertexKeyBuffer,
    vertex_uuids: SimplexVertexUuidBuffer,
    realization: LabeledSimplexRealization<RealizedVertexIdentity<D>, D>,
}

/// Identifies one canonical vertex in a specific periodic covering-space image.
#[derive(Clone, Copy, Debug, Eq, PartialEq)]
struct RealizedVertexIdentity<const D: usize> {
    key: VertexKey,
    offset: [i64; D],
}

impl<const D: usize> RealizedVertexIdentity<D> {
    /// Moves an identity with its simplex so translated copies do not retain stale shared labels.
    fn translated(self, shift: &[i32; D]) -> Self {
        Self {
            key: self.key,
            offset: std::array::from_fn(|axis| self.offset[axis] + i64::from(shift[axis])),
        }
    }
}

type PeriodicShiftRangeBuffer = SmallBuffer<(i32, i32), MAX_PRACTICAL_DIMENSION_SIZE>;

impl<const D: usize> RealizedSimplex<D> {
    /// Builds the lifted, labeled realization for one TDS simplex while preserving
    /// simplex and vertex identities for later diagnostics.
    fn try_from_simplex<U, V>(
        tds: &Tds<U, V, D>,
        topology_model: &impl GlobalTopologyModel<D>,
        simplex_key: SimplexKey,
        simplex: &Simplex<V, D>,
    ) -> Result<Self, TriangulationRealizationValidationError> {
        let mut vertices = SimplexVertexKeyBuffer::with_capacity(simplex.number_of_vertices());
        let mut vertex_uuids = SimplexVertexUuidBuffer::with_capacity(simplex.number_of_vertices());
        let mut coords = SmallBuffer::<[f64; D], MAX_PRACTICAL_DIMENSION_SIZE>::with_capacity(
            simplex.number_of_vertices(),
        );

        let periodic_offsets = simplex.periodic_vertex_offsets();
        if let Some(offsets) = periodic_offsets
            && offsets.len() != simplex.number_of_vertices()
        {
            return Err(TdsError::DimensionMismatch {
                expected: simplex.number_of_vertices(),
                actual: offsets.len(),
                context: format!(
                    "simplex {:?} (key {simplex_key:?}) periodic offset count vs vertex count during realization validation",
                    simplex.uuid(),
                ),
            }
            .into());
        }

        for (vertex_index, &vertex_key) in simplex.vertices().iter().enumerate() {
            let vertex = tds
                .vertex(vertex_key)
                .ok_or_else(|| TdsError::VertexNotFound {
                    vertex_key,
                    context: format!(
                        "realization validation for simplex {:?} (key {simplex_key:?})",
                        simplex.uuid()
                    ),
                })?;
            vertices.push(vertex_key);
            vertex_uuids.push(vertex.uuid());
            let periodic_offset = periodic_offsets.map(|offsets| offsets[vertex_index]);
            let lifted_coords = topology_model
                .lift_for_orientation(*vertex.point().coords(), periodic_offset)
                .map_err(
                    |source| TriangulationRealizationValidationError::TopologyLifting {
                        simplex_key,
                        simplex_uuid: simplex.uuid(),
                        vertex_key,
                        vertex_uuid: vertex.uuid(),
                        source,
                    },
                )?;
            coords.push(lifted_coords);
        }

        let identities = vertices.iter().enumerate().map(|(vertex_index, &key)| {
            let offset = periodic_offsets.map_or([0_i64; D], |offsets| {
                std::array::from_fn(|axis| i64::from(offsets[vertex_index][axis]))
            });
            RealizedVertexIdentity { key, offset }
        });
        let realization = LabeledSimplexRealization::try_new(identities, coords.iter().copied())
            .map_err(|source| {
                labeled_simplex_error_to_realization_error(
                    source,
                    simplex_key,
                    simplex,
                    &vertices,
                    &vertex_uuids,
                )
            })?;

        Ok(Self {
            key: simplex_key,
            uuid: simplex.uuid(),
            vertex_keys: vertices,
            vertex_uuids,
            realization,
        })
    }

    /// Rehydrates one realized vertex coordinate as a validated point for exact predicates.
    fn point_at(
        &self,
        vertex_index: usize,
    ) -> Result<Point<D>, TriangulationRealizationValidationError> {
        self.realization.point_at(vertex_index).ok_or_else(|| {
            TdsError::DimensionMismatch {
                expected: self.realization.labels().len(),
                actual: vertex_index.saturating_add(1),
                context: format!(
                    "realized simplex {:?} (key {:?}) point index during Level 4 validation",
                    self.uuid, self.key,
                ),
            }
            .into()
        })
    }

    /// Finds a lifted vertex identity and validates its point coordinates.
    ///
    /// The full-facet shortcut uses lifted identities rather than coordinate
    /// indices so periodic translations cannot collapse distinct vertex images.
    fn point_for_identity(
        &self,
        identity: RealizedVertexIdentity<D>,
    ) -> Result<Point<D>, TriangulationRealizationValidationError> {
        let vertex_index = self
            .realization
            .labels()
            .iter()
            .position(|candidate| *candidate == identity)
            .ok_or_else(|| TdsError::VertexNotFound {
                vertex_key: identity.key,
                context: format!(
                    "lifted vertex identity ({:?}, offset {:?}) in realized simplex {:?} (key {:?}) facet-side validation",
                    identity.key, identity.offset, self.uuid, self.key,
                ),
            })?;
        self.point_at(vertex_index)
    }

    /// Maps witness vertex keys back to UUIDs from this simplex snapshot.
    fn vertex_uuids_for_keys(&self, vertex_keys: &[VertexKey]) -> SimplexVertexUuidBuffer {
        let mut uuids = SimplexVertexUuidBuffer::with_capacity(vertex_keys.len());
        uuids.extend(vertex_keys.iter().filter_map(|vertex_key| {
            self.vertex_keys
                .iter()
                .zip(&self.vertex_uuids)
                .find_map(|(candidate, &uuid)| (candidate == vertex_key).then_some(uuid))
        }));
        uuids
    }

    /// Builds the public simplex detail payload reused by Level 4 error variants.
    fn detail(&self) -> TriangulationRealizationSimplexDetail {
        TriangulationRealizationSimplexDetail {
            key: self.key,
            uuid: self.uuid,
            vertices: self.vertex_keys.clone(),
            vertex_uuids: self.vertex_uuids.clone(),
        }
    }
}

/// Converts labeled simplex construction failures into Level 4 diagnostics
/// that preserve the owning simplex and vertex identities callers need for
/// repair planning.
fn labeled_simplex_error_to_realization_error<V, const D: usize>(
    source: LabeledSimplexRealizationError,
    simplex_key: SimplexKey,
    simplex: &Simplex<V, D>,
    vertex_keys: &SimplexVertexKeyBuffer,
    vertex_uuids: &SimplexVertexUuidBuffer,
) -> TriangulationRealizationValidationError {
    let (expected, actual) = match source {
        LabeledSimplexRealizationError::LabelCoordinateLengthMismatch {
            label_count,
            coordinate_count,
        } => (label_count, coordinate_count),
        LabeledSimplexRealizationError::InvalidArity { expected, actual } => (expected, actual),
        LabeledSimplexRealizationError::DuplicateLabel {
            first_index,
            duplicate_index,
        } => {
            return duplicate_simplex_realization_label_error(
                simplex_key,
                simplex.uuid(),
                vertex_keys,
                vertex_uuids,
                first_index,
                duplicate_index,
                "duplicate realization label during realization validation",
            );
        }
        LabeledSimplexRealizationError::NonFiniteCoordinate {
            vertex_index,
            coordinate_index,
            coordinate_value,
        } => {
            let Some(&vertex_key) = vertex_keys.get(vertex_index) else {
                return TdsError::DimensionMismatch {
                    expected: vertex_keys.len(),
                    actual: vertex_index.saturating_add(1),
                    context: format!(
                        "simplex {:?} (key {simplex_key:?}) finite-coordinate diagnostic vertex index during realization validation",
                        simplex.uuid(),
                    ),
                }
                .into();
            };
            let Some(&vertex_uuid) = vertex_uuids.get(vertex_index) else {
                return TdsError::DimensionMismatch {
                    expected: vertex_uuids.len(),
                    actual: vertex_index.saturating_add(1),
                    context: format!(
                        "simplex {:?} (key {simplex_key:?}) finite-coordinate diagnostic vertex UUID index during realization validation",
                        simplex.uuid(),
                    ),
                }
                .into();
            };
            return TriangulationRealizationValidationError::CoordinateValidation {
                simplex_key,
                simplex_uuid: simplex.uuid(),
                vertex_key,
                vertex_uuid,
                source: CoordinateValidationError::InvalidCoordinate {
                    coordinate_index,
                    coordinate_value,
                    dimension: D,
                },
            };
        }
        LabeledSimplexRealizationError::InvalidPeriodicDomainPeriod { source } => {
            return TriangulationRealizationValidationError::InvalidPeriodicDomainPeriod {
                simplex_key,
                simplex_uuid: simplex.uuid(),
                detail: Box::new(TriangulationRealizationSimplexDetail {
                    key: simplex_key,
                    uuid: simplex.uuid(),
                    vertices: vertex_keys.clone(),
                    vertex_uuids: vertex_uuids.clone(),
                }),
                source: source.into(),
            };
        }
    };

    TdsError::DimensionMismatch {
        expected,
        actual,
        context: format!(
            "simplex {:?} (key {simplex_key:?}) arity during realization validation",
            simplex.uuid(),
        ),
    }
    .into()
}

/// Preserves duplicate realization labels as structured Level 4 diagnostics.
fn duplicate_simplex_realization_label_error(
    simplex_key: SimplexKey,
    simplex_uuid: Uuid,
    vertex_keys: &SimplexVertexKeyBuffer,
    vertex_uuids: &SimplexVertexUuidBuffer,
    first_index: usize,
    duplicate_index: usize,
    context: &'static str,
) -> TriangulationRealizationValidationError {
    let Some(&vertex_key) = vertex_keys.get(first_index) else {
        return TdsError::DimensionMismatch {
            expected: vertex_keys.len(),
            actual: first_index.saturating_add(1),
            context: format!("{context} for simplex {simplex_uuid} (key {simplex_key:?})"),
        }
        .into();
    };
    let Some(&vertex_uuid) = vertex_uuids.get(first_index) else {
        return TdsError::DimensionMismatch {
            expected: vertex_uuids.len(),
            actual: first_index.saturating_add(1),
            context: format!(
                "{context} vertex UUID for simplex {simplex_uuid} (key {simplex_key:?})"
            ),
        }
        .into();
    };

    TriangulationRealizationValidationError::DuplicateSimplexRealizationLabel {
        simplex_key,
        simplex_uuid,
        detail: Box::new(TriangulationRealizationSimplexDetail {
            key: simplex_key,
            uuid: simplex_uuid,
            vertices: vertex_keys.clone(),
            vertex_uuids: vertex_uuids.clone(),
        }),
        vertex_key,
        vertex_uuid,
        first_index,
        duplicate_index,
    }
}

/// Converts translated realized-simplex construction failures into the same
/// key- and UUID-rich public diagnostics as the primary realization path.
fn labeled_simplex_error_to_realized_simplex_error<const D: usize>(
    source: LabeledSimplexRealizationError,
    simplex: &RealizedSimplex<D>,
) -> TriangulationRealizationValidationError {
    let (expected, actual) = match source {
        LabeledSimplexRealizationError::LabelCoordinateLengthMismatch {
            label_count,
            coordinate_count,
        } => (label_count, coordinate_count),
        LabeledSimplexRealizationError::InvalidArity { expected, actual } => (expected, actual),
        LabeledSimplexRealizationError::DuplicateLabel {
            first_index,
            duplicate_index,
        } => {
            return duplicate_simplex_realization_label_error(
                simplex.key,
                simplex.uuid,
                &simplex.vertex_keys,
                &simplex.vertex_uuids,
                first_index,
                duplicate_index,
                "duplicate translated realization label during realization validation",
            );
        }
        LabeledSimplexRealizationError::NonFiniteCoordinate {
            vertex_index,
            coordinate_index,
            coordinate_value,
        } => {
            let Some(&vertex_key) = simplex.vertex_keys.get(vertex_index) else {
                return TdsError::DimensionMismatch {
                    expected: simplex.vertex_keys.len(),
                    actual: vertex_index.saturating_add(1),
                    context: format!(
                        "simplex {:?} (key {:?}) finite-coordinate translated diagnostic vertex index during realization validation",
                        simplex.uuid, simplex.key,
                    ),
                }
                .into();
            };
            let Some(&vertex_uuid) = simplex.vertex_uuids.get(vertex_index) else {
                return TdsError::DimensionMismatch {
                    expected: simplex.vertex_uuids.len(),
                    actual: vertex_index.saturating_add(1),
                    context: format!(
                        "simplex {:?} (key {:?}) finite-coordinate translated diagnostic vertex UUID index during realization validation",
                        simplex.uuid, simplex.key,
                    ),
                }
                .into();
            };
            return TriangulationRealizationValidationError::CoordinateValidation {
                simplex_key: simplex.key,
                simplex_uuid: simplex.uuid,
                vertex_key,
                vertex_uuid,
                source: CoordinateValidationError::InvalidCoordinate {
                    coordinate_index,
                    coordinate_value,
                    dimension: D,
                },
            };
        }
        LabeledSimplexRealizationError::InvalidPeriodicDomainPeriod { source } => {
            return TriangulationRealizationValidationError::InvalidPeriodicDomainPeriod {
                simplex_key: simplex.key,
                simplex_uuid: simplex.uuid,
                detail: Box::new(simplex.detail()),
                source: source.into(),
            };
        }
    };

    TdsError::DimensionMismatch {
        expected,
        actual,
        context: format!(
            "simplex {:?} (key {:?}) arity during translated realization validation",
            simplex.uuid, simplex.key,
        ),
    }
    .into()
}

impl<K, U, V, const D: usize> Triangulation<K, U, V, D> {
    /// Validates realized geometry only (Level 4).
    ///
    /// This method assumes lower layers have already passed validation. Use
    /// [`validate_realization`](Self::validate_realization) for cumulative Levels
    /// 1-4 validation.
    ///
    /// Euclidean topology is validated in its ordinary affine chart. Toroidal
    /// topology is validated in the stored periodic covering-space charts and
    /// across periodic translates. Spherical and hyperbolic topology currently
    /// return [`TriangulationRealizationValidationError::UnsupportedTopology`]
    /// until their model-specific realization validators are added.
    ///
    /// # Errors
    ///
    /// Returns [`TriangulationRealizationValidationError`] if the topology model is
    /// unsupported, a simplex is negatively oriented or geometrically degenerate,
    /// a periodic simplex is not contained in a single covering chart, or two
    /// maximal simplices intersect outside their shared face.
    ///
    /// # Examples
    ///
    /// ```rust
    /// use delaunay::prelude::construction::{
    ///     DelaunayResult, DelaunayTriangulationBuilder, vertex,
    /// };
    ///
    /// # fn main() -> DelaunayResult<()> {
    /// let vertices = [
    ///     vertex![0.0, 0.0]?,
    ///     vertex![1.0, 0.0]?,
    ///     vertex![0.0, 1.0]?,
    /// ];
    /// let dt = DelaunayTriangulationBuilder::new(&vertices).build()?;
    ///
    /// assert!(dt.as_triangulation().is_valid_realization().is_ok());
    /// # Ok(())
    /// # }
    /// ```
    pub fn is_valid_realization(&self) -> Result<(), TriangulationRealizationValidationError> {
        if let Some(first_violation) = self.realization_diagnostic()? {
            return Err(first_violation);
        }
        Ok(())
    }

    /// Returns the first actionable Level 4 realization diagnostic, if any.
    ///
    /// This is the repair/retry-oriented counterpart to
    /// [`is_valid_realization`](Self::is_valid_realization). It returns at most one
    /// Level 4 violation with simplex keys, simplex UUIDs, and offending vertex
    /// keys/UUIDs where applicable.
    ///
    /// # Errors
    ///
    /// Returns [`TriangulationRealizationValidationError`] when simplex realization
    /// preparation cannot continue because lower-layer TDS data are missing or
    /// malformed.
    ///
    /// # Examples
    ///
    /// ```rust
    /// use delaunay::prelude::construction::{
    ///     DelaunayResult, DelaunayTriangulationBuilder, vertex,
    /// };
    ///
    /// # fn main() -> DelaunayResult<()> {
    /// let vertices = [
    ///     vertex![0.0, 0.0]?,
    ///     vertex![1.0, 0.0]?,
    ///     vertex![0.0, 1.0]?,
    /// ];
    /// let dt = DelaunayTriangulationBuilder::new(&vertices).build()?;
    ///
    /// std::assert_matches!(dt.as_triangulation().realization_diagnostic(), Ok(None));
    /// # Ok(())
    /// # }
    /// ```
    pub fn realization_diagnostic(
        &self,
    ) -> Result<
        Option<TriangulationRealizationValidationError>,
        TriangulationRealizationValidationError,
    > {
        self.first_realization_violation()
    }

    /// Builds a Level 4 realization report with key- and UUID-based violation details.
    ///
    /// This method checks realized geometry only. It does not run lower-layer
    /// TDS/topology validation and does not evaluate the Level 5 Delaunay
    /// property. Use [`validate_realization`](Self::validate_realization) for
    /// cumulative Levels 1-4 validation when pass/fail behavior is enough.
    ///
    /// # Errors
    ///
    /// Returns [`TriangulationRealizationValidationError`] when simplex realization
    /// preparation cannot continue because lower-layer TDS data are missing or
    /// malformed. Ordinary Level 4 violations are returned inside the report.
    ///
    /// # Examples
    ///
    /// ```rust
    /// use delaunay::prelude::construction::{
    ///     DelaunayResult, DelaunayTriangulationBuilder, vertex,
    /// };
    ///
    /// # fn main() -> DelaunayResult<()> {
    /// let vertices = [
    ///     vertex![0.0, 0.0]?,
    ///     vertex![1.0, 0.0]?,
    ///     vertex![0.0, 1.0]?,
    /// ];
    /// let dt = DelaunayTriangulationBuilder::new(&vertices).build()?;
    ///
    /// std::assert_matches!(
    ///     dt.as_triangulation().realization_report(),
    ///     Ok(report) if report.is_valid()
    /// );
    /// # Ok(())
    /// # }
    /// ```
    pub fn realization_report(
        &self,
    ) -> Result<TriangulationRealizationValidationReport, TriangulationRealizationValidationError>
    {
        let topology_model = self.global_topology.model();
        let mut report = TriangulationRealizationValidationReport {
            number_of_vertices: self.tds.number_of_vertices(),
            number_of_simplices: self.tds.number_of_simplices(),
            checked_simplices: 0,
            checked_simplex_pairs: 0,
            violations: Vec::new(),
        };

        if !topology_model.supports_affine_chart_realization_validation() {
            report.violations.push(
                TriangulationRealizationValidationError::UnsupportedTopology {
                    topology: self.global_topology.kind(),
                    dimension: D,
                },
            );
            return Ok(report);
        }

        let simplices = self.collect_realized_simplices()?;
        report.checked_simplices = simplices.len();
        let periodic_domain = topology_model.periodic_domain();
        let periodic_periods = periodic_domain.map(|domain| *domain.periods());
        let mut invalid_simplex_keys = FastHashSet::default();

        for simplex in &simplices {
            if let Err(error) = validate_simplex_orientation(simplex) {
                invalid_simplex_keys.insert(simplex.key);
                report.violations.push(error);
            }
            if let Some(domain) = periodic_domain
                && let Err(error) = validate_periodic_simplex_chart(simplex, domain.periods())
            {
                invalid_simplex_keys.insert(simplex.key);
                report.violations.push(error);
            }
        }

        let (checked_simplex_pairs, _) = for_each_candidate_simplex_pair::<D, ()>(
            &simplices,
            &invalid_simplex_keys,
            periodic_periods,
            |first, second| {
                if let Err(error) =
                    validate_topology_aware_simplex_pair(first, second, periodic_periods)
                {
                    report.violations.push(error);
                }
                ControlFlow::Continue(())
            },
        );
        report.checked_simplex_pairs = checked_simplex_pairs;

        Ok(report)
    }

    /// Performs cumulative validation for Levels 1-4.
    ///
    /// This validates:
    /// - **Levels 1-3** via [`Triangulation::validate`](Self::validate)
    /// - **Level 4** via [`Triangulation::is_valid_realization`](Self::is_valid_realization)
    ///
    /// # Errors
    ///
    /// Returns [`TriangulationRealizationValidationError`] if lower-layer
    /// validation fails, the topology cannot currently be realized-validated,
    /// or realized geometry is invalid.
    ///
    /// # Examples
    ///
    /// ```rust
    /// use delaunay::prelude::construction::{
    ///     DelaunayResult, DelaunayTriangulationBuilder, vertex,
    /// };
    ///
    /// # fn main() -> DelaunayResult<()> {
    /// let vertices = [
    ///     vertex![0.0, 0.0]?,
    ///     vertex![1.0, 0.0]?,
    ///     vertex![0.0, 1.0]?,
    /// ];
    /// let dt = DelaunayTriangulationBuilder::new(&vertices).build()?;
    ///
    /// assert!(dt.as_triangulation().validate_realization().is_ok());
    /// # Ok(())
    /// # }
    /// ```
    pub fn validate_realization(&self) -> Result<(), TriangulationRealizationValidationError>
    where
        K: Kernel<D, Scalar = f64>,
        U: DataType,
        V: DataType,
    {
        self.validate().map_err(|error| match error {
            InvariantError::Tds(source) => source.into(),
            InvariantError::Triangulation(source) => source.into(),
            InvariantError::Realization(source) => source,
            source @ InvariantError::Delaunay(_) => {
                TriangulationRealizationValidationError::UnexpectedValidationLayer {
                    kind: InvariantKind::DelaunayProperty,
                    source: Box::new(source),
                }
            }
        })?;
        self.is_valid_realization()
    }

    /// Validates the Level 4 orientation invariant for a local simplex set.
    ///
    /// This intentionally does not perform pairwise overlap checks; insertion
    /// uses it as a cheap mutation-time guard so negative- or zero-orientation
    /// simplices fail inside the existing rollback transaction. Full realization
    /// validation remains the responsibility of
    /// [`is_valid_realization`](Self::is_valid_realization).
    pub(crate) fn validate_local_realization_orientation(
        &self,
        simplices: &[SimplexKey],
    ) -> Result<(), TriangulationRealizationValidationError> {
        let topology_model = self.global_topology.model();
        if !topology_model.supports_affine_chart_realization_validation() {
            return Ok(());
        }

        let periodic_domain = topology_model.periodic_domain();
        for &simplex_key in simplices {
            let simplex =
                self.tds
                    .simplex(simplex_key)
                    .ok_or_else(|| TdsError::SimplexNotFound {
                        simplex_key,
                        context: "local realization orientation validation".to_string(),
                    })?;
            let realized = RealizedSimplex::try_from_simplex(
                &self.tds,
                &topology_model,
                simplex_key,
                simplex,
            )?;
            validate_simplex_orientation(&realized)?;
            if let Some(domain) = periodic_domain {
                validate_periodic_simplex_chart(&realized, domain.periods())?;
            }
        }

        Ok(())
    }

    /// Validates the Level 4 realization invariant for a changed simplex scope.
    ///
    /// Insertion and repair already assume the pre-existing triangulation was
    /// realization-valid before the local mutation. Under that precondition, only
    /// the changed simplices can introduce a new simplex-orientation or
    /// pairwise-intersection violation, so this checks each scoped simplex
    /// against every candidate it can intersect instead of rescanning all old
    /// simplex pairs.
    pub(crate) fn validate_realization_for_simplices(
        &self,
        local_simplices: &[SimplexKey],
    ) -> Result<(), TriangulationRealizationValidationError> {
        if local_simplices.is_empty() {
            return Ok(());
        }

        let topology_model = self.global_topology.model();
        if !topology_model.supports_affine_chart_realization_validation() {
            return Err(
                TriangulationRealizationValidationError::UnsupportedTopology {
                    topology: self.global_topology.kind(),
                    dimension: D,
                },
            );
        }

        let mut local_simplex_keys = FastHashSet::default();
        local_simplex_keys.reserve(local_simplices.len());
        for &simplex_key in local_simplices {
            if !self.tds.contains_simplex(simplex_key) {
                return Err(TdsError::SimplexNotFound {
                    simplex_key,
                    context: "scoped realization validation".to_string(),
                }
                .into());
            }
            local_simplex_keys.insert(simplex_key);
        }

        let simplices = self.collect_realized_simplices()?;
        let periodic_domain = topology_model.periodic_domain();
        let periodic_periods = periodic_domain.map(|domain| *domain.periods());

        for simplex in &simplices {
            if !local_simplex_keys.contains(&simplex.key) {
                continue;
            }
            validate_simplex_orientation(simplex)?;
            if let Some(domain) = periodic_domain {
                validate_periodic_simplex_chart(simplex, domain.periods())?;
            }
        }

        let empty_skip = FastHashSet::default();
        let (_, violation) =
            for_each_scoped_candidate_simplex_pair::<D, TriangulationRealizationValidationError>(
                &simplices,
                &empty_skip,
                &local_simplex_keys,
                periodic_periods,
                |first, second| match validate_topology_aware_simplex_pair(
                    first,
                    second,
                    periodic_periods,
                ) {
                    Ok(()) => ControlFlow::Continue(()),
                    Err(error) => ControlFlow::Break(error),
                },
            );

        if let Some(error) = violation {
            return Err(error);
        }

        Ok(())
    }

    /// Collects all simplex realizations after applying the topology model's active chart.
    fn collect_realized_simplices(
        &self,
    ) -> Result<Vec<RealizedSimplex<D>>, TriangulationRealizationValidationError> {
        let topology_model = self.global_topology.model();
        self.tds
            .simplices()
            .map(|(simplex_key, simplex)| {
                RealizedSimplex::try_from_simplex(&self.tds, &topology_model, simplex_key, simplex)
            })
            .collect()
    }

    fn first_realization_violation(
        &self,
    ) -> Result<
        Option<TriangulationRealizationValidationError>,
        TriangulationRealizationValidationError,
    > {
        let topology_model = self.global_topology.model();
        if !topology_model.supports_affine_chart_realization_validation() {
            return Ok(Some(
                TriangulationRealizationValidationError::UnsupportedTopology {
                    topology: self.global_topology.kind(),
                    dimension: D,
                },
            ));
        }

        let periodic_domain = topology_model.periodic_domain();
        let periodic_periods = periodic_domain.map(|domain| *domain.periods());
        let mut simplices = Vec::with_capacity(self.tds.number_of_simplices());
        for (simplex_key, simplex) in self.tds.simplices() {
            let realized = RealizedSimplex::try_from_simplex(
                &self.tds,
                &topology_model,
                simplex_key,
                simplex,
            )?;
            if let Err(error) = validate_simplex_orientation(&realized) {
                return Ok(Some(error));
            }
            if let Some(domain) = periodic_domain
                && let Err(error) = validate_periodic_simplex_chart(&realized, domain.periods())
            {
                return Ok(Some(error));
            }
            simplices.push(realized);
        }

        let empty_skip: FastHashSet<SimplexKey> = FastHashSet::default();
        let (_, violation) =
            for_each_candidate_simplex_pair::<D, TriangulationRealizationValidationError>(
                &simplices,
                &empty_skip,
                periodic_periods,
                |first, second| match validate_topology_aware_simplex_pair(
                    first,
                    second,
                    periodic_periods,
                ) {
                    Ok(()) => ControlFlow::Continue(()),
                    Err(error) => ControlFlow::Break(error),
                },
            );

        Ok(violation)
    }
}

/// Dispatches pairwise overlap validation through Euclidean or periodic chart logic.
fn validate_topology_aware_simplex_pair<const D: usize>(
    first: &RealizedSimplex<D>,
    second: &RealizedSimplex<D>,
    periodic_periods: Option<[f64; D]>,
) -> Result<(), TriangulationRealizationValidationError> {
    let Some(periods) = periodic_periods else {
        if bounding_boxes_overlap(first, second) {
            if try_validate_full_facet_pair(first, second)? {
                return Ok(());
            }
            validate_simplex_pair_intersection(first, second)?;
        }
        return Ok(());
    };

    let shift_ranges = periodic_shift_ranges(first, second, &periods)?;
    let mut shift = [0_i32; D];
    validate_periodic_translates(first, second, &periods, &shift_ranges, 0, &mut shift)
}

/// Uses an exact side-of-facet test for adjacent simplices sharing a full facet.
///
/// When two nondegenerate D-simplices share D vertices, their intersection is
/// exactly the shared facet iff the two opposite vertices lie on opposite sides
/// of the shared facet. This avoids the more expensive barycentric intersection
/// solver for the common adjacent-pair case while preserving the same Level 4
/// error shape for invalid same-side realizations.
fn try_validate_full_facet_pair<const D: usize>(
    first: &RealizedSimplex<D>,
    second: &RealizedSimplex<D>,
) -> Result<bool, TriangulationRealizationValidationError> {
    let mut shared = SmallBuffer::<RealizedVertexIdentity<D>, MAX_PRACTICAL_DIMENSION_SIZE>::new();
    let mut first_only =
        SmallBuffer::<RealizedVertexIdentity<D>, MAX_PRACTICAL_DIMENSION_SIZE>::new();
    let mut second_only =
        SmallBuffer::<RealizedVertexIdentity<D>, MAX_PRACTICAL_DIMENSION_SIZE>::new();

    for &identity in first.realization.labels() {
        if second.realization.labels().contains(&identity) {
            shared.push(identity);
        } else {
            first_only.push(identity);
        }
    }
    for &identity in second.realization.labels() {
        if !first.realization.labels().contains(&identity) {
            second_only.push(identity);
        }
    }

    if shared.len() != D || first_only.len() != 1 || second_only.len() != 1 {
        return Ok(false);
    }

    let first_orientation = orientation_against_shared_facet(first, &shared, first_only[0])?;
    let second_orientation = orientation_against_shared_facet(second, &shared, second_only[0])?;
    match (first_orientation, second_orientation) {
        (Orientation::POSITIVE, Orientation::NEGATIVE)
        | (Orientation::NEGATIVE, Orientation::POSITIVE) => Ok(true),
        (
            Orientation::POSITIVE | Orientation::NEGATIVE,
            Orientation::POSITIVE | Orientation::NEGATIVE,
        ) => Err(shared_facet_same_side_intersection(
            first,
            second,
            realized_vertex_keys(&shared),
            realized_vertex_keys(&first_only),
            realized_vertex_keys(&second_only),
        )),
        (Orientation::DEGENERATE, _) => {
            Err(TriangulationRealizationValidationError::DegenerateSimplex {
                simplex_key: first.key,
                simplex_uuid: first.uuid,
                detail: Box::new(first.detail()),
                dimension: D,
            })
        }
        (_, Orientation::DEGENERATE) => {
            Err(TriangulationRealizationValidationError::DegenerateSimplex {
                simplex_key: second.key,
                simplex_uuid: second.uuid,
                detail: Box::new(second.detail()),
                dimension: D,
            })
        }
    }
}

/// Computes which side of a shared facet the opposite vertex occupies.
///
/// The point order is the shared facet vertices followed by one opposite
/// vertex, so the sign can be compared between adjacent simplices without
/// constructing a barycentric intersection system.
fn orientation_against_shared_facet<const D: usize>(
    simplex: &RealizedSimplex<D>,
    shared: &[RealizedVertexIdentity<D>],
    opposite: RealizedVertexIdentity<D>,
) -> Result<Orientation, TriangulationRealizationValidationError> {
    let mut points = SmallBuffer::<Point<D>, MAX_PRACTICAL_DIMENSION_SIZE>::with_capacity(D + 1);
    for &identity in shared {
        points.push(simplex.point_for_identity(identity)?);
    }
    points.push(simplex.point_for_identity(opposite)?);

    robust_orientation(&points).map_err(|source| {
        TriangulationRealizationValidationError::PredicateFailed {
            simplex_key: simplex.key,
            simplex_uuid: simplex.uuid,
            detail: Box::new(simplex.detail()),
            source,
        }
    })
}

/// Builds the standard Level 4 overlap diagnostic for a failed facet-side test.
///
/// Keeping the same [`TriangulationRealizationValidationError`] variant as the
/// barycentric path lets repair/report callers consume one error contract
/// regardless of which validator found the illegal intersection.
fn shared_facet_same_side_intersection<const D: usize>(
    first: &RealizedSimplex<D>,
    second: &RealizedSimplex<D>,
    shared_vertices: SimplexVertexKeyBuffer,
    first_only_witness_vertices: SimplexVertexKeyBuffer,
    second_only_witness_vertices: SimplexVertexKeyBuffer,
) -> TriangulationRealizationValidationError {
    let shared_vertex_uuids = first.vertex_uuids_for_keys(&shared_vertices);
    let first_only_witness_vertex_uuids = first.vertex_uuids_for_keys(&first_only_witness_vertices);
    let second_only_witness_vertex_uuids =
        second.vertex_uuids_for_keys(&second_only_witness_vertices);

    TriangulationRealizationValidationError::SimplexIntersectionOutsideSharedFace {
        first_simplex_key: first.key,
        first_simplex_uuid: first.uuid,
        second_simplex_key: second.key,
        second_simplex_uuid: second.uuid,
        detail: Box::new(TriangulationRealizationIntersectionDetail {
            first_simplex: first.detail(),
            second_simplex: second.detail(),
            shared_vertices,
            shared_vertex_uuids,
            first_only_witness_vertices,
            first_only_witness_vertex_uuids,
            second_only_witness_vertices,
            second_only_witness_vertex_uuids,
        }),
    }
}

/// Recursively checks every periodic translate that can overlap two simplex boxes.
fn validate_periodic_translates<const D: usize>(
    first: &RealizedSimplex<D>,
    second: &RealizedSimplex<D>,
    periods: &[f64; D],
    shift_ranges: &[(i32, i32)],
    axis: usize,
    shift: &mut [i32; D],
) -> Result<(), TriangulationRealizationValidationError> {
    if axis == D {
        let translated = translated_simplex(second, periods, shift)?;
        if bounding_boxes_overlap(first, &translated) {
            if try_validate_full_facet_pair(first, &translated)? {
                return Ok(());
            }
            validate_simplex_pair_intersection(first, &translated)?;
        }
        return Ok(());
    }

    let (start, end) = shift_ranges[axis];
    for value in start..=end {
        shift[axis] = value;
        validate_periodic_translates(first, second, periods, shift_ranges, axis + 1, shift)?;
    }
    Ok(())
}

/// Computes the finite integer shift range needed to test possible periodic overlaps.
fn periodic_shift_ranges<const D: usize>(
    first: &RealizedSimplex<D>,
    second: &RealizedSimplex<D>,
    periods: &[f64; D],
) -> Result<PeriodicShiftRangeBuffer, TriangulationRealizationValidationError> {
    (0..D)
        .map(|axis| {
            let (first_min, first_max) = coordinate_range_for_axis(&first.realization, axis)
                .expect("axis generated from 0..D must be valid");
            let (second_min, second_max) = coordinate_range_for_axis(&second.realization, axis)
                .expect("axis generated from 0..D must be valid");
            let period = periods[axis];
            let lower_bound = ((first_min - second_max) / period).floor();
            let upper_bound = ((first_max - second_min) / period).ceil();
            let Some(start) = lower_bound.to_i32() else {
                return Err(periodic_translate_range_overflow(
                    first,
                    second,
                    axis,
                    lower_bound,
                    upper_bound,
                ));
            };
            let Some(end) = upper_bound.to_i32() else {
                return Err(periodic_translate_range_overflow(
                    first,
                    second,
                    axis,
                    lower_bound,
                    upper_bound,
                ));
            };
            Ok((start, end))
        })
        .collect()
}

/// Builds the shared diagnostic for periodic shift bounds that cannot fit in `i32`.
fn periodic_translate_range_overflow<const D: usize>(
    first: &RealizedSimplex<D>,
    second: &RealizedSimplex<D>,
    axis: usize,
    lower_bound: f64,
    upper_bound: f64,
) -> TriangulationRealizationValidationError {
    TriangulationRealizationValidationError::PeriodicTranslateRangeOverflow {
        first_simplex_key: first.key,
        first_simplex_uuid: first.uuid,
        second_simplex_key: second.key,
        second_simplex_uuid: second.uuid,
        detail: Box::new(TriangulationRealizationSimplexPairDetail {
            first_simplex: first.detail(),
            second_simplex: second.detail(),
        }),
        axis,
        lower_bound,
        upper_bound,
    }
}

/// Translates one realized simplex into a neighboring periodic chart.
fn translated_simplex<const D: usize>(
    simplex: &RealizedSimplex<D>,
    periods: &[f64; D],
    shift: &[i32; D],
) -> Result<RealizedSimplex<D>, TriangulationRealizationValidationError> {
    let translated = simplex
        .realization
        .try_translated(periods, shift)
        .map_err(|source| labeled_simplex_error_to_realized_simplex_error(source, simplex))?;
    let labels = translated
        .labels()
        .iter()
        .map(|identity| identity.translated(shift));
    let realization =
        LabeledSimplexRealization::try_new(labels, translated.coordinates().iter().copied())
            .map_err(|source| labeled_simplex_error_to_realized_simplex_error(source, simplex))?;
    Ok(RealizedSimplex {
        key: simplex.key,
        uuid: simplex.uuid,
        vertex_keys: simplex.vertex_keys.clone(),
        vertex_uuids: simplex.vertex_uuids.clone(),
        realization,
    })
}

/// Rejects a periodic simplex whose lifted vertices cannot fit in one chart.
fn validate_periodic_simplex_chart<const D: usize>(
    simplex: &RealizedSimplex<D>,
    periods: &[f64; D],
) -> Result<(), TriangulationRealizationValidationError> {
    let span = try_periodic_simplex_span(&simplex.realization, periods).map_err(|source| {
        TriangulationRealizationValidationError::InvalidPeriodicDomainPeriod {
            simplex_key: simplex.key,
            simplex_uuid: simplex.uuid,
            detail: Box::new(simplex.detail()),
            source: source.into(),
        }
    })?;
    if let Some(span) = span {
        return Err(
            TriangulationRealizationValidationError::PeriodicSimplexSpansDomain {
                simplex_key: simplex.key,
                simplex_uuid: simplex.uuid,
                detail: Box::new(simplex.detail()),
                axis: span.axis(),
                span: span.span(),
                period: span.period(),
            },
        );
    }
    Ok(())
}

/// Rejects non-positive simplex orientation before pairwise overlap validation runs.
fn validate_simplex_orientation<const D: usize>(
    simplex: &RealizedSimplex<D>,
) -> Result<(), TriangulationRealizationValidationError> {
    let points: SmallBuffer<Point<D>, MAX_PRACTICAL_DIMENSION_SIZE> =
        (0..simplex.realization.labels().len())
            .map(|index| simplex.point_at(index))
            .collect::<Result<_, _>>()?;

    match robust_orientation(&points) {
        Ok(Orientation::POSITIVE) => Ok(()),
        Ok(Orientation::NEGATIVE) => Err(
            TriangulationRealizationValidationError::NegativeSimplexOrientation {
                simplex_key: simplex.key,
                simplex_uuid: simplex.uuid,
                detail: Box::new(simplex.detail()),
                dimension: D,
            },
        ),
        Ok(Orientation::DEGENERATE) => {
            Err(TriangulationRealizationValidationError::DegenerateSimplex {
                simplex_key: simplex.key,
                simplex_uuid: simplex.uuid,
                detail: Box::new(simplex.detail()),
                dimension: D,
            })
        }
        Err(source) => Err(TriangulationRealizationValidationError::PredicateFailed {
            simplex_key: simplex.key,
            simplex_uuid: simplex.uuid,
            detail: Box::new(simplex.detail()),
            source,
        }),
    }
}

/// Applies the cheap bounding-box prefilter before exact intersection work.
fn bounding_boxes_overlap<const D: usize>(
    first: &RealizedSimplex<D>,
    second: &RealizedSimplex<D>,
) -> bool {
    axis_aligned_bounding_boxes_overlap(&first.realization, &second.realization)
}

/// Converts pure simplex-intersection failures into triangulation-level diagnostics.
fn validate_simplex_pair_intersection<const D: usize>(
    first: &RealizedSimplex<D>,
    second: &RealizedSimplex<D>,
) -> Result<(), TriangulationRealizationValidationError> {
    match validate_simplex_realizations_intersect_only_in_shared_faces(
        &first.realization,
        &second.realization,
    ) {
        Ok(()) => Ok(()),
        Err(SimplexIntersectionFailure::SingularBarycentricBasis) => Err(
            TriangulationRealizationValidationError::SingularBarycentricBasis {
                simplex_key: first.key,
                simplex_uuid: first.uuid,
                detail: Box::new(first.detail()),
                dimension: D,
            },
        ),
        Err(SimplexIntersectionFailure::IntersectionOutsideSharedFace { witness, .. }) => {
            let shared_vertices = realized_vertex_keys(&witness.shared);
            let first_only_witness_vertices = realized_vertex_keys(&witness.first_only_witness);
            let second_only_witness_vertices = realized_vertex_keys(&witness.second_only_witness);
            let shared_vertex_uuids = first.vertex_uuids_for_keys(&shared_vertices);
            let first_only_witness_vertex_uuids =
                first.vertex_uuids_for_keys(&first_only_witness_vertices);
            let second_only_witness_vertex_uuids =
                second.vertex_uuids_for_keys(&second_only_witness_vertices);
            Err(
                TriangulationRealizationValidationError::SimplexIntersectionOutsideSharedFace {
                    first_simplex_key: first.key,
                    first_simplex_uuid: first.uuid,
                    second_simplex_key: second.key,
                    second_simplex_uuid: second.uuid,
                    detail: Box::new(TriangulationRealizationIntersectionDetail {
                        first_simplex: first.detail(),
                        second_simplex: second.detail(),
                        shared_vertices,
                        shared_vertex_uuids,
                        first_only_witness_vertices,
                        first_only_witness_vertex_uuids,
                        second_only_witness_vertices,
                        second_only_witness_vertex_uuids,
                    }),
                },
            )
        }
    }
}

/// Projects lifted identities back to canonical keys for public diagnostics.
fn realized_vertex_keys<const D: usize>(
    identities: &[RealizedVertexIdentity<D>],
) -> SimplexVertexKeyBuffer {
    identities.iter().map(|identity| identity.key).collect()
}

/// Axis-aligned bounding box for one realized simplex, tagged with its index
/// in the validated simplex list.
#[derive(Clone, Copy, Debug)]
struct SimplexBoundingBox<const D: usize> {
    /// Index of the owning simplex in the realized-simplex slice.
    simplex_index: usize,
    /// Per-axis lower bounds of the simplex vertices.
    min: [f64; D],
    /// Per-axis upper bounds of the simplex vertices.
    max: [f64; D],
}

impl<const D: usize> SimplexBoundingBox<D> {
    /// Computes the bounding box of a realized simplex from its lifted coordinates.
    fn from_realized(simplex_index: usize, simplex: &RealizedSimplex<D>) -> Self {
        let mut min = [f64::INFINITY; D];
        let mut max = [f64::NEG_INFINITY; D];
        for coords in simplex.realization.coordinates() {
            for (axis, &value) in coords.iter().enumerate() {
                min[axis] = min[axis].min(value);
                max[axis] = max[axis].max(value);
            }
        }
        Self {
            simplex_index,
            min,
            max,
        }
    }

    /// Returns whether two boxes overlap on every axis.
    ///
    /// Two axis-aligned boxes intersect if and only if their projections
    /// overlap on every coordinate axis (the separating-axis test for AABBs;
    /// see Ericson, *Real-Time Collision Detection*, ch. 4-5).
    fn overlaps(&self, other: &Self) -> bool {
        (0..D).all(|axis| self.max[axis] >= other.min[axis] && other.max[axis] >= self.min[axis])
    }
}

/// Returns the axis with the largest global coordinate extent across all boxes.
///
/// Sweeping along the widest axis keeps the active set small, which is what
/// makes sweep-and-prune near-linear in practice.
fn widest_extent_axis<const D: usize>(boxes: &[SimplexBoundingBox<D>]) -> usize {
    let mut global_min = [f64::INFINITY; D];
    let mut global_max = [f64::NEG_INFINITY; D];
    for bounding_box in boxes {
        for (axis, (&min, &max)) in bounding_box.min.iter().zip(&bounding_box.max).enumerate() {
            global_min[axis] = global_min[axis].min(min);
            global_max[axis] = global_max[axis].max(max);
        }
    }
    (0..D)
        .map(|axis| (axis, global_max[axis] - global_min[axis]))
        .max_by(|(_, left), (_, right)| left.total_cmp(right))
        .map_or(0, |(axis, _)| axis)
}

/// Visits candidate overlapping simplex pairs for Level 4 realization validation.
///
/// The all-pairs intersection test is `O(S^2)` in the number of simplices,
/// which dominates validation on large triangulations. For the Euclidean
/// affine chart this routine uses a **sweep-and-prune** broad phase over
/// axis-aligned bounding boxes (AABBs) to enumerate only pairs whose boxes
/// overlap, then hands each candidate to `on_pair` for the exact intersection
/// test. Returning [`ControlFlow::Break`] stops early (used by fast-fail
/// validation); the returned tuple reports the number of candidate pairs
/// examined and the break payload, if any.
///
/// # Soundness ("provably misses nothing")
///
/// Two AABBs intersect if and only if their projections overlap on every
/// coordinate axis (the separating-axis test for boxes). Sweep-and-prune sorts
/// boxes by their lower endpoint on one axis and, when processing a box `b`,
/// retires only active boxes whose upper endpoint precedes `b`'s lower endpoint
/// on that axis. Every still-active box therefore overlaps `b` on the sweep
/// axis, so the examined pairs are a superset of all pairs that overlap on
/// *every* axis. No intersecting simplex pair can be skipped, so replacing the
/// quadratic scan with this broad phase preserves Level 4 correctness while
/// only pruning pairs that provably cannot intersect.
///
/// Periodic (toroidal) charts are excluded: a simplex near one boundary can
/// overlap another near the opposite boundary through a wrap-around translate
/// whose lifted-chart AABB is far away, so a lifted-coordinate sweep is not
/// sound. Those charts (and the degenerate `D == 0` chart, which has no sweep
/// axis) retain exhaustive pairwise enumeration until a periodic-aware broad
/// phase is added.
///
/// # Complexity
///
/// Euclidean: about `O(S log S)` for triangulations with bounded local overlap
/// (sorting dominates); worst case `O(S^2)` when many boxes overlap on the
/// sweep axis. Periodic: `O(S^2)`.
///
/// # References
///
/// - Cohen, Lin, Manocha, and Ponamgi, "I-COLLIDE" (1995): sweep-and-prune.
/// - Baraff, "Dynamic Simulation of Non-Penetrating Rigid Bodies" (1992):
///   coordinate sort-and-sweep.
/// - Ericson, *Real-Time Collision Detection* (2005), ch. 7 (sweep-and-prune)
///   and ch. 4-5 (AABB separating-axis test).
///
/// See `REFERENCES.md`, "Realized-Simplex Overlap Detection (Level 4 Validation)".
fn for_each_candidate_simplex_pair<const D: usize, B>(
    simplices: &[RealizedSimplex<D>],
    skip: &FastHashSet<SimplexKey>,
    periodic_periods: Option<[f64; D]>,
    on_pair: impl FnMut(&RealizedSimplex<D>, &RealizedSimplex<D>) -> ControlFlow<B>,
) -> (usize, Option<B>) {
    // Lifted-chart AABBs cannot express wrap-around overlaps, and a degenerate
    // 0-dimensional chart has no sweep axis, so both fall back to exhaustive
    // pairwise enumeration.
    if periodic_periods.is_some() || D == 0 {
        return exhaustive_candidate_simplex_pairs(simplices, skip, on_pair);
    }
    sweep_and_prune_candidate_simplex_pairs(simplices, skip, on_pair)
}

/// Visits candidate pairs where at least one simplex belongs to a changed scope.
fn for_each_scoped_candidate_simplex_pair<const D: usize, B>(
    simplices: &[RealizedSimplex<D>],
    skip: &FastHashSet<SimplexKey>,
    scope: &FastHashSet<SimplexKey>,
    periodic_periods: Option<[f64; D]>,
    mut on_pair: impl FnMut(&RealizedSimplex<D>, &RealizedSimplex<D>) -> ControlFlow<B>,
) -> (usize, Option<B>) {
    if scope.is_empty() {
        return for_each_candidate_simplex_pair(simplices, skip, periodic_periods, on_pair);
    }
    if periodic_periods.is_some() || D == 0 {
        return scoped_exhaustive_candidate_simplex_pairs(simplices, skip, scope, on_pair);
    }
    sweep_and_prune_candidate_simplex_pairs(simplices, skip, |first, second| {
        if scope.contains(&first.key) || scope.contains(&second.key) {
            on_pair(first, second)
        } else {
            ControlFlow::Continue(())
        }
    })
}

/// Exhaustive `O(S^2)` pairwise enumeration over non-skipped simplices.
fn exhaustive_candidate_simplex_pairs<const D: usize, B>(
    simplices: &[RealizedSimplex<D>],
    skip: &FastHashSet<SimplexKey>,
    mut on_pair: impl FnMut(&RealizedSimplex<D>, &RealizedSimplex<D>) -> ControlFlow<B>,
) -> (usize, Option<B>) {
    let mut examined = 0_usize;
    for (first_index, first_simplex) in simplices.iter().enumerate() {
        if skip.contains(&first_simplex.key) {
            continue;
        }

        for second_simplex in &simplices[first_index + 1..] {
            if skip.contains(&second_simplex.key) {
                continue;
            }

            examined += 1;
            if let ControlFlow::Break(value) = on_pair(first_simplex, second_simplex) {
                return (examined, Some(value));
            }
        }
    }
    (examined, None)
}

/// Exhaustive scoped pair enumeration for periodic charts.
///
/// The periodic path cannot use lifted-coordinate sweep-and-prune, but a local
/// mutation only needs changed-vs-all pairs. This keeps automatic insertion
/// validation proportional to the changed scope instead of all old pairs.
fn scoped_exhaustive_candidate_simplex_pairs<const D: usize, B>(
    simplices: &[RealizedSimplex<D>],
    skip: &FastHashSet<SimplexKey>,
    scope: &FastHashSet<SimplexKey>,
    mut on_pair: impl FnMut(&RealizedSimplex<D>, &RealizedSimplex<D>) -> ControlFlow<B>,
) -> (usize, Option<B>) {
    let mut examined = 0_usize;
    for (local_index, local_simplex) in simplices.iter().enumerate() {
        if !scope.contains(&local_simplex.key) || skip.contains(&local_simplex.key) {
            continue;
        }

        for (other_index, other_simplex) in simplices.iter().enumerate() {
            if other_index == local_index || skip.contains(&other_simplex.key) {
                continue;
            }
            if scope.contains(&other_simplex.key) && other_index < local_index {
                continue;
            }

            examined += 1;
            let first_index = local_index.min(other_index);
            let second_index = local_index.max(other_index);
            if let ControlFlow::Break(value) =
                on_pair(&simplices[first_index], &simplices[second_index])
            {
                return (examined, Some(value));
            }
        }
    }
    (examined, None)
}

/// Sweep-and-prune broad phase over Euclidean simplex bounding boxes.
///
/// See [`for_each_candidate_simplex_pair`] for the completeness argument and
/// references.
fn sweep_and_prune_candidate_simplex_pairs<const D: usize, B>(
    simplices: &[RealizedSimplex<D>],
    skip: &FastHashSet<SimplexKey>,
    mut on_pair: impl FnMut(&RealizedSimplex<D>, &RealizedSimplex<D>) -> ControlFlow<B>,
) -> (usize, Option<B>) {
    let mut boxes: Vec<SimplexBoundingBox<D>> = simplices
        .iter()
        .enumerate()
        .filter(|(_, simplex)| !skip.contains(&simplex.key))
        .map(|(index, simplex)| SimplexBoundingBox::from_realized(index, simplex))
        .collect();
    if boxes.len() < 2 {
        return (0, None);
    }

    let sweep_axis = widest_extent_axis(&boxes);
    boxes.sort_unstable_by(|left, right| left.min[sweep_axis].total_cmp(&right.min[sweep_axis]));

    let mut active: Vec<usize> = Vec::new();
    let mut examined = 0_usize;
    for current in 0..boxes.len() {
        let current_min = boxes[current].min[sweep_axis];
        // Retire boxes that end before the current box begins on the sweep
        // axis; they cannot overlap the current box or any later one.
        active.retain(|&candidate| boxes[candidate].max[sweep_axis] >= current_min);
        for &candidate in &active {
            if !boxes[candidate].overlaps(&boxes[current]) {
                continue;
            }
            examined += 1;
            let first_index = boxes[candidate]
                .simplex_index
                .min(boxes[current].simplex_index);
            let second_index = boxes[candidate]
                .simplex_index
                .max(boxes[current].simplex_index);
            if let ControlFlow::Break(value) =
                on_pair(&simplices[first_index], &simplices[second_index])
            {
                return (examined, Some(value));
            }
        }
        active.push(current);
    }
    (examined, None)
}

#[cfg(test)]
mod tests {
    use super::*;
    use crate::builder::DelaunayTriangulationBuilder;
    use crate::core::tds::{Tds, TriangulationConstructionState};
    use crate::core::triangulation::Triangulation;
    use crate::core::vertex::Vertex;
    use crate::delaunay_property_validation::DelaunayValidationError;
    use crate::geometry::kernel::FastKernel;
    use crate::topology::traits::topological_space::{GlobalTopology, ToroidalConstructionMode};
    use crate::validation::{DelaunayTriangulationValidationError, DelaunayVerificationError};
    use crate::vertex;
    use approx::assert_abs_diff_eq;
    use std::assert_matches;

    fn test_vertex<const D: usize>(coords: [f64; D]) -> Vertex<(), D> {
        vertex!(coords).unwrap()
    }

    fn tds_from_vertices_and_simplices<const D: usize>(
        coords: &[[f64; D]],
        simplices: &[Vec<usize>],
    ) -> Tds<(), (), D> {
        tds_from_vertices_and_simplices_with_keys(coords, simplices).0
    }

    fn tds_from_vertices_and_simplices_with_keys<const D: usize>(
        coords: &[[f64; D]],
        simplices: &[Vec<usize>],
    ) -> (Tds<(), (), D>, Vec<SimplexKey>) {
        let mut tds = Tds::empty();
        let vertex_keys: Vec<_> = coords
            .iter()
            .map(|coords| {
                tds.insert_vertex_with_mapping(test_vertex(*coords))
                    .unwrap()
            })
            .collect();

        let mut simplex_keys = Vec::with_capacity(simplices.len());
        for simplex_vertices in simplices {
            let vertices: Vec<_> = simplex_vertices
                .iter()
                .map(|&index| vertex_keys[index])
                .collect();
            let simplex_key = tds
                .insert_simplex_with_mapping(Simplex::try_new_with_data(vertices, None).unwrap())
                .unwrap();
            simplex_keys.push(simplex_key);
        }

        tds.construction_state = TriangulationConstructionState::Constructed;
        tds.assign_neighbors().unwrap();
        tds.assign_incident_simplices().unwrap();
        (tds, simplex_keys)
    }

    fn tri_from_tds<const D: usize>(
        tds: Tds<(), (), D>,
    ) -> Triangulation<FastKernel<f64>, (), (), D> {
        Triangulation::new_with_tds(FastKernel::new(), tds)
    }

    fn tri_from_tds_with_topology<const D: usize>(
        tds: Tds<(), (), D>,
        global_topology: GlobalTopology<D>,
    ) -> Triangulation<FastKernel<f64>, (), (), D> {
        let mut tri = tri_from_tds(tds);
        tri.global_topology = global_topology;
        tri
    }

    fn realization_detail() -> TriangulationRealizationSimplexDetail {
        TriangulationRealizationSimplexDetail {
            key: SimplexKey::default(),
            uuid: Uuid::nil(),
            vertices: SimplexVertexKeyBuffer::new(),
            vertex_uuids: SimplexVertexUuidBuffer::new(),
        }
    }

    fn realization_pair_detail() -> TriangulationRealizationSimplexPairDetail {
        TriangulationRealizationSimplexPairDetail {
            first_simplex: realization_detail(),
            second_simplex: realization_detail(),
        }
    }

    fn realization_intersection_detail() -> TriangulationRealizationIntersectionDetail {
        TriangulationRealizationIntersectionDetail {
            first_simplex: realization_detail(),
            second_simplex: realization_detail(),
            shared_vertices: SimplexVertexKeyBuffer::new(),
            shared_vertex_uuids: SimplexVertexUuidBuffer::new(),
            first_only_witness_vertices: SimplexVertexKeyBuffer::new(),
            first_only_witness_vertex_uuids: SimplexVertexUuidBuffer::new(),
            second_only_witness_vertices: SimplexVertexKeyBuffer::new(),
            second_only_witness_vertex_uuids: SimplexVertexUuidBuffer::new(),
        }
    }

    fn assert_realization_error_kind(
        source: &TriangulationRealizationValidationError,
        expected: TriangulationRealizationValidationErrorKind,
    ) {
        assert_eq!(
            TriangulationRealizationValidationErrorKind::from(source),
            expected
        );
    }

    fn assert_single_simplex_realizes<const D: usize>() {
        let mut coords = Vec::with_capacity(D + 1);
        coords.push([0.0; D]);
        for axis in 0..D {
            let mut point = [0.0; D];
            point[axis] = 1.0;
            coords.push(point);
        }
        let simplex = (0..=D).collect();
        let mut tri = tri_from_tds(tds_from_vertices_and_simplices(&coords, &[simplex]));
        tri.normalize_and_promote_positive_orientation()
            .expect("fixture orientation should canonicalize");
        assert!(tri.is_valid_realization().is_ok());
    }

    #[test]
    fn is_valid_realization_accepts_single_simplex_dimensions_two_through_five() {
        assert_single_simplex_realizes::<2>();
        assert_single_simplex_realizes::<3>();
        assert_single_simplex_realizes::<4>();
        assert_single_simplex_realizes::<5>();
    }

    #[test]
    fn validate_realization_accepts_builder_constructed_triangulation() {
        let vertices = vec![
            test_vertex([0.0, 0.0, 0.0]),
            test_vertex([1.0, 0.0, 0.0]),
            test_vertex([0.0, 1.0, 0.0]),
            test_vertex([0.0, 0.0, 1.0]),
            test_vertex([0.25, 0.25, 0.25]),
        ];
        let dt = DelaunayTriangulationBuilder::new(&vertices)
            .build()
            .unwrap();

        assert!(dt.as_triangulation().validate_realization().is_ok());
    }

    #[test]
    fn is_valid_realization_accepts_two_tetrahedra_sharing_a_facet() {
        let coords = [
            [0.0, 0.0, 0.0],
            [1.0, 0.0, 0.0],
            [0.0, 1.0, 0.0],
            [0.0, 0.0, 1.0],
            [0.0, 0.0, -1.0],
        ];
        let tds = tds_from_vertices_and_simplices(&coords, &[vec![0, 1, 2, 3], vec![0, 2, 1, 4]]);
        let mut tri = tri_from_tds(tds);
        tri.normalize_and_promote_positive_orientation()
            .expect("fixture orientation should canonicalize");

        assert!(tri.is_valid_realization().is_ok());
    }

    #[test]
    fn full_facet_shortcut_rejects_same_side_overlap() {
        let coords = [
            [0.0, 0.0, 0.0],
            [1.0, 0.0, 0.0],
            [0.0, 1.0, 0.0],
            [0.0, 0.0, 1.0],
            [0.25, 0.25, 0.5],
        ];
        let tds = tds_from_vertices_and_simplices(&coords, &[vec![0, 1, 2, 3], vec![0, 2, 1, 4]]);
        let tri = tri_from_tds(tds);
        let simplices = tri
            .collect_realized_simplices()
            .expect("fixture simplices should realize");
        let err = validate_topology_aware_simplex_pair(&simplices[0], &simplices[1], None)
            .expect_err("same-side simplices must overlap outside their shared facet");

        assert_matches!(
            err,
            TriangulationRealizationValidationError::SimplexIntersectionOutsideSharedFace {
                detail,
                ..
            } if detail.shared_vertices.len() == 3
                && detail.shared_vertex_uuids.len() == 3
                && detail.first_only_witness_vertices.len() == 1
                && detail.first_only_witness_vertex_uuids.len() == 1
                && detail.second_only_witness_vertices.len() == 1
                && detail.second_only_witness_vertex_uuids.len() == 1
        );
    }

    #[test]
    fn validate_realization_rejects_degenerate_simplex() {
        let coords = [[0.0, 0.0], [1.0, 0.0], [2.0, 0.0]];
        let tds = tds_from_vertices_and_simplices(&coords, &[vec![0, 1, 2]]);
        let tri = tri_from_tds(tds);

        let diagnostic = tri
            .realization_diagnostic()
            .unwrap()
            .expect("degenerate simplex should produce a diagnostic");
        let report_first = tri
            .realization_report()
            .unwrap()
            .violations
            .into_iter()
            .next()
            .expect("degenerate simplex should be the first report violation");
        assert_eq!(diagnostic, report_first);

        let err = tri.is_valid_realization().unwrap_err();
        assert_eq!(err, diagnostic);
        assert_matches!(
            err,
            TriangulationRealizationValidationError::DegenerateSimplex { dimension: 2, .. }
        );
    }

    #[test]
    fn negative_orientation_is_level_four_not_level_three() {
        let coords = [[0.0, 0.0], [1.0, 0.0], [0.0, 1.0]];
        let tds = tds_from_vertices_and_simplices(&coords, &[vec![0, 2, 1]]);
        let tri = tri_from_tds(tds);

        tri.is_valid_topology()
            .expect("intrinsic topology must not depend on coordinate orientation");
        let error = tri
            .validate_realization()
            .expect_err("negative coordinate orientation must fail Level 4");

        assert_matches!(
            error,
            TriangulationRealizationValidationError::NegativeSimplexOrientation {
                dimension: 2,
                ..
            }
        );
    }

    #[test]
    fn is_valid_realization_preserves_duplicate_label_detail() {
        let coords = [[0.0, 0.0], [1.0, 0.0], [0.0, 1.0]];
        let (mut tds, simplex_keys) =
            tds_from_vertices_and_simplices_with_keys(&coords, &[vec![0, 1, 2]]);
        let simplex_key = simplex_keys[0];
        let (duplicate_key, middle_key, duplicate_uuid) = {
            let simplex = tds
                .simplex(simplex_key)
                .expect("fixture simplex should exist");
            let duplicate_key = simplex.vertices()[0];
            let middle_key = simplex.vertices()[1];
            let duplicate_uuid = tds
                .vertex(duplicate_key)
                .expect("duplicate fixture vertex should exist")
                .uuid();
            (duplicate_key, middle_key, duplicate_uuid)
        };
        {
            let simplex = tds
                .simplex_mut(simplex_key)
                .expect("fixture simplex should be mutable");
            simplex.clear_vertex_keys();
            simplex.push_vertex_key(duplicate_key);
            simplex.push_vertex_key(middle_key);
            simplex.push_vertex_key(duplicate_key);
        }
        let tri = tri_from_tds(tds);

        let err = tri.is_valid_realization().unwrap_err();

        assert_matches!(
            err,
            TriangulationRealizationValidationError::DuplicateSimplexRealizationLabel {
                simplex_key: observed_simplex_key,
                vertex_key,
                vertex_uuid,
                first_index: 0,
                duplicate_index: 2,
                detail,
                ..
            } if observed_simplex_key == simplex_key
                && vertex_key == duplicate_key
                && vertex_uuid == duplicate_uuid
                && detail.vertices.len() == 3
                && detail.vertex_uuids.len() == 3
        );
    }

    #[test]
    fn realization_report_includes_degenerate_simplex_vertices() {
        let coords = [[0.0, 0.0], [1.0, 0.0], [2.0, 0.0]];
        let tds = tds_from_vertices_and_simplices(&coords, &[vec![0, 1, 2]]);
        let tri = tri_from_tds(tds);

        let report = tri
            .realization_report()
            .expect("realization report should be generated");
        assert!(!report.is_valid());
        assert_eq!(report.checked_simplices, 1);
        assert_matches!(
            &report.violations[..],
            [TriangulationRealizationValidationError::DegenerateSimplex {
                detail,
                dimension: 2,
                ..
            }] if detail.vertices.len() == 3 && detail.vertex_uuids.len() == 3
        );
    }

    #[test]
    fn is_valid_realization_rejects_nonadjacent_edge_crossing() {
        let coords = [[0.0, 0.0], [2.0, 0.0], [0.0, 2.0], [2.0, 2.0], [1.0, -1.0]];
        let tds = tds_from_vertices_and_simplices(
            &coords,
            &[vec![0, 1, 2], vec![2, 1, 3], vec![3, 2, 4]],
        );
        let tri = tri_from_tds(tds);

        let err = tri.is_valid_realization().unwrap_err();
        assert_matches!(
            err,
            TriangulationRealizationValidationError::SimplexIntersectionOutsideSharedFace { .. }
        );
    }

    #[test]
    fn is_valid_realization_sweep_and_prune_detects_interposed_overlap() {
        // Regression guard for the sweep-and-prune broad phase: triangles A and
        // B genuinely overlap (no shared vertices), but triangle C sits between
        // them in the sweep-axis ordering while overlapping neither. A naive
        // "compare only neighbors in sorted order" prune would drop the A/B
        // pair; sweep-and-prune keeps A active across C and still reports the
        // overlap, so the broad phase must not introduce a false negative.
        let coords = [
            [0.0, 0.0],  // 0  A
            [10.0, 0.0], // 1  A
            [0.0, 2.0],  // 2  A
            [3.0, -1.0], // 3  C (x between A and B, disjoint in y)
            [4.0, -1.0], // 4  C
            [3.5, -0.5], // 5  C
            [4.5, -1.0], // 6  B (overlaps A)
            [5.5, -1.0], // 7  B
            [4.5, 2.0],  // 8  B
        ];
        let tds = tds_from_vertices_and_simplices(
            &coords,
            &[vec![0, 1, 2], vec![3, 4, 5], vec![6, 7, 8]],
        );
        let tri = tri_from_tds(tds);

        let err = tri.is_valid_realization().unwrap_err();
        assert_matches!(
            err,
            TriangulationRealizationValidationError::SimplexIntersectionOutsideSharedFace { .. }
        );
    }

    #[test]
    fn realization_report_includes_intersection_witness_vertices() {
        let coords = [[0.0, 0.0], [2.0, 0.0], [0.0, 2.0], [2.0, 2.0], [1.0, -1.0]];
        let tds = tds_from_vertices_and_simplices(
            &coords,
            &[vec![0, 1, 2], vec![2, 1, 3], vec![3, 2, 4]],
        );
        let tri = tri_from_tds(tds);

        let report = tri
            .realization_report()
            .expect("realization report should be generated");
        let intersection =
            report
                .violations
                .iter()
                .find(|violation| {
                    matches!(
                    violation,
                    TriangulationRealizationValidationError::SimplexIntersectionOutsideSharedFace {
                        ..
                    }
                )
                })
                .expect("report should include an illegal simplex intersection");

        assert_matches!(
            intersection,
            TriangulationRealizationValidationError::SimplexIntersectionOutsideSharedFace {
                detail,
                ..
            } if detail.first_simplex.vertices.len() == 3
                && detail.first_simplex.vertex_uuids.len() == 3
                && detail.second_simplex.vertices.len() == 3
                && detail.second_simplex.vertex_uuids.len() == 3
                && !detail.first_only_witness_vertices.is_empty()
                && detail.first_only_witness_vertices.len()
                    == detail.first_only_witness_vertex_uuids.len()
                && !detail.second_only_witness_vertices.is_empty()
                && detail.second_only_witness_vertices.len()
                    == detail.second_only_witness_vertex_uuids.len()
        );
    }

    #[test]
    fn is_valid_realization_accepts_lifted_toroidal_simplex_chart() {
        let coords = [[0.9, 0.1], [0.1, 0.1], [0.9, 0.3]];
        let (mut tds, simplex_keys) =
            tds_from_vertices_and_simplices_with_keys(&coords, &[vec![0, 1, 2]]);
        tds.simplex_mut(simplex_keys[0])
            .unwrap()
            .set_periodic_vertex_offsets(vec![[0, 0], [1, 0], [0, 0]])
            .unwrap();
        let tri = tri_from_tds_with_topology(
            tds,
            GlobalTopology::try_toroidal([1.0, 1.0], ToroidalConstructionMode::PeriodicImagePoint)
                .unwrap(),
        );

        assert!(tri.is_valid_realization().is_ok());
    }

    #[test]
    fn translated_simplex_updates_lifted_vertex_identities() {
        let coords = [[0.9, 0.1], [0.1, 0.1], [0.9, 0.3]];
        let (mut tds, simplex_keys) =
            tds_from_vertices_and_simplices_with_keys(&coords, &[vec![0, 1, 2]]);
        tds.simplex_mut(simplex_keys[0])
            .unwrap()
            .set_periodic_vertex_offsets(vec![[0, 0], [1, 0], [0, 0]])
            .unwrap();
        let tri = tri_from_tds_with_topology(
            tds,
            GlobalTopology::try_toroidal([1.0, 1.0], ToroidalConstructionMode::PeriodicImagePoint)
                .unwrap(),
        );
        let realized = tri
            .collect_realized_simplices()
            .expect("periodic simplex should realize")
            .pop()
            .expect("fixture should contain one simplex");
        let shift = [-1_i32, 2_i32];
        let translated = translated_simplex(&realized, &[1.0, 1.0], &shift)
            .expect("finite periodic translation should succeed");

        for (before, after) in realized
            .realization
            .labels()
            .iter()
            .zip(translated.realization.labels())
        {
            assert_eq!(before.key, after.key);
            assert_eq!(
                after.offset,
                std::array::from_fn(|axis| before.offset[axis] + i64::from(shift[axis])),
            );
        }
    }

    #[test]
    fn point_for_identity_reports_missing_lifted_offset() {
        let coords = [[0.9, 0.1], [0.1, 0.1], [0.9, 0.3]];
        let (mut tds, simplex_keys) =
            tds_from_vertices_and_simplices_with_keys(&coords, &[vec![0, 1, 2]]);
        tds.simplex_mut(simplex_keys[0])
            .unwrap()
            .set_periodic_vertex_offsets(vec![[0, 0], [1, 0], [0, 0]])
            .unwrap();
        let tri = tri_from_tds_with_topology(
            tds,
            GlobalTopology::try_toroidal([1.0, 1.0], ToroidalConstructionMode::PeriodicImagePoint)
                .unwrap(),
        );
        let realized = tri
            .collect_realized_simplices()
            .expect("periodic simplex should realize")
            .pop()
            .expect("fixture should contain one simplex");
        let missing_identity = realized.realization.labels()[0].translated(&[2, -3]);

        let err = realized.point_for_identity(missing_identity).unwrap_err();
        assert_matches!(
            err,
            TriangulationRealizationValidationError::Tds(source)
                if matches!(
                    *source,
                    TdsError::VertexNotFound { vertex_key, ref context }
                        if vertex_key == missing_identity.key
                            && context.contains(&format!("offset {:?}", missing_identity.offset))
                )
        );
    }

    #[test]
    fn is_valid_realization_rejects_unsupported_spherical_topology() {
        let coords = [[0.0, 0.0], [1.0, 0.0], [0.0, 1.0]];
        let tds = tds_from_vertices_and_simplices(&coords, &[vec![0, 1, 2]]);
        let tri = tri_from_tds_with_topology(tds, GlobalTopology::Spherical);

        let err = tri.is_valid_realization().unwrap_err();
        assert_matches!(
            err,
            TriangulationRealizationValidationError::UnsupportedTopology {
                topology: TopologyKind::Spherical,
                dimension: 2,
            }
        );
    }

    #[test]
    fn is_valid_realization_rejects_periodic_simplex_spanning_domain() {
        let coords = [[0.0, 0.0], [1.0, 0.0], [0.0, 0.25]];
        let tds = tds_from_vertices_and_simplices(&coords, &[vec![0, 1, 2]]);
        let tri = tri_from_tds_with_topology(
            tds,
            GlobalTopology::try_toroidal([1.0, 1.0], ToroidalConstructionMode::PeriodicImagePoint)
                .unwrap(),
        );

        let err = tri.is_valid_realization().unwrap_err();
        let (span, period) = match err {
            TriangulationRealizationValidationError::PeriodicSimplexSpansDomain {
                axis: 0,
                span,
                period,
                ..
            } => (span, period),
            other => panic!("expected periodic simplex span violation, got {other:?}"),
        };
        assert_abs_diff_eq!(span, 1.0, epsilon = f64::EPSILON);
        assert_abs_diff_eq!(period, 1.0, epsilon = f64::EPSILON);
    }

    #[test]
    fn is_valid_realization_rejects_periodic_translate_overlap() {
        let coords = [
            [0.0, 0.0],
            [0.2, 0.0],
            [0.0, 0.8],
            [0.95, 0.1],
            [0.15, 0.1],
            [0.95, 0.3],
        ];
        let (mut tds, simplex_keys) =
            tds_from_vertices_and_simplices_with_keys(&coords, &[vec![0, 1, 2], vec![3, 4, 5]]);
        tds.simplex_mut(simplex_keys[1])
            .unwrap()
            .set_periodic_vertex_offsets(vec![[0, 0], [1, 0], [0, 0]])
            .unwrap();
        let tri = tri_from_tds_with_topology(
            tds,
            GlobalTopology::try_toroidal([1.0, 1.0], ToroidalConstructionMode::PeriodicImagePoint)
                .unwrap(),
        );

        let err = tri.is_valid_realization().unwrap_err();
        assert_matches!(
            err,
            TriangulationRealizationValidationError::SimplexIntersectionOutsideSharedFace { .. }
        );
    }

    #[test]
    fn realization_error_kind_covers_wrapped_and_topology_variants() {
        assert_realization_error_kind(
            &TriangulationRealizationValidationError::Tds(Box::new(
                TdsError::InconsistentDataStructure {
                    message: "synthetic TDS failure".to_string(),
                },
            )),
            TriangulationRealizationValidationErrorKind::Tds,
        );
        assert_realization_error_kind(
            &TriangulationRealizationValidationError::Triangulation(Box::new(
                TriangulationValidationError::Disconnected { simplex_count: 2 },
            )),
            TriangulationRealizationValidationErrorKind::Triangulation,
        );
        assert_realization_error_kind(
            &TriangulationRealizationValidationError::UnsupportedTopology {
                topology: TopologyKind::Spherical,
                dimension: 2,
            },
            TriangulationRealizationValidationErrorKind::UnsupportedTopology,
        );
        assert_realization_error_kind(
            &TriangulationRealizationValidationError::TopologyLifting {
                simplex_key: SimplexKey::default(),
                simplex_uuid: Uuid::nil(),
                vertex_key: VertexKey::default(),
                vertex_uuid: Uuid::nil(),
                source: GlobalTopologyModelError::NonFiniteCoordinate {
                    axis: 0,
                    value: f64::NAN,
                },
            },
            TriangulationRealizationValidationErrorKind::TopologyLifting,
        );
    }

    #[test]
    fn realization_error_kind_covers_simplex_geometry_variants() {
        assert_realization_error_kind(
            &TriangulationRealizationValidationError::DuplicateSimplexRealizationLabel {
                simplex_key: SimplexKey::default(),
                simplex_uuid: Uuid::nil(),
                detail: Box::new(realization_detail()),
                vertex_key: VertexKey::default(),
                vertex_uuid: Uuid::nil(),
                first_index: 0,
                duplicate_index: 2,
            },
            TriangulationRealizationValidationErrorKind::DuplicateSimplexRealizationLabel,
        );
        assert_realization_error_kind(
            &TriangulationRealizationValidationError::DegenerateSimplex {
                simplex_key: SimplexKey::default(),
                simplex_uuid: Uuid::nil(),
                detail: Box::new(realization_detail()),
                dimension: 2,
            },
            TriangulationRealizationValidationErrorKind::DegenerateSimplex,
        );
        assert_realization_error_kind(
            &TriangulationRealizationValidationError::NegativeSimplexOrientation {
                simplex_key: SimplexKey::default(),
                simplex_uuid: Uuid::nil(),
                detail: Box::new(realization_detail()),
                dimension: 2,
            },
            TriangulationRealizationValidationErrorKind::NegativeSimplexOrientation,
        );
        assert_realization_error_kind(
            &TriangulationRealizationValidationError::CoordinateValidation {
                simplex_key: SimplexKey::default(),
                simplex_uuid: Uuid::nil(),
                vertex_key: VertexKey::default(),
                vertex_uuid: Uuid::nil(),
                source: CoordinateValidationError::InvalidCoordinate {
                    coordinate_index: 0,
                    coordinate_value: InvalidCoordinateValue::Nan,
                    dimension: 2,
                },
            },
            TriangulationRealizationValidationErrorKind::CoordinateValidation,
        );
        assert_realization_error_kind(
            &TriangulationRealizationValidationError::PredicateFailed {
                simplex_key: SimplexKey::default(),
                simplex_uuid: Uuid::nil(),
                detail: Box::new(realization_detail()),
                source: CoordinateConversionError::NonFiniteValue {
                    coordinate_index: 0,
                    coordinate_value: InvalidCoordinateValue::Nan,
                },
            },
            TriangulationRealizationValidationErrorKind::PredicateFailed,
        );
        assert_realization_error_kind(
            &TriangulationRealizationValidationError::SingularBarycentricBasis {
                simplex_key: SimplexKey::default(),
                simplex_uuid: Uuid::nil(),
                detail: Box::new(realization_detail()),
                dimension: 2,
            },
            TriangulationRealizationValidationErrorKind::SingularBarycentricBasis,
        );
    }

    #[test]
    fn realization_error_kind_covers_intersection_periodic_and_layer_variants() {
        assert_realization_error_kind(
            &TriangulationRealizationValidationError::SimplexIntersectionOutsideSharedFace {
                first_simplex_key: SimplexKey::default(),
                first_simplex_uuid: Uuid::nil(),
                second_simplex_key: SimplexKey::default(),
                second_simplex_uuid: Uuid::nil(),
                detail: Box::new(realization_intersection_detail()),
            },
            TriangulationRealizationValidationErrorKind::SimplexIntersectionOutsideSharedFace,
        );
        assert_realization_error_kind(
            &TriangulationRealizationValidationError::PeriodicSimplexSpansDomain {
                simplex_key: SimplexKey::default(),
                simplex_uuid: Uuid::nil(),
                detail: Box::new(realization_detail()),
                axis: 0,
                span: 1.0,
                period: 1.0,
            },
            TriangulationRealizationValidationErrorKind::PeriodicSimplexSpansDomain,
        );
        assert_realization_error_kind(
            &TriangulationRealizationValidationError::InvalidPeriodicDomainPeriod {
                simplex_key: SimplexKey::default(),
                simplex_uuid: Uuid::nil(),
                detail: Box::new(realization_detail()),
                source: PeriodicDomainPeriodError::NonPositivePeriod {
                    axis: 0,
                    period: 0.0,
                },
            },
            TriangulationRealizationValidationErrorKind::InvalidPeriodicDomainPeriod,
        );
        assert_realization_error_kind(
            &TriangulationRealizationValidationError::PeriodicTranslateRangeOverflow {
                first_simplex_key: SimplexKey::default(),
                first_simplex_uuid: Uuid::nil(),
                second_simplex_key: SimplexKey::default(),
                second_simplex_uuid: Uuid::nil(),
                detail: Box::new(realization_pair_detail()),
                axis: 0,
                lower_bound: f64::from(i32::MIN) - 1.0,
                upper_bound: 0.0,
            },
            TriangulationRealizationValidationErrorKind::PeriodicTranslateRangeOverflow,
        );
        assert_realization_error_kind(
            &TriangulationRealizationValidationError::UnexpectedValidationLayer {
                kind: InvariantKind::DelaunayProperty,
                source: Box::new(InvariantError::Delaunay(
                    DelaunayTriangulationValidationError::VerificationFailed {
                        source: Box::new(DelaunayVerificationError::from(
                            DelaunayValidationError::TriangulationState {
                                source: TdsError::InconsistentDataStructure {
                                    message: "synthetic higher-layer failure".to_string(),
                                },
                            },
                        )),
                    },
                )),
            },
            TriangulationRealizationValidationErrorKind::UnexpectedValidationLayer,
        );
    }
}