delaunay 0.7.8

D-dimensional Delaunay triangulations and convex hulls in Rust, with exact predicates, multi-level validation, and bistellar flips
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
//! Large-scale triangulation debug harness.
//!
//! This module is intended as a **manual debugging tool** for issues that only show up
//! at large vertex counts (slow cases, rare geometric degeneracies, topology/Delaunay
//! validation failures, etc.).
//!
//! The `debug_large_scale_*` harness tests use `#[cfg(feature = "slow-tests")]`
//! because their documented scales exceed the default-suite budget. Run them
//! through `just test-slow`.
//!
//! ## Usage
//!
//! Run one dimension with full output:
//! ```bash
//! cargo test --release --features slow-tests --test large_scale_debug debug_large_scale_2d -- --nocapture
//! ```
//!
//! The slow-tests and `just debug-large-scale-{2,3,4,5}d` helpers all accept
//! the same `[n] [repair_every]` shape. The slow-test defaults are:
//!
//! - 2D: 40,000 vertices
//! - 3D: 7,500 vertices
//! - 4D: 900 vertices
//! - 5D: 150 vertices
//!
//! The `just` helpers may use slightly smaller local defaults so routine
//! acceptance/profiling runs stay near one minute on maintainer Apple M4 Max
//! hardware. Pass `n` explicitly when a run must match a documented scale.

#![cfg_attr(not(feature = "slow-tests"), allow(dead_code))]
//!
//! Each should insert all vertices with zero skips, run final repair, and pass
//! `validation_report` for Levels 1–4. Use local harness output for exact
//! timing.
//!
//! Override defaults via environment variables:
//! ```bash
//! # Base RNG seed (decimal or 0x-hex)
//! DELAUNAY_LARGE_DEBUG_SEED=0xDEADBEEF \
//! # Optional explicit case seed (overrides derived seed_for_case)
//! DELAUNAY_LARGE_DEBUG_CASE_SEED=0x12345678 \
//! # Per-dimension case seed override; {D} is 2, 3, 4, or 5 and overrides the generic case seed
//! DELAUNAY_LARGE_DEBUG_CASE_SEED_3D=0x12345678 \
//! # Override point count for the selected test
//! DELAUNAY_LARGE_DEBUG_N=10000 \
//! # Per-dimension point-count override; e.g. _3D overrides DELAUNAY_LARGE_DEBUG_N for 3D
//! DELAUNAY_LARGE_DEBUG_N_3D=7500 \
//! # Point distribution: "ball" (default) or "box"
//! DELAUNAY_LARGE_DEBUG_DISTRIBUTION=ball \
//! # Ball radius (default: 100) [used when distribution=ball]
//! DELAUNAY_LARGE_DEBUG_BALL_RADIUS=100 \
//! # Box half-width (default: 100) [used when distribution=box]
//! DELAUNAY_LARGE_DEBUG_BOX_HALF_WIDTH=100 \
//! # Construction mode:
//! # - "new" (default): build via DelaunayTriangulation::new() which applies Hilbert ordering
//! # - "incremental": manual insert loop (debug/profiling)
//! DELAUNAY_LARGE_DEBUG_CONSTRUCTION_MODE=new \
//! # Initial simplex strategy for batch construction: "max-volume" (default), "balanced", or "first"
//! DELAUNAY_LARGE_DEBUG_INITIAL_SIMPLEX=max-volume \
//! # Debug mode:
//! # - "cadenced" (default): PLManifold, ridge-link validation during insertion,
//! #   vertex-link validation at completion
//! # - "strict": PLManifoldStrict, vertex-link validation after every insertion
//! DELAUNAY_LARGE_DEBUG_DEBUG_MODE=cadenced \
//! # Deterministically shuffle insertion order (incremental mode only)
//! DELAUNAY_LARGE_DEBUG_SHUFFLE_SEED=123 \
//! # Print progress every N insertions (incremental mode, or batch fallback)
//! DELAUNAY_LARGE_DEBUG_PROGRESS_EVERY=1000 \
//! # (Optional) validate topology every N insertions once simplices exist (incremental mode only; can be expensive)
//! DELAUNAY_LARGE_DEBUG_VALIDATE_EVERY=2000 \
//! # Maximum skipped-vertex percentage before the run fails (default: 5.0)
//! DELAUNAY_LARGE_DEBUG_MAX_SKIP_PCT=5.0 \
//! # Allow any number of skipped vertices (bypasses DELAUNAY_LARGE_DEBUG_MAX_SKIP_PCT)
//! DELAUNAY_LARGE_DEBUG_ALLOW_SKIPS=1 \
//! # Skip the final flip-based repair pass (faster, but may leave Delaunay violations)
//! DELAUNAY_LARGE_DEBUG_SKIP_FINAL_REPAIR=1 \
//! # Run bounded flip repair every N successful insertions (0 disables; default: 1)
//! DELAUNAY_LARGE_DEBUG_REPAIR_EVERY=1 \
//! # Optional: trace cadenced local-repair seed counts, flips, queues, and elapsed time
//! DELAUNAY_BATCH_REPAIR_TRACE=1 \
//! # Hard wall-clock cap in seconds before the harness aborts (0 = no cap; default: 600)
//! DELAUNAY_LARGE_DEBUG_MAX_RUNTIME_SECS=600 \
//! # Optional: emit periodic batch-construction summaries for new()/Hilbert runs.
//! # This is the canonical batch progress knob and takes precedence over
//! # DELAUNAY_LARGE_DEBUG_PROGRESS_EVERY.
//! DELAUNAY_BULK_PROGRESS_EVERY=100 \
//! # Optional: dump the first cavity reduction chain once per run
//! DELAUNAY_DEBUG_CAVITY_REDUCTION_ONCE=1 \
//! # Optional: trace retryable conflict-region skips with attempt/rollback details
//! DELAUNAY_DEBUG_RETRYABLE_SKIP=1 \
//! # Optional: dump the first detected ridge-fan cavity snapshot once per run
//! DELAUNAY_DEBUG_RIDGE_FAN_ONCE=1 \
//! # Optional: dump the first unresolved repair postcondition facet once per run
//! DELAUNAY_REPAIR_DEBUG_POSTCONDITION_FACET=1 \
//! # Optional: only emit ridge repair debug when multiplicity is at least N
//! DELAUNAY_REPAIR_DEBUG_RIDGE_MIN_MULTIPLICITY=4 \
//! cargo test --release --features slow-tests --test large_scale_debug debug_large_scale_4d -- --nocapture
//! ```

#![forbid(unsafe_code)]

use delaunay::geometry::kernel::{ExactPredicates, Kernel, RobustKernel};
use delaunay::geometry::util::{
    generate_random_points_in_ball_seeded, generate_random_points_seeded, safe_usize_to_scalar,
};
use delaunay::prelude::construction::{
    ConstructionOptions, ConstructionStatistics, DelaunayRepairPolicy, DelaunayTriangulation,
    DelaunayTriangulationConstructionErrorWithStatistics, InitialSimplexStrategy,
    TopologyGuarantee, Vertex, vertex,
};
use delaunay::prelude::diagnostics::ConstructionTelemetry;
#[cfg(feature = "diagnostics")]
use delaunay::prelude::insertion::InsertionResult;
use delaunay::prelude::insertion::{InsertionOutcome, InsertionStatistics};
use delaunay::prelude::repair::{DelaunayCheckPolicy, DelaunayRepairHeuristicConfig};
use delaunay::prelude::tds::{InvariantKind, TriangulationValidationReport};
use delaunay::prelude::validation::ValidationCadence;
use rand::{SeedableRng, rngs::StdRng, seq::SliceRandom};
use std::env;
use std::fmt;
use std::io::{self, Write};
use std::num::NonZeroUsize;
use std::process;
use std::sync::{
    Once,
    mpsc::{self, RecvTimeoutError, SyncSender},
};
use std::thread;
use std::time::{Duration, Instant};

/// Writes the timeout diagnostic synchronously so it survives the watchdog abort.
fn write_timeout_abort_message<W: Write>(mut writer: W, max_secs: u64) -> io::Result<()> {
    writeln!(
        writer,
        "=== TIMEOUT: wall time exceeded {max_secs} seconds — aborting ==="
    )?;
    writer.flush()
}

