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
2719
2720
2721
2722
2723
2724
2725
2726
2727
2728
2729
2730
2731
2732
2733
2734
2735
2736
2737
2738
2739
2740
2741
2742
2743
2744
2745
2746
2747
2748
2749
2750
2751
2752
2753
2754
2755
2756
2757
2758
2759
2760
2761
2762
2763
2764
2765
2766
2767
2768
2769
2770
2771
2772
2773
2774
2775
2776
2777
2778
2779
2780
2781
2782
2783
2784
2785
2786
2787
2788
2789
2790
2791
2792
2793
2794
2795
2796
2797
2798
2799
2800
2801
2802
2803
2804
2805
2806
2807
2808
2809
2810
2811
2812
2813
2814
2815
//! Data and operations on d-dimensional triangulation data structures.
//!
//! This module provides the `Tds` (Triangulation Data Structure): a key-based,
//! CGAL-inspired representation of the **combinatorial** topology of a D-dimensional
//! finite simplicial complex (vertices, simplices, and adjacency). The implementation
//! closely follows the design principles of
//! [CGAL Triangulation](https://doc.cgal.org/latest/Triangulation/index.html).
//!
//! The crate follows a layered architecture: `Tds` is topology-focused, while geometric
//! predicates and Delaunay-specific operations live in higher layers (`Triangulation` /
//! `DelaunayTriangulation`) and `core::algorithms`.
//!
//! # Key Features
//!
//! - **CGAL-style layering**: topology in `Tds`, geometry/predicates in higher layers
//! - **Relaxed access bounds**: read-only topology accessors and cache identity helpers do
//!   not require coordinate or payload trait bounds; mutation, validation, and serde paths
//!   add only the bounds they need
//! - **Arbitrary Dimensions**: Supports triangulations in any dimension D ≥ 1
//! - **Hierarchical Simplex Structure**: Stores maximal D-dimensional simplices and infers lower-dimensional
//!   simplices (vertices, edges, facets) from the maximal simplices
//! - **Neighbor Relationships**: Maintains adjacency information between simplices for efficient
//!   topological traversal
//! - **Validation Support**: Structural invariant validation (Level 2) plus cumulative element
//!   validation (Levels 1–2)
//! - **Serialization Support**: Serde support for persistence
//! - **Optimized Storage**: Internal key-based storage with UUIDs for external identity
//!
//! # Geometric Structure
//!
//! The triangulation data structure represents a finite simplicial complex where:
//!
//! - **0-simplices**: Individual vertices realized in D-dimensional Euclidean space
//! - **1-simplices**: Edges connecting two vertices (inferred from maximal simplices)
//! - **2-simplices**: Triangular faces with three vertices (inferred from maximal simplices)
//! - **...**
//! - **D-simplices**: Maximal D-dimensional simplices with D+1 vertices (explicitly stored)
//!
//! For example, in 3D space:
//! - Vertices are 0-dimensional simplices
//! - Edges are 1-dimensional simplices (inferred from tetrahedra)
//! - Faces are 2-dimensional simplices represented as `Facet`s
//! - Tetrahedra are 3-dimensional simplices (maximal simplices)
//!
//! # Delaunay Property
//!
//! When constructed via the Delaunay triangulation algorithm, the structure satisfies
//! the **empty circumsphere property**: no vertex lies inside the circumsphere of any
//! D-dimensional simplex. This property ensures optimal geometric characteristics for
//! many applications including mesh generation, interpolation, and spatial analysis.
//!
//! # Topological Invariants
//!
//! Valid Delaunay triangulations maintain several critical topological invariants:
//!
//! - **Facet Sharing Invariant**: Every facet (D-1 dimensional face) is one-sided or
//!   two-sided. One-sided facets are boundary facets unless closed periodic topology
//!   identifies them with their opposite side. This ensures the triangulation forms a
//!   valid simplicial complex in its ambient topological space.
//! - **Neighbor Consistency**: Adjacent simplices properly reference each other through their
//!   shared facets, maintaining bidirectional neighbor relationships.
//! - **Vertex Incidence**: Each vertex is incident to a well-defined set of simplices that
//!   form a topologically valid star configuration around the vertex.
//! - **Delaunay Property**: No vertex lies inside the circumsphere of any D-dimensional simplex.
//!
//! ## Invariant Enforcement
//!
//! | Invariant Type | Enforcement Location | Method |
//! |---|---|---|
//! | **Delaunay Property** | incremental insertion (`core::algorithms::incremental_insertion`) | Empty circumsphere test via `insphere()` (best-effort) |
//! | **Facet Sharing** | `Tds::is_valid()` / `Tds::validate()` | Each facet shared by ≤ 2 simplices |
//! | **No Duplicate Simplices** | `Tds::is_valid()` / `Tds::validate()` | No simplices with identical vertex sets |
//! | **Neighbor Consistency** | `Tds::is_valid()` / `Tds::validate()` | Mutual neighbor relationships |
//! | **Coherent Orientation** | `Tds::is_valid()` / `Tds::validate()` | Adjacent simplices induce opposite facet orientations |
//! | **Simplex Vertex Keys** | `Tds::is_valid()` / `Tds::validate()` | Simplices reference only valid vertex keys |
//! | **Simplex Coordinate Uniqueness** | `Tds::validate()` | Each simplex key set resolves to distinct coordinates |
//! | **Vertex Incidence** | `Tds::is_valid()` / `Tds::validate()` | `Vertex::incident_simplex` is non-dangling and consistent (when present) |
//! | **Simplex Validity** | `SimplexBuilder::validate()` (vertex count) + `simplex.is_valid()` / `simplex_report()` | Construction + runtime validation |
//! | **Vertex Validity** | [`Point::try_new`](crate::geometry::point::Point::try_new) / [`Point`](crate::geometry::point::Point) coordinate conversion (coordinates) + UUID auto-gen + `vertex.is_valid()` / `vertex_report()` | Construction + runtime validation |
//!
//! The incremental insertion algorithm attempts to maintain the Delaunay property during
//! construction, but rare violations can remain. Structural invariants are enforced
//! **reactively** through validation methods. For a definitive Delaunay check, run
//! Level 4 Valid Realization via `Triangulation::validate_realization()` and
//! Level 5 Geometric Predicates via `DelaunayTriangulation::is_valid_delaunay()` /
//! `DelaunayTriangulation::validate()`.
//!
//! # Validation
//!
//! The TDS participates in a layered validation hierarchy:
//!
//! ## Validation Hierarchy (TDS Role)
//!
//! 1. **Level 1: Element Validity** - [`Simplex::is_valid()`], [`Vertex::is_valid()`]
//!    - Basic data integrity (coordinates, UUIDs, initialization)
//!    - Simplex-local vertex keys resolve to distinct coordinates in cumulative [`Tds::validate()`]
//! 2. **Level 2: Combinatorial Consistency** - [`Tds::is_valid()`] ← **This module**
//!    - UUID ↔ Key mapping consistency
//!    - Simplices reference only valid vertex keys (no stale/missing vertex keys)
//!    - `Vertex::incident_simplex`, when present, must point at an existing simplex that contains the vertex
//!    - Isolated vertices (not referenced by any simplex) are allowed at this layer (`incident_simplex` may be `None`)
//!    - No duplicate simplices
//!    - Coherent orientation (adjacent simplices induce opposite facet orientations)
//!    - Facet sharing invariant (≤2 simplices per facet)
//!    - Neighbor consistency
//! 3. **Level 3: Intrinsic PL Topology** - [`Triangulation::is_valid_topology()`]
//!    - Builds on Level 2, and rejects isolated vertices (every vertex must be incident to ≥ 1 simplex)
//!    - Adds manifold-with-boundary + Euler characteristic
//! 4. **Level 4: Valid Realization** - [`Triangulation::validate_realization()`](crate::Triangulation::validate_realization)
//!    - Nondegenerate realized simplices and no intersections outside shared faces
//! 5. **Level 5: Geometric Predicates** - [`DelaunayTriangulation::is_valid_delaunay()`]
//!    - Implemented Delaunay predicates, including the empty circumsphere property
//!
//! ## TDS Validation Methods
//!
//! - [`is_valid()`](Tds::is_valid) - Level 2 Combinatorial Consistency only; returns first error, stops early
//! - [`validate()`](Tds::validate) - Levels 1–2 (Element Validity + Combinatorial Consistency); returns first error, stops early
//!
//! For cumulative diagnostics across the full stack (Levels 1–5), use
//! [`DelaunayTriangulation::validation_report()`].
//!
//! ## Example: Using Validation
//!
//! ```rust
//! use delaunay::prelude::*;
//!
//! # #[derive(Debug, thiserror::Error)]
//! # enum ExampleError {
//! #     #[error(transparent)]
//! #     Construction(#[from] delaunay::DelaunayTriangulationConstructionError),
//! #     #[error(transparent)]
//! #     Insertion(#[from] delaunay::prelude::insertion::InsertionError),
//! #     #[error(transparent)]
//! #     Tds(#[from] delaunay::prelude::tds::TdsError),
//! #     #[error(transparent)]
//! #     TdsConstruction(#[from] delaunay::prelude::tds::TdsConstructionError),
//! #     #[error(transparent)]
//! #     Invariant(#[from] delaunay::prelude::tds::InvariantError),
//! #     #[error(transparent)]
//! #     Facet(#[from] delaunay::prelude::tds::FacetError),
//! #     #[error(transparent)]
//! #     Simplex(#[from] delaunay::prelude::tds::SimplexValidationError),
//! #     #[error(transparent)]
//! #     Validation(#[from] delaunay::DelaunayTriangulationValidationError),
//! #     #[error(transparent)]
//! #     Coordinate(#[from] delaunay::prelude::geometry::CoordinateConversionError),
//! # }
//! # fn main() -> Result<(), ExampleError> {
//! let vertices = [
//!     vertex![0.0, 0.0, 0.0]?,
//!     vertex![1.0, 0.0, 0.0]?,
//!     vertex![0.0, 1.0, 0.0]?,
//!     vertex![0.0, 0.0, 1.0]?,
//! ];
//! let dt = DelaunayTriangulationBuilder::new(&vertices).build()?;
//!
//! // Level 2: Combinatorial Consistency only (fast)
//! assert!(dt.is_valid_structure().is_ok());
//!
//! // Levels 1–2: Element Validity + Combinatorial Consistency
//! assert!(dt.validate_structure().is_ok());
//!
//! // Full report across Levels 1–5
//! match dt.validation_report() {
//!     Ok(()) => println!("✓ All invariants satisfied"),
//!     Err(report) => {
//!         for violation in report.violations {
//!             eprintln!("Invariant: {:?}, Error: {}", violation.kind, violation.error);
//!         }
//!     }
//! }
//! # Ok(())
//! # }
//! ```
//!
//! See [`docs/validation.md`](https://github.com/acgetchell/delaunay/blob/main/docs/validation.md)
//! for a comprehensive validation guide.
//!
//! [`Simplex::is_valid()`]: crate::prelude::tds::Simplex::is_valid
//! [`Vertex::is_valid()`]: crate::prelude::Vertex::is_valid
//! [`Triangulation::is_valid_topology()`]: crate::prelude::triangulation::Triangulation::is_valid_topology
//! [`DelaunayTriangulation::is_valid_delaunay()`]: crate::DelaunayTriangulation::is_valid_delaunay
//! [`DelaunayTriangulation::validation_report()`]: crate::DelaunayTriangulation::validation_report
//!
//! # Examples
//!
//! ## Creating a 3D Triangulation
//!
//! ```rust
//! use delaunay::prelude::*;
//!
//! # #[derive(Debug, thiserror::Error)]
//! # enum ExampleError {
//! #     #[error(transparent)]
//! #     Construction(#[from] delaunay::DelaunayTriangulationConstructionError),
//! #     #[error(transparent)]
//! #     Insertion(#[from] delaunay::prelude::insertion::InsertionError),
//! #     #[error(transparent)]
//! #     Tds(#[from] delaunay::prelude::tds::TdsError),
//! #     #[error(transparent)]
//! #     TdsConstruction(#[from] delaunay::prelude::tds::TdsConstructionError),
//! #     #[error(transparent)]
//! #     Invariant(#[from] delaunay::prelude::tds::InvariantError),
//! #     #[error(transparent)]
//! #     Facet(#[from] delaunay::prelude::tds::FacetError),
//! #     #[error(transparent)]
//! #     Simplex(#[from] delaunay::prelude::tds::SimplexValidationError),
//! #     #[error(transparent)]
//! #     Validation(#[from] delaunay::DelaunayTriangulationValidationError),
//! #     #[error(transparent)]
//! #     Coordinate(#[from] delaunay::prelude::geometry::CoordinateConversionError),
//! # }
//! # fn main() -> Result<(), ExampleError> {
//! // Create vertices for a tetrahedron
//! 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]?,
//! ];
//!
//! // Create Delaunay triangulation
//! let dt = DelaunayTriangulationBuilder::new(&vertices).build()?;
//!
//! // Query triangulation properties
//! assert_eq!(dt.number_of_vertices(), 4);
//! assert_eq!(dt.number_of_simplices(), 1);
//! assert_eq!(dt.dim(), 3);
//! assert!(dt.validate().is_ok());
//! # Ok(())
//! # }
//! ```
//!
//! ## Adding Vertices to Existing Triangulation
//!
//! ```rust
//! use delaunay::prelude::*;
//!
//! # #[derive(Debug, thiserror::Error)]
//! # enum ExampleError {
//! #     #[error(transparent)]
//! #     Construction(#[from] delaunay::DelaunayTriangulationConstructionError),
//! #     #[error(transparent)]
//! #     Insertion(#[from] delaunay::prelude::insertion::InsertionError),
//! #     #[error(transparent)]
//! #     Tds(#[from] delaunay::prelude::tds::TdsError),
//! #     #[error(transparent)]
//! #     TdsConstruction(#[from] delaunay::prelude::tds::TdsConstructionError),
//! #     #[error(transparent)]
//! #     Invariant(#[from] delaunay::prelude::tds::InvariantError),
//! #     #[error(transparent)]
//! #     Facet(#[from] delaunay::prelude::tds::FacetError),
//! #     #[error(transparent)]
//! #     Simplex(#[from] delaunay::prelude::tds::SimplexValidationError),
//! #     #[error(transparent)]
//! #     Validation(#[from] delaunay::DelaunayTriangulationValidationError),
//! #     #[error(transparent)]
//! #     Coordinate(#[from] delaunay::prelude::geometry::CoordinateConversionError),
//! # }
//! # fn main() -> Result<(), ExampleError> {
//! // Start with initial vertices
//! let initial_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 mut dt = DelaunayTriangulationBuilder::new(&initial_vertices).build()?;
//!
//! // Add a new vertex
//! let new_vertex = vertex![0.2, 0.2, 0.2]?;
//! dt.insert_vertex(new_vertex)?;
//!
//! assert_eq!(dt.number_of_vertices(), 5);
//! assert!(dt.validate().is_ok());
//! # Ok(())
//! # }
//! ```
//!
//! ## 4D Triangulation
//!
//! ```rust
//! use delaunay::prelude::*;
//!
//! # #[derive(Debug, thiserror::Error)]
//! # enum ExampleError {
//! #     #[error(transparent)]
//! #     Construction(#[from] delaunay::DelaunayTriangulationConstructionError),
//! #     #[error(transparent)]
//! #     Insertion(#[from] delaunay::prelude::insertion::InsertionError),
//! #     #[error(transparent)]
//! #     Tds(#[from] delaunay::prelude::tds::TdsError),
//! #     #[error(transparent)]
//! #     TdsConstruction(#[from] delaunay::prelude::tds::TdsConstructionError),
//! #     #[error(transparent)]
//! #     Invariant(#[from] delaunay::prelude::tds::InvariantError),
//! #     #[error(transparent)]
//! #     Facet(#[from] delaunay::prelude::tds::FacetError),
//! #     #[error(transparent)]
//! #     Simplex(#[from] delaunay::prelude::tds::SimplexValidationError),
//! #     #[error(transparent)]
//! #     Validation(#[from] delaunay::DelaunayTriangulationValidationError),
//! #     #[error(transparent)]
//! #     Coordinate(#[from] delaunay::prelude::geometry::CoordinateConversionError),
//! # }
//! # fn main() -> Result<(), ExampleError> {
//! // Create 4D triangulation with 5 vertices (needed for a 4-simplex)
//! let vertices_4d = [
//!     delaunay::vertex![0.0, 0.0, 0.0, 0.0]?,  // Origin
//!     delaunay::vertex![1.0, 0.0, 0.0, 0.0]?,  // Unit vector along first dimension
//!     delaunay::vertex![0.0, 1.0, 0.0, 0.0]?,  // Unit vector along second dimension
//!     delaunay::vertex![0.0, 0.0, 1.0, 0.0]?,  // Unit vector along third dimension
//!     delaunay::vertex![0.0, 0.0, 0.0, 1.0]?,  // Unit vector along fourth dimension
//! ];
//!
//! let dt_4d = DelaunayTriangulationBuilder::new(&vertices_4d).build()?;
//! assert_eq!(dt_4d.dim(), 4);
//! assert_eq!(dt_4d.number_of_vertices(), 5);
//! assert_eq!(dt_4d.number_of_simplices(), 1);
//! assert!(dt_4d.validate().is_ok());
//! # Ok(())
//! # }
//! ```
//!
//! # References
//!
//! - [CGAL Triangulation Documentation](https://doc.cgal.org/latest/Triangulation/index.html)
//! - Bowyer, A. "Computing Dirichlet tessellations." The Computer Journal 24.2 (1981): 162-166
//! - Watson, D.F. "Computing the n-dimensional Delaunay tessellation with application to Voronoi polytopes." The Computer Journal 24.2 (1981): 167-172
//! - de Berg, M., et al. "Computational Geometry: Algorithms and Applications." 3rd ed. Springer-Verlag, 2008

