delaunay 0.8.3

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.
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
//! Delaunay-level validation APIs, consuming promotion boundaries, and construction diagnostics.
//!
//! This module owns validation at the [`DelaunayTriangulation`]
//! boundary: Level 5 fast-fail checks, first diagnostics, aggregate reports,
//! cumulative validation roll-up, and construction-time candidate promotion. The
//! lower-level empty-circumsphere scan over bare [`Tds`](crate::tds::Tds) storage lives in
//! `property_validation`.

#![forbid(unsafe_code)]

use crate::core::algorithms::flips::{
    DelaunayRepairError, verify_complete_euclidean_tds_via_robust_flip_predicates,
    verify_tds_via_flip_predicates_assuming_connected,
};
use crate::core::collections::ViolationBuffer;
use crate::core::tds::{SimplexKey, Tds, TdsError, TopologyOwnerId};
use crate::delaunay_model::DelaunayTriangulation;
#[cfg(feature = "diagnostics")]
use crate::delaunay_property_validation::debug_print_first_delaunay_violation as debug_print_first_tds_delaunay_violation;
use crate::delaunay_property_validation::{
    DelaunayValidationError, DelaunayViolationReport,
    delaunay_violation_report as tds_delaunay_violation_report, is_delaunay_property_only,
};
use crate::draft::DelaunayTriangulationDraft;
use crate::geometry::kernel::Kernel;
use crate::refinement::RefinementError;
use crate::repair::DelaunayRepairOperation;
use crate::topology::traits::topological_space::GlobalTopology;
use crate::triangulation::Triangulation;
use crate::triangulation::builder::{
    TriangulationBuildFailure, TriangulationBuilder, TriangulationBuilderError,
};
use crate::triangulation::realization::TriangulationRealizationValidationError;
use crate::triangulation::validation::{
    TopologyCertificationEvidence, TopologyConstructionProvenance, TopologyGuarantee,
    TriangulationValidationError,
};
pub use crate::validation_report::{
    InvariantError, InvariantKind, InvariantViolation, TriangulationValidationReport,
};
use std::num::NonZeroUsize;
use thiserror::Error;

/// Discriminant for compact Level 5 Delaunay-validation summaries.
#[derive(Clone, Copy, Debug, Eq, PartialEq)]
#[non_exhaustive]
pub enum DelaunayValidationErrorKind {
    /// Lower-layer TDS validation failed.
    Tds,
    /// Lower-layer topology validation failed.
    Triangulation,
    /// Lower-layer realized-geometry validation failed.
    Realization,
    /// Delaunay verification failed.
    VerificationFailed,
    /// Typed repair validation failed.
    RepairOperationFailed,
}

impl From<&DelaunayTriangulationValidationError> for DelaunayValidationErrorKind {
    fn from(source: &DelaunayTriangulationValidationError) -> Self {
        match source {
            DelaunayTriangulationValidationError::Tds { source: _ } => Self::Tds,
            DelaunayTriangulationValidationError::Triangulation { source: _ } => {
                Self::Triangulation
            }
            DelaunayTriangulationValidationError::Realization { source: _ } => Self::Realization,
            DelaunayTriangulationValidationError::VerificationFailed { .. } => {
                Self::VerificationFailed
            }
            DelaunayTriangulationValidationError::RepairOperationFailed { .. } => {
                Self::RepairOperationFailed
            }
        }
    }
}

impl<K, U, V, const D: usize> Triangulation<K, U, V, D> {
    /// Builds a detailed Level 5 empty-circumsphere diagnostic without claiming
    /// that this Levels 1–4 owner is Delaunay.
    ///
    /// # Errors
    ///
    /// Returns [`DelaunayValidationError`] if a simplex is malformed, a vertex
    /// reference is stale, or an exact predicate cannot be evaluated.
    ///
    /// # Examples
    ///
    /// A Levels 1–4 owner can report a Level 5 violation without claiming the
    /// stronger [`DelaunayTriangulation`] contract:
    ///
    /// ```rust
    /// use delaunay::prelude::construction::{
    ///     DelaunayResult, DelaunayTriangulationBuilder,
    ///     DelaunayTriangulationConstructionError,
    /// };
    ///
    /// # fn main() -> DelaunayResult<()> {
    /// let vertices = vec![
    ///     delaunay::vertex![0.0, 0.0]?,
    ///     delaunay::vertex![4.0, 0.0]?,
    ///     delaunay::vertex![4.0, 2.0]?,
    ///     delaunay::vertex![1.0, 2.0]?,
    /// ];
    /// let simplices = vec![vec![0, 1, 2], vec![0, 2, 3]];
    /// let triangulation =
    ///     DelaunayTriangulationBuilder::try_from_vertices_and_simplices(&vertices, &simplices)
    ///         .map_err(DelaunayTriangulationConstructionError::from)?
    ///         .build_triangulation()?;
    ///
    /// let report = triangulation.delaunay_violation_report(None)?;
    /// assert!(!report.is_valid());
    /// # Ok(())
    /// # }
    /// ```
    pub fn delaunay_violation_report(
        &self,
        simplices_to_check: Option<&[SimplexKey]>,
    ) -> Result<DelaunayViolationReport, DelaunayValidationError> {
        tds_delaunay_violation_report(self.tds(), simplices_to_check)
    }

    /// Logs the first Level 5 violation in this generic triangulation.
    ///
    /// # Examples
    ///
    /// ```rust
    /// use delaunay::prelude::construction::{DelaunayResult, DelaunayTriangulationBuilder};
    ///
    /// # fn main() -> DelaunayResult<()> {
    /// let vertices = [
    ///     delaunay::vertex![0.0, 0.0]?,
    ///     delaunay::vertex![1.0, 0.0]?,
    ///     delaunay::vertex![0.0, 1.0]?,
    /// ];
    /// let triangulation = DelaunayTriangulationBuilder::new(&vertices)
    ///     .build_triangulation()?;
    /// triangulation.debug_print_first_delaunay_violation(None);
    /// # Ok(())
    /// # }
    /// ```
    #[cfg(feature = "diagnostics")]
    #[cfg_attr(docsrs, doc(cfg(feature = "diagnostics")))]
    pub fn debug_print_first_delaunay_violation(&self, simplices_subset: Option<&[SimplexKey]>) {
        debug_print_first_tds_delaunay_violation(self.tds(), simplices_subset);
    }
}

/// Level 5 evidence bound to one exact topology state.
///
/// Only the validation functions in this module can create a certificate.
/// Publication checks its owner, generation, topology provenance, and evidence
/// source before using it, so validation evidence cannot outlive a topology
/// mutation or certify a stronger predicate than the one actually checked.
#[derive(Clone, Debug)]
pub(crate) struct DelaunayLevelFiveCertificate<const D: usize> {
    owner_id: TopologyOwnerId,
    generation: u64,
    global_topology: GlobalTopology<D>,
    evidence: DelaunayLevelFiveEvidence,
}

#[derive(Clone, Copy, Debug, Eq, PartialEq)]
enum DelaunayLevelFiveEvidence {
    EuclideanEmptyCircumsphere,
    FlipPredicates,
}

impl<const D: usize> DelaunayLevelFiveCertificate<D> {
    /// Captures the exact topology state whose Level 5 predicate just passed.
    fn for_triangulation<K, U, V>(
        triangulation: &Triangulation<K, U, V, D>,
        evidence: DelaunayLevelFiveEvidence,
    ) -> Self {
        Self {
            owner_id: triangulation.tds.topology_owner_id(),
            generation: triangulation.tds.generation(),
            global_topology: triangulation.global_topology,
            evidence,
        }
    }

    /// Returns whether this evidence describes the owner's exact topology state.
    pub(crate) fn applies_to<K, U, V>(&self, triangulation: &Triangulation<K, U, V, D>) -> bool {
        self.owner_id == triangulation.tds.topology_owner_id()
            && self.generation == triangulation.tds.generation()
            && self.global_topology == triangulation.global_topology
            && match self.evidence {
                DelaunayLevelFiveEvidence::EuclideanEmptyCircumsphere => {
                    triangulation.global_topology.is_euclidean()
                }
                DelaunayLevelFiveEvidence::FlipPredicates => {
                    !triangulation.global_topology.is_euclidean()
                }
            }
    }
}

/// Certifies only Level 5 for a proof-bearing Levels 1–4 owner.
///
/// Delaunayize uses this borrowed form before committing its outer rollback
/// transaction, ensuring that a failed final check can still restore and return
/// the original triangulation.
pub(crate) fn certify_level_five_for_refinement<K, U, V, const D: usize>(
    triangulation: &Triangulation<K, U, V, D>,
) -> Result<DelaunayLevelFiveCertificate<D>, DelaunayTriangulationValidationError>
where
    K: Kernel<D, Scalar = f64>,
{
    if triangulation.global_topology().is_euclidean() {
        is_delaunay_property_only(&triangulation.tds).map_err(|source| {
            DelaunayTriangulationValidationError::VerificationFailed {
                source: Box::new(DelaunayVerificationError::from(source)),
            }
        })?;
    } else {
        verify_tds_via_flip_predicates_assuming_connected(
            &triangulation.tds,
            &triangulation.kernel,
            triangulation.global_topology,
        )
        .map_err(
            |source| DelaunayTriangulationValidationError::VerificationFailed {
                source: Box::new(DelaunayVerificationError::from(source)),
            },
        )?;
    }

    let evidence = if triangulation.global_topology().is_euclidean() {
        DelaunayLevelFiveEvidence::EuclideanEmptyCircumsphere
    } else {
        DelaunayLevelFiveEvidence::FlipPredicates
    };
    Ok(DelaunayLevelFiveCertificate::for_triangulation(
        triangulation,
        evidence,
    ))
}