/// Installs a per-test wall-clock cap.
///
/// Spawns a watchdog thread that calls [`process::abort`] if `max_secs` elapses.
/// Returns a [`SyncSender`] whose **drop** cancels the watchdog: when
/// the sender is dropped (i.e. the test completes normally), the channel disconnects and
/// the watchdog thread exits without aborting.  This prevents a stale watchdog installed
/// for one test from firing during a subsequent test.
fn install_runtime_cap(max_secs: u64) -> SyncSender<()> {
    let (tx, rx) = mpsc::sync_channel::<()>(0);
    thread::spawn(move || {
        match rx.recv_timeout(Duration::from_secs(max_secs)) {
            // Sender dropped (test finished) or explicit send — exit cleanly.
            Ok(()) | Err(RecvTimeoutError::Disconnected) => {}
            // Deadline exceeded — hard abort.
            Err(RecvTimeoutError::Timeout) => {
                if let Err(err) = write_timeout_abort_message(io::stderr().lock(), max_secs) {
                    tracing::warn!(?err, "failed to flush timeout message before abort");
                }
                process::abort();
            }
        }
    });
    tx
}

#[derive(Debug, Clone)]
struct SkipSample<const D: usize> {
    index: usize,
    uuid: uuid::Uuid,
    coords: Option<[f64; D]>,
    attempts: usize,
    error: String,
}

#[derive(Debug, Clone)]
#[cfg(feature = "diagnostics")]
struct SlowInsertionSample {
    index: usize,
    uuid: uuid::Uuid,
    attempts: usize,
    result: InsertionResult,
    elapsed_nanos: u64,
    simplices_after: usize,
    locate_calls: usize,
    locate_walk_steps_total: usize,
    conflict_region_calls: usize,
    conflict_region_simplices_total: usize,
    cavity_insertion_calls: usize,
    global_conflict_scans: usize,
    hull_extension_calls: usize,
    topology_validation_calls: usize,
}

#[derive(Debug, Default, Clone)]
struct InsertionSummary<const D: usize> {
    inserted: usize,
    skipped_duplicate: usize,
    skipped_degeneracy: usize,

    total_attempts: usize,
    max_attempts: usize,
    attempts_histogram: Vec<usize>,

    used_perturbation: usize,

    simplices_removed_total: usize,
    simplices_removed_max: usize,

    telemetry: ConstructionTelemetry,

    #[cfg(feature = "diagnostics")]
    slow_insertions: Vec<SlowInsertionSample>,
    skip_samples: Vec<SkipSample<D>>,
}

impl<const D: usize> InsertionSummary<D> {
    fn record(&mut self, stats: InsertionStatistics) {
        self.total_attempts = self.total_attempts.saturating_add(stats.attempts);
        self.max_attempts = self.max_attempts.max(stats.attempts);

        if self.attempts_histogram.len() <= stats.attempts {
            self.attempts_histogram.resize(stats.attempts + 1, 0);
        }
        self.attempts_histogram[stats.attempts] =
            self.attempts_histogram[stats.attempts].saturating_add(1);

        if stats.used_perturbation() {
            self.used_perturbation = self.used_perturbation.saturating_add(1);
        }

        self.simplices_removed_total = self
            .simplices_removed_total
            .saturating_add(stats.simplices_removed_during_repair);
        self.simplices_removed_max = self
            .simplices_removed_max
            .max(stats.simplices_removed_during_repair);
    }

    fn record_inserted(&mut self, stats: InsertionStatistics) {
        self.inserted = self.inserted.saturating_add(1);
        self.record(stats);
    }

    fn record_skipped(&mut self, sample: SkipSample<D>, stats: InsertionStatistics) {
        if stats.skipped_duplicate() {
            self.skipped_duplicate = self.skipped_duplicate.saturating_add(1);
        } else {
            self.skipped_degeneracy = self.skipped_degeneracy.saturating_add(1);
        }

        // Keep the first few skip samples so we have concrete reproduction anchors.
        if self.skip_samples.len() < 8 {
            self.skip_samples.push(sample);
        }

        self.record(stats);
    }

    const fn total_skipped(&self) -> usize {
        self.skipped_duplicate + self.skipped_degeneracy
    }
}

impl<const D: usize> From<ConstructionStatistics> for InsertionSummary<D> {
    fn from(stats: ConstructionStatistics) -> Self {
        #[cfg(feature = "diagnostics")]
        let slow_insertions = stats
            .slow_insertions
            .into_iter()
            .map(|sample| SlowInsertionSample {
                index: sample.index,
                uuid: sample.uuid,
                attempts: sample.attempts,
                result: sample.result,
                elapsed_nanos: sample.elapsed_nanos,
                simplices_after: sample.simplices_after,
                locate_calls: sample.locate_calls,
                locate_walk_steps_total: sample.locate_walk_steps_total,
                conflict_region_calls: sample.conflict_region_calls,
                conflict_region_simplices_total: sample.conflict_region_simplices_total,
                cavity_insertion_calls: sample.cavity_insertion_calls,
                global_conflict_scans: sample.global_conflict_scans,
                hull_extension_calls: sample.hull_extension_calls,
                topology_validation_calls: sample.topology_validation_calls,
            })
            .collect();
        let skip_samples: Vec<SkipSample<D>> = stats
            .skip_samples
            .into_iter()
            .map(|s| {
                let coords = if s.coords_available {
                    s.coords.as_slice().try_into().map_or_else(
                        |_| {
                            tracing::warn!(
                                index = s.index,
                                uuid = %s.uuid,
                                coords_len = s.coords.len(),
                                expected_dim = D,
                                "preserving skip sample without coordinates due to coordinate dimension mismatch"
                            );
                            None
                        },
                        Some,
                    )
                } else {
                    None
                };
                SkipSample {
                    index: s.index,
                    uuid: s.uuid,
                    coords,
                    attempts: s.attempts,
                    error: s.error,
                }
            })
            .collect();

        Self {
            inserted: stats.inserted,
            skipped_duplicate: stats.skipped_duplicate,
            skipped_degeneracy: stats.skipped_degeneracy,
            total_attempts: stats.total_attempts,
            max_attempts: stats.max_attempts,
            attempts_histogram: stats.attempts_histogram,
            used_perturbation: stats.used_perturbation,
            simplices_removed_total: stats.simplices_removed_total,
            simplices_removed_max: stats.simplices_removed_max,
            telemetry: stats.telemetry,
            #[cfg(feature = "diagnostics")]
            slow_insertions,
            skip_samples,
        }
    }
}

fn parse_u64(s: &str) -> Option<u64> {
    let s = s.trim();
    s.strip_prefix("0x")
        .or_else(|| s.strip_prefix("0X"))
        .map_or_else(|| s.parse().ok(), |hex| u64::from_str_radix(hex, 16).ok())
}

fn env_u64(name: &str) -> Option<u64> {
    env::var(name).ok().and_then(|v| parse_u64(&v))
}

fn env_usize(name: &str) -> Option<usize> {
    env::var(name).ok().and_then(|v| {
        let trimmed = v.trim();
        trimmed.parse().ok().or_else(|| {
            trimmed
                .split_once('=')
                .and_then(|(_, rhs)| rhs.trim().parse().ok())
        })
    })
}

fn bulk_progress_every_from_env() -> Option<usize> {
    env_usize("DELAUNAY_BULK_PROGRESS_EVERY")
        .or_else(|| env_usize("DELAUNAY_LARGE_DEBUG_PROGRESS_EVERY"))
        .filter(|every| *every > 0)
}

fn env_flag(name: &str) -> bool {
    env::var(name).ok().is_some_and(|v| {
        let v = v.trim();
        !v.is_empty() && v != "0" && v != "false"
    })
}

fn init_tracing() {
    static INIT: Once = Once::new();
    INIT.call_once(|| {
        // Debug-level tracing is needed to surface the release-visible diagnostic hooks
        // (retryable-skip, cavity-reduction, ridge/postcondition repair debug,
        // bulk-progress, bulk-retry) emitted through `tracing::debug!` inside the library.
        let debug_env_vars = [
            "DELAUNAY_INSERT_TRACE",
            "DELAUNAY_DEBUG_RETRYABLE_SKIP",
            "DELAUNAY_DEBUG_CAVITY_REDUCTION_ONCE",
            "DELAUNAY_DEBUG_RIDGE_FAN_ONCE",
            "DELAUNAY_REPAIR_DEBUG_POSTCONDITION_FACET",
            "DELAUNAY_REPAIR_DEBUG_RIDGE_MIN_MULTIPLICITY",
            "DELAUNAY_BULK_PROGRESS_EVERY",
            "DELAUNAY_LARGE_DEBUG_PROGRESS_EVERY",
            "DELAUNAY_BATCH_REPAIR_TRACE",
            "DELAUNAY_DEBUG_SHUFFLE",
        ];
        let default_filter = if debug_env_vars
            .iter()
            .any(|name| env::var_os(name).is_some())
        {
            "debug"
        } else {
            "warn"
        };
        let filter = tracing_subscriber::EnvFilter::try_from_default_env()
            .unwrap_or_else(|_| tracing_subscriber::EnvFilter::new(default_filter));
        let _ = tracing_subscriber::fmt()
            .with_env_filter(filter)
            .with_test_writer()
            .try_init();
    });
}