#![forbid(unsafe_code)]

use crate::core::collections::{
    MAX_PRACTICAL_DIMENSION_SIZE, SimplexKeySet, SmallBuffer, StorageMap, UuidToSimplexKeyMap,
    UuidToVertexKeyMap,
};
use crate::core::tds::errors::{NeighborValidationError, TdsError, TriangulationConstructionState};
use crate::core::tds::incidence::VertexIncidenceIndex;
use crate::core::tds::{SimplexKey, VertexKey};
use crate::core::{
    facet::facet_key_from_vertices, simplex::Simplex,
    util::periodic_facet_key_from_lifted_vertices, vertex::Vertex,
};
use std::{
    fmt::Debug,
    sync::{
        Arc,
        atomic::{AtomicU64, Ordering},
    },
};
use uuid::Uuid;

/// Opaque runtime identity for one live topology owner.
///
/// `TopologyOwnerId` is a proof token, not durable serialized identity. It is
/// minted from a live [`Tds`]. Cloning a `TopologyOwnerId` preserves the same
/// proof token, while cloning or deserializing the owning `Tds` mints a fresh
/// token so detached proposals from one storage owner cannot be mistaken for
/// proposals from another owner.
///
/// # Examples
///
/// ```
/// use delaunay::prelude::tds::Tds;
///
/// let tds: Tds<(), (), 2> = Tds::empty();
/// let cloned = tds.clone();
///
/// assert_ne!(tds.topology_owner_id(), cloned.topology_owner_id());
/// ```
#[derive(Clone, Debug)]
#[must_use]
pub struct TopologyOwnerId {
    identity: Arc<Uuid>,
}

impl TopologyOwnerId {
    /// Creates an owner token from the live runtime identity stored in a [`Tds`].
    pub(crate) fn from_identity(identity: &Arc<Uuid>) -> Self {
        Self {
            identity: Arc::clone(identity),
        }
    }
}

impl PartialEq for TopologyOwnerId {
    fn eq(&self, other: &Self) -> bool {
        Arc::ptr_eq(&self.identity, &other.identity)
    }
}

impl Eq for TopologyOwnerId {}

/// Trait for values that own a canonical topology storage identity.
///
/// Pachner proposals and other detached topology artifacts use this trait to
/// reject cross-owner reuse before interpreting runtime-local keys.
///
/// # Examples
///
/// ```rust
/// use delaunay::prelude::tds::{Tds, TopologyOwner};
///
/// let tds: Tds<(), (), 2> = Tds::empty();
///
/// assert_eq!(tds.topology_owner_id(), tds.topology_owner_id());
/// assert_eq!(tds.topology_generation(), tds.generation());
/// ```
pub trait TopologyOwner {
    /// Returns the runtime identity token for the canonical topology owner.
    fn topology_owner_id(&self) -> TopologyOwnerId;

    /// Returns the current structural generation for the canonical topology owner.
    fn topology_generation(&self) -> u64;
}

#[derive(Debug)]
/// The `Tds` struct represents a triangulation data structure with vertices
/// and simplices, where the vertices and simplices are identified by UUIDs.
///
/// # Properties
///
/// - `vertices`: A storage map that stores vertices with stable keys for efficient access.
///   Each [`Vertex`] has validated coordinates, optional data of type `U`, and a constant `D` dimension.
/// - `simplices`: A storage map that stores maximal [`Simplex`] objects with stable keys.
///   Each [`Simplex`] stores [`VertexKey`]s (keys into `vertices`) and optional neighbor [`SimplexKey`]s,
///   plus simplex data of type `V`.
///   Note the dimensionality of the simplex may differ from D, though the [`Tds`]
///   only stores simplices of maximal dimensionality D and infers other lower
///   dimensional simplices (cf. Facets) from the maximal simplices and their vertices.
///
/// For example, in 3 dimensions:
///
/// - A 0-dimensional simplex is a [`Vertex`].
/// - A 1-dimensional simplex is an `Edge` given by the `Tetrahedron` and two
///   [`Vertex`] endpoints.
/// - A 2-dimensional simplex is a `Facet` given by the `Tetrahedron` and the
///   opposite [`Vertex`].
/// - A 3-dimensional simplex is a `Tetrahedron`, the maximal simplex.
///
/// A similar pattern holds for higher dimensions.
///
/// In typical usage, vertices carry coordinates in D-dimensional Euclidean space.
/// However, the core `Tds` API is designed to be **combinatorial**: most methods
/// operate purely on keys and adjacency.
///
/// # Usage
///
/// `Tds` is the low-level topology container used by
/// [`Triangulation`](crate::prelude::triangulation::Triangulation) and
/// [`crate::DelaunayTriangulation`].
///
/// Most users should construct triangulations via `DelaunayTriangulation` and use the
/// owner query and validation methods on that type. Use [`Tds::empty`](Self::empty)
/// for low-level or test scenarios where you want to manipulate the topology directly.
///
/// ```rust
/// use delaunay::prelude::*;
///
/// # #[derive(Debug, thiserror::Error)]
/// # enum ExampleError {
/// #     #[error(transparent)]
/// #     Construction(#[from] delaunay::DelaunayTriangulationConstructionError),
/// #     #[error(transparent)]
/// #     Insertion(#[from] delaunay::prelude::insertion::InsertionError),
/// #     #[error(transparent)]
/// #     Tds(#[from] delaunay::prelude::tds::TdsError),
/// #     #[error(transparent)]
/// #     TdsConstruction(#[from] delaunay::prelude::tds::TdsConstructionError),
/// #     #[error(transparent)]
/// #     Invariant(#[from] delaunay::prelude::tds::InvariantError),
/// #     #[error(transparent)]
/// #     Facet(#[from] delaunay::prelude::tds::FacetError),
/// #     #[error(transparent)]
/// #     Simplex(#[from] delaunay::prelude::tds::SimplexValidationError),
/// #     #[error(transparent)]
/// #     Validation(#[from] delaunay::DelaunayTriangulationValidationError),
/// #     #[error(transparent)]
/// #     Coordinate(#[from] delaunay::prelude::geometry::CoordinateConversionError),
/// # }
/// # fn main() -> Result<(), ExampleError> {
/// // Create vertices for a 2D triangulation
/// let vertices = [
///     delaunay::vertex![0.0, 0.0]?,
///     delaunay::vertex![1.0, 0.0]?,
///     delaunay::vertex![0.5, 1.0]?,
/// ];
///
/// // Create a new triangulation
/// let dt = DelaunayTriangulationBuilder::new(&vertices).build()?;
///
/// // Check the number of simplices and vertices
/// assert_eq!(dt.number_of_simplices(), 1);
/// assert_eq!(dt.number_of_vertices(), 3);
/// # Ok(())
/// # }
/// ```
pub struct Tds<U, V, const D: usize> {
    /// Storage map for vertices, allowing stable keys and efficient access.
    pub(super) vertices: StorageMap<VertexKey, Vertex<U, D>>,

    /// Storage map for simplices, providing stable keys and efficient access.
    pub(super) simplices: StorageMap<SimplexKey, Simplex<V, D>>,

    /// Fast mapping from Vertex UUIDs to their `VertexKeys` for efficient UUID → Key lookups.
    /// This optimizes the common operation of looking up vertex keys by UUID.
    /// For reverse Key → UUID lookups, we use direct storage map access: `vertices[key].uuid()`.
    ///
    /// INVARIANT: External mutation of this map will violate TDS invariants.
    /// This should only be modified through TDS methods that maintain consistency.
    ///
    /// Note: Not serialized - reconstructed during deserialization from vertices.
    pub(crate) uuid_to_vertex_key: UuidToVertexKeyMap,

    /// Fast mapping from Simplex UUIDs to their `SimplexKeys` for efficient UUID → Key lookups.
    /// This optimizes the common operation of looking up simplex keys by UUID.
    /// For reverse Key → UUID lookups, we use direct storage map access: `simplices[key].uuid()`.
    ///
    /// INVARIANT: External mutation of this map will violate TDS invariants.
    /// This should only be modified through TDS methods that maintain consistency.
    ///
    /// Note: Not serialized - reconstructed during deserialization from simplices.
    pub(crate) uuid_to_simplex_key: UuidToSimplexKeyMap,

    /// Maintained vertex-to-simplices incidence index.
    ///
    /// This is the canonical exact vertex-star relation for TDS storage. It is updated
    /// together with simplex insertion/removal and rebuilt during deserialization or
    /// bulk incidence repair. Isolated vertices are represented by present-but-empty
    /// entries.
    ///
    /// Note: Not serialized - reconstructed during deserialization from simplices.
    pub(super) vertex_to_simplices: VertexIncidenceIndex,

    /// The current construction state of the triangulation.
    /// This field tracks whether the triangulation has enough vertices to form a complete
    /// D-dimensional triangulation or if it's still being incrementally built.
    ///
    /// Note: Not serialized - only constructed triangulations should be serialized.
    pub(crate) construction_state: TriangulationConstructionState,

    /// Generation counter for invalidating caches.
    /// This counter is incremented whenever the triangulation structure is modified
    /// (vertices added, simplices created/removed, etc.), allowing dependent caches to
    /// detect when they need to refresh.
    /// Uses `Arc<AtomicU64>` for thread-safe operations in concurrent contexts while allowing Clone.
    ///
    /// Note: Not serialized - generation is runtime-only.
    pub(super) generation: Arc<AtomicU64>,

    /// Runtime identity for cache/handle provenance checks.
    ///
    /// Cloning or deserializing a `Tds` creates a fresh identity so handles cached
    /// from another storage snapshot cannot be reused against the reconstructed
    /// storage by generation alone.
    ///
    /// Note: Not serialized - identity is runtime-only.
    pub(super) identity: Arc<Uuid>,
}

impl<U, V, const D: usize> Clone for Tds<U, V, D>
where
    U: Clone,
    V: Clone,
{
    fn clone(&self) -> Self {
        Self {
            vertices: self.vertices.clone(),
            simplices: self.simplices.clone(),
            uuid_to_vertex_key: self.uuid_to_vertex_key.clone(),
            uuid_to_simplex_key: self.uuid_to_simplex_key.clone(),
            vertex_to_simplices: self.vertex_to_simplices.clone(),
            construction_state: self.construction_state.clone(),
            generation: Arc::new(AtomicU64::new(self.generation.load(Ordering::Relaxed))),
            identity: Arc::new(Uuid::new_v4()),
        }
    }
}