/// Typed source for Level 5 Delaunay verification failures.
///
/// Passive validation has two implementation paths:
/// - flip-predicate verification via
///   [`DelaunayTriangulation::verify_via_flip_predicates`](crate::DelaunayTriangulation::verify_via_flip_predicates),
///   used as a fast certificate for complete Euclidean point-set triangulations
///   and as the topology-aware validator for non-Euclidean triangulations
/// - empty-circumsphere validation via `is_delaunay_property_only`, used for
///   Euclidean publication and whenever the stronger flip-normal-form check is
///   inconclusive
///
/// This wrapper preserves which path failed and carries the original typed
/// error so callers can inspect predicate, topology, and simplex-key context
/// without parsing display text.
///
/// # Examples
///
/// ```rust
/// use delaunay::prelude::repair::{DelaunayRepairError, DelaunayRepairPostconditionFailure};
/// use delaunay::prelude::validation::{
///     DelaunayVerificationError, DelaunayVerificationErrorKind,
/// };
///
/// let source =
///     DelaunayVerificationError::from(DelaunayRepairError::PostconditionFailed {
///         reason: Box::new(DelaunayRepairPostconditionFailure::Disconnected { simplex_count: 1 }),
///     });
///
/// assert_eq!(
///     DelaunayVerificationErrorKind::from(&source),
///     DelaunayVerificationErrorKind::FlipPredicates,
/// );
/// ```
#[derive(Clone, Debug, Error, PartialEq)]
#[non_exhaustive]
pub enum DelaunayVerificationError {
    /// Flip-predicate verification failed.
    #[error("flip-predicate verification failed: {source}")]
    FlipPredicates {
        /// Underlying flip verification error.
        #[source]
        source: Box<DelaunayRepairError>,
    },

    /// Empty-circumsphere validation failed.
    #[error("empty-circumsphere validation failed: {source}")]
    EmptyCircumsphere {
        /// Underlying Delaunay property validation error.
        #[source]
        source: Box<DelaunayValidationError>,
    },
}

impl From<DelaunayRepairError> for DelaunayVerificationError {
    fn from(source: DelaunayRepairError) -> Self {
        Self::FlipPredicates {
            source: Box::new(source),
        }
    }
}

impl From<DelaunayValidationError> for DelaunayVerificationError {
    fn from(source: DelaunayValidationError) -> Self {
        Self::EmptyCircumsphere {
            source: Box::new(source),
        }
    }
}

/// Discriminant for compact Level 5 verification-source summaries.
///
/// # Examples
///
/// ```rust
/// use delaunay::prelude::repair::{DelaunayRepairError, DelaunayRepairPostconditionFailure};
/// use delaunay::prelude::validation::{
///     DelaunayVerificationError, DelaunayVerificationErrorKind,
/// };
///
/// let source =
///     DelaunayVerificationError::from(DelaunayRepairError::PostconditionFailed {
///         reason: Box::new(DelaunayRepairPostconditionFailure::Disconnected { simplex_count: 1 }),
///     });
/// let kind = DelaunayVerificationErrorKind::from(&source);
///
/// assert_eq!(kind, DelaunayVerificationErrorKind::FlipPredicates);
/// ```
#[derive(Clone, Copy, Debug, Eq, PartialEq)]
#[non_exhaustive]
pub enum DelaunayVerificationErrorKind {
    /// Flip-predicate verification failed.
    FlipPredicates,
    /// Empty-circumsphere validation failed.
    EmptyCircumsphere,
}

impl From<&DelaunayVerificationError> for DelaunayVerificationErrorKind {
    fn from(source: &DelaunayVerificationError) -> Self {
        match source {
            DelaunayVerificationError::FlipPredicates { .. } => Self::FlipPredicates,
            DelaunayVerificationError::EmptyCircumsphere { .. } => Self::EmptyCircumsphere,
        }
    }
}

/// Errors that can occur during Delaunay triangulation validation and repair.
///
/// The first four variants are returned by [`DelaunayTriangulation::validate`](crate::DelaunayTriangulation::validate)
/// (validation Levels 1-5):
/// - [`Tds`](Self::Tds) — element or TDS structural errors (Levels 1–2).
/// - [`Triangulation`](Self::Triangulation) — topology errors (Level 3).
/// - [`Realization`](Self::Realization) — realized-geometry errors (Level 4).
/// - [`VerificationFailed`](Self::VerificationFailed) — Delaunay property violation (Level 5).
///
/// [`DelaunayTriangulation::is_valid_delaunay`](crate::DelaunayTriangulation::is_valid_delaunay) returns only the Level 5
/// [`VerificationFailed`](Self::VerificationFailed) variant.
///
/// The repair-failure variants are **not** returned by `validate()` or
/// `is_valid()`. They are produced by mutating operations that invoke
/// flip-based repair internally (e.g. [`DelaunayTriangulation::delete_vertex`](crate::DelaunayTriangulation::delete_vertex)).
///
/// When manually forwarding lower-layer validation errors, prefer
/// `DelaunayTriangulationValidationError::from(tds_error)` or `.into()` for
/// [`TdsError`] and [`TriangulationValidationError`]. The enum stores those
/// sources behind `Box` to keep `Result<_, DelaunayTriangulationValidationError>`
/// compact while preserving typed error inspection.
///
/// # Examples
///
/// ```rust
/// use delaunay::prelude::construction::{DelaunayResult, DelaunayTriangulationBuilder};
/// use delaunay::prelude::validation::DelaunayTriangulationValidationError;
///
/// # fn main() -> DelaunayResult<()> {
/// let vertices = vec![
///     delaunay::vertex![0.0, 0.0, 0.0]?,
///     delaunay::vertex![1.0, 0.0, 0.0]?,
///     delaunay::vertex![0.0, 1.0, 0.0]?,
///     delaunay::vertex![0.0, 0.0, 1.0]?,
/// ];
/// let dt = DelaunayTriangulationBuilder::new(&vertices).build()?;
///
/// let result: Result<(), DelaunayTriangulationValidationError> = dt.validate();
/// assert!(result.is_ok());
/// # Ok(())
/// # }
/// ```
#[derive(Clone, Debug, Error, PartialEq)]
#[non_exhaustive]
pub enum DelaunayTriangulationValidationError {
    /// Lower-layer element or TDS structural validation error (Levels 1–2).
    #[error(transparent)]
    Tds {
        /// Boxed TDS source error.
        source: Box<TdsError>,
    },

    /// Lower-layer topology validation error (Level 3).
    #[error(transparent)]
    Triangulation {
        /// Boxed topology-validation source error.
        source: Box<TriangulationValidationError>,
    },

    /// Lower-layer realized-geometry validation error (Level 4).
    #[error(transparent)]
    Realization {
        /// Boxed realization-validation source error.
        source: Box<TriangulationRealizationValidationError>,
    },

    /// Delaunay verification detected a violation.
    ///
    /// This is returned by [`DelaunayTriangulation::is_valid_delaunay`](crate::DelaunayTriangulation::is_valid_delaunay) when Level 5
    /// validation fails. The error is a Level 5 (Delaunay property) issue, not
    /// a Level 1–2 structural problem. The [`DelaunayVerificationError`] source
    /// distinguishes flip-predicate validation from Euclidean
    /// empty-circumsphere validation.
    #[error("Delaunay verification failed: {source}")]
    VerificationFailed {
        /// Typed verification failure source.
        #[source]
        source: Box<DelaunayVerificationError>,
    },

    /// Flip-based Delaunay repair failed during a specific mutating operation.
    ///
    /// This preserves the underlying [`DelaunayRepairError`] so callers can
    /// inspect budget exhaustion, topology errors, predicate failures, and other
    /// repair causes without parsing display text. Operations that report this
    /// variant are responsible for documenting whether failure is transactional;
    /// [`delete_vertex`](crate::DelaunayTriangulation::delete_vertex)
    /// restores the pre-deletion triangulation when post-deletion repair fails.
    ///
    /// **Not** returned by `validate()` or `is_valid()` — those use
    /// [`VerificationFailed`](Self::VerificationFailed) for passive checks.
    #[error("Delaunay repair failed during {operation}: {source}")]
    RepairOperationFailed {
        /// Mutating operation that invoked repair.
        operation: DelaunayRepairOperation,
        /// Underlying flip-repair failure.
        #[source]
        source: Box<DelaunayRepairError>,
    },
}

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

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