#[derive(Debug, Clone, Copy, PartialEq, Eq)]
enum PointDistribution {
    Ball,
    Box,
}

#[derive(Debug, Clone, Copy, PartialEq, Eq)]
enum ConstructionMode {
    /// Build via `DelaunayTriangulation::new()` (batch construction + Hilbert ordering).
    New,
    /// Insert vertices one by one (manual incremental construction).
    Incremental,
}

impl ConstructionMode {
    const fn name(self) -> &'static str {
        match self {
            Self::New => "new",
            Self::Incremental => "incremental",
        }
    }
}

fn initial_simplex_strategy_name(strategy: InitialSimplexStrategy) -> &'static str {
    match strategy {
        InitialSimplexStrategy::First => "first",
        InitialSimplexStrategy::Balanced => "balanced",
        InitialSimplexStrategy::MaxVolume => "max-volume",
        _ => {
            tracing::debug!(?strategy, "unknown initial simplex strategy");
            "unknown"
        }
    }
}

fn initial_simplex_strategy_from_name(raw: &str) -> Option<InitialSimplexStrategy> {
    let raw = raw.trim();
    if raw.is_empty() {
        return Some(InitialSimplexStrategy::MaxVolume);
    }

    if raw.eq_ignore_ascii_case("first") {
        return Some(InitialSimplexStrategy::First);
    }

    if raw.eq_ignore_ascii_case("balanced") {
        return Some(InitialSimplexStrategy::Balanced);
    }

    if raw.eq_ignore_ascii_case("max-volume")
        || raw.eq_ignore_ascii_case("max_volume")
        || raw.eq_ignore_ascii_case("maxvolume")
    {
        return Some(InitialSimplexStrategy::MaxVolume);
    }

    None
}

fn initial_simplex_strategy_from_env() -> InitialSimplexStrategy {
    let Ok(raw) = env::var("DELAUNAY_LARGE_DEBUG_INITIAL_SIMPLEX") else {
        return InitialSimplexStrategy::MaxVolume;
    };

    initial_simplex_strategy_from_name(&raw).unwrap_or_else(|| {
        panic!(
            "invalid DELAUNAY_LARGE_DEBUG_INITIAL_SIMPLEX={raw:?} (expected 'max-volume', 'balanced', or 'first')"
        )
    })
}

#[derive(Debug, Clone, Copy, PartialEq, Eq)]
enum DebugMode {
    /// Faster default: repair/check in cadence, with suspicion-driven automatic validation.
    Cadenced,
    /// Maximal diagnostics: strict guarantee + per-insertion automatic validation.
    Strict,
}

impl DebugMode {
    const fn name(self) -> &'static str {
        match self {
            Self::Cadenced => "cadenced",
            Self::Strict => "strict",
        }
    }
}

/// Selects the topology guarantee that matches the requested debug intensity.
const fn topology_for_debug_mode(debug_mode: DebugMode) -> TopologyGuarantee {
    match debug_mode {
        DebugMode::Cadenced => TopologyGuarantee::PLManifold,
        DebugMode::Strict => TopologyGuarantee::PLManifoldStrict,
    }
}

/// Converts the repair cadence knob into the policy shared by batch and incremental modes.
const fn repair_policy_from_repair_every(repair_every: usize) -> DelaunayRepairPolicy {
    match NonZeroUsize::new(repair_every) {
        None => DelaunayRepairPolicy::Never,
        Some(n) if n.get() == 1 => DelaunayRepairPolicy::EveryInsertion,
        Some(n) => DelaunayRepairPolicy::EveryN(n),
    }
}

impl PointDistribution {
    const fn name(self) -> &'static str {
        match self {
            Self::Ball => "ball",
            Self::Box => "box",
        }
    }
}

/// Reads the skipped-vertex percentage budget for large-scale debug runs.
fn max_skip_pct_from_env() -> f64 {
    let max_skip_pct = env_f64("DELAUNAY_LARGE_DEBUG_MAX_SKIP_PCT").unwrap_or(5.0);
    assert!(
        max_skip_pct.is_finite() && max_skip_pct >= 0.0,
        "invalid DELAUNAY_LARGE_DEBUG_MAX_SKIP_PCT={max_skip_pct:?} (expected finite non-negative percentage)"
    );
    max_skip_pct
}

/// Computes the skipped-vertex percentage for budget checks and reporting.
fn skip_percentage(skipped: usize, total: usize) -> f64 {
    if total == 0 {
        return 0.0;
    }

    let skipped = safe_usize_to_scalar::<f64>(skipped)
        .expect("skipped-vertex count should fit in f64 for debug reporting");
    let total = safe_usize_to_scalar::<f64>(total)
        .expect("point count should fit in f64 for debug reporting");
    (skipped / total) * 100.0
}

fn env_f64(name: &str) -> Option<f64> {
    let Ok(raw) = env::var(name) else {
        return None;
    };

    let raw = raw.trim();
    if raw.is_empty() {
        return None;
    }

    Some(
        raw.parse()
            .unwrap_or_else(|e| panic!("invalid {name}={raw:?}: {e}")),
    )
}

fn point_distribution_from_env() -> PointDistribution {
    let Ok(raw) = env::var("DELAUNAY_LARGE_DEBUG_DISTRIBUTION") else {
        return PointDistribution::Ball;
    };

    let raw = raw.trim();
    if raw.is_empty() || raw.eq_ignore_ascii_case("ball") {
        return PointDistribution::Ball;
    }

    if raw.eq_ignore_ascii_case("box") {
        return PointDistribution::Box;
    }

    panic!("invalid DELAUNAY_LARGE_DEBUG_DISTRIBUTION={raw:?} (expected 'ball' or 'box')");
}

fn construction_mode_from_env() -> ConstructionMode {
    let Ok(raw) = env::var("DELAUNAY_LARGE_DEBUG_CONSTRUCTION_MODE") else {
        return ConstructionMode::New;
    };

    let raw = raw.trim();
    if raw.is_empty() || raw.eq_ignore_ascii_case("new") {
        return ConstructionMode::New;
    }

    if raw.eq_ignore_ascii_case("incremental") {
        return ConstructionMode::Incremental;
    }

    panic!(
        "invalid DELAUNAY_LARGE_DEBUG_CONSTRUCTION_MODE={raw:?} (expected 'new' or 'incremental')"
    );
}

fn debug_mode_from_env() -> DebugMode {
    let Ok(raw) = env::var("DELAUNAY_LARGE_DEBUG_DEBUG_MODE") else {
        return DebugMode::Cadenced;
    };

    let raw = raw.trim();
    if raw.is_empty() || raw.eq_ignore_ascii_case("cadenced") {
        return DebugMode::Cadenced;
    }

    if raw.eq_ignore_ascii_case("strict") {
        return DebugMode::Strict;
    }

    panic!("invalid DELAUNAY_LARGE_DEBUG_DEBUG_MODE={raw:?} (expected 'cadenced' or 'strict')");
}

fn seed_for_case<const D: usize>(base_seed: u64, n_points: usize) -> u64 {
    const SEED_SALT: u64 = 0x9E37_79B9_7F4A_7C15;
    base_seed
        .wrapping_add((n_points as u64).wrapping_mul(SEED_SALT))
        .wrapping_add((D as u64).wrapping_mul(SEED_SALT.rotate_left(17)))
}
/// Classifies debug harness outcomes into distinct categories for structured reporting.
///
/// The harness still prints full diagnostic output during the run; this enum captures
/// the final outcome so callers can emit a single summary line and fail tests explicitly.
#[derive(Debug, Clone)]
enum DebugOutcome {
    Success,
    ConstructionFailure {
        error: String,
    },
    SkippedVertices {
        skipped: usize,
        total: usize,
        skip_pct: f64,
        max_skip_pct: f64,
    },
    RepairNonConvergence {
        error: String,
    },
    ValidationFailure {
        kind: InvariantKind,
        details: String,
    },
}