impl<U, V, const D: usize> Tds<U, V, D>
where
    U: Clone,
    V: Clone,
{
    /// Clones storage for an internal transactional snapshot while preserving
    /// the runtime identity promised to cache and handle provenance checks.
    pub(crate) fn clone_for_rollback(&self) -> Self {
        Self {
            vertices: self.vertices.clone(),
            simplices: self.simplices.clone(),
            uuid_to_vertex_key: self.uuid_to_vertex_key.clone(),
            uuid_to_simplex_key: self.uuid_to_simplex_key.clone(),
            vertex_to_simplices: self.vertex_to_simplices.clone(),
            construction_state: self.construction_state.clone(),
            generation: Arc::new(AtomicU64::new(self.generation.load(Ordering::Relaxed))),
            identity: Arc::clone(&self.identity),
        }
    }

    /// Replaces this storage with a rollback snapshot of `source`.
    ///
    /// This has the same cache and handle provenance semantics as
    /// [`Self::clone_for_rollback`] while reusing existing backing allocations
    /// where `clone_from` can do so. Hot mutation paths use it to recycle a
    /// scratch TDS without weakening rollback isolation.
    pub(crate) fn clone_from_for_rollback(&mut self, source: &Self) {
        self.vertices.clone_from(&source.vertices);
        self.simplices.clone_from(&source.simplices);
        self.uuid_to_vertex_key
            .clone_from(&source.uuid_to_vertex_key);
        self.uuid_to_simplex_key
            .clone_from(&source.uuid_to_simplex_key);
        self.vertex_to_simplices
            .clone_from(&source.vertex_to_simplices);
        self.construction_state
            .clone_from(&source.construction_state);
        self.generation = Arc::new(AtomicU64::new(source.generation.load(Ordering::Relaxed)));
        self.identity = Arc::clone(&source.identity);
    }
}

// =============================================================================
// CORE FUNCTIONALITY
// =============================================================================

// =============================================================================
// PURE COMBINATORIAL METHODS (No geometric operations)
// =============================================================================
// These methods work with the combinatorial structure only - vertices, simplices,
// neighbors, facets, keys, and UUIDs. They do NOT require coordinate operations
// and are designed to be independent of geometry.
//
// Following CGAL's Triangulation_data_structure pattern, these methods operate
// on topology independently of geometry.
//
impl<U, V, const D: usize> Tds<U, V, D> {
    #[inline]
    pub(super) fn allows_periodic_self_neighbor(simplex: &Simplex<V, D>) -> bool {
        let Some(offsets) = simplex.periodic_vertex_offsets() else {
            return false;
        };
        !offsets.is_empty() && offsets.len() == simplex.number_of_vertices()
    }
    pub(crate) fn periodic_facet_key_from_simplex_vertices(
        simplex: &Simplex<V, D>,
        vertices: &[VertexKey],
        facet_index: usize,
    ) -> Result<u64, TdsError> {
        if facet_index >= vertices.len() {
            return Err(TdsError::IndexOutOfBounds {
                index: facet_index,
                bound: vertices.len(),
                context: format!("facet index for simplex with {} vertices", vertices.len()),
            });
        }

        let Some(periodic_offsets) = simplex.periodic_vertex_offsets() else {
            // Non-periodic path: build facet_vertices only when needed
            let mut facet_vertices: SmallBuffer<VertexKey, MAX_PRACTICAL_DIMENSION_SIZE> =
                SmallBuffer::new();
            for (i, &vertex_key) in vertices.iter().enumerate() {
                if i != facet_index {
                    facet_vertices.push(vertex_key);
                }
            }
            return Ok(facet_key_from_vertices(&facet_vertices));
        };

        if periodic_offsets.len() != vertices.len() {
            return Err(TdsError::DimensionMismatch {
                expected: vertices.len(),
                actual: periodic_offsets.len(),
                context: "simplex periodic offset count vs vertex count".to_string(),
            });
        }

        let mut lifted_vertices: SmallBuffer<(VertexKey, [i8; D]), MAX_PRACTICAL_DIMENSION_SIZE> =
            SmallBuffer::new();
        for (vertex_idx, &vertex_key) in vertices.iter().enumerate() {
            lifted_vertices.push((vertex_key, periodic_offsets[vertex_idx]));
        }

        periodic_facet_key_from_lifted_vertices::<D>(&lifted_vertices, facet_index).map_err(
            |error| TdsError::InconsistentDataStructure {
                message: format!(
                    "Failed to derive periodic facet key for simplex {:?} facet {facet_index}: {error}",
                    simplex.uuid()
                ),
            },
        )
    }

    pub(super) fn build_periodic_vertex_uuid_offsets(
        &self,
        simplex_key: SimplexKey,
        vertices: &[VertexKey],
    ) -> Result<SimplexUuidSortKey<D>, TdsError> {
        let simplex = self
            .simplices
            .get(simplex_key)
            .ok_or_else(|| TdsError::SimplexNotFound {
                simplex_key,
                context: "building periodic vertex identity (UUID/offset)".to_string(),
            })?;

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

        let mut vertex_uuid_offsets = SimplexUuidSortKey::<D>::new();
        for (vertex_idx, &vertex_key) in vertices.iter().enumerate() {
            let vertex = self
                .vertices
                .get(vertex_key)
                .ok_or_else(|| TdsError::VertexNotFound {
                    vertex_key,
                    context: format!(
                        "referenced by simplex {simplex_key:?} at index {vertex_idx} while building periodic vertex identity (UUID/offset)",
                    ),
                })?;
            let offset = periodic_offsets.map_or([0_i8; D], |offsets| offsets[vertex_idx]);
            vertex_uuid_offsets.push((vertex.uuid(), offset));
        }
        vertex_uuid_offsets.sort_unstable();

        Ok(vertex_uuid_offsets)
    }

    pub(super) fn lifted_vertex_identities(
        simplex_key: SimplexKey,
        simplex: &Simplex<V, D>,
    ) -> Result<SmallBuffer<(VertexKey, [i8; D]), MAX_PRACTICAL_DIMENSION_SIZE>, TdsError> {
        let vertices = simplex.vertices();
        let periodic_offsets = simplex.periodic_vertex_offsets();
        if let Some(offsets) = periodic_offsets
            && offsets.len() != vertices.len()
        {
            return Err(TdsError::DimensionMismatch {
                expected: vertices.len(),
                actual: offsets.len(),
                context: format!(
                    "simplex {simplex_key:?} periodic offset count vs vertex count in neighbor topology validation"
                ),
            });
        }

        let mut lifted_vertices: SmallBuffer<(VertexKey, [i8; D]), MAX_PRACTICAL_DIMENSION_SIZE> =
            SmallBuffer::new();
        for (vertex_idx, &vertex_key) in vertices.iter().enumerate() {
            let offset = periodic_offsets.map_or([0_i8; D], |offsets| offsets[vertex_idx]);
            lifted_vertices.push((vertex_key, offset));
        }

        Ok(lifted_vertices)
    }

    pub(super) fn matching_lifted_facet_index(
        simplex: &Simplex<V, D>,
        neighbor: &Simplex<V, D>,
    ) -> Result<Option<usize>, TdsError> {
        let simplex_vertices = simplex.vertices();
        let neighbor_vertices = neighbor.vertices();

        for simplex_facet_index in 0..simplex_vertices.len() {
            let simplex_facet_key = Self::periodic_facet_key_from_simplex_vertices(
                simplex,
                simplex_vertices,
                simplex_facet_index,
            )?;
            for neighbor_facet_index in 0..neighbor_vertices.len() {
                let neighbor_facet_key = Self::periodic_facet_key_from_simplex_vertices(
                    neighbor,
                    neighbor_vertices,
                    neighbor_facet_index,
                )?;
                if simplex_facet_key == neighbor_facet_key {
                    return Ok(Some(simplex_facet_index));
                }
            }
        }

        Ok(None)
    }

    /// Finds the neighbor facet that matches a source facet in lifted periodic coordinates.
    pub(super) fn matching_lifted_mirror_facet_index(
        simplex: &Simplex<V, D>,
        facet_idx: usize,
        neighbor: &Simplex<V, D>,
        context: &str,
    ) -> Result<usize, TdsError> {
        let simplex_facet_key =
            Self::periodic_facet_key_from_simplex_vertices(simplex, simplex.vertices(), facet_idx)?;
        let mut mirror_idx = None;
        for neighbor_facet_idx in 0..neighbor.vertices().len() {
            let neighbor_facet_key = Self::periodic_facet_key_from_simplex_vertices(
                neighbor,
                neighbor.vertices(),
                neighbor_facet_idx,
            )?;
            if neighbor_facet_key == simplex_facet_key
                && mirror_idx.replace(neighbor_facet_idx).is_some()
            {
                return Err(TdsError::InvalidNeighbors {
                    reason: NeighborValidationError::MirrorFacetAmbiguous {
                        simplex_uuid: simplex.uuid(),
                        neighbor_uuid: neighbor.uuid(),
                    },
                });
            }
        }

        mirror_idx.ok_or_else(|| TdsError::InvalidNeighbors {
            reason: NeighborValidationError::MirrorFacetMissing {
                simplex_uuid: simplex.uuid(),
                facet_index: facet_idx,
                neighbor_uuid: neighbor.uuid(),
                context: context.to_string(),
            },
        })
    }

    pub(crate) fn facet_key_for_simplex_facet(
        &self,
        simplex_key: SimplexKey,
        facet_index: usize,
    ) -> Result<u64, TdsError> {
        let vertices = self.simplex_vertices(simplex_key)?;
        let simplex = self
            .simplices
            .get(simplex_key)
            .ok_or_else(|| TdsError::SimplexNotFound {
                simplex_key,
                context: format!("deriving facet key for index {facet_index}"),
            })?;
        Self::periodic_facet_key_from_simplex_vertices(simplex, vertices, facet_index)
    }

    /// Returns an iterator over all simplices in the triangulation.
    ///
    /// This method provides read-only access to the simplices collection without
    /// exposing the underlying storage implementation. The iterator yields
    /// `(SimplexKey, &Simplex)` pairs for each simplex in the triangulation.
    ///
    /// For direct key-based access, use [`simplex`](Self::simplex).
    ///
    /// # Returns
    ///
    /// An iterator over `(SimplexKey, &Simplex<V, D>)` pairs.
    ///
    /// # Example
    ///
    /// ```
    /// use delaunay::prelude::*;
    ///
    /// # #[derive(Debug, thiserror::Error)]
    /// # enum ExampleError {
    /// #     #[error(transparent)]
    /// #     Construction(#[from] delaunay::DelaunayTriangulationConstructionError),
    /// #     #[error(transparent)]
    /// #     Insertion(#[from] delaunay::prelude::insertion::InsertionError),
    /// #     #[error(transparent)]
    /// #     Tds(#[from] delaunay::prelude::tds::TdsError),
    /// #     #[error(transparent)]
    /// #     TdsConstruction(#[from] delaunay::prelude::tds::TdsConstructionError),
    /// #     #[error(transparent)]
    /// #     Invariant(#[from] delaunay::prelude::tds::InvariantError),
    /// #     #[error(transparent)]
    /// #     Facet(#[from] delaunay::prelude::tds::FacetError),
    /// #     #[error(transparent)]
    /// #     Simplex(#[from] delaunay::prelude::tds::SimplexValidationError),
    /// #     #[error(transparent)]
    /// #     Validation(#[from] delaunay::DelaunayTriangulationValidationError),
    /// #     #[error(transparent)]
    /// #     Coordinate(#[from] delaunay::prelude::geometry::CoordinateConversionError),
    /// # }
    /// # fn main() -> Result<(), ExampleError> {
    /// 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()?;
    ///
    /// for (simplex_key, simplex) in dt.simplices() {
    ///     println!("Simplex {:?} has {} vertices", simplex_key, simplex.number_of_vertices());
    /// }
    /// # Ok(())
    /// # }
    /// ```
    pub fn simplices(&self) -> impl Iterator<Item = (SimplexKey, &Simplex<V, D>)> {
        self.simplices.iter()
    }

    /// Returns an iterator over all vertices in the triangulation.
    ///
    /// This method provides read-only access to the vertices collection without
    /// exposing the underlying storage implementation. The iterator yields
    /// `(VertexKey, &Vertex)` pairs for each vertex in the triangulation.
    ///
    /// For direct key-based access, use [`vertex`](Self::vertex).
    ///
    /// # Returns
    ///
    /// An iterator over `(VertexKey, &Vertex<U, D>)` pairs.
    ///
    /// # Example
    ///
    /// ```
    /// use delaunay::prelude::*;
    ///
    /// # #[derive(Debug, thiserror::Error)]
    /// # enum ExampleError {
    /// #     #[error(transparent)] Coordinates(#[from] delaunay::prelude::geometry::CoordinateConversionError),
    /// #     #[error(transparent)] Construction(#[from] delaunay::DelaunayTriangulationConstructionError),
    /// #     #[error(transparent)] Insertion(#[from] delaunay::prelude::insertion::InsertionError),
    /// #     #[error(transparent)] Tds(#[from] delaunay::prelude::tds::TdsError),
    /// #     #[error(transparent)] TdsMutation(#[from] delaunay::prelude::tds::TdsMutationError),
    /// #     #[error(transparent)] TdsConstruction(#[from] delaunay::prelude::tds::TdsConstructionError),
    /// #     #[error(transparent)] Invariant(#[from] delaunay::prelude::tds::InvariantError),
    /// #     #[error(transparent)] Facet(#[from] delaunay::prelude::tds::FacetError),
    /// #     #[error(transparent)] Simplex(#[from] delaunay::prelude::tds::SimplexValidationError),
    /// # }
    /// # fn main() -> Result<(), ExampleError> {
    /// let vertices = [
    ///     delaunay::vertex![0.0, 0.0]?,
    ///     delaunay::vertex![1.0, 0.0]?,
    ///     delaunay::vertex![0.5, 1.0]?,
    /// ];
    /// let dt = DelaunayTriangulationBuilder::new(&vertices).build()?;
    ///
    /// for (vertex_key, vertex) in dt.vertices() {
    ///     println!("Vertex {:?} at {:?}", vertex_key, vertex.point());
    /// }
    /// # Ok(())
    /// # }
    /// ```
    pub fn vertices(&self) -> impl Iterator<Item = (VertexKey, &Vertex<U, D>)> {
        self.vertices.iter()
    }