impl From<TriangulationRealizationValidationError> for DelaunayTriangulationValidationError {
    fn from(source: TriangulationRealizationValidationError) -> Self {
        match source {
            TriangulationRealizationValidationError::Tds { source } => Self::Tds { source },
            TriangulationRealizationValidationError::Triangulation { source } => {
                Self::Triangulation { source }
            }
            source => Self::Realization {
                source: Box::new(source),
            },
        }
    }
}

/// Recoverable failure to refine a Levels 1–4 [`Triangulation`] through Level 5.
pub type DelaunayTriangulationRefinementError<K, U, V, const D: usize> =
    RefinementError<Triangulation<K, U, V, D>, DelaunayTriangulationValidationError>;

/// Stage-specific failure while composing TDS restoration through Level 5.
///
/// The variant identifies the strongest proof-bearing owner reached before
/// rejection. A Levels 3–4 failure retains the original [`Tds`]; a Level 5
/// failure retains the successfully promoted [`Triangulation`].
#[derive(Clone, Debug, Error)]
#[non_exhaustive]
pub(crate) enum DelaunayTdsRestorationError<K, U, V, const D: usize> {
    /// Levels 3–4 certification failed, leaving the Levels 1–2 owner intact.
    #[error("TDS-to-triangulation refinement failed: {failure}")]
    Triangulation {
        /// Recoverable TDS and typed Levels 3–4 diagnostic.
        #[source]
        failure: TriangulationBuildFailure<U, V, D>,
    },
    /// Level 5 certification failed after Levels 3–4 succeeded.
    #[error("triangulation-to-Delaunay refinement failed: {failure}")]
    Delaunay {
        /// Recoverable triangulation and typed Level 5 diagnostic.
        #[source]
        failure: DelaunayTriangulationRefinementError<K, U, V, D>,
    },
}

/// Owner-independent typed reason extracted from a failed checkpoint restoration.
#[derive(Clone, Debug, PartialEq)]
pub(crate) enum DelaunayTdsRestorationReason {
    /// Levels 3–4 promotion failed.
    Triangulation {
        /// Typed Levels 3–4 promotion failure.
        source: TriangulationBuilderError,
    },
    /// Level 5 promotion failed.
    Delaunay {
        /// Typed Level 5 promotion failure.
        source: DelaunayTriangulationValidationError,
    },
}

impl<K, U, V, const D: usize> DelaunayTdsRestorationError<K, U, V, D> {
    /// Discards the retained lower-layer owner while preserving the typed reason.
    pub(crate) fn into_reason(self) -> DelaunayTdsRestorationReason {
        match self {
            Self::Triangulation { failure } => DelaunayTdsRestorationReason::Triangulation {
                source: failure.into_reason(),
            },
            Self::Delaunay { failure } => DelaunayTdsRestorationReason::Delaunay {
                source: failure.into_reason(),
            },
        }
    }
}

/// Cadence for explicit validation checkpoints during construction diagnostics.
///
/// This is separate from [`crate::ValidationPolicy`],
/// which controls automatic insertion-time validation inside
/// [`crate::Triangulation`]. Diagnostic
/// harnesses can use this cadence for explicit periodic
/// [`DelaunayTriangulation::is_valid_delaunay`](crate::DelaunayTriangulation::is_valid_delaunay)
/// checks without overloading repair policy or exposing raw `Option<usize>`
/// scheduling in logs.
///
/// # Examples
///
/// ```rust
/// use delaunay::prelude::validation::ValidationCadence;
///
/// let cadence = ValidationCadence::from_optional_every(Some(128));
/// assert!(!cadence.should_validate(0));
/// assert!(!cadence.should_validate(127));
/// assert!(cadence.should_validate(128));
/// ```
#[must_use = "validation cadence values only affect diagnostics when they are used"]
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum ValidationCadence {
    /// Disable explicit periodic validation checkpoints.
    Never,
    /// Run explicit validation every N successful insertion attempts.
    EveryN(NonZeroUsize),
}

impl ValidationCadence {
    /// Converts an optional integer cadence into a typed validation cadence.
    ///
    /// `None` and `Some(0)` disable periodic validation.
    ///
    /// # Examples
    ///
    /// ```rust
    /// use delaunay::prelude::validation::ValidationCadence;
    ///
    /// std::assert_matches!(
    ///     ValidationCadence::from_optional_every(Some(32)),
    ///     ValidationCadence::EveryN(every) if every.get() == 32,
    /// );
    /// assert_eq!(
    ///     ValidationCadence::from_optional_every(None),
    ///     ValidationCadence::Never,
    /// );
    /// ```
    pub const fn from_optional_every(validate_every: Option<usize>) -> Self {
        match validate_every {
            None | Some(0) => Self::Never,
            Some(every) => {
                if let Some(every) = NonZeroUsize::new(every) {
                    Self::EveryN(every)
                } else {
                    // Logically unreachable because `Some(0)` is matched above.
                    // Keep this branch so the function remains const without
                    // introducing unsafe code to construct `NonZeroUsize`.
                    Self::Never
                }
            }
        }
    }

    /// Returns true when validation should run for a one-based insertion count.
    ///
    /// A count of `0` never triggers validation because no insertion has
    /// completed yet.
    ///
    /// # Examples
    ///
    /// ```rust
    /// use delaunay::prelude::validation::ValidationCadence;
    ///
    /// let cadence = ValidationCadence::from_optional_every(Some(4));
    /// assert!(!cadence.should_validate(0));
    /// assert!(!cadence.should_validate(3));
    /// assert!(cadence.should_validate(4));
    /// ```
    #[must_use]
    pub const fn should_validate(self, insertion_count: usize) -> bool {
        match self {
            Self::Never => false,
            Self::EveryN(every) => {
                insertion_count != 0 && insertion_count.is_multiple_of(every.get())
            }
        }
    }
}

// =============================================================================
// VALIDATION (Minimal Bounds)
// =============================================================================