impl fmt::Display for DebugOutcome {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        match self {
            Self::Success => write!(f, "Success"),
            Self::ConstructionFailure { error } => {
                write!(f, "ConstructionFailure | {error}")
            }
            Self::SkippedVertices {
                skipped,
                total,
                skip_pct,
                max_skip_pct,
            } => {
                write!(
                    f,
                    "SkippedVertices | {skipped}/{total} skipped ({skip_pct:.2}%, max {max_skip_pct:.2}%)"
                )
            }
            Self::RepairNonConvergence { error } => {
                write!(f, "RepairNonConvergence | {error}")
            }
            Self::ValidationFailure { kind, details } => {
                write!(f, "ValidationFailure({kind:?}) | {details}")
            }
        }
    }
}

fn print_abort_summary<const D: usize>(
    outcome: &DebugOutcome,
    seed: u64,
    n_points: usize,
    phase: &str,
) {
    println!();
    println!("OUTCOME: {outcome}");
    println!("Phase:   {phase}");
    println!();
    println!("Replay command:");
    println!(
        "  DELAUNAY_LARGE_DEBUG_N_{D}D={n_points} DELAUNAY_LARGE_DEBUG_CASE_SEED_{D}D=0x{seed:X} DELAUNAY_LARGE_DEBUG_ALLOW_SKIPS=1 cargo test --release --features slow-tests --test large_scale_debug debug_large_scale_{D}d -- --nocapture"
    );
}

fn classify_validation_report(report: &TriangulationValidationReport) -> DebugOutcome {
    let first = report.violations.first();
    let (kind, details) = first.map_or_else(
        || {
            (
                InvariantKind::Topology,
                "no violations captured".to_string(),
            )
        },
        |violation| (violation.kind, format!("{}", violation.error)),
    );
    DebugOutcome::ValidationFailure { kind, details }
}

fn print_validation_report(report: &TriangulationValidationReport) {
    println!(
        "Validation report: {} violation(s)",
        report.violations.len()
    );
    for (idx, violation) in report.violations.iter().enumerate() {
        println!("  {}. {:?}: {}", idx + 1, violation.kind, violation.error);
    }
}

#[cfg(feature = "diagnostics")]
fn usize_to_u128(value: usize) -> u128 {
    u128::try_from(value).expect("usize should always fit in u128")
}

#[cfg(feature = "diagnostics")]
fn format_ratio_2(numerator: usize, denominator: usize) -> String {
    format_ratio_2_u128(usize_to_u128(numerator), usize_to_u128(denominator))
}

#[cfg(feature = "diagnostics")]
fn format_ratio_2_u128(numerator: u128, denominator: u128) -> String {
    if denominator == 0 {
        return "0.00".to_string();
    }

    let scaled = numerator.saturating_mul(100) / denominator;
    format!("{}.{:02}", scaled / 100, scaled % 100)
}

#[cfg(feature = "diagnostics")]
fn format_nanos_as_ms(nanos: u64) -> String {
    let micros = u128::from(nanos) / 1_000;
    format!("{}.{:03}", micros / 1_000, micros % 1_000)
}

#[cfg(feature = "diagnostics")]
fn format_avg_nanos_as_ms(total_nanos: u64, count: usize) -> String {
    if count == 0 {
        return "0.000".to_string();
    }

    let count = u64::try_from(count).expect("sample count should fit in u64 for debug reporting");
    format_nanos_as_ms(total_nanos / count)
}

#[cfg(feature = "diagnostics")]
fn print_timing_summary(label: &str, calls: usize, total_nanos: u64, max_nanos: u64) {
    if calls == 0 {
        return;
    }

    println!(
        "    {label}: calls={calls} total_ms={} avg_ms={} max_ms={}",
        format_nanos_as_ms(total_nanos),
        format_avg_nanos_as_ms(total_nanos, calls),
        format_nanos_as_ms(max_nanos)
    );
}

#[cfg(feature = "diagnostics")]
fn print_repair_seed_accumulation_telemetry(telemetry: &ConstructionTelemetry) {
    if telemetry.repair_seed_accumulation_calls == 0 {
        return;
    }

    println!(
        "    repair_seed_accumulation: calls={} simplices_added_total={} avg_simplices_added={} max_simplices_added={} total_ms={} avg_ms={} max_ms={}",
        telemetry.repair_seed_accumulation_calls,
        telemetry.repair_seed_simplices_added_total,
        format_ratio_2(
            telemetry.repair_seed_simplices_added_total,
            telemetry.repair_seed_accumulation_calls,
        ),
        telemetry.repair_seed_simplices_added_max,
        format_nanos_as_ms(telemetry.repair_seed_accumulation_nanos),
        format_avg_nanos_as_ms(
            telemetry.repair_seed_accumulation_nanos,
            telemetry.repair_seed_accumulation_calls,
        ),
        format_nanos_as_ms(telemetry.repair_seed_accumulation_nanos_max)
    );
}

#[cfg(feature = "diagnostics")]
fn print_local_repair_frontier_telemetry(telemetry: &ConstructionTelemetry) {
    if telemetry.local_repair_calls == 0 {
        return;
    }

    println!(
        "    local_repair_frontiers: seed_simplices_total={} avg_seed_simplices={} max_seed_simplices={} cadence_triggers={} backlog_triggers={}",
        telemetry.local_repair_seed_simplices_total,
        format_ratio_2(
            telemetry.local_repair_seed_simplices_total,
            telemetry.local_repair_calls,
        ),
        telemetry.local_repair_seed_simplices_max,
        telemetry.local_repair_cadence_triggers,
        telemetry.local_repair_backlog_triggers
    );
}

#[cfg(feature = "diagnostics")]
fn print_local_repair_work_telemetry(telemetry: &ConstructionTelemetry) {
    if telemetry.local_repair_calls == 0 {
        return;
    }

    println!(
        "    local_repair_work: checked_total={} avg_checked={} flips_total={} avg_flips={} max_flips={} max_queue={} no_flip_calls={}",
        telemetry.local_repair_items_checked_total,
        format_ratio_2(
            telemetry.local_repair_items_checked_total,
            telemetry.local_repair_calls,
        ),
        telemetry.local_repair_flips_total,
        format_ratio_2(
            telemetry.local_repair_flips_total,
            telemetry.local_repair_calls
        ),
        telemetry.local_repair_flips_max,
        telemetry.local_repair_queue_len_max,
        telemetry.local_repair_no_flip_calls
    );
}

#[cfg(feature = "diagnostics")]
fn print_local_repair_slow_samples(telemetry: &ConstructionTelemetry) {
    if telemetry.local_repair_slow_samples.is_empty() {
        return;
    }

    println!(
        "    local_repair_slow_samples (top {}):",
        telemetry.local_repair_slow_samples.len()
    );
    for sample in &telemetry.local_repair_slow_samples {
        println!(
            "      idx={} trigger={:?} seed_simplices={} elapsed_ms={} checked={} flips={} max_queue={} facet_ms={} ridge_ms={} postcondition_ms={}",
            sample.index,
            sample.trigger,
            sample.seed_simplices,
            format_nanos_as_ms(sample.elapsed_nanos),
            sample.items_checked,
            sample.flips_performed,
            sample.max_queue_len,
            format_nanos_as_ms(sample.facet_nanos),
            format_nanos_as_ms(sample.ridge_nanos),
            format_nanos_as_ms(sample.postcondition_nanos)
        );
    }
}

#[cfg(feature = "diagnostics")]
fn print_local_repair_phase_telemetry(telemetry: &ConstructionTelemetry) {
    let phase_total = telemetry
        .local_repair_snapshot_nanos
        .saturating_add(telemetry.local_repair_attempt_nanos)
        .saturating_add(telemetry.local_repair_postcondition_nanos)
        .saturating_add(telemetry.local_repair_restore_nanos);
    if phase_total == 0 {
        return;
    }

    print_timing_summary(
        "local_repair_snapshot",
        telemetry.local_repair_calls,
        telemetry.local_repair_snapshot_nanos,
        telemetry.local_repair_snapshot_nanos_max,
    );
    print_timing_summary(
        "local_repair_attempts",
        telemetry.local_repair_calls,
        telemetry.local_repair_attempt_nanos,
        telemetry.local_repair_attempt_nanos_max,
    );
    print_timing_summary(
        "local_repair_attempt_seed",
        telemetry.local_repair_calls,
        telemetry.local_repair_attempt_seed_nanos,
        telemetry.local_repair_attempt_seed_nanos_max,
    );
    print_timing_summary(
        "local_repair_attempt_facets",
        telemetry.local_repair_calls,
        telemetry.local_repair_attempt_facet_nanos,
        telemetry.local_repair_attempt_facet_nanos_max,
    );
    print_timing_summary(
        "local_repair_attempt_ridges",
        telemetry.local_repair_calls,
        telemetry.local_repair_attempt_ridge_nanos,
        telemetry.local_repair_attempt_ridge_nanos_max,
    );
    print_timing_summary(
        "local_repair_attempt_edges",
        telemetry.local_repair_calls,
        telemetry.local_repair_attempt_edge_nanos,
        telemetry.local_repair_attempt_edge_nanos_max,
    );
    print_timing_summary(
        "local_repair_attempt_triangles",
        telemetry.local_repair_calls,
        telemetry.local_repair_attempt_triangle_nanos,
        telemetry.local_repair_attempt_triangle_nanos_max,
    );
    print_timing_summary(
        "local_repair_postconditions",
        telemetry.local_repair_calls,
        telemetry.local_repair_postcondition_nanos,
        telemetry.local_repair_postcondition_nanos_max,
    );
    print_timing_summary(
        "local_repair_restores",
        telemetry.local_repair_calls,
        telemetry.local_repair_restore_nanos,
        telemetry.local_repair_restore_nanos_max,
    );
}