    /// Returns an iterator over all vertex keys in the triangulation.
    ///
    /// # Returns
    ///
    /// An iterator over `VertexKey` values.
    ///
    /// # Examples
    ///
    /// ```
    /// use delaunay::prelude::*;
    ///
    /// # #[derive(Debug, thiserror::Error)]
    /// # enum ExampleError {
    /// #     #[error(transparent)] Coordinates(#[from] delaunay::prelude::geometry::CoordinateConversionError),
    /// #     #[error(transparent)] Construction(#[from] delaunay::DelaunayTriangulationConstructionError),
    /// #     #[error(transparent)] Insertion(#[from] delaunay::prelude::insertion::InsertionError),
    /// #     #[error(transparent)] Tds(#[from] delaunay::prelude::tds::TdsError),
    /// #     #[error(transparent)] TdsMutation(#[from] delaunay::prelude::tds::TdsMutationError),
    /// #     #[error(transparent)] TdsConstruction(#[from] delaunay::prelude::tds::TdsConstructionError),
    /// #     #[error(transparent)] Invariant(#[from] delaunay::prelude::tds::InvariantError),
    /// #     #[error(transparent)] Facet(#[from] delaunay::prelude::tds::FacetError),
    /// #     #[error(transparent)] Simplex(#[from] delaunay::prelude::tds::SimplexValidationError),
    /// # }
    /// # fn main() -> Result<(), ExampleError> {
    /// 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 keys: Vec<_> = dt.vertices().map(|(key, _)| key).collect();
    /// assert_eq!(keys.len(), 3);
    /// # Ok(())
    /// # }
    /// ```
    pub fn vertex_keys(&self) -> impl Iterator<Item = VertexKey> + '_ {
        self.vertices.keys()
    }

    /// Returns an iterator over all simplex keys in the triangulation.
    ///
    /// # Returns
    ///
    /// An iterator over `SimplexKey` values.
    ///
    /// # Examples
    ///
    /// ```
    /// use delaunay::prelude::*;
    ///
    /// # #[derive(Debug, thiserror::Error)]
    /// # enum ExampleError {
    /// #     #[error(transparent)] Coordinates(#[from] delaunay::prelude::geometry::CoordinateConversionError),
    /// #     #[error(transparent)] Construction(#[from] delaunay::DelaunayTriangulationConstructionError),
    /// #     #[error(transparent)] Insertion(#[from] delaunay::prelude::insertion::InsertionError),
    /// #     #[error(transparent)] Tds(#[from] delaunay::prelude::tds::TdsError),
    /// #     #[error(transparent)] TdsMutation(#[from] delaunay::prelude::tds::TdsMutationError),
    /// #     #[error(transparent)] TdsConstruction(#[from] delaunay::prelude::tds::TdsConstructionError),
    /// #     #[error(transparent)] Invariant(#[from] delaunay::prelude::tds::InvariantError),
    /// #     #[error(transparent)] Facet(#[from] delaunay::prelude::tds::FacetError),
    /// #     #[error(transparent)] Simplex(#[from] delaunay::prelude::tds::SimplexValidationError),
    /// # }
    /// # fn main() -> Result<(), ExampleError> {
    /// 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 keys: Vec<_> = dt.simplices().map(|(key, _)| key).collect();
    /// assert_eq!(keys.len(), 1);
    /// # Ok(())
    /// # }
    /// ```
    pub fn simplex_keys(&self) -> impl Iterator<Item = SimplexKey> + '_ {
        self.simplices.keys()
    }

    /// Returns the concrete simplex-key iterator for internal iterator structs
    /// that need to store traversal state without allocating a key snapshot.
    pub(crate) fn simplex_key_iter(&self) -> slotmap::dense::Keys<'_, SimplexKey, Simplex<V, D>> {
        self.simplices.keys()
    }

    /// Returns a reference to a simplex by its key.
    ///
    /// # Returns
    ///
    /// `Some(&Simplex)` if the key exists, `None` otherwise.
    ///
    /// # Examples
    ///
    /// ```
    /// use delaunay::prelude::*;
    ///
    /// # #[derive(Debug, thiserror::Error)]
    /// # enum ExampleError {
    /// #     #[error(transparent)] Construction(#[from] delaunay::DelaunayTriangulationConstructionError),
    /// #     #[error(transparent)] Insertion(#[from] delaunay::prelude::insertion::InsertionError),
    /// #     #[error(transparent)] Tds(#[from] delaunay::prelude::tds::TdsError),
    /// #     #[error(transparent)] TdsMutation(#[from] delaunay::prelude::tds::TdsMutationError),
    /// #     #[error(transparent)] TdsConstruction(#[from] delaunay::prelude::tds::TdsConstructionError),
    /// #     #[error(transparent)] Invariant(#[from] delaunay::prelude::tds::InvariantError),
    /// #     #[error(transparent)] Facet(#[from] delaunay::prelude::tds::FacetError),
    /// #     #[error(transparent)] Simplex(#[from] delaunay::prelude::tds::SimplexValidationError),
    /// #     #[error(transparent)]
    /// #     Coordinate(#[from] delaunay::prelude::geometry::CoordinateConversionError),
    /// # }
    /// # fn main() -> Result<(), ExampleError> {
    /// 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 Some((simplex_key, _)) = dt.simplices().next() else {
    ///     return Ok(());
    /// };
    /// let Some(simplex) = dt.simplex(simplex_key) else {
    ///     return Ok(());
    /// };
    /// assert_eq!(simplex.number_of_vertices(), 3);
    /// # Ok(())
    /// # }
    /// ```
    #[must_use]
    pub fn simplex(&self, key: SimplexKey) -> Option<&Simplex<V, D>> {
        self.simplices.get(key)
    }

    /// Checks if a simplex key exists in the triangulation.
    ///
    /// # Returns
    ///
    /// `true` if the key exists, `false` otherwise.
    ///
    /// # Examples
    ///
    /// ```
    /// use delaunay::prelude::*;
    ///
    /// # #[derive(Debug, thiserror::Error)]
    /// # enum ExampleError {
    /// #     #[error(transparent)] Construction(#[from] delaunay::DelaunayTriangulationConstructionError),
    /// #     #[error(transparent)] Insertion(#[from] delaunay::prelude::insertion::InsertionError),
    /// #     #[error(transparent)] Tds(#[from] delaunay::prelude::tds::TdsError),
    /// #     #[error(transparent)] TdsMutation(#[from] delaunay::prelude::tds::TdsMutationError),
    /// #     #[error(transparent)] TdsConstruction(#[from] delaunay::prelude::tds::TdsConstructionError),
    /// #     #[error(transparent)] Invariant(#[from] delaunay::prelude::tds::InvariantError),
    /// #     #[error(transparent)] Facet(#[from] delaunay::prelude::tds::FacetError),
    /// #     #[error(transparent)] Simplex(#[from] delaunay::prelude::tds::SimplexValidationError),
    /// #     #[error(transparent)]
    /// #     Coordinate(#[from] delaunay::prelude::geometry::CoordinateConversionError),
    /// # }
    /// # fn main() -> Result<(), ExampleError> {
    /// 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 Some((simplex_key, _)) = dt.simplices().next() else {
    ///     return Ok(());
    /// };
    /// assert!(dt.contains_simplex(simplex_key));
    /// # Ok(())
    /// # }
    /// ```
    #[must_use]
    pub fn contains_simplex(&self, key: SimplexKey) -> bool {
        self.simplices.contains_key(key)
    }

    /// The function returns the number of vertices in the triangulation
    /// data structure.
    ///
    /// # Returns
    ///
    /// The number of [Vertex] objects in the [Tds].
    ///
    /// # Examples
    ///
    /// Count vertices in an empty triangulation:
    ///
    /// ```
    /// use delaunay::prelude::tds::Tds;
    ///
    /// let tds = Tds::<(), (), 3>::empty();
    /// assert_eq!(tds.number_of_vertices(), 0);
    /// ```
    ///
    /// Count vertices after adding them:
    ///
    /// ```no_run
    /// use delaunay::prelude::*;
    ///
    /// # #[derive(Debug, thiserror::Error)]
    /// # enum ExampleError {
    /// #     #[error(transparent)] Construction(#[from] delaunay::DelaunayTriangulationConstructionError),
    /// #     #[error(transparent)] Insertion(#[from] delaunay::prelude::insertion::InsertionError),
    /// #     #[error(transparent)] Tds(#[from] delaunay::prelude::tds::TdsError),
    /// #     #[error(transparent)] TdsConstruction(#[from] delaunay::prelude::tds::TdsConstructionError),
    /// #     #[error(transparent)] Invariant(#[from] delaunay::prelude::tds::InvariantError),
    /// #     #[error(transparent)] Facet(#[from] delaunay::prelude::tds::FacetError),
    /// #     #[error(transparent)] Simplex(#[from] delaunay::prelude::tds::SimplexValidationError),
    /// #     #[error(transparent)]
    /// #     Coordinate(#[from] delaunay::prelude::geometry::CoordinateConversionError),
    /// # }
    /// # fn main() -> Result<(), ExampleError> {
    /// let mut dt: DelaunayTriangulation<_, (), (), 3> = DelaunayTriangulation::empty();
    /// let vertex1: Vertex<(), 3> = vertex![1.0, 2.0, 3.0]?;
    /// let vertex2: Vertex<(), 3> = vertex![4.0, 5.0, 6.0]?;
    ///
    /// dt.insert_vertex(vertex1)?;
    /// assert_eq!(dt.number_of_vertices(), 1);
    ///
    /// dt.insert_vertex(vertex2)?;
    /// assert_eq!(dt.number_of_vertices(), 2);
    /// # Ok(())
    /// # }
    /// ```
    ///
    /// Count vertices initialized from points:
    ///
    /// ```
    /// use delaunay::prelude::*;
    ///
    /// # #[derive(Debug, thiserror::Error)]
    /// # enum ExampleError {
    /// #     #[error(transparent)] Construction(#[from] delaunay::DelaunayTriangulationConstructionError),
    /// #     #[error(transparent)] Insertion(#[from] delaunay::prelude::insertion::InsertionError),
    /// #     #[error(transparent)] Tds(#[from] delaunay::prelude::tds::TdsError),
    /// #     #[error(transparent)] TdsConstruction(#[from] delaunay::prelude::tds::TdsConstructionError),
    /// #     #[error(transparent)] Invariant(#[from] delaunay::prelude::tds::InvariantError),
    /// #     #[error(transparent)] Facet(#[from] delaunay::prelude::tds::FacetError),
    /// #     #[error(transparent)] Simplex(#[from] delaunay::prelude::tds::SimplexValidationError),
    /// #     #[error(transparent)] Coordinate(#[from] delaunay::prelude::geometry::CoordinateConversionError),
    /// # }
    /// # fn main() -> Result<(), ExampleError> {
    /// let points = [
    ///     Point::try_from([0.0, 0.0, 0.0])?,
    ///     Point::try_from([1.0, 0.0, 0.0])?,
    ///     Point::try_from([0.0, 1.0, 0.0])?,
    ///     Point::try_from([0.0, 0.0, 1.0])?,
    /// ];
    ///
    /// let vertices = delaunay::try_vertices_from_points(&points)?;
    /// let dt = DelaunayTriangulationBuilder::new(&vertices).build()?;
    /// assert_eq!(dt.number_of_vertices(), 4);
    /// # Ok(())
    /// # }
    /// ```
    #[must_use]
    pub fn number_of_vertices(&self) -> usize {
        self.vertices.len()
    }

    /// The `dim` function returns the dimensionality of the [Tds].
    ///
    /// # Returns
    ///
    /// The `dim` function returns the minimum value between the number of
    /// vertices minus one and the value of `D` as an [i32].
    ///
    /// # Examples
    ///
    /// Dimension of an empty triangulation:
    ///
    /// ```
    /// use delaunay::prelude::tds::Tds;
    /// use delaunay::prelude::geometry::Point;
    /// use delaunay::prelude::geometry::Coordinate;
    ///
    /// let tds = Tds::<(), (), 3>::empty();
    /// assert_eq!(tds.dim(), -1); // Empty triangulation
    /// ```
    ///
    /// Dimension progression as vertices are added:
    ///
    /// ```no_run
    /// use delaunay::prelude::*;
    ///
    /// # #[derive(Debug, thiserror::Error)]
    /// # enum ExampleError {
    /// #     #[error(transparent)] Coordinates(#[from] delaunay::prelude::geometry::CoordinateConversionError),
    /// #     #[error(transparent)] Construction(#[from] delaunay::DelaunayTriangulationConstructionError),
    /// #     #[error(transparent)] Insertion(#[from] delaunay::prelude::insertion::InsertionError),
    /// #     #[error(transparent)] Tds(#[from] delaunay::prelude::tds::TdsError),
    /// #     #[error(transparent)] TdsConstruction(#[from] delaunay::prelude::tds::TdsConstructionError),
    /// #     #[error(transparent)] Invariant(#[from] delaunay::prelude::tds::InvariantError),
    /// #     #[error(transparent)] Facet(#[from] delaunay::prelude::tds::FacetError),
    /// #     #[error(transparent)] Simplex(#[from] delaunay::prelude::tds::SimplexValidationError),
    /// # }
    /// # fn main() -> Result<(), ExampleError> {
    /// let mut dt: DelaunayTriangulation<_, (), (), 3> = DelaunayTriangulation::empty();
    ///
    /// // Start empty
    /// assert_eq!(dt.dim(), -1);
    ///
    /// // Add vertices incrementally
    /// let vertex1: Vertex<(), 3> = vertex![0.0, 0.0, 0.0]?;
    /// dt.insert_vertex(vertex1)?;
    /// assert_eq!(dt.dim(), 0);
    ///
    /// let vertex2: Vertex<(), 3> = vertex![1.0, 0.0, 0.0]?;
    /// dt.insert_vertex(vertex2)?;
    /// assert_eq!(dt.dim(), 1);
    ///
    /// let vertex3: Vertex<(), 3> = vertex![0.0, 1.0, 0.0]?;
    /// dt.insert_vertex(vertex3)?;
    /// assert_eq!(dt.dim(), 2);
    ///
    /// let vertex4: Vertex<(), 3> = vertex![0.0, 0.0, 1.0]?;
    /// dt.insert_vertex(vertex4)?;
    /// assert_eq!(dt.number_of_vertices(), 4);
    /// assert_eq!(dt.dim(), 3);
    /// # Ok(())
    /// # }
    /// ```
    ///
    /// Different dimensional triangulations:
    ///
    /// ```
    /// use delaunay::prelude::*;
    ///
    /// # #[derive(Debug, thiserror::Error)]
    /// # enum ExampleError {
    /// #     #[error(transparent)] Construction(#[from] delaunay::DelaunayTriangulationConstructionError),
    /// #     #[error(transparent)] Insertion(#[from] delaunay::prelude::insertion::InsertionError),
    /// #     #[error(transparent)] Tds(#[from] delaunay::prelude::tds::TdsError),
    /// #     #[error(transparent)] TdsConstruction(#[from] delaunay::prelude::tds::TdsConstructionError),
    /// #     #[error(transparent)] Invariant(#[from] delaunay::prelude::tds::InvariantError),
    /// #     #[error(transparent)] Facet(#[from] delaunay::prelude::tds::FacetError),
    /// #     #[error(transparent)] Simplex(#[from] delaunay::prelude::tds::SimplexValidationError),
    /// #     #[error(transparent)] Coordinate(#[from] delaunay::prelude::geometry::CoordinateConversionError),
    /// # }
    /// # fn main() -> Result<(), ExampleError> {
    /// // 2D triangulation
    /// let points_2d = [
    ///     Point::try_from([0.0, 0.0])?,
    ///     Point::try_from([1.0, 0.0])?,
    ///     Point::try_from([0.5, 1.0])?,
    /// ];
    /// let vertices_2d = delaunay::try_vertices_from_points(&points_2d)?;
    /// let dt_2d = DelaunayTriangulationBuilder::new(&vertices_2d).build()?;
    /// assert_eq!(dt_2d.dim(), 2);
    ///
    /// // 4D triangulation with 5 vertices (minimum for 4D simplex)
    /// let points_4d = [
    ///     Point::try_from([0.0, 0.0, 0.0, 0.0])?,
    ///     Point::try_from([1.0, 0.0, 0.0, 0.0])?,
    ///     Point::try_from([0.0, 1.0, 0.0, 0.0])?,
    ///     Point::try_from([0.0, 0.0, 1.0, 0.0])?,
    ///     Point::try_from([0.0, 0.0, 0.0, 1.0])?,
    /// ];
    /// let vertices_4d = delaunay::try_vertices_from_points(&points_4d)?;
    /// let dt_4d = DelaunayTriangulationBuilder::new(&vertices_4d).build()?;
    /// assert_eq!(dt_4d.dim(), 4);
    /// # Ok(())
    /// # }
    /// ```
    #[must_use]
    pub fn dim(&self) -> i32 {
        let nv = self.number_of_vertices();
        // Convert to i32 first, then subtract to handle empty case (0 - 1 = -1)
        let nv_i32 = i32::try_from(nv).unwrap_or(i32::MAX);
        let d_i32 = i32::try_from(D).unwrap_or(i32::MAX);
        nv_i32.saturating_sub(1).min(d_i32)
    }

    /// Returns the current construction state of this triangulation data structure.
    ///
    /// The state is maintained by checked TDS and Delaunay construction paths. It
    /// is exposed read-only so callers can inspect incomplete vs. constructed
    /// topology without bypassing mutation invariants.
    ///
    /// # Examples
    ///
    /// ```rust
    /// use delaunay::prelude::tds::{Tds, TriangulationConstructionState};
    ///
    /// let tds: Tds<(), (), 3> = Tds::empty();
    /// std::assert_matches!(
    ///     tds.construction_state(),
    ///     TriangulationConstructionState::Incomplete(0)
    /// );
    /// ```
    #[inline]
    #[must_use]
    pub const fn construction_state(&self) -> &TriangulationConstructionState {
        &self.construction_state
    }

    /// Refreshes the derived vertex count carried by an incomplete construction state.
    #[inline]
    pub(super) fn refresh_incomplete_construction_state(&mut self) {
        if matches!(
            self.construction_state,
            TriangulationConstructionState::Incomplete(_)
        ) {
            self.construction_state =
                TriangulationConstructionState::Incomplete(self.vertices.len());
        }
    }

    /// The function `number_of_simplices` returns the number of simplices in the [Tds].
    ///
    /// # Returns
    ///
    /// The number of [Simplex]s in the [Tds].
    ///
    /// # Examples
    ///
    /// Count simplices in a newly created triangulation:
    ///
    /// ```
    /// use delaunay::prelude::*;
    ///
    /// # #[derive(Debug, thiserror::Error)]
    /// # enum ExampleError {
    /// #     #[error(transparent)] Construction(#[from] delaunay::DelaunayTriangulationConstructionError),
    /// #     #[error(transparent)] Insertion(#[from] delaunay::prelude::insertion::InsertionError),
    /// #     #[error(transparent)] Tds(#[from] delaunay::prelude::tds::TdsError),
    /// #     #[error(transparent)] TdsConstruction(#[from] delaunay::prelude::tds::TdsConstructionError),
    /// #     #[error(transparent)] Invariant(#[from] delaunay::prelude::tds::InvariantError),
    /// #     #[error(transparent)] Facet(#[from] delaunay::prelude::tds::FacetError),
    /// #     #[error(transparent)] Simplex(#[from] delaunay::prelude::tds::SimplexValidationError),
    /// #     #[error(transparent)] Coordinate(#[from] delaunay::prelude::geometry::CoordinateConversionError),
    /// # }
    /// # fn main() -> Result<(), ExampleError> {
    /// let points = [
    ///     Point::try_from([0.0, 0.0, 0.0])?,
    ///     Point::try_from([1.0, 0.0, 0.0])?,
    ///     Point::try_from([0.0, 1.0, 0.0])?,
    ///     Point::try_from([0.0, 0.0, 1.0])?,
    /// ];
    ///
    /// let vertices = delaunay::try_vertices_from_points(&points)?;
    /// let dt = DelaunayTriangulationBuilder::new(&vertices).build()?;
    /// assert_eq!(dt.number_of_simplices(), 1); // Simplices are automatically created via triangulation
    /// # Ok(())
    /// # }
    /// ```
    ///
    /// Count simplices after triangulation:
    ///
    /// ```
    /// use delaunay::prelude::*;
    ///
    /// # #[derive(Debug, thiserror::Error)]
    /// # enum ExampleError {
    /// #     #[error(transparent)] Construction(#[from] delaunay::DelaunayTriangulationConstructionError),
    /// #     #[error(transparent)] Insertion(#[from] delaunay::prelude::insertion::InsertionError),
    /// #     #[error(transparent)] Tds(#[from] delaunay::prelude::tds::TdsError),
    /// #     #[error(transparent)] TdsConstruction(#[from] delaunay::prelude::tds::TdsConstructionError),
    /// #     #[error(transparent)] Invariant(#[from] delaunay::prelude::tds::InvariantError),
    /// #     #[error(transparent)] Facet(#[from] delaunay::prelude::tds::FacetError),
    /// #     #[error(transparent)] Simplex(#[from] delaunay::prelude::tds::SimplexValidationError),
    /// #     #[error(transparent)] Coordinate(#[from] delaunay::prelude::geometry::CoordinateConversionError),
    /// # }
    /// # fn main() -> Result<(), ExampleError> {
    /// let points = [
    ///     Point::try_from([0.0, 0.0, 0.0])?,
    ///     Point::try_from([1.0, 0.0, 0.0])?,
    ///     Point::try_from([0.0, 1.0, 0.0])?,
    ///     Point::try_from([0.0, 0.0, 1.0])?,
    /// ];
    ///
    /// let vertices = delaunay::try_vertices_from_points(&points)?;
    /// let dt = DelaunayTriangulationBuilder::new(&vertices).build()?;
    /// assert_eq!(dt.number_of_simplices(), 1); // One tetrahedron for 4 points in 3D
    /// # Ok(())
    /// # }
    /// ```
    ///
    /// Empty triangulation has no simplices:
    ///
    /// ```
    /// use delaunay::prelude::tds::Tds;
    ///
    /// let tds = Tds::<(), (), 3>::empty();
    /// assert_eq!(tds.number_of_simplices(), 0); // No simplices for empty input
    /// ```
    #[must_use]
    pub fn number_of_simplices(&self) -> usize {
        self.simplices.len()
    }

    /// Returns `true` if the simplex neighbor graph is a single connected component.
    ///
    /// An empty triangulation (no simplices) is trivially connected.
    ///
    /// Connectivity is a **Level 3 Intrinsic PL Topology** invariant: it is not checked
    /// by [`Tds::is_valid`] (Level 2 Combinatorial Consistency), but it *is* checked by [`Triangulation::is_valid_topology`].
    /// This method exposes the underlying BFS so that diagnostic code and the
    /// `Triangulation`-layer check can both reuse the same primitive without going
    /// through a full `Triangulation` wrapper.
    ///
    /// Time complexity: O(N · D), where N is the number of simplices (each simplex has at most
    /// D+1 neighbors, so the BFS visits at most N·(D+1) edges).
    ///
    /// [`Triangulation::is_valid_topology`]: crate::prelude::triangulation::Triangulation::is_valid_topology
    ///
    /// # Examples
    ///
    /// ```
    /// use delaunay::prelude::*;
    ///
    /// # #[derive(Debug, thiserror::Error)]
    /// # enum ExampleError {
    /// #     #[error(transparent)] Construction(#[from] delaunay::DelaunayTriangulationConstructionError),
    /// #     #[error(transparent)] Insertion(#[from] delaunay::prelude::insertion::InsertionError),
    /// #     #[error(transparent)] Tds(#[from] delaunay::prelude::tds::TdsError),
    /// #     #[error(transparent)] TdsConstruction(#[from] delaunay::prelude::tds::TdsConstructionError),
    /// #     #[error(transparent)] Invariant(#[from] delaunay::prelude::tds::InvariantError),
    /// #     #[error(transparent)] Facet(#[from] delaunay::prelude::tds::FacetError),
    /// #     #[error(transparent)] Simplex(#[from] delaunay::prelude::tds::SimplexValidationError),
    /// #     #[error(transparent)]
    /// #     Coordinate(#[from] delaunay::prelude::geometry::CoordinateConversionError),
    /// # }
    /// # fn main() -> Result<(), ExampleError> {
    /// 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()?;
    /// assert!(dt.as_triangulation().is_valid_topology().is_ok());
    ///
    /// let empty_or_connected =
    ///     dt.number_of_simplices() == 0 || dt.as_triangulation().is_valid_topology().is_ok();
    /// assert!(empty_or_connected);
    /// # Ok(())
    /// # }
    /// ```
    #[must_use]
    pub fn is_connected(&self) -> bool {
        let total = self.simplices.len();
        if total == 0 {
            return true;
        }

        let Some(start) = self.simplex_keys().next() else {
            return true;
        };

        let mut visited: SimplexKeySet = SimplexKeySet::default();
        visited.reserve(total);
        let mut stack: Vec<SimplexKey> = Vec::with_capacity(total.min(64));
        stack.push(start);

        while let Some(ck) = stack.pop() {
            if !visited.insert(ck) {
                continue;
            }
            let Some(simplex) = self.simplices.get(ck) else {
                continue;
            };
            let Some(neighbors) = simplex.neighbor_keys() else {
                continue;
            };
            for n_opt in neighbors {
                let Some(nk) = n_opt else {
                    continue;
                };
                if self.simplices.contains_key(nk) && !visited.contains(&nk) {
                    stack.push(nk);
                }
            }
        }

        visited.len() == total
    }

    /// Increments the generation counter to invalidate dependent caches.
    ///
    /// This method should be called whenever the triangulation structure is modified
    /// (vertices added, simplices created/removed, etc.). It uses relaxed memory ordering
    /// since it's just an invalidation counter.
    ///
    /// # Thread Safety
    ///
    /// This method is thread-safe due to the use of `Arc<AtomicU64>`.
    #[inline]
    pub(super) fn bump_generation(&self) {
        // Relaxed is fine for an invalidation counter
        self.generation.fetch_add(1, Ordering::Relaxed);
    }

    /// Gets the current generation value.
    ///
    /// This can be used by external code to detect when the triangulation has changed.
    /// The generation counter is incremented on any structural modification.
    ///
    /// # Returns
    ///
    /// The current generation counter value.
    ///
    /// # Examples
    ///
    /// ```
    /// use delaunay::prelude::tds::Tds;
    ///
    /// let tds: Tds<(), (), 2> = Tds::empty();
    /// assert_eq!(tds.generation(), 0);
    /// ```
    #[inline]
    #[must_use]
    pub fn generation(&self) -> u64 {
        self.generation.load(Ordering::Relaxed)
    }

    /// Returns the opaque runtime identity token for this topology owner.
    ///
    /// Cloning a [`Tds`] creates a fresh owner identity, while internal rollback
    /// snapshots preserve the identity of the owner they protect.
    ///
    /// # Examples
    ///
    /// ```
    /// use delaunay::prelude::tds::Tds;
    ///
    /// let tds: Tds<(), (), 3> = Tds::empty();
    /// let owner = tds.topology_owner_id();
    ///
    /// assert_eq!(owner, tds.topology_owner_id());
    /// ```
    #[inline]
    pub fn topology_owner_id(&self) -> TopologyOwnerId {
        TopologyOwnerId::from_identity(&self.identity)
    }

    /// Returns the runtime identity used by cache owners to reject handles from another TDS.
    #[inline]
    pub(crate) const fn identity(&self) -> &Arc<Uuid> {
        &self.identity
    }

    /// Marks the triangulation topology as modified and invalidates generation-keyed caches.
    ///
    /// This is intended for crate-internal mutation paths that adjust simplex slot ordering
    /// without going through the standard insertion/removal APIs.
    #[inline]
    pub(crate) fn mark_topology_modified(&self) {
        self.bump_generation();
    }
}