impl<K, U, V, const D: usize> DelaunayTriangulation<K, U, V, D>
where
    K: Kernel<D, Scalar = f64>,
{
    // -------------------------------------------------------------------------
    // VALIDATION
    // -------------------------------------------------------------------------

    /// Validates the Delaunay empty-circumsphere property (Level 5).
    ///
    /// This is the Delaunay layer's `is_valid`: it checks **only** the Delaunay property
    /// and intentionally does **not** run lower-layer validation.
    ///
    /// **Performance**: Complete Euclidean point-set triangulations first use
    /// O(simplices) robust flip predicates. Because that check also enforces a
    /// stronger flip normal form, a negative result falls back to the exact
    /// O(simplices × vertices) empty-circumsphere check. Non-Euclidean
    /// triangulations use the topology-aware flip verifier.
    ///
    /// For cumulative validation across the whole hierarchy, use [`validate`](Self::validate).
    ///
    /// # Errors
    ///
    /// Returns a [`DelaunayTriangulationValidationError`] if Level 5 verification
    /// detects a Delaunay violation, or if the underlying triangulation state is
    /// inconsistent and prevents geometric predicates from being evaluated. The
    /// [`VerificationFailed`](DelaunayTriangulationValidationError::VerificationFailed)
    /// variant preserves the typed [`DelaunayVerificationError`] source.
    ///
    /// # Examples
    ///
    /// ```rust
    /// use delaunay::prelude::construction::{DelaunayResult, DelaunayTriangulationBuilder};
    /// use delaunay::prelude::query::*;
    ///
    /// # fn main() -> DelaunayResult<()> {
    /// let vertices_4d = [
    ///     delaunay::vertex![0.0, 0.0, 0.0, 0.0]?,
    ///     delaunay::vertex![1.0, 0.0, 0.0, 0.0]?,
    ///     delaunay::vertex![0.0, 1.0, 0.0, 0.0]?,
    ///     delaunay::vertex![0.0, 0.0, 1.0, 0.0]?,
    ///     delaunay::vertex![0.0, 0.0, 0.0, 1.0]?,
    /// ];
    /// let dt = DelaunayTriangulationBuilder::new(&vertices_4d).build()?;
    ///
    /// // Level 5: Delaunay property only
    /// assert!(dt.is_valid_delaunay().is_ok());
    /// # Ok(())
    /// # }
    /// ```
    pub fn is_valid_delaunay(&self) -> Result<(), DelaunayTriangulationValidationError> {
        if self.global_topology().is_euclidean() {
            if self.euclidean_report_domain.supports_local_certificate()
                && verify_complete_euclidean_tds_via_robust_flip_predicates(&self.tri.tds).is_ok()
            {
                return Ok(());
            }

            return is_delaunay_property_only(&self.tri.tds).map_err(|source| {
                DelaunayTriangulationValidationError::VerificationFailed {
                    source: Box::new(DelaunayVerificationError::from(source)),
                }
            });
        }

        self.verify_via_flip_predicates().map_err(|source| {
            DelaunayTriangulationValidationError::VerificationFailed {
                source: Box::new(DelaunayVerificationError::from(source)),
            }
        })
    }

    /// Returns the first actionable Level 5 Delaunay diagnostic, if any.
    ///
    /// # 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.delaunay_diagnostic().is_none());
    /// # Ok(())
    /// # }
    /// ```
    #[must_use]
    pub fn delaunay_diagnostic(&self) -> Option<InvariantViolation> {
        self.delaunay_report()
            .err()
            .and_then(|report| report.violations.into_iter().next())
    }

    /// Builds a Level 5 Delaunay-property report.
    ///
    /// Euclidean triangulations produced by complete point-set insertion first
    /// use robust local flip predicates as an O(simplices) validity certificate.
    /// A successful certificate avoids the all-vertices empty-circumsphere scan.
    /// Explicit, reconstructed, or otherwise unproven connectivity delegates
    /// directly to the global scan; a failed or inconclusive local certificate
    /// also falls back so invalid reports retain every violating simplex and the
    /// same typed details. Non-Euclidean topologies use the topology-aware flip
    /// verifier and report the first violation it finds, avoiding an ordinary
    /// Euclidean circumsphere scan in periodic charts.
    ///
    /// # Errors
    ///
    /// Returns `Err(TriangulationValidationReport)` when one or more checkable
    /// Level 5 violations are found or when Delaunay predicates cannot be
    /// evaluated.
    ///
    /// # 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.delaunay_report().is_ok());
    /// # Ok(())
    /// # }
    /// ```
    pub fn delaunay_report(&self) -> Result<(), TriangulationValidationReport> {
        if self.global_topology().is_euclidean() {
            return match self.delaunay_violation_report(None) {
                Ok(report) if report.is_valid() => Ok(()),
                Ok(report) => Err(TriangulationValidationReport {
                    violations: report
                        .violation_details
                        .into_iter()
                        .map(|detail| InvariantViolation {
                            kind: InvariantKind::DelaunayProperty,
                            error: InvariantError::Delaunay {
                                source: DelaunayTriangulationValidationError::VerificationFailed {
                                    source: Box::new(DelaunayVerificationError::from(
                                        DelaunayValidationError::from(detail),
                                    )),
                                },
                            },
                        })
                        .collect(),
                }),
                Err(source) => Err(TriangulationValidationReport {
                    violations: vec![InvariantViolation {
                        kind: InvariantKind::DelaunayProperty,
                        error: InvariantError::Delaunay {
                            source: DelaunayTriangulationValidationError::VerificationFailed {
                                source: Box::new(DelaunayVerificationError::from(source)),
                            },
                        },
                    }],
                }),
            };
        }

        self.is_valid_delaunay()
            .map_err(|error| TriangulationValidationReport {
                violations: vec![InvariantViolation {
                    kind: InvariantKind::DelaunayProperty,
                    error: InvariantError::Delaunay { source: error },
                }],
            })
    }

    /// Builds a detailed Delaunay empty-circumsphere violation report.
    ///
    /// This is the high-level owner-bound counterpart to the TDS-level
    /// [`delaunay_violation_report`](crate::delaunay_violation_report) helper.
    /// For a full Euclidean report over connectivity proven to triangulate the
    /// complete point set, it first uses O(simplices) robust local flip predicates
    /// as a validity certificate. Explicit, reconstructed, and other unproven
    /// connectivity delegates directly to the TDS-level brute-force scan. A
    /// failed or inconclusive certificate also delegates so the returned
    /// violation set and typed diagnostics remain exact. Subset reports delegate
    /// directly because a global invalidity outside the subset says nothing
    /// about the requested simplices.
    ///
    /// # Errors
    ///
    /// Returns [`DelaunayValidationError`] if the scan encounters invalid
    /// simplex structure, missing vertex references, or robust predicate
    /// conversion failures.
    ///
    /// # Examples
    ///
    /// ```rust
    /// use delaunay::prelude::construction::{
    ///     DelaunayResult, DelaunayTriangulationBuilder,
    /// };
    ///
    /// # fn main() -> DelaunayResult<()> {
    /// let vertices = [
    ///     delaunay::vertex![0.0, 0.0]?,
    ///     delaunay::vertex![1.0, 0.0]?,
    ///     delaunay::vertex![0.0, 1.0]?,
    /// ];
    /// let dt = DelaunayTriangulationBuilder::new(&vertices).build()?;
    ///
    /// let report = dt.delaunay_violation_report(None)?;
    /// assert!(report.is_valid());
    /// # Ok(())
    /// # }
    /// ```
    pub fn delaunay_violation_report(
        &self,
        simplices_to_check: Option<&[SimplexKey]>,
    ) -> Result<DelaunayViolationReport, DelaunayValidationError> {
        if simplices_to_check.is_none()
            && self.global_topology().is_euclidean()
            && self.euclidean_report_domain.supports_local_certificate()
            && verify_complete_euclidean_tds_via_robust_flip_predicates(&self.tri.tds).is_ok()
        {
            return Ok(DelaunayViolationReport {
                number_of_vertices: self.number_of_vertices(),
                number_of_simplices: self.number_of_simplices(),
                checked_simplices: self.number_of_simplices(),
                violating_simplices: ViolationBuffer::new(),
                violation_details: Vec::new(),
            });
        }

        tds_delaunay_violation_report(&self.tri.tds, simplices_to_check)
    }

    /// Logs detailed information for the first Delaunay violation, when present.
    ///
    /// This diagnostics-only method keeps debug workflows on the high-level
    /// triangulation owner instead of requiring public TDS access.
    ///
    /// # Examples
    ///
    /// ```rust
    /// use delaunay::prelude::construction::{DelaunayResult, DelaunayTriangulationBuilder};
    ///
    /// # fn main() -> DelaunayResult<()> {
    /// let vertices = [
    ///     delaunay::vertex![0.0, 0.0]?,
    ///     delaunay::vertex![1.0, 0.0]?,
    ///     delaunay::vertex![0.0, 1.0]?,
    /// ];
    /// let dt = DelaunayTriangulationBuilder::new(&vertices).build()?;
    ///
    /// dt.debug_print_first_delaunay_violation(None);
    /// # Ok(())
    /// # }
    /// ```
    #[cfg(feature = "diagnostics")]
    #[cfg_attr(docsrs, doc(cfg(feature = "diagnostics")))]
    pub fn debug_print_first_delaunay_violation(&self, simplices_subset: Option<&[SimplexKey]>) {
        debug_print_first_tds_delaunay_violation(&self.tri.tds, simplices_subset);
    }

    /// Verify the local Delaunay flip normal form in O(simplices).
    ///
    /// This tests k=2 facets, k=3 ridges, and their inverse configurations.
    /// For Euclidean degenerate inputs, more than one triangulation can satisfy
    /// the empty-circumsphere property while only one is in this stronger local
    /// normal form. Consequently, an error is not by itself proof of a Euclidean
    /// Level 5 violation; use [`is_valid_delaunay`](Self::is_valid_delaunay),
    /// which falls back to the global empty-circumsphere check.
    ///
    /// Ideal for property-based testing with many iterations.
    ///
    /// # Errors
    ///
    /// Returns [`DelaunayRepairError`] if any flip predicate detects a Delaunay violation.
    ///
    /// # Examples
    ///
    /// ```
    /// use delaunay::prelude::construction::{DelaunayResult, DelaunayTriangulationBuilder};
    /// use delaunay::prelude::query::*;
    ///
    /// # fn main() -> DelaunayResult<()> {
    /// let vertices = vec![
    ///     delaunay::vertex![0.0, 0.0, 0.0]?,
    ///     delaunay::vertex![1.0, 0.0, 0.0]?,
    ///     delaunay::vertex![0.0, 1.0, 0.0]?,
    ///     delaunay::vertex![0.0, 0.0, 1.0]?,
    /// ];
    ///
    /// let dt = DelaunayTriangulationBuilder::new(&vertices).build()?;
    ///
    /// // Fast O(N) verification
    /// assert!(dt.verify_via_flip_predicates().is_ok());
    /// # Ok(())
    /// # }
    /// ```
    pub fn verify_via_flip_predicates(&self) -> Result<(), DelaunayRepairError> {
        verify_tds_via_flip_predicates_assuming_connected(
            &self.tri.tds,
            &self.tri.kernel,
            self.tri.global_topology,
        )
    }

    /// Performs cumulative validation for Levels 1–5.
    ///
    /// This validates:
    /// - **Levels 1–4** via [`Triangulation::validate_realization`](crate::Triangulation::validate_realization)
    /// - **Level 5** via [`DelaunayTriangulation::is_valid_delaunay`](Self::is_valid_delaunay)
    ///
    /// # Errors
    ///
    /// Returns a [`DelaunayTriangulationValidationError`] if lower-layer validation fails, if
    /// Level 4 realized-geometry validation fails, or if the Delaunay property check (Level 5)
    /// fails.
    ///
    /// # Examples
    ///
    /// ```rust
    /// use delaunay::prelude::construction::{DelaunayResult, DelaunayTriangulationBuilder};
    /// use delaunay::prelude::query::*;
    ///
    /// # fn main() -> DelaunayResult<()> {
    /// let vertices_4d = [
    ///     delaunay::vertex![0.0, 0.0, 0.0, 0.0]?,
    ///     delaunay::vertex![1.0, 0.0, 0.0, 0.0]?,
    ///     delaunay::vertex![0.0, 1.0, 0.0, 0.0]?,
    ///     delaunay::vertex![0.0, 0.0, 1.0, 0.0]?,
    ///     delaunay::vertex![0.0, 0.0, 0.0, 1.0]?,
    /// ];
    /// let dt = DelaunayTriangulationBuilder::new(&vertices_4d).build()?;
    ///
    /// // Levels 1–5: elements + structure + topology + realization + Delaunay property
    /// assert!(dt.validate().is_ok());
    /// # Ok(())
    /// # }
    /// ```
    pub fn validate(&self) -> Result<(), DelaunayTriangulationValidationError> {
        self.tri.validate_realization()?;
        self.is_valid_delaunay()
    }

    /// Generate a comprehensive validation report for the full validation hierarchy.
    ///
    /// This is intended for debugging/telemetry (e.g. `insert_with_statistics`) where
    /// you want to see *all* violated invariants, not just the first one.
    ///
    /// # Notes
    /// - If UUID↔key mappings are inconsistent, this returns only mapping failures (other
    ///   checks may produce misleading secondary errors).
    /// - This report is **cumulative** across Levels 1–5.
    ///
    /// # Errors
    ///
    /// Returns `Err(TriangulationValidationReport)` containing all violated invariants.
    ///
    /// # Examples
    ///
    /// ```rust
    /// use delaunay::prelude::construction::{DelaunayResult, DelaunayTriangulationBuilder};
    /// use delaunay::prelude::query::*;
    ///
    /// # fn main() -> DelaunayResult<()> {
    /// let vertices = [
    ///     delaunay::vertex![0.0, 0.0, 0.0]?,
    ///     delaunay::vertex![1.0, 0.0, 0.0]?,
    ///     delaunay::vertex![0.0, 1.0, 0.0]?,
    ///     delaunay::vertex![0.0, 0.0, 1.0]?,
    /// ];
    /// let dt = DelaunayTriangulationBuilder::new(&vertices).build()?;
    ///
    /// // Returns Ok(()) on success; otherwise returns a report listing all violations.
    /// let report = dt.validation_report();
    /// assert!(report.is_ok());
    /// # Ok(())
    /// # }
    /// ```
    pub fn validation_report(&self) -> Result<(), TriangulationValidationReport> {
        // Levels 1–3: reuse the Triangulation layer report.
        match self.tri.validation_report() {
            Ok(()) => {
                // Level 4 (realized geometry)
                let realization_report = self.tri.realization_report().map_err(|error| {
                    TriangulationValidationReport {
                        violations: vec![InvariantViolation {
                            kind: InvariantKind::Realization,
                            error: error.into(),
                        }],
                    }
                })?;
                let mut violations = Vec::new();
                if !realization_report.is_valid() {
                    violations.extend(realization_report.violations.into_iter().map(|error| {
                        InvariantViolation {
                            kind: InvariantKind::Realization,
                            error: error.into(),
                        }
                    }));
                }

                // Level 5 (Delaunay property)
                if let Err(delaunay_report) = self.delaunay_report() {
                    violations.extend(delaunay_report.violations);
                }

                if violations.is_empty() {
                    Ok(())
                } else {
                    Err(TriangulationValidationReport { violations })
                }
            }
            Err(mut report) => {
                // If mappings are inconsistent, return the lower-layer report unchanged.
                if report.violations.iter().any(|v| {
                    matches!(
                        v.kind,
                        InvariantKind::VertexMappings | InvariantKind::SimplexMappings
                    )
                }) {
                    return Err(report);
                }

                // Level 4 (realized geometry)
                match self.tri.realization_report() {
                    Ok(realization_report) => {
                        report
                            .violations
                            .extend(realization_report.violations.into_iter().map(|error| {
                                InvariantViolation {
                                    kind: InvariantKind::Realization,
                                    error: InvariantError::Realization { source: error },
                                }
                            }));
                    }
                    Err(source) => {
                        report.violations.push(InvariantViolation {
                            kind: InvariantKind::Realization,
                            error: InvariantError::Realization { source },
                        });
                    }
                }

                // Level 5 (Delaunay property)
                if let Err(delaunay_report) = self.delaunay_report() {
                    report.violations.extend(delaunay_report.violations);
                }

                if report.violations.is_empty() {
                    Ok(())
                } else {
                    Err(report)
                }
            }
        }
    }
    // -------------------------------------------------------------------------
    // PURE STRUCT ASSEMBLY
    // -------------------------------------------------------------------------
    /// Restores a checkpoint after an independent replay proved construction provenance.
    pub(crate) fn try_restore_with_provenance(
        tds: Tds<U, V, D>,
        kernel: K,
        topology_guarantee: TopologyGuarantee,
        global_topology: GlobalTopology<D>,
        construction_provenance: TopologyConstructionProvenance,
    ) -> Result<(Self, TopologyCertificationEvidence), DelaunayTdsRestorationError<K, U, V, D>>
    where
        U: Clone,
        V: Clone,
    {
        let (triangulation, topology_evidence) = TriangulationBuilder::new(tds, kernel)
            .topology_guarantee(topology_guarantee)
            .global_topology(global_topology)
            .construction_provenance(construction_provenance)
            .build_with_topology_evidence()
            .map_err(|failure| DelaunayTdsRestorationError::Triangulation { failure })?;
        let triangulation = DelaunayTriangulationDraft::from_triangulation(triangulation)
            .try_into_delaunay()
            .map_err(|failure| DelaunayTdsRestorationError::Delaunay { failure })?;
        Ok((triangulation, topology_evidence))
    }
}