#[cfg(feature = "diagnostics")]
fn print_construction_phase_telemetry(telemetry: &ConstructionTelemetry) {
    let outer_total_nanos = telemetry
        .construction_preprocessing_nanos
        .saturating_add(telemetry.construction_insert_loop_nanos)
        .saturating_add(telemetry.construction_finalize_nanos)
        .saturating_add(telemetry.construction_final_delaunay_validation_nanos);
    if outer_total_nanos == 0 {
        return;
    }

    println!(
        "    construction_phases: preprocessing_ms={} insert_loop_ms={} finalize_ms={} final_delaunay_validation_ms={} outer_total_ms={}",
        format_nanos_as_ms(telemetry.construction_preprocessing_nanos),
        format_nanos_as_ms(telemetry.construction_insert_loop_nanos),
        format_nanos_as_ms(telemetry.construction_finalize_nanos),
        format_nanos_as_ms(telemetry.construction_final_delaunay_validation_nanos),
        format_nanos_as_ms(outer_total_nanos)
    );

    let finalize_breakdown_nanos = telemetry
        .construction_completion_repair_nanos
        .saturating_add(telemetry.construction_orientation_nanos)
        .saturating_add(telemetry.construction_topology_validation_nanos);
    if finalize_breakdown_nanos == 0 {
        return;
    }

    println!(
        "    finalize_breakdown: completion_repair_ms={} orientation_ms={} topology_validation_ms={}",
        format_nanos_as_ms(telemetry.construction_completion_repair_nanos),
        format_nanos_as_ms(telemetry.construction_orientation_nanos),
        format_nanos_as_ms(telemetry.construction_topology_validation_nanos)
    );
}

#[cfg_attr(
    not(feature = "diagnostics"),
    expect(
        clippy::missing_const_for_fn,
        reason = "the diagnostics build of this helper emits detailed output"
    )
)]
fn print_construction_telemetry(telemetry: &ConstructionTelemetry) {
    #[cfg(not(feature = "diagnostics"))]
    let _ = telemetry.has_data();

    #[cfg(feature = "diagnostics")]
    if telemetry.has_data() {
        println!();
        println!("  insertion telemetry:");
        print_construction_phase_telemetry(telemetry);
        print_timing_summary(
            "insertion_wall",
            telemetry.insertion_wall_time_calls,
            telemetry.insertion_wall_time_nanos,
            telemetry.insertion_wall_time_nanos_max,
        );
        println!(
            "    locate: calls={} walk_steps_total={} avg_walk={} max_walk={} hint_uses={} scan_fallbacks={}",
            telemetry.locate_calls,
            telemetry.locate_walk_steps_total,
            format_ratio_2(telemetry.locate_walk_steps_total, telemetry.locate_calls),
            telemetry.locate_walk_steps_max,
            telemetry.locate_hint_uses,
            telemetry.locate_scan_fallbacks
        );
        println!(
            "    locate_results: inside={} outside={} boundary={}",
            telemetry.located_inside, telemetry.located_outside, telemetry.located_on_boundary
        );

        if telemetry.conflict_region_calls > 0 {
            println!(
                "    conflict_regions: calls={} simplices_total={} avg_simplices={} max_simplices={} total_ms={} avg_ms={} max_ms={}",
                telemetry.conflict_region_calls,
                telemetry.conflict_region_simplices_total,
                format_ratio_2(
                    telemetry.conflict_region_simplices_total,
                    telemetry.conflict_region_calls,
                ),
                telemetry.conflict_region_simplices_max,
                format_nanos_as_ms(telemetry.conflict_region_nanos),
                format_avg_nanos_as_ms(
                    telemetry.conflict_region_nanos,
                    telemetry.conflict_region_calls,
                ),
                format_nanos_as_ms(telemetry.conflict_region_nanos_max)
            );
        }

        print_timing_summary(
            "cavity_insertions",
            telemetry.cavity_insertion_calls,
            telemetry.cavity_insertion_nanos,
            telemetry.cavity_insertion_nanos_max,
        );
        print_timing_summary(
            "hull_extensions",
            telemetry.hull_extension_calls,
            telemetry.hull_extension_nanos,
            telemetry.hull_extension_nanos_max,
        );
        print_timing_summary(
            "topology_validations",
            telemetry.topology_validation_calls,
            telemetry.topology_validation_nanos,
            telemetry.topology_validation_nanos_max,
        );
        print_timing_summary(
            "local_repairs",
            telemetry.local_repair_calls,
            telemetry.local_repair_nanos,
            telemetry.local_repair_nanos_max,
        );
        print_local_repair_phase_telemetry(telemetry);
        print_local_repair_frontier_telemetry(telemetry);
        print_local_repair_work_telemetry(telemetry);
        print_local_repair_slow_samples(telemetry);
        print_repair_seed_accumulation_telemetry(telemetry);

        if telemetry.global_conflict_scans > 0 {
            let scans = u64::try_from(telemetry.global_conflict_scans)
                .expect("scan count should fit in u64 for debug reporting");
            println!(
                "    global_conflict_scans: scans={} simplices_scanned_total={} avg_simplices_scanned={} simplices_found_total={} avg_simplices_found={} max_simplices_found={} total_ms={} avg_ms={}",
                telemetry.global_conflict_scans,
                telemetry.global_conflict_simplices_scanned,
                format_ratio_2(
                    telemetry.global_conflict_simplices_scanned,
                    telemetry.global_conflict_scans,
                ),
                telemetry.global_conflict_simplices_found_total,
                format_ratio_2(
                    telemetry.global_conflict_simplices_found_total,
                    telemetry.global_conflict_scans,
                ),
                telemetry.global_conflict_simplices_found_max,
                format_nanos_as_ms(telemetry.global_conflict_scan_nanos),
                format_nanos_as_ms(telemetry.global_conflict_scan_nanos / scans)
            );
        }
    }
}

fn print_insertion_summary<const D: usize>(
    summary: &InsertionSummary<D>,
    elapsed: Duration,
    include_batch_diagnostics: bool,
) {
    println!("Insertion summary:");
    println!("  inserted:          {}", summary.inserted);
    println!("  skipped_duplicate: {}", summary.skipped_duplicate);
    println!("  skipped_degeneracy:{}", summary.skipped_degeneracy);
    println!("  total_skipped:     {}", summary.total_skipped());
    println!();

    println!("  total_attempts:    {}", summary.total_attempts);
    println!("  max_attempts:      {}", summary.max_attempts);
    println!("  used_perturbation: {}", summary.used_perturbation);
    println!(
        "  simplices_removed_during_repair: total={}, max={} (insertion safety-net / repair bookkeeping)",
        summary.simplices_removed_total, summary.simplices_removed_max
    );

    if !summary.attempts_histogram.is_empty() {
        println!("  attempts_histogram (attempts -> count):");
        for (attempts, count) in summary.attempts_histogram.iter().enumerate().skip(1) {
            if *count > 0 {
                println!("    {attempts} -> {count}");
            }
        }
    }

    if include_batch_diagnostics {
        print_construction_telemetry(&summary.telemetry);
    }

    #[cfg(feature = "diagnostics")]
    if include_batch_diagnostics && !summary.slow_insertions.is_empty() {
        println!();
        println!(
            "  slow_insertions (top {} by transactional insertion wall time):",
            summary.slow_insertions.len()
        );
        for s in &summary.slow_insertions {
            println!(
                "    idx={} uuid={} attempts={} result={:?} elapsed_ms={} simplices_after={} locate_calls={} walk_steps={} conflict_calls={} conflict_simplices={} cavity_calls={} global_scans={} hull_calls={} validation_calls={}",
                s.index,
                s.uuid,
                s.attempts,
                s.result,
                format_nanos_as_ms(s.elapsed_nanos),
                s.simplices_after,
                s.locate_calls,
                s.locate_walk_steps_total,
                s.conflict_region_calls,
                s.conflict_region_simplices_total,
                s.cavity_insertion_calls,
                s.global_conflict_scans,
                s.hull_extension_calls,
                s.topology_validation_calls
            );
        }
    }

    if !summary.skip_samples.is_empty() {
        println!();
        println!("  skip_samples (first {}):", summary.skip_samples.len());
        for s in &summary.skip_samples {
            let coords = s.coords.as_ref().map_or_else(
                || "<unavailable>".to_string(),
                |coords| format!("{coords:?}"),
            );
            println!(
                "    idx={} uuid={} attempts={} coords={} error={}",
                s.index, s.uuid, s.attempts, coords, s.error
            );
        }
    }

    println!();
    println!("Insertion wall time: {elapsed:?}");
}