impl<U, V, const D: usize> Tds<U, V, D> {}

impl<U, V, const D: usize> TopologyOwner for Tds<U, V, D> {
    #[inline]
    fn topology_owner_id(&self) -> TopologyOwnerId {
        Self::topology_owner_id(self)
    }

    #[inline]
    fn topology_generation(&self) -> u64 {
        self.generation()
    }
}

impl<U, V, const D: usize> Tds<U, V, D> {
    /// Returns a validated borrowed view of a simplex's vertex keys.
    ///
    /// This performs O(D) validation of the requested simplex's vertex keys and
    /// returns the canonical slice stored by the simplex. The returned view is
    /// borrowed from this TDS, so it cannot outlive the storage it observes.
    ///
    /// This method provides:
    /// - O(1) simplex lookup via storage map key
    /// - O(D) validation that all vertex keys exist in the triangulation
    /// - Direct key access without UUID→key lookups
    /// - Zero allocation on success
    ///
    /// # Arguments
    ///
    /// * `simplex_key` - The key of the simplex whose vertex keys we need
    ///
    /// # Returns
    ///
    /// A borrowed [`VertexKey`] slice if the [`SimplexKey`] exists and all
    /// referenced vertices are valid.
    ///
    /// # Errors
    ///
    /// Returns [`TdsError`] if:
    /// - The simplex with the given key doesn't exist
    /// - A vertex key from the simplex doesn't exist in the vertex storage (TDS corruption)
    ///
    /// # Performance
    ///
    /// This uses direct storage map access with O(1) key lookup for the simplex and O(D)
    /// validation for vertex keys. It returns the stored slice directly and performs no
    /// allocation in the hot path.
    ///
    /// # Examples
    ///
    /// ```
    /// use delaunay::prelude::*;
    ///
    /// # #[derive(Debug, thiserror::Error)]
    /// # enum ExampleError {
    /// #     #[error(transparent)] Construction(#[from] delaunay::DelaunayTriangulationConstructionError),
    /// #     #[error(transparent)] Insertion(#[from] delaunay::prelude::insertion::InsertionError),
    /// #     #[error(transparent)] Tds(#[from] delaunay::prelude::tds::TdsError),
    /// #     #[error(transparent)] TdsConstruction(#[from] delaunay::prelude::tds::TdsConstructionError),
    /// #     #[error(transparent)] Invariant(#[from] delaunay::prelude::tds::InvariantError),
    /// #     #[error(transparent)] Facet(#[from] delaunay::prelude::tds::FacetError),
    /// #     #[error(transparent)] Simplex(#[from] delaunay::prelude::tds::SimplexValidationError),
    /// #     #[error(transparent)]
    /// #     Coordinate(#[from] delaunay::prelude::geometry::CoordinateConversionError),
    /// # }
    /// # fn main() -> Result<(), ExampleError> {
    /// 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 Some((simplex_key, _)) = dt.simplices().next() else {
    ///     return Ok(());
    /// };
    /// let keys = dt.simplex_vertices(simplex_key)?;
    /// assert_eq!(keys.len(), 3);
    /// # Ok(())
    /// # }
    /// ```
    #[inline]
    pub fn simplex_vertices(&self, simplex_key: SimplexKey) -> Result<&[VertexKey], TdsError> {
        let simplex = self
            .simplices
            .get(simplex_key)
            .ok_or_else(|| TdsError::SimplexNotFound {
                simplex_key,
                context: "simplex_vertices lookup".to_string(),
            })?;

        // Validate keys in one pass before lending the canonical slice.
        let simplex_vertices = simplex.vertices();
        for (idx, &vertex_key) in simplex_vertices.iter().enumerate() {
            if !self.vertices.contains_key(vertex_key) {
                return Err(TdsError::VertexNotFound {
                    vertex_key,
                    context: format!(
                        "referenced by simplex {} (key {simplex_key:?}) at position {idx}",
                        simplex.uuid()
                    ),
                });
            }
        }
        Ok(simplex_vertices)
    }