#[cfg(test)]
mod tests {
    use super::*;
    use crate::builder::DelaunayTriangulationBuilder;
    use crate::core::algorithms::flips::{
        DelaunayRepairDiagnostics, DelaunayRepairPostconditionFailure, RepairQueueOrder,
    };
    use crate::core::tds::{TdsBuilder, VertexKey};
    use crate::core::traits::data_type::DataType;
    use crate::core::vertex::Vertex;
    use crate::delaunay_model::EuclideanDelaunayReportDomain;
    use crate::geometry::coordinate_range::CoordinateRange;
    use crate::geometry::kernel::{AdaptiveKernel, ExactPredicates};
    use crate::geometry::point::Point;
    use crate::geometry::traits::coordinate::CoordinateConversionError;
    use crate::geometry::util::generate_random_points_in_range_seeded;
    use crate::vertex;
    use slotmap::KeyData;
    use std::{assert_matches, error::Error, sync::Once};
    use uuid::Uuid;

    impl<K, U, V, const D: usize> DelaunayTriangulation<K, U, V, D>
    where
        K: Kernel<D, Scalar = f64>,
        U: DataType,
        V: DataType,
    {
        /// Restores a test TDS with explicit topology context and no provenance.
        pub(crate) fn try_restore_from_tds_with_topology_context(
            tds: Tds<U, V, D>,
            kernel: K,
            topology_guarantee: TopologyGuarantee,
            global_topology: GlobalTopology<D>,
        ) -> Result<Self, DelaunayTdsRestorationError<K, U, V, D>> {
            Self::try_restore_with_provenance(
                tds,
                kernel,
                topology_guarantee,
                global_topology,
                TopologyConstructionProvenance::Unproven,
            )
            .map(|(triangulation, _evidence)| triangulation)
        }
    }

    #[derive(Clone, Debug)]
    struct PanickingKernel;

    impl<const D: usize> Kernel<D> for PanickingKernel {
        type Scalar = f64;

        fn orientation(&self, _points: &[Point<D>]) -> Result<i32, CoordinateConversionError> {
            panic!("the structured report must not call its owner's kernel")
        }

        fn in_sphere(
            &self,
            _simplex_points: &[Point<D>],
            _test_point: &Point<D>,
        ) -> Result<i32, CoordinateConversionError> {
            panic!("the structured report must not call its owner's kernel")
        }
    }

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

    fn init_tracing() {
        static INIT: Once = Once::new();
        INIT.call_once(|| {
            let filter = tracing_subscriber::EnvFilter::try_from_default_env()
                .unwrap_or_else(|_| tracing_subscriber::EnvFilter::new("warn"));
            let _ = tracing_subscriber::fmt()
                .with_env_filter(filter)
                .with_test_writer()
                .try_init();
        });
    }

    fn non_delaunay_quad_tds() -> Tds<(), (), 2> {
        let vertices = [
            test_vertex([0.0, 0.0]),
            test_vertex([4.0, 0.0]),
            test_vertex([4.0, 2.0]),
            test_vertex([1.0, 2.0]),
        ];
        let simplices = [vec![0, 1, 2], vec![0, 2, 3]];
        TdsBuilder::new(&vertices, &simplices).build().unwrap()
    }