#[expect(
    clippy::too_many_lines,
    reason = "Intentional debug harness; kept as a single flow for manual inspection"
)]
fn debug_large_case<const D: usize>(dimension_name: &str, default_n_points: usize) -> DebugOutcome
where
    RobustKernel<f64>: ExactPredicates<D> + Kernel<D, Scalar = f64>,
{
    init_tracing();

    // Install a hard wall-clock cap so the harness doesn't hang indefinitely.
    // Override with DELAUNAY_LARGE_DEBUG_MAX_RUNTIME_SECS (0 = no cap).
    let max_runtime_secs = env_usize("DELAUNAY_LARGE_DEBUG_MAX_RUNTIME_SECS").unwrap_or(600);
    // Hold the sender for the lifetime of this function; dropping it at return
    // cancels the watchdog thread so it does not outlive this test.
    let _watchdog = (max_runtime_secs > 0).then(|| install_runtime_cap(max_runtime_secs as u64));

    let base_seed = env_u64("DELAUNAY_LARGE_DEBUG_SEED").unwrap_or(42);

    let n_points = env_usize(&format!("DELAUNAY_LARGE_DEBUG_N_{D}D"))
        .or_else(|| env_usize("DELAUNAY_LARGE_DEBUG_N"))
        .unwrap_or(default_n_points)
        .max(D + 1);

    let seed = env_u64(&format!("DELAUNAY_LARGE_DEBUG_CASE_SEED_{D}D"))
        .or_else(|| env_u64("DELAUNAY_LARGE_DEBUG_CASE_SEED"))
        .unwrap_or_else(|| seed_for_case::<D>(base_seed, n_points));
    let distribution = point_distribution_from_env();
    let ball_radius = env_f64("DELAUNAY_LARGE_DEBUG_BALL_RADIUS").unwrap_or(100.0);
    let box_half_width = env_f64("DELAUNAY_LARGE_DEBUG_BOX_HALF_WIDTH").unwrap_or(100.0);

    let mode = construction_mode_from_env();
    let initial_simplex_strategy = initial_simplex_strategy_from_env();
    let debug_mode = debug_mode_from_env();
    let topology_guarantee = topology_for_debug_mode(debug_mode);

    let shuffle_seed = env_u64("DELAUNAY_LARGE_DEBUG_SHUFFLE_SEED");
    let progress_every = env_usize("DELAUNAY_LARGE_DEBUG_PROGRESS_EVERY")
        .unwrap_or(1000)
        .max(1);
    let bulk_progress_every = bulk_progress_every_from_env();

    let allow_skips = env_flag("DELAUNAY_LARGE_DEBUG_ALLOW_SKIPS");
    let max_skip_pct = max_skip_pct_from_env();
    let skip_final_repair = env_flag("DELAUNAY_LARGE_DEBUG_SKIP_FINAL_REPAIR");

    // Delaunay repair scheduling
    // - 0 disables incremental repair
    // - 1 runs repair after every insertion
    // - N>1 runs repair after every N successful insertions
    let repair_every = env_usize("DELAUNAY_LARGE_DEBUG_REPAIR_EVERY").unwrap_or(1);
    let repair_policy = repair_policy_from_repair_every(repair_every);
    let repair_max_flips = env_usize("DELAUNAY_LARGE_DEBUG_REPAIR_MAX_FLIPS");
    let validate_every = env_usize("DELAUNAY_LARGE_DEBUG_VALIDATE_EVERY").or_else(|| {
        if matches!(debug_mode, DebugMode::Cadenced) {
            (repair_every != 0).then_some(repair_every)
        } else {
            None
        }
    });
    let validation_cadence = ValidationCadence::from_optional_every(validate_every);

    println!("=============================================");
    println!("Large-scale triangulation debug: {dimension_name}");
    println!("=============================================");
    println!("Config:");
    println!("  D:             {D}");
    println!("  n_points:      {n_points}");
    println!("  base_seed:     0x{base_seed:X} ({base_seed})");
    println!("  case_seed:     0x{seed:X} ({seed})");
    println!(
        "  distribution: {distribution}",
        distribution = distribution.name()
    );
    match distribution {
        PointDistribution::Ball => println!("  ball_radius:  {ball_radius}"),
        PointDistribution::Box => println!("  box_half_width:{box_half_width}"),
    }
    println!("  construction_mode: {}", mode.name());
    println!(
        "  initial_simplex: {}",
        initial_simplex_strategy_name(initial_simplex_strategy)
    );
    println!("  debug_mode:    {}", debug_mode.name());
    println!("  topology_guarantee: {topology_guarantee:?}");
    println!("  shuffle_seed:  {shuffle_seed:?}");
    match mode {
        ConstructionMode::New => {
            let bulk_progress = bulk_progress_every
                .map_or_else(|| "disabled".to_owned(), |every| every.to_string());
            println!("  bulk_progress_every:{bulk_progress}");
            println!("  bulk_progress_scope: remaining vertices after initial simplex");
        }
        ConstructionMode::Incremental => println!("  progress_every:{progress_every}"),
    }
    println!("  validation_cadence: {validation_cadence:?}");
    println!("  allow_skips:   {allow_skips}");
    println!("  max_skip_pct:  {max_skip_pct}");
    println!("  skip_final_repair: {skip_final_repair}");
    println!("  repair_every:  {repair_every}");
    println!("  repair_policy: {repair_policy:?}");
    println!("  repair_max_flips: {repair_max_flips:?}");
    if max_runtime_secs > 0 {
        println!("  max_runtime_secs: {max_runtime_secs}");
    }
    println!();

    println!("Generating points...");
    let t_gen = Instant::now();
    let points = match distribution {
        PointDistribution::Ball => {
            generate_random_points_in_ball_seeded::<f64, D>(n_points, ball_radius, seed)
                .unwrap_or_else(|e| {
                    panic!(
                        "failed to generate deterministic ball points (radius={ball_radius}): {e}"
                    )
                })
        }
        PointDistribution::Box => {
            let range = (-box_half_width, box_half_width);
            generate_random_points_seeded::<f64, D>(n_points, range, seed).unwrap_or_else(|e| {
                panic!("failed to generate deterministic box points (range={range:?}): {e}")
            })
        }
    };
    println!("Generated {} points in {:?}", points.len(), t_gen.elapsed());

    println!("Building vertices...");
    let t_vertices = Instant::now();
    let mut vertices: Vec<Vertex<f64, (), D>> = points.into_iter().map(|p| vertex!(p)).collect();
    println!(
        "Built {} vertices in {:?}",
        vertices.len(),
        t_vertices.elapsed()
    );

    let t_insert = Instant::now();

    let mut dt: DelaunayTriangulation<_, (), (), D> = match mode {
        ConstructionMode::New => {
            // `DelaunayTriangulation::new()` applies Hilbert ordering during batch construction.
            // Use the statistics-returning variant so we can report aggregate insertion telemetry.
            let kernel = RobustKernel::<f64>::new();
            println!("Starting batch construction (new)...");
            let t_batch = Instant::now();
            let options = ConstructionOptions::default()
                .with_initial_simplex_strategy(initial_simplex_strategy)
                .with_batch_repair_policy(repair_policy);
            match DelaunayTriangulation::with_options_and_statistics(
                &kernel,
                &vertices,
                topology_guarantee,
                options,
            ) {
                Ok((dt, stats)) => {
                    let summary: InsertionSummary<D> = stats.into();
                    print_insertion_summary(&summary, t_insert.elapsed(), true);
                    println!("Batch construction completed in {:?}", t_batch.elapsed());
                    dt
                }
                Err(e) => {
                    let DelaunayTriangulationConstructionErrorWithStatistics {
                        error,
                        statistics,
                        ..
                    } = e;
                    let summary: InsertionSummary<D> = statistics.into();
                    print_insertion_summary(&summary, t_insert.elapsed(), true);
                    println!("Batch construction failed after {:?}", t_batch.elapsed());
                    println!("construction failed: {error}");
                    let outcome = DebugOutcome::ConstructionFailure {
                        error: format!("{error}"),
                    };
                    print_abort_summary::<D>(&outcome, seed, n_points, "batch construction");
                    return outcome;
                }
            }
        }
        ConstructionMode::Incremental => {
            if let Some(shuffle_seed) = shuffle_seed {
                let mut rng = StdRng::seed_from_u64(shuffle_seed);
                vertices.shuffle(&mut rng);
                println!("Shuffled insertion order with seed {shuffle_seed}");
            }

            let validation_policy = topology_guarantee.default_validation_policy();

            let mut dt: DelaunayTriangulation<_, (), (), D> =
                DelaunayTriangulation::with_empty_kernel_and_topology_guarantee(
                    RobustKernel::<f64>::new(),
                    topology_guarantee,
                );

            // Delaunay policies:
            // - Enable bounded incremental repair (local flip queue) every N successful insertions.
            // - Keep global Delaunay checks off during insertion; the harness can optionally run a final
            //   global repair pass at the end.
            dt.set_delaunay_repair_policy(repair_policy);
            dt.set_delaunay_check_policy(DelaunayCheckPolicy::EndOnly);

            // Debug-mode-dependent topology validation strategy:
            // - cadenced: suspicion-driven automatic checks + periodic explicit checks
            // - strict: per-insertion automatic checks
            dt.set_validation_policy(validation_policy);

            println!("Policies:");
            println!("  topology_guarantee:   {:?}", dt.topology_guarantee());
            println!("  validation_policy:    {:?}", dt.validation_policy());
            println!("  delaunay_repair_policy:{:?}", dt.delaunay_repair_policy());
            println!("  delaunay_check_policy: {:?}", dt.delaunay_check_policy());
            println!();

            let mut summary: InsertionSummary<D> = InsertionSummary::default();
            let mut had_simplices = false;
            let mut t_last_progress = Instant::now();

            for (idx, vertex) in vertices.iter().copied().enumerate() {
                let coords = *vertex.point().coords();
                let uuid = vertex.uuid();

                let inserted_this_loop = match dt.insert_best_effort_with_statistics(vertex) {
                    Ok((InsertionOutcome::Inserted { .. }, stats)) => {
                        summary.record_inserted(stats);
                        true
                    }
                    Ok((InsertionOutcome::Skipped { error }, stats)) => {
                        let sample = SkipSample {
                            index: idx,
                            uuid,
                            coords: Some(coords),
                            attempts: stats.attempts,
                            error: error.to_string(),
                        };
                        summary.record_skipped(sample, stats);
                        false
                    }
                    Err(err) => {
                        println!(
                            "Non-retryable insertion error at idx={idx} uuid={uuid} coords={coords:?}"
                        );
                        println!("  error: {err}");

                        if let Err(report) = dt.validation_report() {
                            print_validation_report(&report);
                        } else {
                            println!("validation_report: OK (after rollback)");
                        }
                        let outcome = DebugOutcome::ConstructionFailure {
                            error: format!("{err}"),
                        };
                        print_abort_summary::<D>(&outcome, seed, n_points, "incremental insertion");
                        return outcome;
                    }
                };

                if !had_simplices && dt.number_of_simplices() > 0 {
                    had_simplices = true;
                    println!("Initial simplex created at insertion {}", idx + 1);
                }

                if inserted_this_loop
                    && had_simplices
                    && validation_cadence.should_validate(summary.inserted)
                    && let Err(e) = dt.as_triangulation().is_valid()
                {
                    println!("Topology validation failed at idx={idx}: {e}");
                    let outcome = if let Err(report) = dt.validation_report() {
                        print_validation_report(&report);
                        classify_validation_report(&report)
                    } else {
                        DebugOutcome::ValidationFailure {
                            kind: InvariantKind::Topology,
                            details: format!("{e}"),
                        }
                    };
                    print_abort_summary::<D>(&outcome, seed, n_points, "periodic validation");
                    return outcome;
                }

                if (idx + 1) % progress_every == 0 {
                    let chunk_elapsed = t_last_progress.elapsed();
                    let progress_f64: f64 =
                        safe_usize_to_scalar(progress_every).unwrap_or(f64::NAN);
                    let rate = progress_f64 / chunk_elapsed.as_secs_f64().max(1e-9);
                    println!(
                        "progress: {}/{} inserted={} skipped={} simplices={} elapsed={:?} ({:.1} pts/s last {})",
                        idx + 1,
                        n_points,
                        summary.inserted,
                        summary.total_skipped(),
                        dt.number_of_simplices(),
                        t_insert.elapsed(),
                        rate,
                        progress_every,
                    );
                    t_last_progress = Instant::now();
                }
            }

            print_insertion_summary(&summary, t_insert.elapsed(), false);

            dt
        }
    };

    // Infer skipped count from the resulting triangulation size.
    let skipped_total = n_points.saturating_sub(dt.number_of_vertices());

    println!(
        "Triangulation size: vertices={} (skipped={skipped_total}) simplices={} dim={}",
        dt.number_of_vertices(),
        dt.number_of_simplices(),
        dt.dim()
    );

    let skipped_pct = skip_percentage(skipped_total, n_points);
    if !allow_skips && skipped_pct > max_skip_pct {
        let outcome = DebugOutcome::SkippedVertices {
            skipped: skipped_total,
            total: n_points,
            skip_pct: skipped_pct,
            max_skip_pct,
        };
        print_abort_summary::<D>(&outcome, seed, n_points, "skip check");
        return outcome;
    }

    let mut repair_failure: Option<String> = None;
    if !skip_final_repair && dt.number_of_simplices() > 0 {
        println!();
        println!("Running final flip-based repair (advanced)...");
        let t_repair = Instant::now();
        let mut repair_config = DelaunayRepairHeuristicConfig::default();
        repair_config.max_flips = repair_max_flips;
        match dt.repair_delaunay_with_flips_advanced(repair_config) {
            Ok(outcome) => {
                println!(
                    "repair: checked={} flips={} max_queue={} used_heuristic={}",
                    outcome.stats.facets_checked,
                    outcome.stats.flips_performed,
                    outcome.stats.max_queue_len,
                    outcome.used_heuristic()
                );
                if let Some(seeds) = outcome.heuristic {
                    println!(
                        "repair heuristic seeds: shuffle_seed={} perturbation_seed={}",
                        seeds.shuffle_seed, seeds.perturbation_seed
                    );
                }
            }
            Err(e) => {
                println!("repair failed: {e}");
                repair_failure = Some(format!("{e}"));
            }
        }
        println!("repair wall time: {:?}", t_repair.elapsed());
    }

    println!();
    println!("Running validation_report (Levels 1–4)...");
    let t_validate = Instant::now();
    let validation_result = dt.validation_report();
    println!("validation_report wall time: {:?}", t_validate.elapsed());
    match validation_result {
        Ok(()) => println!("validation_report: OK"),
        Err(report) => {
            print_validation_report(&report);
            let outcome = classify_validation_report(&report);
            print_abort_summary::<D>(&outcome, seed, n_points, "final validation");
            return outcome;
        }
    }

    // If repair failed but validation passed, surface the repair failure as the outcome.
    // This ensures operators see repair non-convergence even when the triangulation
    // happens to pass L1-L4 validation (e.g. the violations are below the flip budget).
    if let Some(error) = repair_failure {
        let outcome = DebugOutcome::RepairNonConvergence { error };
        print_abort_summary::<D>(&outcome, seed, n_points, "final repair");
        return outcome;
    }

    println!();
    println!("Total wall time: {:?}", t_gen.elapsed());
    DebugOutcome::Success
}