    /// Helper function to get a simplex key from a simplex UUID using the optimized UUID→Key mapping.
    ///
    /// # Arguments
    ///
    /// * `simplex_uuid` - The UUID of the simplex to look up
    ///
    /// # Returns
    ///
    /// An `Option<SimplexKey>` if the simplex is found, `None` otherwise.
    ///
    /// # Performance
    ///
    /// This uses `FastHashMap` for O(1) UUID→Key lookups.
    ///
    /// # Examples
    ///
    /// Successfully finding a simplex key from a UUID:
    ///
    /// ```
    /// use delaunay::prelude::*;
    ///
    /// # #[derive(Debug, thiserror::Error)]
    /// # enum ExampleError {
    /// #     #[error(transparent)] Construction(#[from] delaunay::DelaunayTriangulationConstructionError),
    /// #     #[error(transparent)] Insertion(#[from] delaunay::prelude::insertion::InsertionError),
    /// #     #[error(transparent)] Tds(#[from] delaunay::prelude::tds::TdsError),
    /// #     #[error(transparent)] TdsConstruction(#[from] delaunay::prelude::tds::TdsConstructionError),
    /// #     #[error(transparent)] Invariant(#[from] delaunay::prelude::tds::InvariantError),
    /// #     #[error(transparent)] Facet(#[from] delaunay::prelude::tds::FacetError),
    /// #     #[error(transparent)] Simplex(#[from] delaunay::prelude::tds::SimplexValidationError),
    /// #     #[error(transparent)]
    /// #     Coordinate(#[from] delaunay::prelude::geometry::CoordinateConversionError),
    /// # }
    /// # fn main() -> Result<(), ExampleError> {
    /// // Create a triangulation with some vertices
    /// 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()?;
    ///
    /// // Get the first simplex and its UUID
    /// let Some((simplex_key, simplex)) = dt.simplices().next() else {
    ///     return Ok(());
    /// };
    /// let simplex_uuid = simplex.uuid();
    ///
    /// // Use the helper function to find the simplex key from its UUID
    /// let found_key = dt.simplex_key_from_uuid(&simplex_uuid);
    /// assert_eq!(found_key, Some(simplex_key));
    /// # Ok(())
    /// # }
    /// ```
    ///
    /// Returns `None` for non-existent UUID:
    ///
    /// ```
    /// use delaunay::prelude::tds::Tds;
    /// use uuid::Uuid;
    ///
    /// let tds: Tds<(), (), 3> = Tds::empty();
    /// let random_uuid = Uuid::new_v4();
    ///
    /// let result = tds.simplex_key_from_uuid(&random_uuid);
    /// assert_eq!(result, None);
    /// ```
    #[inline]
    #[must_use]
    pub fn simplex_key_from_uuid(&self, simplex_uuid: &Uuid) -> Option<SimplexKey> {
        self.uuid_to_simplex_key.get(simplex_uuid).copied()
    }

    /// Helper function to get a vertex key from a vertex UUID using the optimized UUID→Key mapping.
    /// This provides efficient UUID→Key lookups in hot paths.
    ///
    /// # Arguments
    ///
    /// * `vertex_uuid` - The UUID of the vertex to look up
    ///
    /// # Returns
    ///
    /// An `Option<VertexKey>` if the vertex is found, `None` otherwise.
    ///
    /// # Performance
    ///
    /// This uses `FastHashMap` for O(1) UUID→Key lookups.
    ///
    /// # Examples
    ///
    /// Successfully finding a vertex key from a UUID:
    ///
    /// ```
    /// use delaunay::prelude::*;
    ///
    /// # #[derive(Debug, thiserror::Error)]
    /// # enum ExampleError {
    /// #     #[error(transparent)] Construction(#[from] delaunay::DelaunayTriangulationConstructionError),
    /// #     #[error(transparent)] Insertion(#[from] delaunay::prelude::insertion::InsertionError),
    /// #     #[error(transparent)] Tds(#[from] delaunay::prelude::tds::TdsError),
    /// #     #[error(transparent)] TdsConstruction(#[from] delaunay::prelude::tds::TdsConstructionError),
    /// #     #[error(transparent)] Invariant(#[from] delaunay::prelude::tds::InvariantError),
    /// #     #[error(transparent)] Facet(#[from] delaunay::prelude::tds::FacetError),
    /// #     #[error(transparent)] Simplex(#[from] delaunay::prelude::tds::SimplexValidationError),
    /// #     #[error(transparent)]
    /// #     Coordinate(#[from] delaunay::prelude::geometry::CoordinateConversionError),
    /// # }
    /// # fn main() -> Result<(), ExampleError> {
    /// // Create a triangulation with some vertices
    /// 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()?;
    ///
    /// // Get the first vertex and its UUID
    /// let Some((vertex_key, vertex)) = dt.vertices().next() else {
    ///     return Ok(());
    /// };
    /// let vertex_uuid = vertex.uuid();
    ///
    /// // Use the helper function to find the vertex key from its UUID
    /// let found_key = dt.vertex_key_from_uuid(&vertex_uuid);
    /// assert_eq!(found_key, Some(vertex_key));
    /// # Ok(())
    /// # }
    /// ```
    ///
    /// Returns `None` for non-existent UUID:
    ///
    /// ```
    /// use delaunay::prelude::tds::Tds;
    /// use uuid::Uuid;
    ///
    /// let tds: Tds<(), (), 3> = Tds::empty();
    /// let random_uuid = Uuid::new_v4();
    ///
    /// let result = tds.vertex_key_from_uuid(&random_uuid);
    /// assert_eq!(result, None);
    /// ```
    #[inline]
    #[must_use]
    pub fn vertex_key_from_uuid(&self, vertex_uuid: &Uuid) -> Option<VertexKey> {
        self.uuid_to_vertex_key.get(vertex_uuid).copied()
    }

    /// Helper function to get a simplex UUID from a simplex key using direct `storage map` access.
    /// This is the reverse of `simplex_key_from_uuid()` for the less common Key→UUID direction.
    ///
    /// # Arguments
    ///
    /// * `simplex_key` - The key of the simplex to look up
    ///
    /// # Returns
    ///
    /// An `Option<Uuid>` if the simplex is found, `None` otherwise.
    ///
    /// # Performance
    ///
    /// This uses direct `storage map` indexing for O(1) Key→UUID lookups.
    ///
    /// # Examples
    ///
    /// Successfully getting a UUID from a simplex key:
    ///
    /// ```
    /// use delaunay::prelude::*;
    ///
    /// # #[derive(Debug, thiserror::Error)]
    /// # enum ExampleError {
    /// #     #[error(transparent)] Construction(#[from] delaunay::DelaunayTriangulationConstructionError),
    /// #     #[error(transparent)] Insertion(#[from] delaunay::prelude::insertion::InsertionError),
    /// #     #[error(transparent)] Tds(#[from] delaunay::prelude::tds::TdsError),
    /// #     #[error(transparent)] TdsConstruction(#[from] delaunay::prelude::tds::TdsConstructionError),
    /// #     #[error(transparent)] Invariant(#[from] delaunay::prelude::tds::InvariantError),
    /// #     #[error(transparent)] Facet(#[from] delaunay::prelude::tds::FacetError),
    /// #     #[error(transparent)] Simplex(#[from] delaunay::prelude::tds::SimplexValidationError),
    /// #     #[error(transparent)]
    /// #     Coordinate(#[from] delaunay::prelude::geometry::CoordinateConversionError),
    /// # }
    /// # fn main() -> Result<(), ExampleError> {
    /// // Create a triangulation with some vertices
    /// 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()?;
    ///
    /// // Get the first simplex key and expected UUID
    /// let Some((simplex_key, simplex)) = dt.simplices().next() else {
    ///     return Ok(());
    /// };
    /// let expected_uuid = simplex.uuid();
    ///
    /// // Use the helper function to get UUID from the simplex key
    /// let found_uuid = dt.simplex_uuid_from_key(simplex_key);
    /// assert_eq!(found_uuid, Some(expected_uuid));
    /// # Ok(())
    /// # }
    /// ```
    ///
    /// Round-trip conversion between UUID and key:
    ///
    /// ```
    /// use delaunay::prelude::*;
    ///
    /// # #[derive(Debug, thiserror::Error)]
    /// # enum ExampleError {
    /// #     #[error(transparent)] Construction(#[from] delaunay::DelaunayTriangulationConstructionError),
    /// #     #[error(transparent)] Insertion(#[from] delaunay::prelude::insertion::InsertionError),
    /// #     #[error(transparent)] Tds(#[from] delaunay::prelude::tds::TdsError),
    /// #     #[error(transparent)] TdsConstruction(#[from] delaunay::prelude::tds::TdsConstructionError),
    /// #     #[error(transparent)] Invariant(#[from] delaunay::prelude::tds::InvariantError),
    /// #     #[error(transparent)] Facet(#[from] delaunay::prelude::tds::FacetError),
    /// #     #[error(transparent)] Simplex(#[from] delaunay::prelude::tds::SimplexValidationError),
    /// #     #[error(transparent)]
    /// #     Coordinate(#[from] delaunay::prelude::geometry::CoordinateConversionError),
    /// # }
    /// # fn main() -> Result<(), ExampleError> {
    /// // Create a triangulation with some vertices
    /// 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()?;
    ///
    /// // Get the first simplex's UUID
    /// let Some((_, simplex)) = dt.simplices().next() else {
    ///     return Ok(());
    /// };
    /// let original_uuid = simplex.uuid();
    ///
    /// // Convert UUID to key, then key back to UUID
    /// let Some(simplex_key) = dt.simplex_key_from_uuid(&original_uuid) else {
    ///     return Ok(());
    /// };
    /// let round_trip_uuid = dt.simplex_uuid_from_key(simplex_key);
    /// assert_eq!(Some(original_uuid), round_trip_uuid);
    /// # Ok(())
    /// # }
    /// ```
    #[inline]
    #[must_use]
    pub fn simplex_uuid_from_key(&self, simplex_key: SimplexKey) -> Option<Uuid> {
        self.simplices.get(simplex_key).map(Simplex::uuid)
    }

    /// Helper function to get a vertex UUID from a vertex key using direct `storage map` access.
    /// This is the reverse of `vertex_key_from_uuid()` for the less common Key→UUID direction.
    ///
    /// # Arguments
    ///
    /// * `vertex_key` - The key of the vertex to look up
    ///
    /// # Returns
    ///
    /// An `Option<Uuid>` if the vertex is found, `None` otherwise.
    ///
    /// # Performance
    ///
    /// This uses direct `storage map` indexing for O(1) Key→UUID lookups.
    ///
    /// # Examples
    ///
    /// Successfully getting a UUID from a vertex key:
    ///
    /// ```
    /// use delaunay::prelude::*;
    ///
    /// # #[derive(Debug, thiserror::Error)]
    /// # enum ExampleError {
    /// #     #[error(transparent)] Construction(#[from] delaunay::DelaunayTriangulationConstructionError),
    /// #     #[error(transparent)] Insertion(#[from] delaunay::prelude::insertion::InsertionError),
    /// #     #[error(transparent)] Tds(#[from] delaunay::prelude::tds::TdsError),
    /// #     #[error(transparent)] TdsConstruction(#[from] delaunay::prelude::tds::TdsConstructionError),
    /// #     #[error(transparent)] Invariant(#[from] delaunay::prelude::tds::InvariantError),
    /// #     #[error(transparent)] Facet(#[from] delaunay::prelude::tds::FacetError),
    /// #     #[error(transparent)] Simplex(#[from] delaunay::prelude::tds::SimplexValidationError),
    /// #     #[error(transparent)]
    /// #     Coordinate(#[from] delaunay::prelude::geometry::CoordinateConversionError),
    /// # }
    /// # fn main() -> Result<(), ExampleError> {
    /// // Create a triangulation with some vertices
    /// 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()?;
    ///
    /// // Get the first vertex key and expected UUID
    /// let Some((vertex_key, vertex)) = dt.vertices().next() else {
    ///     return Ok(());
    /// };
    /// let expected_uuid = vertex.uuid();
    ///
    /// // Use the helper function to get UUID from the vertex key
    /// let found_uuid = dt.vertex_uuid_from_key(vertex_key);
    /// assert_eq!(found_uuid, Some(expected_uuid));
    /// # Ok(())
    /// # }
    /// ```
    ///
    /// Round-trip conversion between UUID and key:
    ///
    /// ```
    /// use delaunay::prelude::*;
    ///
    /// # #[derive(Debug, thiserror::Error)]
    /// # enum ExampleError {
    /// #     #[error(transparent)] Construction(#[from] delaunay::DelaunayTriangulationConstructionError),
    /// #     #[error(transparent)] Insertion(#[from] delaunay::prelude::insertion::InsertionError),
    /// #     #[error(transparent)] Tds(#[from] delaunay::prelude::tds::TdsError),
    /// #     #[error(transparent)] TdsConstruction(#[from] delaunay::prelude::tds::TdsConstructionError),
    /// #     #[error(transparent)] Invariant(#[from] delaunay::prelude::tds::InvariantError),
    /// #     #[error(transparent)] Facet(#[from] delaunay::prelude::tds::FacetError),
    /// #     #[error(transparent)] Simplex(#[from] delaunay::prelude::tds::SimplexValidationError),
    /// #     #[error(transparent)]
    /// #     Coordinate(#[from] delaunay::prelude::geometry::CoordinateConversionError),
    /// # }
    /// # fn main() -> Result<(), ExampleError> {
    /// // Create a triangulation with some vertices
    /// 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()?;
    ///
    /// // Get the first vertex's UUID
    /// let Some((_, vertex)) = dt.vertices().next() else {
    ///     return Ok(());
    /// };
    /// let original_uuid = vertex.uuid();
    ///
    /// // Convert UUID to key, then key back to UUID
    /// let Some(vertex_key) = dt.vertex_key_from_uuid(&original_uuid) else {
    ///     return Ok(());
    /// };
    /// let round_trip_uuid = dt.vertex_uuid_from_key(vertex_key);
    /// assert_eq!(Some(original_uuid), round_trip_uuid);
    /// # Ok(())
    /// # }
    /// ```
    #[inline]
    #[must_use]
    pub fn vertex_uuid_from_key(&self, vertex_key: VertexKey) -> Option<Uuid> {
        self.vertices.get(vertex_key).map(Vertex::uuid)
    }