    fn isolated_vertex_tds_3d() -> Tds<(), (), 3> {
        let vertices = [
            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]),
        ];
        let dt: DelaunayTriangulation<_, (), (), 3> =
            DelaunayTriangulation::builder(&vertices).build().unwrap();
        let mut tds = dt.into_triangulation().into_tds();
        tds.insert_vertex_with_mapping(test_vertex([0.5, 0.5, 0.5]))
            .unwrap();
        tds
    }

    fn tds_from_2d_vertices_and_simplices(
        coords: &[[f64; 2]],
        simplices: &[Vec<usize>],
    ) -> Tds<(), (), 2> {
        let vertices: Vec<_> = coords.iter().copied().map(test_vertex).collect();
        TdsBuilder::new(&vertices, simplices).build().unwrap()
    }

    fn unchecked_test_delaunay_from_tds<const D: usize>(
        tds: Tds<(), (), D>,
    ) -> DelaunayTriangulation<AdaptiveKernel<f64>, (), (), D> {
        DelaunayTriangulationDraft::assemble_unchecked_for_test(
            tds,
            AdaptiveKernel::new(),
            TopologyGuarantee::Pseudomanifold,
            GlobalTopology::Euclidean,
        )
        .into_unproven_delaunay_for_test()
    }

    fn synthetic_flip_verification_source(message: &str) -> DelaunayVerificationError {
        let _ = message;
        DelaunayVerificationError::from(DelaunayRepairError::PostconditionFailed {
            reason: Box::new(DelaunayRepairPostconditionFailure::Disconnected { simplex_count: 1 }),
        })
    }

    fn randomized_delaunay<const D: usize>(
        base_seed: u64,
    ) -> DelaunayTriangulation<AdaptiveKernel<f64>, (), (), D>
    where
        AdaptiveKernel<f64>: ExactPredicates<D>,
    {
        let bounds = CoordinateRange::try_new(-10.0, 10.0).unwrap();
        for offset in 0..32 {
            let points = generate_random_points_in_range_seeded::<D>(
                D + 8,
                bounds,
                base_seed.wrapping_add(offset),
            )
            .unwrap();
            let vertices: Vec<_> = points
                .iter()
                .map(|point| test_vertex(*point.coords()))
                .collect();
            if let Ok(triangulation) = DelaunayTriangulationBuilder::new(&vertices).build() {
                return triangulation;
            }
        }

        panic!("failed to build seeded randomized {D}D Delaunay test fixture");
    }

    fn shared_facet_flip_adversary<const D: usize>() -> Triangulation<AdaptiveKernel<f64>, (), (), D>
    where
        AdaptiveKernel<f64>: ExactPredicates<D>,
    {
        let dim = u32::try_from(D).unwrap();
        let high_apex_coordinate = 1.1 / f64::from(dim);
        let mut vertices = Vec::with_capacity(D + 2);
        vertices.push(test_vertex([0.0; D]));
        for axis in 0..D {
            let mut coordinates = [0.0; D];
            coordinates[axis] = 1.0;
            vertices.push(test_vertex(coordinates));
        }
        vertices.push(test_vertex([high_apex_coordinate; D]));

        let low_simplex = (0..=D).collect();
        let mut high_simplex: Vec<usize> = (1..=D).collect();
        high_simplex.push(D + 1);
        let simplices = vec![low_simplex, high_simplex];

        DelaunayTriangulationBuilder::try_from_vertices_and_simplices(&vertices, &simplices)
            .unwrap()
            .topology_guarantee(TopologyGuarantee::Pseudomanifold)
            .build_triangulation()
            .unwrap()
    }

    fn assert_randomized_full_report_matches_brute_force<const D: usize>()
    where
        AdaptiveKernel<f64>: ExactPredicates<D>,
    {
        for seed in [0x483, 0x483_0001, 0x483_0002] {
            let triangulation = randomized_delaunay::<D>(seed);
            assert!(triangulation.verify_via_flip_predicates().is_ok());

            let optimized = triangulation.delaunay_violation_report(None).unwrap();
            let tds = triangulation.into_triangulation().into_tds();
            let brute_force = tds_delaunay_violation_report(&tds, None).unwrap();
            assert_eq!(optimized, brute_force);
        }
    }

    fn assert_adversarial_full_report_matches_brute_force<const D: usize>()
    where
        AdaptiveKernel<f64>: ExactPredicates<D>,
    {
        let triangulation = shared_facet_flip_adversary::<D>();
        assert!(
            triangulation
                .delaunay_violation_report(None)
                .is_ok_and(|report| !report.is_valid())
        );

        let optimized = triangulation.delaunay_violation_report(None).unwrap();
        let brute_force = tds_delaunay_violation_report(triangulation.tds(), None).unwrap();
        assert_eq!(optimized, brute_force);
    }

    macro_rules! generate_full_report_agreement_tests {
        ($dimension:literal) => {
            pastey::paste! {
                #[test]
                fn [<randomized_full_report_matches_brute_force_ $dimension d>]() {
                    assert_randomized_full_report_matches_brute_force::<$dimension>();
                }

                #[test]
                fn [<adversarial_full_report_matches_brute_force_ $dimension d>]() {
                    assert_adversarial_full_report_matches_brute_force::<$dimension>();
                }
            }
        };
    }

    generate_full_report_agreement_tests!(2);
    generate_full_report_agreement_tests!(3);
    generate_full_report_agreement_tests!(4);
    generate_full_report_agreement_tests!(5);

    #[test]
    fn complete_point_set_report_uses_robust_predicates_instead_of_owner_kernel() {
        let source = randomized_delaunay::<2>(0x483_1001);
        assert_eq!(
            source.euclidean_report_domain,
            EuclideanDelaunayReportDomain::CompletePointSet
        );
        let topology_guarantee = source.topology_guarantee();
        let global_topology = source.global_topology();
        let source_tds = source.into_triangulation().into_tds();

        let mut triangulation = DelaunayTriangulationDraft::assemble_unchecked_for_test(
            source_tds,
            PanickingKernel,
            topology_guarantee,
            global_topology,
        )
        .into_unproven_delaunay_for_test();
        triangulation.euclidean_report_domain = EuclideanDelaunayReportDomain::CompletePointSet;

        let report = triangulation.delaunay_violation_report(None).unwrap();
        let tds = triangulation.into_triangulation().into_tds();
        let brute_force = tds_delaunay_violation_report(&tds, None).unwrap();
        assert_eq!(report, brute_force);
    }

    #[test]
    fn failed_complete_point_set_certificate_falls_back_to_global_report() {
        let triangulation = shared_facet_flip_adversary::<2>();
        let mut triangulation = DelaunayTriangulationDraft::from_triangulation(triangulation)
            .into_unproven_delaunay_for_test();
        triangulation.euclidean_report_domain = EuclideanDelaunayReportDomain::CompletePointSet;

        let report = triangulation.delaunay_violation_report(None).unwrap();
        let tds = triangulation.into_triangulation().into_tds();
        let brute_force = tds_delaunay_violation_report(&tds, None).unwrap();
        assert!(!report.is_valid());
        assert_eq!(report, brute_force);
    }

    #[test]
    fn unproven_connectivity_bypasses_local_certificate() {
        let tds = tds_from_2d_vertices_and_simplices(
            &[[0.0, 0.0], [2.0, 0.0], [0.0, 2.0], [0.25, 0.25]],
            &[vec![0, 1, 2]],
        );
        assert!(verify_complete_euclidean_tds_via_robust_flip_predicates(&tds).is_ok());

        let triangulation = DelaunayTriangulationDraft::assemble_unchecked_for_test(
            tds,
            PanickingKernel,
            TopologyGuarantee::Pseudomanifold,
            GlobalTopology::Euclidean,
        )
        .into_unproven_delaunay_for_test();
        assert_eq!(
            triangulation.euclidean_report_domain,
            EuclideanDelaunayReportDomain::Unproven
        );

        assert_matches!(
            triangulation.is_valid_delaunay(),
            Err(DelaunayTriangulationValidationError::VerificationFailed { source })
                if matches!(
                    source.as_ref(),
                    DelaunayVerificationError::EmptyCircumsphere { source }
                        if matches!(
                            source.as_ref(),
                            DelaunayValidationError::DelaunayViolation { .. }
                        )
                )
        );

        let report = triangulation.delaunay_violation_report(None).unwrap();
        let tds = triangulation.into_triangulation().into_tds();
        let brute_force = tds_delaunay_violation_report(&tds, None).unwrap();
        assert!(!report.is_valid());
        assert_eq!(report, brute_force);
    }

    #[test]
    fn complete_point_set_nonflippable_pyramid_matches_global_report() {
        let vertices = [
            test_vertex([-1.0, 0.0, 0.0]),
            test_vertex([1.0, 0.0, 0.0]),
            test_vertex([0.0, 0.0, 1.0]),
            test_vertex([0.0, 1.0, 0.0]),
            test_vertex([0.0, -0.5, 0.0]),
        ];
        let simplices = [vec![0, 1, 2, 3], vec![0, 2, 1, 4]];
        let tri =
            DelaunayTriangulationBuilder::try_from_vertices_and_simplices(&vertices, &simplices)
                .unwrap()
                .build_triangulation()
                .unwrap();
        tri.validate_realization().unwrap();
        let mut dt =
            DelaunayTriangulationDraft::from_triangulation(tri).into_unproven_delaunay_for_test();
        // The two tetrahedra cover the convex hull of all five vertices.
        // This is the geometric precondition for the optimized certificate.
        dt.euclidean_report_domain = EuclideanDelaunayReportDomain::CompletePointSet;

        // Independent analytic witness: ABCD's circumsphere is the unit sphere;
        // E is strictly inside it, despite coplanarity of the proposed ABDE.
        let global = tds_delaunay_violation_report(&dt.tri.tds, None).unwrap();
        assert!(!global.is_valid());
        assert_eq!(dt.delaunay_violation_report(None).unwrap(), global);
        assert!(dt.is_valid_delaunay().is_err());
        assert!(dt.delaunay_report().is_err());
    }

    #[test]
    fn flip_predicate_certificate_cannot_publish_euclidean_topology() {
        let vertices = [
            test_vertex([0.0, 0.0]),
            test_vertex([1.0, 0.0]),
            test_vertex([0.0, 1.0]),
        ];
        let triangulation = DelaunayTriangulationBuilder::new(&vertices)
            .build_triangulation()
            .unwrap();

        verify_tds_via_flip_predicates_assuming_connected(
            &triangulation.tds,
            &triangulation.kernel,
            triangulation.global_topology,
        )
        .unwrap();
        let flip_certificate = DelaunayLevelFiveCertificate::for_triangulation(
            &triangulation,
            DelaunayLevelFiveEvidence::FlipPredicates,
        );
        assert!(!flip_certificate.applies_to(&triangulation));

        let publication_certificate = certify_level_five_for_refinement(&triangulation).unwrap();
        assert!(publication_certificate.applies_to(&triangulation));
    }

    #[test]
    fn validation_cadence_maps_optional_every() {
        assert_eq!(
            ValidationCadence::from_optional_every(None),
            ValidationCadence::Never
        );
        assert_eq!(
            ValidationCadence::from_optional_every(Some(0)),
            ValidationCadence::Never
        );
        assert_eq!(
            ValidationCadence::from_optional_every(Some(128)),
            ValidationCadence::EveryN(NonZeroUsize::new(128).unwrap())
        );
    }

    #[test]
    fn validation_cadence_should_validate_on_multiples() {
        let cadence = ValidationCadence::EveryN(NonZeroUsize::new(64).unwrap());

        assert!(!cadence.should_validate(0));
        assert!(!cadence.should_validate(63));
        assert!(cadence.should_validate(64));
        assert!(!cadence.should_validate(65));
        assert!(cadence.should_validate(128));
        assert!(!ValidationCadence::Never.should_validate(64));
    }

    #[test]
    fn verification_failed_display_includes_context() {
        let err = DelaunayTriangulationValidationError::VerificationFailed {
            source: synthetic_flip_verification_source(
                "flip predicate detected non-Delaunay facet",
            )
            .into(),
        };
        let msg = err.to_string();

        assert!(
            msg.contains("Delaunay verification failed"),
            "Display should contain prefix: {msg}"
        );
        assert!(
            msg.contains("repair pass disconnected the triangulation"),
            "Display should contain inner message: {msg}"
        );
        let DelaunayTriangulationValidationError::VerificationFailed { source } = &err else {
            panic!("expected typed flip-predicate verification source, got {err:?}");
        };
        assert_matches!(
            source.as_ref(),
            DelaunayVerificationError::FlipPredicates { source }
                if matches!(
                    source.as_ref(),
                    DelaunayRepairError::PostconditionFailed { .. }
                )
        );
    }

    #[test]
    fn verification_error_kind_covers_empty_circumsphere_source() {
        let simplex_key = SimplexKey::default();
        let source = DelaunayVerificationError::from(DelaunayValidationError::DelaunayViolation {
            simplex_key,
            simplex_vertices: Box::default(),
            offending_vertex: None,
            neighbor_simplices: Box::default(),
        });

        assert_eq!(
            DelaunayVerificationErrorKind::from(&source),
            DelaunayVerificationErrorKind::EmptyCircumsphere,
        );
        assert!(source.to_string().contains("empty-circumsphere"));
        let DelaunayVerificationError::EmptyCircumsphere { source } = source else {
            panic!("expected empty-circumsphere source");
        };
        assert_matches!(
            source.as_ref(),
            DelaunayValidationError::DelaunayViolation {
                simplex_key: actual,
                ..
            } if *actual == simplex_key
        );
    }

    #[test]
    fn repair_operation_failed_preserves_source() {
        let source = DelaunayRepairError::NonConvergent {
            max_flips: 7,
            diagnostics: Box::new(DelaunayRepairDiagnostics {
                facets_checked: 3,
                flips_performed: 7,
                max_queue_len: 5,
                ambiguous_predicates: 0,
                ambiguous_predicate_samples: Vec::new(),
                predicate_failures: 0,
                cycle_detections: 0,
                cycle_signature_samples: Vec::new(),
                attempt: 1,
                queue_order: RepairQueueOrder::Fifo,
            }),
        };
        let err = DelaunayTriangulationValidationError::RepairOperationFailed {
            operation: DelaunayRepairOperation::VertexRemoval,
            source: Box::new(source),
        };

        let msg = err.to_string();
        assert!(msg.contains("vertex removal"));
        match &err {
            DelaunayTriangulationValidationError::RepairOperationFailed {
                operation: DelaunayRepairOperation::VertexRemoval,
                source,
            } if matches!(
                source.as_ref(),
                DelaunayRepairError::NonConvergent { max_flips: 7, .. }
            ) => {}
            other => panic!("expected typed vertex-removal repair source, got {other:?}"),
        }
        let chained = err
            .source()
            .expect("typed repair failure should expose source error")
            .to_string();
        assert!(chained.contains("failed to converge after 7 flips"));
    }

    #[test]
    fn tds_variant_display_delegates_to_source() {
        let inner = TdsError::InconsistentDataStructure {
            message: "broken link".to_string(),
        };
        let err = DelaunayTriangulationValidationError::from(inner);

        assert!(err.to_string().contains("broken link"));
    }

    #[test]
    fn triangulation_variant_display_delegates_to_source() {
        let inner = TriangulationValidationError::IsolatedVertex {
            vertex_key: VertexKey::from(KeyData::from_ffi(1)),
            vertex_uuid: Uuid::nil(),
        };
        let err = DelaunayTriangulationValidationError::from(inner);

        assert!(err.to_string().contains("Isolated vertex"));
    }

    #[test]
    fn try_from_tds_rejects_non_delaunay_connectivity() {
        init_tracing();
        let tds = non_delaunay_quad_tds();

        let err = DelaunayTriangulation::try_restore_from_tds_with_topology_context(
            tds,
            AdaptiveKernel::new(),
            TopologyGuarantee::DEFAULT,
            GlobalTopology::DEFAULT,
        )
        .expect_err("checked TDS reconstruction must reject non-Delaunay connectivity");

        let failure = match err {
            DelaunayTdsRestorationError::Delaunay { failure } => failure,
            other => panic!("expected Level 5 refinement failure, got {other:?}"),
        };
        let (triangulation, reason) = failure.into_parts();
        assert!(matches!(
            reason,
            DelaunayTriangulationValidationError::VerificationFailed { .. }
        ));
        triangulation
            .validate_realization()
            .expect("failed Level 5 refinement must return the valid Levels 1-4 owner");
    }

    #[test]
    fn report_domain_cannot_select_local_level_five_publication() {
        let triangulation = shared_facet_flip_adversary::<2>();
        let mut draft = DelaunayTriangulationDraft::from_triangulation(triangulation);
        draft.set_euclidean_report_domain_for_test(EuclideanDelaunayReportDomain::CompletePointSet);

        let failure = draft
            .try_into_delaunay()
            .expect_err("the adversarial shared facet must fail global Level 5 verification");
        let (triangulation, reason) = failure.into_parts();
        assert_matches!(
            reason,
            DelaunayTriangulationValidationError::VerificationFailed { source }
                if matches!(
                    source.as_ref(),
                    DelaunayVerificationError::EmptyCircumsphere { .. }
                )
        );
        triangulation
            .validate_realization()
            .expect("failed Level 5 promotion must return the valid Levels 1-4 owner");
    }

    #[test]
    fn tds_audit_rejects_structural_corruption_before_proof_consumption() {
        init_tracing();
        let vertices = [
            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]),
        ];
        let dt: DelaunayTriangulation<_, (), (), 3> =
            DelaunayTriangulation::builder(&vertices).build().unwrap();
        let mut tds = dt.into_triangulation().into_tds();

        let vk = tds.vertex_keys().next().unwrap();
        let uuid = tds.vertex(vk).unwrap().uuid();
        tds.remove_vertex_uuid_mapping_for_test(&uuid);

        let err = tds
            .validate()
            .expect_err("the Levels 1–2 owner audit must reject broken UUID mappings");
        assert_matches!(err, TdsError::MappingInconsistency { .. });
    }

    #[test]
    fn try_from_tds_rejects_topology_validation_failure() {
        init_tracing();
        let err = DelaunayTriangulation::try_restore_from_tds_with_topology_context(
            isolated_vertex_tds_3d(),
            AdaptiveKernel::new(),
            TopologyGuarantee::DEFAULT,
            GlobalTopology::DEFAULT,
        )
        .expect_err("checked TDS reconstruction must reject isolated vertices");
        let failure = match err {
            DelaunayTdsRestorationError::Triangulation { failure } => failure,
            other => panic!("expected Levels 3-4 refinement failure, got {other:?}"),
        };
        let (tds, reason) = failure.into_parts();
        assert_matches!(
            reason,
            TriangulationBuilderError::TopologyValidation { source }
                if matches!(
                    source.as_ref(),
                    InvariantError::Triangulation {
                        source: TriangulationValidationError::IsolatedVertex { .. }
                    }
                )
        );
        tds.validate()
            .expect("failed Levels 3-4 refinement must return the valid Levels 1-2 owner");
    }

    #[test]
    fn restoration_reason_preserves_topology_failure_without_owner() {
        let err = DelaunayTriangulation::try_restore_from_tds_with_topology_context(
            isolated_vertex_tds_3d(),
            AdaptiveKernel::new(),
            TopologyGuarantee::DEFAULT,
            GlobalTopology::DEFAULT,
        )
        .expect_err("checked TDS reconstruction must reject isolated vertices");

        assert_matches!(
            err.into_reason(),
            DelaunayTdsRestorationReason::Triangulation {
                source: TriangulationBuilderError::TopologyValidation { source }
            } if matches!(
                source.as_ref(),
                InvariantError::Triangulation {
                    source: TriangulationValidationError::IsolatedVertex { .. }
                }
            )
        );
    }

    #[test]
    fn test_validation_report_ok_for_valid_triangulation() {
        init_tracing();
        let vertices = [
            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]),
        ];

        let dt: DelaunayTriangulation<_, (), (), 3> =
            DelaunayTriangulation::builder(&vertices).build().unwrap();
        assert!(dt.validation_report().is_ok());
    }

    #[test]
    fn test_validation_report_returns_mapping_failures_only() {
        init_tracing();
        let vertices = [
            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]),
        ];

        let mut dt: DelaunayTriangulation<_, (), (), 3> =
            DelaunayTriangulation::builder(&vertices).build().unwrap();

        // Break UUID↔key mappings: remove one vertex UUID entry.
        let uuid = dt.tri.tds.vertices().next().unwrap().1.uuid();
        dt.tri.tds.remove_vertex_uuid_mapping_for_test(&uuid);

        let report = dt.validation_report().unwrap_err();
        assert!(!report.violations.is_empty());
        assert!(report.violations.iter().all(|v| {
            matches!(
                v.kind,
                InvariantKind::VertexMappings | InvariantKind::SimplexMappings
            )
        }));

        // Early-return on mapping failures: do not add derived invariants.
        assert!(
            report
                .violations
                .iter()
                .all(|v| v.kind != InvariantKind::DelaunayProperty)
        );
    }

    #[test]
    fn test_validation_report_includes_vertex_incidence_violation() {
        init_tracing();
        let vertices = [
            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]),
        ];

        let mut dt: DelaunayTriangulation<_, (), (), 3> =
            DelaunayTriangulation::builder(&vertices).build().unwrap();

        // Corrupt a `Vertex::incident_simplex` pointer.
        let vertex_key = dt.tri.tds.vertices().next().unwrap().0;
        dt.tri
            .tds
            .vertex_mut_for_test(vertex_key)
            .unwrap()
            .set_incident_simplex(Some(SimplexKey::default()));

        let report = dt.validation_report().unwrap_err();
        assert!(
            report
                .violations
                .iter()
                .any(|v| v.kind == InvariantKind::VertexIncidence)
        );
    }

    #[test]
    fn validation_report_includes_delaunay_after_realization_violations() {
        init_tracing();
        let tds = tds_from_2d_vertices_and_simplices(
            &[[0.0, 0.0], [2.0, 0.0], [0.0, 2.0], [2.0, 2.0], [1.0, -1.0]],
            &[vec![0, 1, 2], vec![2, 1, 3], vec![3, 2, 4]],
        );
        let dt = unchecked_test_delaunay_from_tds(tds);

        let report = dt.validation_report().unwrap_err();

        assert!(
            report
                .violations
                .iter()
                .any(|v| v.kind == InvariantKind::Realization),
            "expected realization violation in report: {report:?}"
        );
        assert!(
            report
                .violations
                .iter()
                .any(|v| v.kind == InvariantKind::DelaunayProperty),
            "expected Delaunay violation in report: {report:?}"
        );
    }

    #[test]
    fn test_dt_validate_maps_tds_error_to_tds_variant() {
        init_tracing();
        let vertices = [
            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]),
        ];
        let mut dt: DelaunayTriangulation<_, (), (), 3> =
            DelaunayTriangulation::builder(&vertices).build().unwrap();

        // Break vertex mapping so Level 2 structural validation fails.
        let vk = dt.vertices().next().unwrap().0;
        let uuid = dt.vertex(vk).unwrap().uuid();
        dt.tds_mut_for_repair()
            .remove_vertex_uuid_mapping_for_test(&uuid);

        match dt.validate() {
            Err(DelaunayTriangulationValidationError::Tds { source })
                if matches!(source.as_ref(), TdsError::MappingInconsistency { .. }) => {}
            other => panic!(
                "Expected DelaunayTriangulationValidationError::Tds with MappingInconsistency source, got {other:?}"
            ),
        }
    }

    #[test]
    fn test_dt_validate_maps_topology_error_to_triangulation_variant() {
        init_tracing();
        let vertices = [
            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]),
        ];
        let mut dt: DelaunayTriangulation<_, (), (), 3> =
            DelaunayTriangulation::builder(&vertices).build().unwrap();

        // Add an isolated vertex so Level 3 (topology) fails.
        let _ = dt
            .tds_mut_for_repair()
            .insert_vertex_with_mapping(test_vertex([0.5, 0.5, 0.5]))
            .unwrap();

        match dt.validate() {
            Err(DelaunayTriangulationValidationError::Triangulation { source })
                if matches!(
                    source.as_ref(),
                    TriangulationValidationError::IsolatedVertex { .. }
                ) => {}
            other => panic!(
                "Expected DelaunayTriangulationValidationError::Triangulation with IsolatedVertex source, got {other:?}"
            ),
        }
    }
}