#[derive(Clone, Copy)]
enum FailingWriterMode {
    Write,
    Flush,
}

struct FailingWriter {
    mode: FailingWriterMode,
    kind: io::ErrorKind,
}

impl Write for FailingWriter {
    fn write(&mut self, buf: &[u8]) -> io::Result<usize> {
        if matches!(self.mode, FailingWriterMode::Write) {
            return Err(io::Error::new(self.kind, "synthetic write failure"));
        }

        Ok(buf.len())
    }

    fn flush(&mut self) -> io::Result<()> {
        if matches!(self.mode, FailingWriterMode::Flush) {
            return Err(io::Error::new(self.kind, "synthetic flush failure"));
        }

        Ok(())
    }
}

#[test]
fn test_write_timeout_abort_message_flushes_message() {
    let mut output = Vec::new();

    write_timeout_abort_message(&mut output, 17).expect("timeout diagnostic write should succeed");

    let message = String::from_utf8(output).expect("timeout diagnostic should be UTF-8");
    assert_eq!(
        message,
        "=== TIMEOUT: wall time exceeded 17 seconds — aborting ===\n"
    );
}

#[test]
fn test_write_timeout_abort_message_propagates_error() {
    // `install_runtime_cap` aborts immediately after this helper returns, so the
    // caller must be able to observe write or flush failures before aborting.
    let cases = [
        (FailingWriterMode::Write, io::ErrorKind::BrokenPipe),
        (FailingWriterMode::Flush, io::ErrorKind::WriteZero),
    ];

    for (mode, kind) in cases {
        let err = write_timeout_abort_message(FailingWriter { mode, kind }, 17)
            .expect_err("timeout diagnostic should propagate writer failures");
        assert_eq!(err.kind(), kind);
    }
}