    // =========================================================================
    // KEY-BASED ACCESS METHODS
    // =========================================================================
    // These methods work directly with keys to avoid UUID lookups in hot paths.
    // They complement the existing UUID-based methods for internal algorithm use.

    /// Gets a mutable reference to a simplex directly by its key.
    ///
    /// This method provides direct mutable access to simplices, similar to [`vertex_mut()`](Self::vertex_mut).
    /// While this allows modifying simplex data fields, callers should use safe topology setter APIs
    /// like [`set_neighbors_by_key()`](Self::set_neighbors_by_key) when modifying neighbor relationships.
    ///
    /// # Arguments
    ///
    /// * `simplex_key` - The key of the simplex to retrieve
    ///
    /// # Returns
    ///
    /// An `Option` containing a mutable reference to the simplex if it exists.
    ///
    #[inline]
    #[must_use]
    pub(crate) fn simplex_mut(&mut self, simplex_key: SimplexKey) -> Option<&mut Simplex<V, D>> {
        self.simplices.get_mut(simplex_key)
    }

    /// Gets a vertex directly by its key without UUID lookup.
    ///
    /// This is a key-based optimization of the UUID-based vertex access.
    /// Use this method in internal algorithms to avoid UUID→Key conversion overhead.
    ///
    /// # Arguments
    ///
    /// * `vertex_key` - The key of the vertex to retrieve
    ///
    /// # Returns
    ///
    /// An `Option` containing a reference to the vertex if it exists.
    ///
    /// # Examples
    ///
    /// ```
    /// use delaunay::prelude::*;
    ///
    /// # #[derive(Debug, thiserror::Error)]
    /// # enum ExampleError {
    /// #     #[error(transparent)] Construction(#[from] delaunay::DelaunayTriangulationConstructionError),
    /// #     #[error(transparent)] Insertion(#[from] delaunay::prelude::insertion::InsertionError),
    /// #     #[error(transparent)] Tds(#[from] delaunay::prelude::tds::TdsError),
    /// #     #[error(transparent)] TdsConstruction(#[from] delaunay::prelude::tds::TdsConstructionError),
    /// #     #[error(transparent)] Invariant(#[from] delaunay::prelude::tds::InvariantError),
    /// #     #[error(transparent)] Facet(#[from] delaunay::prelude::tds::FacetError),
    /// #     #[error(transparent)] Simplex(#[from] delaunay::prelude::tds::SimplexValidationError),
    /// #     #[error(transparent)]
    /// #     Coordinate(#[from] delaunay::prelude::geometry::CoordinateConversionError),
    /// # }
    /// # fn main() -> Result<(), ExampleError> {
    /// 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 Some((vertex_key, _)) = dt.vertices().next() else {
    ///     return Ok(());
    /// };
    /// assert!(dt.vertex(vertex_key).is_some());
    /// # Ok(())
    /// # }
    /// ```
    #[inline]
    #[must_use]
    pub fn vertex(&self, vertex_key: VertexKey) -> Option<&Vertex<U, D>> {
        self.vertices.get(vertex_key)
    }

    /// Gets a mutable reference to a vertex directly by its key.
    ///
    /// # Arguments
    ///
    /// * `vertex_key` - The key of the vertex to retrieve
    ///
    /// # Returns
    ///
    /// An `Option` containing a mutable reference to the vertex if it exists.
    ///
    #[inline]
    #[must_use]
    pub(crate) fn vertex_mut(&mut self, vertex_key: VertexKey) -> Option<&mut Vertex<U, D>> {
        self.vertices.get_mut(vertex_key)
    }

    /// Checks if a vertex key exists in the triangulation.
    ///
    /// # Arguments
    ///
    /// * `vertex_key` - The key to check
    ///
    /// # Returns
    ///
    /// `true` if the vertex exists, `false` otherwise.
    ///
    /// # Examples
    ///
    /// ```
    /// use delaunay::prelude::*;
    ///
    /// # #[derive(Debug, thiserror::Error)]
    /// # enum ExampleError {
    /// #     #[error(transparent)] Construction(#[from] delaunay::DelaunayTriangulationConstructionError),
    /// #     #[error(transparent)] Insertion(#[from] delaunay::prelude::insertion::InsertionError),
    /// #     #[error(transparent)] Tds(#[from] delaunay::prelude::tds::TdsError),
    /// #     #[error(transparent)] TdsConstruction(#[from] delaunay::prelude::tds::TdsConstructionError),
    /// #     #[error(transparent)] Invariant(#[from] delaunay::prelude::tds::InvariantError),
    /// #     #[error(transparent)] Facet(#[from] delaunay::prelude::tds::FacetError),
    /// #     #[error(transparent)] Simplex(#[from] delaunay::prelude::tds::SimplexValidationError),
    /// #     #[error(transparent)]
    /// #     Coordinate(#[from] delaunay::prelude::geometry::CoordinateConversionError),
    /// # }
    /// # fn main() -> Result<(), ExampleError> {
    /// 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 Some((vertex_key, _)) = dt.vertices().next() else {
    ///     return Ok(());
    /// };
    /// assert!(dt.contains_vertex_key(vertex_key));
    /// # Ok(())
    /// # }
    /// ```
    #[inline]
    #[must_use]
    pub fn contains_vertex_key(&self, vertex_key: VertexKey) -> bool {
        self.vertices.contains_key(vertex_key)
    }

    /// Registers an isolated vertex in the maintained vertex-to-simplices index.
    #[inline]
    pub(super) fn insert_empty_vertex_incidence(
        &mut self,
        vertex_key: VertexKey,
    ) -> Result<(), TdsError> {
        self.vertex_to_simplices.insert_vertex(vertex_key)
    }

    /// Removes a vertex from the maintained vertex-to-simplices index.
    #[inline]
    pub(super) fn remove_vertex_incidence(
        &mut self,
        vertex_key: VertexKey,
    ) -> Result<(), TdsError> {
        self.vertex_to_simplices.remove_isolated_vertex(vertex_key)
    }

    /// Registers a simplex under each of its vertices in the maintained incidence index.
    pub(super) fn add_simplex_to_vertex_incidence(
        &mut self,
        simplex_key: SimplexKey,
        vertices: &[VertexKey],
    ) -> Result<(), TdsError> {
        self.vertex_to_simplices
            .insert_simplex(simplex_key, vertices)
    }

    /// Rebuilds the maintained vertex-to-simplices incidence index from simplex storage.
    ///
    /// # Errors
    ///
    /// Returns [`TdsError::VertexNotFound`] if a simplex references a missing vertex key.
    pub(super) fn rebuild_vertex_to_simplices_index(&mut self) -> Result<(), TdsError> {
        let mut vertex_to_simplices =
            VertexIncidenceIndex::with_vertex_capacity(self.vertices.len());
        for vertex_key in self.vertices.keys() {
            vertex_to_simplices.insert_vertex(vertex_key)?;
        }

        for (simplex_key, simplex) in &self.simplices {
            vertex_to_simplices.insert_simplex(simplex_key, simplex.vertices())?;
        }

        self.vertex_to_simplices = vertex_to_simplices;
        Ok(())
    }

    /// Returns the maintained vertex-to-simplices incidence index.
    #[inline]
    pub(crate) const fn vertex_to_simplices_index(&self) -> &VertexIncidenceIndex {
        &self.vertex_to_simplices
    }

    /// Returns every simplex key whose simplex contains `vertex_key`.
    ///
    /// This is an exact lookup against the maintained vertex-to-simplices incidence
    /// index. It deliberately does not rely on `Vertex::incident_simplex` or neighbor
    /// pointers, so callers get complete results even while inspecting disconnected
    /// but otherwise structurally consistent TDS states.
    pub(crate) fn simplex_keys_containing_vertex(
        &self,
        vertex_key: VertexKey,
    ) -> impl Iterator<Item = SimplexKey> + '_ {
        self.vertex_to_simplices.simplex_keys(vertex_key)
    }

    /// Returns one simplex key incident to `vertex_key` from the maintained incidence index.
    ///
    /// This is the O(1) hint form of
    /// [`Self::simplex_keys_containing_vertex`]. It preserves the distinction
    /// between canonical incidence lookup and full simplex-storage scans.
    #[inline]
    pub(crate) fn first_simplex_containing_vertex(
        &self,
        vertex_key: VertexKey,
    ) -> Option<SimplexKey> {
        self.vertex_to_simplices.first_simplex(vertex_key)
    }
}

#[cfg(test)]
mod test_support {
    use super::Tds;
    use crate::core::collections::PeriodicOffsetBuffer;
    use crate::core::tds::{SimplexKey, VertexKey};

    impl<U, V, const D: usize> Tds<U, V, D> {
        /// Clears one vertex incidence buffer for tests that need corrupted storage.
        pub(in crate::core) fn clear_vertex_incidence_for_test(&mut self, vertex_key: VertexKey) {
            self.vertex_to_simplices.clear_vertex_for_test(vertex_key);
        }

        /// Adds a simplex to one vertex incidence buffer without changing simplex storage.
        pub(in crate::core) fn add_simplex_to_vertex_incidence_for_test(
            &mut self,
            vertex_key: VertexKey,
            simplex_key: SimplexKey,
        ) {
            self.vertex_to_simplices
                .insert_simplex(simplex_key, &[vertex_key])
                .expect("test helper should receive an existing vertex incidence entry");
        }

        /// Removes a simplex from storage while deliberately preserving incidence.
        ///
        /// Tests use this to model stale vertex-to-simplices entries that normal TDS
        /// mutation APIs must never create, then assert callers fail with typed
        /// structural errors instead of silently accepting the corruption.
        pub(in crate::core) fn remove_simplex_storage_only_for_test(
            &mut self,
            simplex_key: SimplexKey,
        ) {
            self.simplices.remove(simplex_key);
            self.uuid_to_simplex_key
                .retain(|_, mapped_key| *mapped_key != simplex_key);
        }

        /// Appends a vertex key to the first stored simplex without updating mappings.
        ///
        /// Tests use this to model malformed simplex vertex storage while keeping
        /// the corruption explicit and local to TDS test fixtures.
        pub(crate) fn push_first_simplex_vertex_key_storage_only_for_test(
            &mut self,
            vertex_key: VertexKey,
        ) {
            if let Some(simplex) = self.simplices.values_mut().next() {
                simplex.push_vertex_key(vertex_key);
            }
        }

        /// Removes a vertex from storage while deliberately preserving simplex references.
        ///
        /// Tests use this to model stale simplex-to-vertex references that normal
        /// TDS mutation APIs must never create, then assert read-only callers fail
        /// with typed errors instead of panicking or silently accepting corruption.
        pub(crate) fn remove_vertex_storage_only_for_test(&mut self, vertex_key: VertexKey) {
            if let Some(vertex) = self.vertices.remove(vertex_key) {
                let vertex_uuid = vertex.uuid();
                self.uuid_to_vertex_key
                    .retain(|uuid, mapped_key| *uuid != vertex_uuid && *mapped_key != vertex_key);
            }
        }

        /// Replaces periodic offsets on the first stored simplex without validation.
        ///
        /// Tests use this to model offset/storage mismatches that normal simplex
        /// constructors and setters must reject.
        pub(crate) fn set_first_simplex_periodic_offsets_storage_only_for_test(
            &mut self,
            offsets: Option<PeriodicOffsetBuffer<D>>,
        ) {
            if let Some(simplex) = self.simplices.values_mut().next() {
                simplex.periodic_vertex_offsets = offsets;
            }
        }
    }
}

impl<U, V, const D: usize> Tds<U, V, D> {
    /// Creates a new empty triangulation data structure.
    ///
    ///
    /// This function creates an empty triangulation with no vertices and no simplices.
    /// Use [`DelaunayTriangulation::empty()`](crate::DelaunayTriangulation::empty)
    /// for the high-level API, or this method for low-level Tds construction.
    ///
    /// # Returns
    ///
    /// An empty triangulation data structure with:
    /// - No vertices
    /// - No simplices
    /// - Construction state set to `Incomplete(0)`
    /// - Dimension of -1 (empty)
    ///
    /// # Examples
    ///
    /// ```
    /// use delaunay::prelude::tds::Tds;
    /// use delaunay::prelude::tds::TriangulationConstructionState;
    ///
    /// let tds: Tds<(), (), 3> = Tds::empty();
    /// assert_eq!(tds.number_of_vertices(), 0);
    /// assert_eq!(tds.number_of_simplices(), 0);
    /// assert_eq!(tds.dim(), -1);
    /// std::assert_matches!(
    ///     tds.construction_state(),
    ///     TriangulationConstructionState::Incomplete(0)
    /// );
    /// ```
    #[must_use]
    pub fn empty() -> Self {
        Self {
            vertices: StorageMap::with_key(),
            simplices: StorageMap::with_key(),
            uuid_to_vertex_key: UuidToVertexKeyMap::default(),
            uuid_to_simplex_key: UuidToSimplexKeyMap::default(),
            vertex_to_simplices: VertexIncidenceIndex::default(),
            construction_state: TriangulationConstructionState::Incomplete(0),
            generation: Arc::new(AtomicU64::new(0)),
            identity: Arc::new(Uuid::new_v4()),
        }
    }
}