#[cfg(test)]
mod summary_tests {
    use super::*;
    use crate::core::algorithms::flips::DelaunayRepairPostconditionFailure;
    use crate::topology::traits::topological_space::TopologyKind;

    fn synthetic_delaunay_verification_error() -> DelaunayTriangulationValidationError {
        DelaunayTriangulationValidationError::VerificationFailed {
            source: DelaunayVerificationError::from(DelaunayRepairError::PostconditionFailed {
                reason: Box::new(DelaunayRepairPostconditionFailure::Disconnected {
                    simplex_count: 1,
                }),
            })
            .into(),
        }
    }

    #[test]
    fn delaunay_validation_error_kind_from_error_preserves_all_variants() {
        let cases = [
            (
                DelaunayTriangulationValidationError::from(TdsError::InconsistentDataStructure {
                    message: "dangling simplex".to_string(),
                }),
                DelaunayValidationErrorKind::Tds,
            ),
            (
                DelaunayTriangulationValidationError::from(
                    TriangulationValidationError::Disconnected { simplex_count: 2 },
                ),
                DelaunayValidationErrorKind::Triangulation,
            ),
            (
                DelaunayTriangulationValidationError::Realization {
                    source: Box::new(
                        TriangulationRealizationValidationError::UnsupportedTopology {
                            topology: TopologyKind::Hyperbolic,
                            dimension: 2,
                        },
                    ),
                },
                DelaunayValidationErrorKind::Realization,
            ),
            (
                synthetic_delaunay_verification_error(),
                DelaunayValidationErrorKind::VerificationFailed,
            ),
            (
                DelaunayTriangulationValidationError::RepairOperationFailed {
                    operation: DelaunayRepairOperation::VertexRemoval,
                    source: Box::new(DelaunayRepairError::PostconditionFailed {
                        reason: Box::new(DelaunayRepairPostconditionFailure::Disconnected {
                            simplex_count: 1,
                        }),
                    }),
                },
                DelaunayValidationErrorKind::RepairOperationFailed,
            ),
        ];

        for (source, expected) in cases {
            assert_eq!(DelaunayValidationErrorKind::from(&source), expected);
        }
    }
}