#[test]
fn test_topology_for_debug_mode_uses_ridge_links_by_default() {
    assert_eq!(
        topology_for_debug_mode(DebugMode::Cadenced),
        TopologyGuarantee::PLManifold
    );
    assert_eq!(
        topology_for_debug_mode(DebugMode::Strict),
        TopologyGuarantee::PLManifoldStrict
    );
}

#[test]
fn test_initial_simplex_strategy_from_name_maps_supported_values() {
    assert_eq!(
        initial_simplex_strategy_from_name(""),
        Some(InitialSimplexStrategy::MaxVolume)
    );
    assert_eq!(
        initial_simplex_strategy_from_name("first"),
        Some(InitialSimplexStrategy::First)
    );
    assert_eq!(
        initial_simplex_strategy_from_name("BALANCED"),
        Some(InitialSimplexStrategy::Balanced)
    );
    assert_eq!(
        initial_simplex_strategy_from_name("max-volume"),
        Some(InitialSimplexStrategy::MaxVolume)
    );
    assert_eq!(
        initial_simplex_strategy_from_name("MAX_VOLUME"),
        Some(InitialSimplexStrategy::MaxVolume)
    );
    assert_eq!(initial_simplex_strategy_from_name("unknown"), None);
    assert_eq!(
        initial_simplex_strategy_name(InitialSimplexStrategy::Balanced),
        "balanced"
    );
    assert_eq!(
        initial_simplex_strategy_name(InitialSimplexStrategy::MaxVolume),
        "max-volume"
    );
}

#[test]
fn test_skip_percentage_reports_ratio() {
    assert!((skip_percentage(0, 100) - 0.0).abs() < f64::EPSILON);
    assert!((skip_percentage(0, 0) - 0.0).abs() < f64::EPSILON);
    assert!((skip_percentage(4, 400) - 1.0).abs() < f64::EPSILON);
    assert!((skip_percentage(12, 100) - 12.0).abs() < f64::EPSILON);
}

#[test]
fn test_repair_policy_from_repair_every_maps_cadence() {
    assert_eq!(
        repair_policy_from_repair_every(0),
        DelaunayRepairPolicy::Never
    );
    assert_eq!(
        repair_policy_from_repair_every(1),
        DelaunayRepairPolicy::EveryInsertion
    );
    assert_eq!(
        repair_policy_from_repair_every(2),
        DelaunayRepairPolicy::EveryN(NonZeroUsize::new(2).unwrap())
    );
    assert_eq!(
        repair_policy_from_repair_every(4),
        DelaunayRepairPolicy::EveryN(NonZeroUsize::new(4).unwrap())
    );
}

/// Regression test for issue #228: 3D 1000-point flip-repair non-convergence.
///
/// Before the fix, `AdaptiveKernel`'s exact+SoS predicates were overridden by
/// `use_robust_on_ambiguous` in the flip repair code, causing tolerance-based
/// predicates to return wrong signs for near-degenerate cases and triggering
/// flip cycles.
///
/// This test uses the exact seed that reproduced the original failure:
/// `seed_for_case::<3>(42, 1000)` with ball distribution (radius=100).
///
/// Uses `PLManifold` topology for full PL-manifold validation including
/// geometric simplex orientation (#258 fixed the negative-orientation gap that
/// previously required the `Pseudomanifold` workaround).
///
/// Gated behind `slow-tests` because 1000-point 3D construction belongs to
/// the explicit slow-test bucket. Run with:
/// ```bash
/// cargo test --release --test large_scale_debug --features slow-tests regression_issue_228_3d_1000_flip_repair_convergence -- --nocapture
/// ```
#[cfg(feature = "slow-tests")]
#[test]
fn regression_issue_228_3d_1000_flip_repair_convergence() {
    let seed = seed_for_case::<3>(42, 1000);
    let points = generate_random_points_in_ball_seeded::<f64, 3>(1000, 100.0, seed)
        .expect("point generation should succeed");
    let vertices: Vec<Vertex<f64, (), 3>> = points.into_iter().map(|p| vertex!(p)).collect();

    // Use the default kernel (AdaptiveKernel — exact+SoS predicates) to match the
    // actual regression scenario.  PLManifold enables full orientation validation
    // now that #258 is fixed.
    let dt: DelaunayTriangulation<_, (), (), 3> =
        DelaunayTriangulation::new_with_topology_guarantee(
            &vertices,
            TopologyGuarantee::PLManifold,
        )
        .expect("construction must not fail (#228 regression)");

    assert!(
        dt.as_triangulation().validate().is_ok(),
        "Topology validation (L1-L3) must pass (#228 regression, seed=0x{seed:X})"
    );
    assert!(
        dt.is_delaunay_via_flips().is_ok(),
        "Delaunay property must hold (#228 regression, seed=0x{seed:X})"
    );
}

/// Regression test for issue #230: 4D 100-point orientation failure path.
///
/// This locks in the 4D seed used by the debug harness:
/// `seed_for_case::<4>(42, 100)` with ball distribution (radius=100).
///
/// Current expected behavior:
/// - Batch construction succeeds
/// - Some vertices may be skipped due to degeneracy handling/retries
/// - Resulting triangulation passes topology validation (L1-L3)
///
/// Gated behind `slow-tests` because 4D construction can take more than the
/// default-suite budget.
#[cfg(feature = "slow-tests")]
#[test]
fn regression_issue_230_4d_100_orientation() {
    let seed = seed_for_case::<4>(42, 100);
    let points = generate_random_points_in_ball_seeded::<f64, 4>(100, 100.0, seed)
        .expect("point generation should succeed");
    let vertices: Vec<Vertex<f64, (), 4>> = points.into_iter().map(|p| vertex!(p)).collect();

    let kernel = RobustKernel::<f64>::new();
    let (dt, stats) =
        DelaunayTriangulation::<RobustKernel<f64>, (), (), 4>::with_options_and_statistics(
            &kernel,
            &vertices,
            TopologyGuarantee::PLManifoldStrict,
            ConstructionOptions::default(),
        )
        .expect("construction must not fail (#230 regression)");

    println!(
        "regression_issue_230: inserted={} skipped={} (duplicate={} degeneracy={}) seed=0x{seed:X}",
        stats.inserted,
        stats.total_skipped(),
        stats.skipped_duplicate,
        stats.skipped_degeneracy
    );

    assert!(
        dt.as_triangulation().validate().is_ok(),
        "Topology validation (L1-L3) must pass (#230 regression, seed=0x{seed:X})"
    );
}

#[test]
#[cfg(feature = "slow-tests")]
fn debug_large_scale_2d() {
    let outcome = debug_large_case::<2>("2D", 40_000);
    assert!(matches!(outcome, DebugOutcome::Success), "{outcome}");
}

#[test]
#[cfg(feature = "slow-tests")]
fn debug_large_scale_3d() {
    let outcome = debug_large_case::<3>("3D", 7_500);
    assert!(matches!(outcome, DebugOutcome::Success), "{outcome}");
}

#[test]
#[cfg(feature = "slow-tests")]
fn debug_large_scale_4d() {
    let outcome = debug_large_case::<4>("4D", 900);
    assert!(matches!(outcome, DebugOutcome::Success), "{outcome}");
}

#[test]
#[cfg(feature = "slow-tests")]
fn debug_large_scale_5d() {
    let outcome = debug_large_case::<5>("5D", 150);
    assert!(matches!(outcome, DebugOutcome::Success), "{outcome}");
}