// =============================================================================
// TRAIT IMPLEMENTATIONS
// =============================================================================

pub(super) type SimplexUuidSortKey<const D: usize> =
    SmallBuffer<(Uuid, [i8; D]), MAX_PRACTICAL_DIMENSION_SIZE>;

// =============================================================================
// TESTS
// =============================================================================
#[cfg(test)]
mod tests {
    use super::*;
    use crate::core::simplex::Simplex;
    use crate::core::tds::TdsRollbackTransaction;
    use crate::vertex;
    use std::assert_matches;
    use std::sync::Arc;

    fn insert_test_vertex<const D: usize>(tds: &mut Tds<(), (), D>, coordinate: f64) -> VertexKey {
        let vertex = vertex!([coordinate; D]).unwrap();
        tds.insert_vertex_with_mapping(vertex).unwrap()
    }

    #[test]
    fn test_empty_initializes_storage_identity_and_counts() {
        let tds: Tds<(), (), 3> = Tds::empty();

        assert_eq!(tds.number_of_vertices(), 0);
        assert_eq!(tds.number_of_simplices(), 0);
        assert_eq!(tds.dim(), -1);
        assert!(tds.vertices().next().is_none());
        assert!(tds.simplices().next().is_none());
        assert!(tds.vertex_to_simplices_index().is_empty());
        assert!(tds.vertex_key_from_uuid(&Uuid::new_v4()).is_none());
        assert!(tds.simplex_key_from_uuid(&Uuid::new_v4()).is_none());
        assert_matches!(
            tds.construction_state(),
            TriangulationConstructionState::Incomplete(0)
        );
    }

    #[test]
    fn test_incomplete_construction_state_tracks_vertex_count() {
        let mut tds: Tds<(), (), 2> = Tds::empty();

        let v0 = tds
            .insert_vertex_with_mapping(vertex!([0.0, 0.0]).unwrap())
            .unwrap();
        assert_matches!(
            tds.construction_state(),
            TriangulationConstructionState::Incomplete(1)
        );

        let _v1 = tds
            .insert_vertex_with_mapping(vertex!([1.0, 0.0]).unwrap())
            .unwrap();
        assert_matches!(
            tds.construction_state(),
            TriangulationConstructionState::Incomplete(2)
        );

        tds.remove_isolated_vertex(v0).unwrap();
        assert_matches!(
            tds.construction_state(),
            TriangulationConstructionState::Incomplete(1)
        );
    }

    #[test]
    fn test_vertex_to_simplices_index_tracks_simplex_insertion() {
        let mut tds: Tds<(), (), 2> = Tds::empty();
        let v0 = tds
            .insert_vertex_with_mapping(vertex!([0.0, 0.0]).unwrap())
            .unwrap();
        let v1 = tds
            .insert_vertex_with_mapping(vertex!([1.0, 0.0]).unwrap())
            .unwrap();
        let v2 = tds
            .insert_vertex_with_mapping(vertex!([0.0, 1.0]).unwrap())
            .unwrap();

        for vertex_key in [v0, v1, v2] {
            assert!(tds.vertex_to_simplices_index().contains_vertex(vertex_key));
            assert_eq!(
                tds.vertex_to_simplices_index()
                    .number_of_simplices(vertex_key),
                0
            );
        }

        let simplex_key = tds
            .insert_simplex_with_mapping(
                Simplex::try_new_with_data(vec![v0, v1, v2], None).unwrap(),
            )
            .unwrap();

        for vertex_key in [v0, v1, v2] {
            let simplices: SimplexKeySet = tds.simplex_keys_containing_vertex(vertex_key).collect();
            assert_eq!(simplices.len(), 1);
            assert!(simplices.contains(&simplex_key));
        }

        assert!(
            tds.simplex_keys_containing_vertex(VertexKey::default())
                .next()
                .is_none()
        );
    }

    #[test]
    fn test_vertex_to_simplices_index_returns_disconnected_vertex_star() {
        let mut tds: Tds<(), (), 2> = Tds::empty();
        let shared = tds
            .insert_vertex_with_mapping(vertex!([0.0, 0.0]).unwrap())
            .unwrap();
        let v1 = tds
            .insert_vertex_with_mapping(vertex!([1.0, 0.0]).unwrap())
            .unwrap();
        let v2 = tds
            .insert_vertex_with_mapping(vertex!([0.0, 1.0]).unwrap())
            .unwrap();
        let v3 = tds
            .insert_vertex_with_mapping(vertex!([-1.0, 0.0]).unwrap())
            .unwrap();
        let v4 = tds
            .insert_vertex_with_mapping(vertex!([0.0, -1.0]).unwrap())
            .unwrap();

        let first = tds
            .insert_simplex_with_mapping(
                Simplex::try_new_with_data(vec![shared, v1, v2], None).unwrap(),
            )
            .unwrap();
        let second = tds
            .insert_simplex_with_mapping(
                Simplex::try_new_with_data(vec![shared, v3, v4], None).unwrap(),
            )
            .unwrap();

        tds.vertex_mut(shared)
            .unwrap()
            .set_incident_simplex(Some(first));

        let simplices: SimplexKeySet = tds.simplex_keys_containing_vertex(shared).collect();
        assert_eq!(simplices.len(), 2);
        assert!(simplices.contains(&first));
        assert!(simplices.contains(&second));
    }

    #[test]
    fn test_facet_key_for_simplex_facet_maps_periodic_derivation_errors() {
        let mut tds: Tds<(), (), 2> = Tds::empty();
        let v_a = tds
            .insert_vertex_with_mapping(vertex!([0.0, 0.0]).unwrap())
            .unwrap();
        let v_b = tds
            .insert_vertex_with_mapping(vertex!([1.0, 0.0]).unwrap())
            .unwrap();
        let v_c = tds
            .insert_vertex_with_mapping(vertex!([0.0, 1.0]).unwrap())
            .unwrap();

        let simplex_key = tds
            .insert_simplex_with_mapping(
                Simplex::try_new_with_data(vec![v_a, v_b, v_c], None).unwrap(),
            )
            .unwrap();
        tds.simplex_mut(simplex_key)
            .unwrap()
            .set_periodic_vertex_offsets(vec![[-128_i8, 0_i8], [127_i8, 0_i8], [0_i8, 0_i8]])
            .unwrap();

        let err = tds.facet_key_for_simplex_facet(simplex_key, 2).unwrap_err();
        assert_matches!(
            err,
            TdsError::InconsistentDataStructure { message }
                if message.contains("Failed to derive periodic facet key")
                    && message.contains("facet 2")
        );
    }

    #[test]
    fn test_generation_counter_bumps_on_topology_modification() {
        let mut tds: Tds<(), (), 2> = Tds::empty();
        assert_eq!(tds.generation(), 0);

        let _v = tds
            .insert_vertex_with_mapping(vertex!([0.0, 0.0]).unwrap())
            .unwrap();
        assert!(tds.generation() > 0);

        let gen_before = tds.generation();
        tds.mark_topology_modified();
        assert!(tds.generation() > gen_before);
    }

    // =========================================================================
    // GET SIMPLEX VERTICES: ERROR PATH
    // =========================================================================

    #[test]
    fn test_simplex_vertices_errors_on_missing_vertex_key() {
        let mut tds: Tds<(), (), 2> = Tds::empty();
        let v0 = tds
            .insert_vertex_with_mapping(vertex!([0.0, 0.0]).unwrap())
            .unwrap();
        let v1 = tds
            .insert_vertex_with_mapping(vertex!([1.0, 0.0]).unwrap())
            .unwrap();
        let v2 = tds
            .insert_vertex_with_mapping(vertex!([0.0, 1.0]).unwrap())
            .unwrap();

        let ck = tds
            .insert_simplex_with_mapping(
                Simplex::try_new_with_data(vec![v0, v1, v2], None).unwrap(),
            )
            .unwrap();

        // Corrupt: remove a vertex that the simplex references.
        tds.vertices.remove(v2);
        tds.uuid_to_vertex_key.retain(|_, &mut vk| vk != v2);

        let err = tds.simplex_vertices(ck).unwrap_err();
        assert_matches!(err, TdsError::VertexNotFound { .. });
    }

    // =========================================================================
    // VALIDATE SIMPLEX COORDINATE UNIQUENESS
    // =========================================================================

    // =========================================================================
    // GENERATION COUNTER
    // =========================================================================

    #[test]
    fn test_mark_topology_modified_bumps_generation() {
        let tds: Tds<(), (), 2> = Tds::empty();
        let gen_before = tds.generation();
        tds.mark_topology_modified();
        assert_eq!(tds.generation(), gen_before + 1);
    }

    macro_rules! test_clone_identity_dimensions {
        ($($dim:expr),+ $(,)?) => {
            pastey::paste! {
                $(
                    #[test]
                    fn [<test_clone_uses_fresh_runtime_identity_ $dim d>]() {
                        let tds: Tds<(), (), $dim> = Tds::empty();
                        let cloned = tds.clone();

                        assert!(
                            !Arc::ptr_eq(tds.identity(), cloned.identity()),
                            "ordinary TDS clones must have distinct runtime identities"
                        );
                        assert_eq!(tds.generation(), cloned.generation());
                    }

                    #[test]
                    fn [<test_clone_for_rollback_preserves_identity_with_independent_generation_ $dim d>]() {
                        let mut tds: Tds<(), (), $dim> = Tds::empty();
                        let _v = tds
                            .insert_vertex_with_mapping(vertex!([0.0_f64; $dim]).unwrap())
                            .unwrap();
                        let snapshot = tds.clone_for_rollback();
                        let snapshot_generation = snapshot.generation();

                        assert!(
                            Arc::ptr_eq(tds.identity(), snapshot.identity()),
                            "rollback snapshots should preserve runtime identity"
                        );

                        tds.mark_topology_modified();

                        assert_eq!(
                            snapshot.generation(),
                            snapshot_generation,
                            "rollback snapshots need an independent generation counter"
                        );
                    }

                    #[test]
                    fn [<test_clone_from_for_rollback_replaces_storage_and_preserves_identity_ $dim d>]() {
                        let mut source: Tds<(), (), $dim> = Tds::empty();
                        let source_vertex = source
                            .insert_vertex_with_mapping(vertex!([0.0_f64; $dim]).unwrap())
                            .unwrap();
                        let source_generation = source.generation();

                        let mut target: Tds<(), (), $dim> = Tds::empty();
                        let _stale_vertex = target
                            .insert_vertex_with_mapping(vertex!([1.0_f64; $dim]).unwrap())
                            .unwrap();
                        let _extra_stale_vertex = target
                            .insert_vertex_with_mapping(vertex!([2.0_f64; $dim]).unwrap())
                            .unwrap();
                        assert!(
                            !Arc::ptr_eq(source.identity(), target.identity()),
                            "source and scratch storage should start with distinct identities"
                        );

                        target.clone_from_for_rollback(&source);

                        assert!(
                            Arc::ptr_eq(source.identity(), target.identity()),
                            "rollback scratch storage should adopt the source runtime identity"
                        );
                        assert_eq!(target.generation(), source_generation);
                        assert_eq!(target.number_of_vertices(), source.number_of_vertices());
                        assert_eq!(target.number_of_simplices(), source.number_of_simplices());
                        assert!(target.vertex(source_vertex).is_some());

                        source.mark_topology_modified();

                        assert_eq!(
                            target.generation(),
                            source_generation,
                            "clone_from_for_rollback must keep an independent generation counter"
                        );
                    }

                    #[test]
                    fn [<test_rollback_transaction_drop_restores_snapshot_ $dim d>]() {
                        let mut tds: Tds<(), (), $dim> = Tds::empty();
                        let source_vertex = insert_test_vertex(&mut tds, 0.0);
                        let source_generation = tds.generation();
                        let source_identity = Arc::clone(tds.identity());

                        {
                            let mut transaction = TdsRollbackTransaction::begin(&mut tds);
                            let _transient_vertex = insert_test_vertex(transaction.tds_mut(), 1.0);
                        }

                        assert!(Arc::ptr_eq(&source_identity, tds.identity()));
                        assert_eq!(tds.generation(), source_generation);
                        assert_eq!(tds.number_of_vertices(), 1);
                        assert!(tds.vertex(source_vertex).is_some());
                    }

                    #[test]
                    fn [<test_rollback_transaction_explicit_rollback_restores_snapshot_ $dim d>]() {
                        let mut tds: Tds<(), (), $dim> = Tds::empty();
                        let source_vertex = insert_test_vertex(&mut tds, 0.0);
                        let source_generation = tds.generation();

                        {
                            let mut transaction = TdsRollbackTransaction::begin(&mut tds);
                            let _transient_vertex = insert_test_vertex(transaction.tds_mut(), 1.0);
                            transaction.rollback();
                        }

                        assert_eq!(tds.generation(), source_generation);
                        assert_eq!(tds.number_of_vertices(), 1);
                        assert!(tds.vertex(source_vertex).is_some());
                    }

                    #[test]
                    fn [<test_rollback_transaction_restore_keeps_transaction_open_ $dim d>]() {
                        let mut tds: Tds<(), (), $dim> = Tds::empty();
                        let source_vertex = insert_test_vertex(&mut tds, 0.0);

                        let committed_vertex = {
                            let mut transaction = TdsRollbackTransaction::begin(&mut tds);
                            let _transient_vertex = insert_test_vertex(transaction.tds_mut(), 1.0);
                            transaction.restore();
                            let committed_vertex = insert_test_vertex(transaction.tds_mut(), 2.0);
                            transaction.commit();
                            committed_vertex
                        };

                        assert_eq!(tds.number_of_vertices(), 2);
                        assert!(tds.vertex(source_vertex).is_some());
                        assert!(tds.vertex(committed_vertex).is_some());
                    }

                    #[test]
                    fn [<test_rollback_transaction_commit_preserves_mutation_ $dim d>]() {
                        let mut tds: Tds<(), (), $dim> = Tds::empty();
                        let source_vertex = insert_test_vertex(&mut tds, 0.0);

                        let committed_vertex = {
                            let mut transaction = TdsRollbackTransaction::begin(&mut tds);
                            let committed_vertex = insert_test_vertex(transaction.tds_mut(), 1.0);
                            transaction.commit();
                            committed_vertex
                        };

                        assert_eq!(tds.number_of_vertices(), 2);
                        assert!(tds.vertex(source_vertex).is_some());
                        assert!(tds.vertex(committed_vertex).is_some());
                    }
                )+
            }
        };
    }

    test_clone_identity_dimensions!(2, 3, 4, 5);
}