BREP_reconstruction 0.10.0

Kernel integration for neutral BREP_RANSAC recognition results
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
//! STL-mesh to STEP conversion orchestration.
//!
//! The kernel's mesh segmentation runs first on every closed mesh. When it
//! reads the mesh as a whole primitive — every triangle on one of at most
//! three analytic regions — RANSAC recognition runs and its fitted
//! parameters build an exact sphere, torus, capped cylinder or capped cone.
//! If tessellation features fragmented the segmentation, recognition is also
//! eligible when every triangle lies on one segmented curved carrier or its
//! possible end caps. This eligibility check never substitutes for recognition.
//! Otherwise RANSAC is skipped: every consumer of its result needs that
//! whole-primitive shape, and on an eleven-thousand-facet part it cost 75 s
//! for a result nothing read. Safe plane, cylinder, cone, and sphere regions
//! can be rebuilt analytically beside unsupported source-triangle faces; an
//! analytic region is locally demoted when its shared boundary cannot be
//! represented exactly. If no validated mixed shell can be built, the complete
//! source mesh is sent through the kernel's repairable faceted importer. No
//! source triangle is omitted.
//!
//! Every one of those analytic lanes needs a closed two-manifold, which a mesh
//! FILE frequently is not — a dropped facet, a duplicated sheet, a degenerate
//! sliver. Such a body is repaired FIRST (`repair_triangle_soup`, the same
//! weld/prune/cap the faceted importer applies) and the analytic lanes run on
//! the repaired mesh, so a defect costs a body only the facets it touches
//! instead of every curved surface in it. A body whose repair still does not
//! close keeps the refusal it has always had. Closed shells retain their mesh
//! geometry; inward shells are oriented outward for reconstruction and restored
//! as cavities when an enclosing component is present.

mod cavities;
mod colors;
mod degenerate_coverage;
mod feature_fragments;
mod primitive_gate;
pub mod t_junctions;

use crate::{
    recognize_surfaces_with_candidates, reconstruct_surface, AnalyticSurface, ComponentCandidate,
    ConeSurface, CylinderSurface, Mesh, PlaneSurface, SphereSurface, TorusSurface,
    MeshAnalysisOptions, PhaseTimings, RecognitionOptions, SamplingMode, SurfaceFitResult,
    SurfaceHint, SurfaceRegion, SurfaceType, Vec3,
};
use brep_kernel::{
    audit_step_manifold, export_step, import_step, make_cone_brep, make_cylinder_brep,
    make_sphere_brep, make_torus_brep, merge_same_surface_faces, mesh_regions_to_brep,
    mesh_to_faceted_brep, repair_triangle_soup, segment_mesh_faces, MeshSegmentation,
    RegionCarrier, SegmentOptions,
    UNASSIGNED_REGION,
};
use serde::{Deserialize, Serialize};
use std::collections::{BTreeMap, BTreeSet, HashMap, VecDeque};
use std::fmt::{Display, Formatter};
use web_time::Instant;

/// Whether an unprovable analytic conversion may preserve the mesh as a
/// repaired faceted STEP solid.
#[derive(Clone, Copy, Debug, Default, PartialEq, Eq, Deserialize, Serialize)]
pub enum ConversionPolicy {
    /// Preserve arbitrary repairable input by falling back to faceted BREP.
    #[default]
    AllowFacetedFallback,
    /// Return an error unless the complete mesh can be rebuilt analytically.
    RequireFullyAnalytic,
}

/// Controls recognition and STEP topology construction.
#[derive(Clone, Debug, Deserialize, Serialize)]
#[serde(default)]
pub struct StlConversionOptions {
    /// RANSAC recognition settings. Recognition runs only when the kernel
    /// segmentation reads the mesh as a whole primitive (see the module doc);
    /// every other mesh is rebuilt from the segmentation alone.
    pub recognition: RecognitionOptions,
    /// Analytic-only versus repairable-faceted behavior.
    pub policy: ConversionPolicy,
    /// Try the kernel's plane/cylinder/cone region rebuilder when the kernel
    /// segmentation proves that the whole mesh is plane/cylinder/cone.
    pub try_kernel_analytic_rebuild: bool,
    /// Try the conservative mixed plane/cylinder/cone/sphere/faceted topology builder.
    ///
    /// This is enabled by default so recognized safe regions remain analytic
    /// even when other regions cannot be represented analytically. Disabling
    /// it is primarily useful for diagnosing the fully faceted repair path.
    pub try_hybrid_rebuild: bool,
    /// Vertex weld tolerance for hybrid segmentation and faceted repair;
    /// Non-positive uses the STL reader's scale-relative tolerance for
    /// segmentation; faceted repair retains the kernel's default tolerance.
    pub weld_tolerance: f64,
    /// Absolute coordinate uncertainty introduced by the source encoding.
    ///
    /// The converter will not run recognition below this distance even when
    /// [`RecognitionOptions::distance_tolerance`] requests a smaller value.
    /// Leave this at zero for text or double-precision sources. The CLI sets
    /// it automatically for binary STL, whose coordinates are IEEE-754 f32.
    pub coordinate_precision_tolerance: f64,
    /// Deflection angle used by the kernel analytic segmentation paths.
    pub kernel_deflection_angle_degrees: f64,
    /// Scale-relative carrier tolerance used by the kernel analytic segmentation paths.
    pub kernel_fit_tolerance: f64,
    /// Normal gate used by the kernel analytic segmentation paths.
    pub kernel_normal_tolerance_degrees: f64,
}

impl Default for StlConversionOptions {
    fn default() -> Self {
        let mut recognition = RecognitionOptions::default();
        recognition.collect_phase_timings = true;
        // Facet centroids lie on polygon chords rather than on the
        // underlying design carrier. Welded STL vertices retain the best
        // available samples of cylinders and other curved CAD surfaces.
        recognition.sampling = SamplingMode::Vertices;
        recognition.torus_fast = crate::hypothesis_switch::torus_fast();
        Self {
            recognition,
            policy: ConversionPolicy::AllowFacetedFallback,
            try_kernel_analytic_rebuild: true,
            try_hybrid_rebuild: true,
            weld_tolerance: -1.0,
            coordinate_precision_tolerance: 0.0,
            kernel_deflection_angle_degrees: 30.0,
            kernel_fit_tolerance: 1.0e-3,
            kernel_normal_tolerance_degrees: 15.0,
        }
    }
}

/// Topology path used to produce the final STEP body.
#[derive(Clone, Copy, Debug, PartialEq, Eq, Deserialize, Serialize)]
#[serde(rename_all = "snake_case")]
pub enum ConversionBackend {
    /// Exact full sphere from the RANSAC carrier.
    RansacSphere,
    /// Exact full ring torus from the RANSAC carrier.
    RansacTorus,
    /// Exact cylinder wall and caps from RANSAC carriers.
    RansacCappedCylinder,
    /// Exact cone wall and cap or caps from RANSAC carriers.
    RansacCappedCone,
    /// The kernel segmentation proved full plane/cylinder/cone coverage and
    /// the kernel region rebuilder built the shell from it.
    KernelAnalyticRebuild,
    /// A mesh boolean cut spherical facets; precise carriers and bidirectional
    /// mesh coverage proved a primitive union rebuilt with analytic CSG trims.
    KernelSphericalUnion,
    /// A conservative local topology builder reconstructed a complete shell
    /// with exact plane/cylinder/cone/sphere regions and faceted unsupported regions.
    #[serde(alias = "hybrid_plane_cylinder_rebuild")]
    HybridAnalyticRebuild,
    /// Complete source triangles were preserved through mesh repair.
    FacetedRepair,
    /// Complete source triangles were repaired, then adjacent coplanar
    /// triangle faces were safely coalesced by the kernel.
    FacetedRepairCoplanarMerged,
    /// No body: every lane, faceted repair included, refused this component
    /// of a multi-body mesh. It is NOT in the STEP document; its record's
    /// `refusal` says why. The document's own backend is never this.
    Refused,
}

/// Human- and machine-readable details for one RANSAC region.
#[derive(Clone, Debug, Deserialize, Serialize)]
pub struct ConversionRegionReport {
    /// Selected analytic family.
    pub surface_type: SurfaceType,
    /// Fitted carrier parameters.
    pub surface: AnalyticSurface,
    /// Number of supporting input triangles.
    pub support_triangles: usize,
    /// Total area of the supporting triangles.
    pub supported_area: f64,
    /// Root-mean-square positional residual.
    pub rms_error: f64,
    /// Maximum positional residual.
    pub max_error: f64,
    /// Root-mean-square normal residual, in radians.
    pub rms_normal_error_radians: f64,
    /// Maximum normal residual, in radians.
    pub max_normal_error_radians: f64,
    /// Residual-evidence confidence score.
    pub confidence: f64,
    /// Carrier orientation relative to mesh winding.
    pub orientation: i8,
    /// Recognition-path explanation.
    pub reason: String,
    /// Production recognizer's detailed phase measurements.
    pub phase_timings: PhaseTimings,
}

/// Wall-clock measurements for conversion stages.
#[derive(Clone, Copy, Debug, Default, Deserialize, Serialize)]
pub struct ConversionTimings {
    /// Time spent in the kernel mesh segmentation that gates recognition.
    #[serde(default)]
    pub segmentation_seconds: f64,
    /// Time spent in RANSAC recognition; zero when it was skipped.
    pub recognition_seconds: f64,
    /// Time spent building and validating in-memory topology.
    pub topology_build_seconds: f64,
    /// Time spent serializing STEP.
    pub step_export_seconds: f64,
    /// Time spent auditing and round-trip importing STEP.
    pub step_validation_seconds: f64,
    /// End-to-end conversion time.
    pub total_seconds: f64,
}

/// Face and source-triangle accounting for a mixed analytic/faceted rebuild.
#[derive(Clone, Copy, Debug, Default, Deserialize, Serialize)]
pub struct HybridConversionReport {
    /// Total output BREP faces.
    pub total_faces: usize,
    /// Exact analytic plane faces.
    pub analytic_plane_faces: usize,
    /// Source triangles represented by analytic plane faces.
    pub analytic_plane_triangles: usize,
    /// Exact analytic cylinder faces.
    pub analytic_cylinder_faces: usize,
    /// Source triangles represented by analytic cylinder faces.
    pub analytic_cylinder_triangles: usize,
    /// Exact analytic cone faces.
    #[serde(default)]
    pub analytic_cone_faces: usize,
    /// Source triangles represented by analytic cone faces.
    #[serde(default)]
    pub analytic_cone_triangles: usize,
    /// Exact analytic sphere faces.
    #[serde(default)]
    pub analytic_sphere_faces: usize,
    /// Source triangles represented by analytic sphere faces.
    #[serde(default)]
    pub analytic_sphere_triangles: usize,
    /// Exact analytic torus faces.
    #[serde(default)]
    pub analytic_torus_faces: usize,
    /// Source triangles represented by analytic torus faces.
    #[serde(default)]
    pub analytic_torus_triangles: usize,
    /// Coplanar planar faces retained for unsupported or unsafe regions.
    pub faceted_faces: usize,
    /// Source triangles represented by those coplanar fallback faces.
    pub faceted_triangles: usize,
    /// Segmented analytic regions conservatively demoted to facets.
    pub demoted_regions: usize,
    /// Source triangles in demoted regions.
    pub demoted_triangles: usize,
    /// Plane regions found by the independent topology segmentation.
    pub segmentation_plane_regions: usize,
    /// Cylinder regions found by the independent topology segmentation.
    pub segmentation_cylinder_regions: usize,
    /// Cone regions found by the independent topology segmentation.
    #[serde(default)]
    pub segmentation_cone_regions: usize,
    /// Sphere regions found by the independent topology segmentation.
    #[serde(default)]
    pub segmentation_sphere_regions: usize,
    /// Torus regions found by the independent topology segmentation.
    #[serde(default)]
    pub segmentation_torus_regions: usize,
    /// Unsupported regions found by the independent topology segmentation.
    pub segmentation_unsupported_regions: usize,
}

/// Lane V row 1: why the mixed builder demoted a recognised analytic region.
/// The edge causes come from the boundary check before any surface is built
/// (`local_regions`); the others are the build stage whose localized failure
/// forced the demotion and a retry.
#[derive(Clone, Copy, Debug, PartialEq, Eq, PartialOrd, Ord, Hash, Deserialize, Serialize)]
#[serde(rename_all = "snake_case")]
pub enum DemotionCause {
    /// A shared edge with a retained cone (or cylinder) is not a coaxial ring.
    CylinderConeEdge,
    /// Two cylinders meet in neither a shared ruling nor an equal-radius crossing.
    CylinderCylinderEdge,
    /// A sphere edge with a retained revolve is not a coaxial ring.
    SphereRingEdge,
    /// A torus edge with a retained revolve is not a coaxial ring.
    TorusRingEdge,
    /// Two cones meet in other than a coaxial ring.
    ConeConeEdge,
    /// A revolve pair with no exact-edge rule.
    SameKindRevolveEdge,
    /// An edge with a segmented plane is not that plane's section.
    PlaneNeighbourEdge,
    /// An edge with an unsupported region's facet is not in the facet's plane.
    FacetNeighbourEdge,
    /// Recursive demotion: the neighbour revolve was demoted to facets and the
    /// shared edge is not a ruling.
    DemotedNeighbourNotRuling,
    /// Snapping a cylinder axis to its planar trims failed.
    CylinderAxisSnap,
    /// Snapping a cone carrier failed.
    ConeSnap,
    /// A pointed or zero-span cone.
    ConeSpan,
    /// Building the cylinder surface failed.
    CylinderSurface,
    /// No single parameter seam avoids every trim of a cylinder.
    PeriodicSeam,
    /// Building the cone surface failed.
    ConeSurface,
    /// Building the sphere surface failed.
    SphereSurface,
    /// Building the torus surface failed.
    TorusSurface,
    /// A chain edge failed; blamed on its sphere or torus side.
    ChainEdgeCurved,
    /// A chain edge failed; blamed on its cone side.
    ChainEdgeCone,
    /// A chain edge failed; blamed on its cylinder side.
    ChainEdgeCylinder,
    /// A chain between non-revolves failed; blamed on the revolve whose chain
    /// first placed one of its end vertices.
    ChainEdgeVertexPlacer,
    /// Building the cylinder face failed.
    CylinderFace,
    /// Building the cone face failed.
    ConeFace,
    /// Building the sphere face failed.
    SphereFace,
    /// Building the torus face failed.
    TorusFace,
    /// The assembled shell failed a whole-body check with fitted-pcurve
    /// regions on it; those regions were demoted together.
    WholeBodyCheck,
    /// A test-injected failure.
    Injected,
}

/// The carrier kind a demoted region had.
#[derive(Clone, Copy, Debug, PartialEq, Eq, PartialOrd, Ord, Hash, Deserialize, Serialize)]
#[serde(rename_all = "snake_case")]
pub enum DemotedKind {
    /// Cylinder carrier.
    Cylinder,
    /// Cone carrier.
    Cone,
    /// Sphere carrier.
    Sphere,
    /// Torus carrier.
    Torus,
}

/// One demoted region of a mixed analytic/faceted rebuild.
#[derive(Clone, Debug, PartialEq, Eq, Deserialize, Serialize)]
pub struct HybridDemotion {
    /// Segmentation region id.
    pub region: u32,
    /// Its carrier kind.
    pub kind: DemotedKind,
    /// Its source triangles.
    pub triangles: usize,
    /// Why it was demoted.
    pub cause: DemotionCause,
    /// The cause at the start of a recursive demotion chain: the neighbour's
    /// root cause for `DemotedNeighbourNotRuling`, otherwise `cause`.
    pub root_cause: DemotionCause,
    /// The neighbouring region across the failing edge, for an edge cause.
    pub neighbour: Option<u32>,
    /// Boundary-check round that demoted it, from 1; 0 for a forced demotion.
    pub round: usize,
    /// The builder's message, for a forced demotion.
    pub message: Option<String>,
}

/// One body of the document: a single vertex-connected component of the input
/// mesh, reconstructed on its own.
#[derive(Clone, Debug, Deserialize, Serialize)]
pub struct ComponentConversionReport {
    /// Position in the document, counting from zero.
    pub index: usize,
    /// The lowest source triangle index this component holds; what orders the
    /// bodies, and what names one in a refusal.
    pub first_triangle: usize,
    /// Vertices of this component's recognition mesh.
    pub input_vertices: usize,
    /// Triangles of this component.
    pub input_triangles: usize,
    /// Topology construction path this body took.
    pub backend: ConversionBackend,
    /// Explanation of why that backend was selected.
    pub backend_reason: String,
    /// Why an analytic backend was unavailable, for a faceted body.
    pub fallback_cause: Option<String>,
    /// Why RANSAC recognition did not run for this body; `None` when it ran.
    pub recognition_skipped: Option<String>,
    /// Accepted analytic regions for this body.
    pub recognized_regions: usize,
    /// Triangles assigned to those regions.
    pub recognized_triangles: usize,
    /// Non-degenerate triangles left unresolved.
    pub unresolved_triangles: usize,
    /// Whether this component alone is a consistently wound closed manifold.
    pub source_closed_manifold: bool,
    /// Whether the analytic lanes ran on the REPAIRED mesh because the source
    /// was not a closed two-manifold. The `input_*` counts above are always
    /// the source's. This says only which mesh the lanes were given, never
    /// that one of them succeeded — `backend` says that.
    #[serde(default)]
    pub analytic_used_repaired_mesh: bool,
    /// Mixed analytic/faceted accounting for this body.
    pub hybrid_rebuild: Option<HybridConversionReport>,
    /// Lane V row 1: why each region the mixed builder demoted was demoted;
    /// their triangles sum to `hybrid_rebuild.demoted_triangles`.
    #[serde(default)]
    pub hybrid_demotions: Vec<HybridDemotion>,
    /// Face count immediately after faceted repair, when that path was used.
    pub faceted_faces_before_merge: Option<usize>,
    /// Face count after the safe coplanar merge attempt.
    pub faceted_faces_after_merge: Option<usize>,
    /// BREP faces of the constructed solid.
    pub faces: usize,
    /// Why this body is NOT in the document: every lane refused it, and the
    /// other bodies were built without it. `None` for every built body.
    #[serde(default)]
    pub refusal: Option<String>,
    /// The source's own name for this body (a 3MF object's `name`), when the
    /// caller knows it. The converter never sets it.
    #[serde(default)]
    pub source_name: Option<String>,
}

/// Detailed conversion outcome suitable for terminal or JSON reporting.
///
/// Counts are TOTALS over every body and `regions` is their concatenation. The
/// fields that can only describe one body — `backend`, `topology_refit`, the
/// recognition tolerances — are the FIRST body's; `components` is the per-body
/// record, and `backend_reason` names every body when there is more than one.
#[derive(Clone, Debug, Deserialize, Serialize)]
pub struct StlConversionReport {
    /// Topology construction path used.
    pub backend: ConversionBackend,
    /// Explanation of why the backend was selected.
    pub backend_reason: String,
    /// Why an analytic backend was unavailable, for faceted output.
    pub fallback_cause: Option<String>,
    /// Number of vertices in the recognition mesh.
    pub input_vertices: usize,
    /// Number of triangles in the input.
    pub input_triangles: usize,
    /// Number of accepted analytic regions.
    pub recognized_regions: usize,
    /// Number of triangles assigned to analytic regions.
    pub recognized_triangles: usize,
    /// Number of non-degenerate triangles left unresolved.
    pub unresolved_triangles: usize,
    /// Why RANSAC recognition did not run; `None` when it ran. The region
    /// counts above are zero when this is set.
    #[serde(default)]
    pub recognition_skipped: Option<String>,
    /// Whether indexed input topology is a consistently wound closed manifold.
    pub source_closed_manifold: bool,
    /// Whether ANY body's analytic lanes ran on a repaired mesh because the
    /// source was not a closed two-manifold. Which mesh they were given, not
    /// whether one of them succeeded.
    #[serde(default)]
    pub analytic_used_repaired_mesh: bool,
    /// Absolute recognition distance requested by the caller.
    #[serde(default)]
    pub requested_distance_tolerance: f64,
    /// Minimum distance imposed by the coordinate encoding.
    #[serde(default)]
    pub coordinate_precision_tolerance: f64,
    /// Absolute distance actually supplied to recognition.
    #[serde(default)]
    pub effective_distance_tolerance: f64,
    /// Accepted region count by analytic family name.
    pub region_type_counts: BTreeMap<String, usize>,
    /// Per-region carrier and quality diagnostics.
    pub regions: Vec<ConversionRegionReport>,
    /// Topology-informed production refit used by a direct backend, when the
    /// initially selected carrier was an observational limiting family.
    pub topology_refit: Option<ConversionRegionReport>,
    /// Detailed accounting when the mixed analytic builder was used. With
    /// several bodies this sums every body that took that backend.
    #[serde(default)]
    pub hybrid_rebuild: Option<HybridConversionReport>,
    /// Lane V row 1: every body's demotion records, in document order.
    #[serde(default)]
    pub hybrid_demotions: Vec<HybridDemotion>,
    /// One record per body, in document order — the authoritative per-body
    /// account when the input held several closed shells. Always populated;
    /// a single-body conversion has exactly one entry.
    #[serde(default)]
    pub components: Vec<ComponentConversionReport>,
    /// Serialized STEP document size.
    pub exported_step_bytes: usize,
    /// Number of serialized `ADVANCED_FACE` entities.
    pub exported_advanced_faces: usize,
    /// Face count immediately after faceted repair, when that path was used.
    #[serde(default)]
    pub faceted_faces_before_merge: Option<usize>,
    /// Face count after the safe coplanar merge attempt, when faceted repair
    /// was used. This equals `faceted_faces_before_merge` if no merge was
    /// possible or the validated merge was unavailable.
    #[serde(default)]
    pub faceted_faces_after_merge: Option<usize>,
    /// Number of solids recovered by round-trip STEP import.
    pub roundtrip_solids: usize,
    /// Serialized manifold audit issues; empty on every successful result.
    pub manifold_audit_issues: Vec<String>,
    /// Stage and total wall-clock measurements.
    pub timings: ConversionTimings,
    /// Counted RANSAC recognition work, summed over every body.
    #[serde(default)]
    pub recognition_work: RecognitionWorkReport,
    /// Row 11's local scan on whole carriers (lane J row 13), summed.
    #[serde(default)]
    pub whole_carrier_scan: WholeCarrierScanReport,
    /// Useful chronological terminal messages.
    pub messages: Vec<String>,
}

/// Counted work of the top-level RANSAC recognition.
#[derive(Clone, Copy, Debug, Default, PartialEq, Eq, Deserialize, Serialize)]
pub struct RecognitionWorkReport {
    /// Generic hypotheses drawn.
    pub hypotheses: usize,
    /// Regions accepted by generic extraction.
    pub rounds: usize,
    /// Connected components accepted whole on the segmentation's own carrier
    /// after their own whole fit was refused (lane J row 12).
    pub seeded_components: usize,
}

/// Lane J row 13: verdicts of row 11's local residual scan on the carriers
/// of a whole primitive (RANSAC's direct builders and the segmentation's
/// whole sphere or torus). An abstention is not a pass: the residuals were
/// not independent noise (or too few to tell), so the scan could not decide
/// and the build went ahead as before.
#[derive(Clone, Copy, Debug, Default, PartialEq, Eq, Deserialize, Serialize)]
pub struct WholeCarrierScanReport {
    /// Carriers the scan read at or under its threshold.
    pub accepted: usize,
    /// Carriers the scan withheld from a whole-primitive build.
    pub declined: usize,
    /// Carriers above the threshold whose residuals failed the independence test.
    pub abstained: usize,
}

impl WholeCarrierScanReport {
    pub(crate) fn add(&mut self, verdict: crate::hybrid_whole_freeform::ScanVerdict) {
        use crate::hybrid_whole_freeform::ScanVerdict;
        match verdict {
            ScanVerdict::Accepted => self.accepted += 1,
            ScanVerdict::Declined => self.declined += 1,
            ScanVerdict::Abstained => self.abstained += 1,
        }
    }

    fn sum(self, other: Self) -> Self {
        Self {
            accepted: self.accepted + other.accepted,
            declined: self.declined + other.declined,
            abstained: self.abstained + other.abstained,
        }
    }
}

/// STEP text and its complete conversion report.
#[derive(Clone, Debug, Deserialize, Serialize)]
pub struct StlConversionOutput {
    /// Validated AP242 STEP Part 21 document.
    pub step_text: String,
    /// Detailed conversion outcome.
    pub report: StlConversionReport,
}

/// A conversion failure. The message is intentionally ready for terminal use.
#[derive(Clone, Debug, PartialEq, Eq)]
pub struct StlConversionError(pub String);

impl Display for StlConversionError {
    fn fmt(&self, formatter: &mut Formatter<'_>) -> std::fmt::Result {
        formatter.write_str(&self.0)
    }
}

impl std::error::Error for StlConversionError {}

impl From<String> for StlConversionError {
    fn from(value: String) -> Self {
        Self(value)
    }
}

/// Returns a conservative positional-error bound for binary STL coordinates.
///
/// Binary STL stores each coordinate as an IEEE-754 `f32`. For a normally
/// sized finite value, round-to-nearest introduces at most half a relative
/// `f32` epsilon per coordinate. Multiplying the largest absolute coordinate
/// by that bound and by `sqrt(3)` covers simultaneous x/y/z rounding. The
/// model diagonal is also considered so origin-centered geometry receives a
/// useful scale-aware floor. This is deliberately a source-encoding bound,
/// not a general modeling tolerance.
pub fn binary_stl_coordinate_precision_tolerance(mesh: &Mesh) -> f64 {
    let maximum_absolute_coordinate = mesh
        .vertices
        .iter()
        .flat_map(|point| [point.x.abs(), point.y.abs(), point.z.abs()])
        .fold(0.0_f64, f64::max);
    let coordinate_scale = maximum_absolute_coordinate.max(mesh_diagonal(mesh));
    coordinate_scale * (f32::EPSILON as f64) * 0.5 * 3.0_f64.sqrt()
}

/// Recognize a parsed STL mesh and serialize a validated AP242 STEP document.
///
/// Each vertex-connected shell is reconstructed independently. Closed inward
/// shells contained by an outward component are restored as cavities of that
/// body; other components remain independent solids. STEP round-trip validation
/// certifies the assembled cavity topology and containment.
///
/// `source_positions` and `source_indices` must describe the same triangles
/// represented by `mesh`. They are kept separately because an STL reader may
/// preserve the original triangle soup while welding a second copy for robust
/// recognition. The original buffers are always used by faceted repair.
pub fn convert_stl_mesh_to_step(
    mesh: &Mesh,
    source_positions: &[f64],
    source_indices: Option<&[u32]>,
    options: &StlConversionOptions,
    part_name: &str,
    unit: &str,
    timestamp: &str,
) -> Result<StlConversionOutput, StlConversionError> {
    convert_stl_mesh_to_step_with_colors(
        mesh,
        source_positions,
        source_indices,
        None,
        options,
        part_name,
        unit,
        timestamp,
    )
}

/// [`convert_stl_mesh_to_step`] with the source triangles' COLOURS carried
/// onto the reconstructed bodies and faces as the STEP document's presentation
/// styles. `triangle_colors`, when given, is parallel to `mesh.triangles`
/// (8-bit sRGB, `None` for an uncoloured triangle — a 3MF's base materials, see
/// `brep_kernel::ThreeMfReadResult::triangle_colors`); each body takes the
/// colour most of its triangles carry and a face whose own plurality differs is
/// styled on its own, matched by geometry since the triangles themselves do
/// not survive (`stl_conversion/colors.rs`). `None`, or a slice with no colour
/// in it, is exactly [`convert_stl_mesh_to_step`].
#[allow(clippy::too_many_arguments)]
pub fn convert_stl_mesh_to_step_with_colors(
    mesh: &Mesh,
    source_positions: &[f64],
    source_indices: Option<&[u32]>,
    triangle_colors: Option<&[Option<[u8; 3]>]>,
    options: &StlConversionOptions,
    part_name: &str,
    unit: &str,
    timestamp: &str,
) -> Result<StlConversionOutput, StlConversionError> {
    let total_started = Instant::now();
    validate_source_buffers(mesh, source_positions, source_indices)?;
    if !options.coordinate_precision_tolerance.is_finite()
        || options.coordinate_precision_tolerance < 0.0
    {
        return Err(StlConversionError(
            "coordinate_precision_tolerance must be finite and non-negative".to_owned(),
        ));
    }

    let components = triangle_components(mesh);
    let count = components.len();
    if count == 0 {
        return Err(StlConversionError(
            "the mesh contains no triangles to reconstruct".to_owned(),
        ));
    }

    let mut solids = Vec::with_capacity(count);
    let mut component_ids = Vec::with_capacity(count);
    let mut details = Vec::with_capacity(count);
    let mut first_refusal = None;
    for (index, triangles) in components.iter().enumerate() {
        if count == 1 {
            let built = convert_component(mesh, source_positions, source_indices, options)?;
            solids.push(built.0);
            component_ids.push(index);
            details.push(built.1);
            continue;
        }
        let part = component_mesh(mesh, source_positions, source_indices, triangles);
        match convert_component(
            &part.mesh,
            &part.positions,
            part.indices.as_deref(),
            options,
        ) {
            Ok(built) => {
                solids.push(built.0);
                component_ids.push(index);
                details.push(built.1);
            }
            // One body that no lane can build — faceted repair included —
            // must not sink the others: it is left out of the document and
            // its record says why, by body and first source triangle.
            Err(error) => {
                first_refusal.get_or_insert_with(|| {
                    format!(
                        "body {} of {count} (from source triangle {}, {} triangle(s)): {error}",
                        index + 1,
                        triangles[0],
                        triangles.len()
                    )
                });
                details.push(refused_component(&part.mesh, triangles.len(), error.0));
            }
        }
    }
    // Nothing survived: the first body's refusal is the import's.
    if solids.is_empty() {
        let refusal = first_refusal.unwrap_or_default();
        return Err(StlConversionError(if count > 1 {
            format!("{refusal} (every one of the {count} bodies was refused)")
        } else {
            refusal
        }));
    }

    let (mut solids, cavity_messages) = cavities::assemble(mesh, &components, solids, &component_ids)?;
    let export_started = Instant::now();
    // Colours, when the source has any: decided by geometry against the
    // finished solids, then written as presentation styles keyed by the body
    // and face names the pass assigns.
    let colored = triangle_colors.filter(|colors| colors.iter().any(Option::is_some));
    let mut color_message = None;
    let step_text = match colored {
        Some(triangle_colors) => {
            let assignment = colors::assign(mesh, triangle_colors, &mut solids, part_name)?;
            let named: Vec<(String, &brep_kernel::BrepSolid)> =
                assignment.body_names.iter().cloned().zip(solids.iter()).collect();
            color_message = Some(format!(
                "source colours: {} of {} bodies and {} faces styled; {} coloured source triangles matched no face",
                assignment.bodies,
                solids.len(),
                assignment.faces,
                assignment.unmatched
            ));
            brep_kernel::export_step_report_named(
                &named,
                part_name,
                unit,
                timestamp,
                None,
                Some(&assignment.colors),
            )
            .map(|report| report.text)
        }
        None => export_step(&solids, part_name, unit, timestamp),
    }
    .map_err(|error| StlConversionError(format!("STEP export failed: {error}")))?;
    let step_export_seconds = export_started.elapsed().as_secs_f64();

    let validation_started = Instant::now();
    let manifold_audit_issues = audit_step_manifold(&step_text);
    if !manifold_audit_issues.is_empty() {
        return Err(StlConversionError(format!(
            "STEP manifold audit failed: {}",
            manifold_audit_issues.join("; ")
        )));
    }
    let imported = import_step(&step_text).map_err(|error| {
        StlConversionError(format!("STEP round-trip validation failed: {error}"))
    })?;
    if let Some(issues) = imported
        .iter()
        .map(|solid| solid.validate())
        .find(|issues| !issues.is_empty())
    {
        return Err(StlConversionError(format!(
            "round-tripped STEP has invalid topology: {issues:?}"
        )));
    }
    if imported.len() != solids.len() {
        return Err(StlConversionError(format!(
            "{} body/bodies were written but {} came back out of the STEP document",
            solids.len(),
            imported.len()
        )));
    }
    let step_validation_seconds = validation_started.elapsed().as_secs_f64();

    let mut report = aggregate_report(&components, details, count, options);
    report.messages.extend(cavity_messages);
    report.messages.extend(color_message);
    report.messages.push(format!(
        "STEP manifold audit and round-trip import passed for {} solid(s)",
        imported.len()
    ));
    report.messages.push(report.backend_reason.clone());
    report.exported_step_bytes = step_text.len();
    report.exported_advanced_faces = step_text.matches("ADVANCED_FACE(").count();
    report.roundtrip_solids = imported.len();
    report.manifold_audit_issues = manifold_audit_issues;
    report.timings.step_export_seconds = step_export_seconds;
    report.timings.step_validation_seconds = step_validation_seconds;
    report.timings.total_seconds = total_started.elapsed().as_secs_f64();
    Ok(StlConversionOutput { step_text, report })
}

/// The record of a body every lane refused: its source counts, the refusal,
/// and nothing else — it contributes no face, region or timing, and no solid.
fn refused_component(mesh: &Mesh, triangles: usize, reason: String) -> ComponentDetail {
    ComponentDetail {
        backend: ConversionBackend::Refused,
        backend_reason: format!("refused, not in the model: {reason}"),
        fallback_cause: None,
        input_vertices: mesh.vertices.len(),
        input_triangles: triangles,
        recognized_regions: 0,
        recognized_triangles: 0,
        unresolved_triangles: 0,
        recognition_skipped: None,
        source_closed_manifold: closed_manifold(mesh),
        analytic_used_repaired_mesh: false,
        requested_distance_tolerance: 0.0,
        effective_distance_tolerance: 0.0,
        region_type_counts: BTreeMap::new(),
        regions: Vec::new(),
        topology_refit: None,
        hybrid_rebuild: None,
        hybrid_demotions: Vec::new(),
        faceted_faces_before_merge: None,
        faceted_faces_after_merge: None,
        faces: 0,
        segmentation_seconds: 0.0,
        recognition_seconds: 0.0,
        recognition_work: RecognitionWorkReport::default(),
        whole_carrier_scan: WholeCarrierScanReport::default(),
        topology_build_seconds: 0.0,
        messages: vec![format!("refused, not in the model: {reason}")],
        refusal: Some(reason),
    }
}

/// Everything one component contributes to the document's report, plus the
/// per-body record the report publishes.
struct ComponentDetail {
    backend: ConversionBackend,
    backend_reason: String,
    fallback_cause: Option<String>,
    input_vertices: usize,
    input_triangles: usize,
    recognized_regions: usize,
    recognized_triangles: usize,
    unresolved_triangles: usize,
    recognition_skipped: Option<String>,
    source_closed_manifold: bool,
    analytic_used_repaired_mesh: bool,
    requested_distance_tolerance: f64,
    effective_distance_tolerance: f64,
    region_type_counts: BTreeMap<String, usize>,
    regions: Vec<ConversionRegionReport>,
    topology_refit: Option<ConversionRegionReport>,
    hybrid_rebuild: Option<HybridConversionReport>,
    hybrid_demotions: Vec<HybridDemotion>,
    faceted_faces_before_merge: Option<usize>,
    faceted_faces_after_merge: Option<usize>,
    faces: usize,
    segmentation_seconds: f64,
    recognition_seconds: f64,
    recognition_work: RecognitionWorkReport,
    whole_carrier_scan: WholeCarrierScanReport,
    topology_build_seconds: f64,
    messages: Vec<String>,
    /// Why every lane refused this body; set only by [`refused_component`].
    refusal: Option<String>,
}

/// ONE body: the complete mesh-to-BREP chain over a single closed shell,
/// stopping at the validated solid. Export, the manifold audit and the STEP
/// round trip belong to the document and run once over every body.
fn convert_component(
    mesh: &Mesh,
    source_positions: &[f64],
    source_indices: Option<&[u32]>,
    options: &StlConversionOptions,
) -> Result<(brep_kernel::BrepSolid, ComponentDetail), StlConversionError> {
    // Reconstruct each closed shell outward; assembly restores inward shells
    // as cavities after their analytic topology has been validated.
    let outward = cavities::outward_component(mesh, source_positions, source_indices);
    let (mesh, source_positions, source_indices) = match &outward {
        Some(part) => (&part.mesh, part.positions.as_slice(), part.indices.as_deref()),
        None => (mesh, source_positions, source_indices),
    };
    let mut recognition_options = options.recognition.clone();
    recognition_options.collect_phase_timings = true;
    let requested_distance_tolerance = recognition_options.distance_tolerance;
    recognition_options.distance_tolerance = recognition_options
        .distance_tolerance
        .max(options.coordinate_precision_tolerance);
    let encoding_distance_tolerance = recognition_options.distance_tolerance;

    let source_closed_manifold = closed_manifold(mesh);
    let input_vertices = mesh.vertices.len();
    let input_triangles = mesh.triangles.len();
    // A mesh file is routinely a few triangles short of a closed
    // two-manifold — one dropped facet, a duplicated sheet, a degenerate
    // sliver — and EVERY analytic lane below requires one. The faceted
    // fallback already repairs exactly that and builds a valid closed solid
    // from the result, so the repaired mesh is offered to the analytic lanes
    // first instead of letting a handful of stray triangles cost the body
    // every cylinder, cone and sphere the segmentation can see. A closed
    // source is never repaired, so its conversion is unchanged.
    let repaired = if source_closed_manifold {
        None
    } else {
        repaired_closed_mesh(source_positions, source_indices, options)
    };
    let (mesh, source_positions, source_indices) = match &repaired {
        Some(repaired) => (
            &repaired.mesh,
            repaired.positions.as_slice(),
            Some(repaired.indices.as_slice()),
        ),
        None => (mesh, source_positions, source_indices),
    };
    // What the lanes below may assume, as opposed to what the FILE was;
    // `source_closed_manifold` stays the report's record of the input.
    let closed_for_analytics = source_closed_manifold || repaired.is_some();

    let segmentation_started = Instant::now();
    let segmentation = if closed_for_analytics {
        gate_segmentation(source_positions, source_indices, options)
    } else {
        Err("the source mesh is not a closed two-manifold".to_owned())
    };
    let segmentation_seconds = segmentation_started.elapsed().as_secs_f64();
    let initial_recognition_gate = recognition_gate(&segmentation);
    let geometric_gate_rescue = initial_recognition_gate.is_err()
        && closed_for_analytics
        && segmentation.as_ref().is_ok_and(|segmentation| {
            primitive_gate::has_whole_primitive_candidate(mesh, segmentation, &recognition_options)
        });
    let recognition_gate = if geometric_gate_rescue {
        Ok(())
    } else {
        initial_recognition_gate
    };
    // The encoding floor above bounds only what storing a coordinate cost.
    // An exporter can snap vertices far more coarsely than that — OpenSCAD's
    // spheres, cylinders AND flat caps sit ~6e-5 off their carriers where
    // f32 accounts for ~4e-6 — and RANSAC held below the data's own noise
    // shreds one sphere into slivers, costs minutes doing it, and never proves
    // the coverage its lanes need. When the gate passes, the segmentation has
    // already fitted every region and measured how far every VERTEX sits from
    // its carrier, so recognition is not asked to be tighter than that.
    let measured_region_deviation = match (&recognition_gate, &segmentation) {
        (Ok(()), Ok(segmentation)) => segmentation
            .regions
            .iter()
            .map(|region| region.max_deviation)
            .fold(0.0_f64, f64::max),
        _ => 0.0,
    };
    recognition_options.distance_tolerance = recognition_options
        .distance_tolerance
        .max(measured_region_deviation);
    let effective_distance_tolerance = recognition_options.distance_tolerance;

    let recognition_started = Instant::now();
    let mut recognition_work = RecognitionWorkReport::default();
    let (recognition, completed_plane_regions, completed_degenerate_triangles) = if recognition_gate.is_ok() {
        let candidates = match &segmentation {
            Ok(segmentation) if segment_carrier_enabled() => segmentation_candidates(mesh, segmentation),
            _ => Vec::new(),
        };
        let (mut recognition, work) =
            recognize_surfaces_with_candidates(mesh, &recognition_options, &candidates)
                .map_err(|error| {
                    StlConversionError(format!("surface recognition failed: {error}"))
                })?;
        recognition_work = RecognitionWorkReport {
            hypotheses: work.attempts,
            rounds: work.rounds,
            seeded_components: work.seeded_components,
        };
        feature_fragments::complete(
            mesh,
            &recognition_options,
            &mut recognition.regions,
            &mut recognition.unresolved_triangles,
        )?;
        let completed_plane_regions = complete_small_planar_regions(
            mesh,
            &recognition_options,
            &mut recognition.regions,
            &mut recognition.unresolved_triangles,
        )?;
        let completed_degenerate_triangles = degenerate_coverage::complete(
            mesh, &recognition_options, &mut recognition.regions,
        )?;
        (recognition, completed_plane_regions, completed_degenerate_triangles)
    } else {
        (
            crate::RecognitionResult {
                regions: Vec::new(),
                unresolved_triangles: Vec::new(),
                unresolved_diagnostics: Vec::new(),
            },
            0,
            0,
        )
    };
    let recognition_seconds = if recognition_gate.is_ok() {
        recognition_started.elapsed().as_secs_f64()
    } else {
        0.0
    };
    let recognized_triangles = recognition
        .regions
        .iter()
        .map(|region| region.triangle_indices.len())
        .sum();
    let regions = recognition
        .regions
        .iter()
        .map(region_report)
        .collect::<Vec<_>>();
    let mut region_type_counts = BTreeMap::new();
    for region in &recognition.regions {
        *region_type_counts
            .entry(region.surface.surface_type().name().to_owned())
            .or_insert(0) += 1;
    }

    let topology_started = Instant::now();
    let analytic_coverage = recognition.unresolved_triangles.is_empty()
        && recognized_triangles == mesh.triangles.len()
        && disjoint_complete_partition(&recognition.regions, mesh.triangles.len());
    let spherical_union = if closed_for_analytics && options.try_kernel_analytic_rebuild {
        segmentation.as_ref().ok().and_then(|seg| {
            brep_kernel::reconstruct_spherical_mesh_union(
                source_positions,
                source_indices.unwrap_or(&[]),
                seg,
                &segmentation_options(source_positions, options),
            )
        })
    } else {
        None
    };
    // Lane J row 12: a component accepted on the segmentation's carrier is a
    // noisy one (its own refit missed the tolerance the noise set), and the
    // direct capped builders place their caps at the EXTREME vertex heights
    // along the axis, which jitter biases outward. Such a body takes the
    // rebuild lanes below, as it did when generic extraction shredded it;
    // recognition only got cheaper.
    let mut whole_carrier_scan = WholeCarrierScanReport::default();
    let primitive = if analytic_coverage
        && closed_for_analytics
        && recognition_work.seeded_components == 0
        && whole_fits_pass_the_local_scan(mesh, &recognition.regions, encoding_distance_tolerance, &mut whole_carrier_scan)
    {
        direct_analytic_solid(mesh, &recognition.regions, &recognition_options)
    } else {
        None
    };

    let mut fallback_cause = None;
    let mut messages = vec![match &recognition_gate {
        Ok(()) => format!(
            "RANSAC recognized {} region(s) covering {recognized_triangles}/{} triangles",
            recognition.regions.len(),
            mesh.triangles.len()
        ),
        Err(reason) => format!("RANSAC recognition skipped: {reason}"),
    }];
    if geometric_gate_rescue {
        messages.push("whole-primitive recognition enabled by triangle coverage on a segmented curved carrier and its possible end caps".to_owned());
    }
    if outward.is_some() {
        messages.push("inward source shell reconstructed outward before cavity assembly".into());
    }
    if let Some(repaired) = &repaired {
        messages.push(repaired.message.clone());
    }
    if encoding_distance_tolerance > requested_distance_tolerance {
        messages.push(format!(
            "source coordinate precision raised the absolute recognition distance from {requested_distance_tolerance:.6e} to {encoding_distance_tolerance:.6e}"
        ));
    }
    if effective_distance_tolerance > encoding_distance_tolerance {
        messages.push(format!(
            "the segmentation's measured vertex deviation raised the absolute recognition distance from {encoding_distance_tolerance:.6e} to {effective_distance_tolerance:.6e}"
        ));
    }
    if completed_degenerate_triangles > 0 {
        messages.push(format!(
            "attached {completed_degenerate_triangles} numerically degenerate triangle(s) to their surrounding fitted carrier; excluded from fit support metrics"
        ));
    }
    if completed_plane_regions > 0 {
        messages.push(format!(
            "a plane-only completion pass recovered {completed_plane_regions} small feature-bounded planar region(s)"
        ));
    }

    let mut hybrid_demotions = Vec::new();
    let (
        solid,
        backend,
        backend_reason,
        topology_refit,
        hybrid_rebuild,
        faceted_faces_before_merge,
        faceted_faces_after_merge,
    ) = if let Some(primitive) = primitive {
        (
            primitive.solid?,
            primitive.backend,
            primitive.reason,
            primitive.topology_refit,
            None,
            None,
            None,
        )
    } else if let Some(solid) = spherical_union {
        (
            solid,
            ConversionBackend::KernelSphericalUnion,
            "precise sphere carriers and bidirectional mesh coverage verified a primitive union; rebuilt exact analytic intersections across the mesh boolean cut strips".to_owned(),
            None,
            None,
            None,
            None,
        )
    } else {
        let direct_cause = match &recognition_gate {
            Err(reason) => format!("whole-primitive recognition skipped: {reason}"),
            Ok(()) if !analytic_coverage => format!(
                "RANSAC did not prove complete analytic coverage ({} unresolved triangle(s))",
                recognition.unresolved_triangles.len()
            ),
            Ok(()) if !closed_for_analytics => {
                "recognized mesh is not a closed two-manifold".to_owned()
            }
            Ok(()) => {
                "recognized regions do not match a safe complete primitive topology".to_owned()
            }
        };

        let kernel_eligible = segmentation.as_ref().is_ok_and(|segmentation| {
            segmentation_is_complete(segmentation)
                && segmentation.regions.iter().all(|region| {
                    matches!(
                        region.carrier,
                        RegionCarrier::Plane { .. }
                            | RegionCarrier::Cylinder { .. }
                            | RegionCarrier::Cone { .. }
                    )
                })
        });
        let kernel_attempt = if closed_for_analytics
            && kernel_eligible
            && options.try_kernel_analytic_rebuild
        {
            try_kernel_analytic(source_positions, source_indices, options)
        } else {
            Err("kernel analytic rebuild requires the kernel segmentation to prove complete plane/cylinder/cone coverage".to_owned())
        };

        let analytic_attempt = match kernel_attempt {
            Ok(solid) => Ok((
                solid,
                ConversionBackend::KernelAnalyticRebuild,
                "kernel segmentation proved complete plane/cylinder/cone coverage; the kernel region rebuilder then reconstructed and validated the complete analytic shell".to_owned(),
                None,
            )),
            Err(kernel_error) => {
                let hybrid_attempt = if closed_for_analytics && options.try_hybrid_rebuild {
                    try_hybrid_analytic(source_positions, source_indices, options)
                } else if !options.try_hybrid_rebuild {
                    Err("mixed analytic/faceted rebuild was disabled".to_owned())
                } else {
                    Err("mixed analytic/faceted rebuild requires a closed two-manifold".to_owned())
                };
                // An opt-in round trip of the rebuilt solid alone: a solid
                // its own STEP cannot import takes the faceted fallback.
                let hybrid_attempt = hybrid_attempt.and_then(|output| {
                    if hybrid_roundtrip_fallback_enabled() {
                        if let Err(error) = solid_round_trips(&output.solid) {
                            // Promotion 14's switch first: the rebuild
                            // without it.
                            let joined = crate::hybrid_region_brep::hybrid_plane_cylinder_brep_before_promotion_14(
                                source_positions,
                                source_indices,
                                &segmentation_options(source_positions, options),
                            );
                            if let Ok(Some(joined)) = joined {
                                if solid_round_trips(&joined.solid).is_ok() {
                                    return Ok(joined);
                                }
                            }
                            // Then promotion 13's switches: the rebuild
                            // without them (and promotion 14's).
                            let latest = crate::hybrid_region_brep::hybrid_plane_cylinder_brep_before_promotion_13(
                                source_positions,
                                source_indices,
                                &segmentation_options(source_positions, options),
                            );
                            if let Ok(Some(latest)) = latest {
                                if solid_round_trips(&latest.solid).is_ok() {
                                    return Ok(latest);
                                }
                            }
                            // Then promotion 12's switch: the rebuild
                            // without it (and promotion 13's).
                            let newest = crate::hybrid_region_brep::hybrid_plane_cylinder_brep_before_promotion_12(
                                source_positions,
                                source_indices,
                                &segmentation_options(source_positions, options),
                            );
                            if let Ok(Some(newest)) = newest {
                                if solid_round_trips(&newest.solid).is_ok() {
                                    return Ok(newest);
                                }
                            }
                            // Then promotion 11's switches: the rebuild
                            // without them (and promotion 12's).
                            let first = crate::hybrid_region_brep::hybrid_plane_cylinder_brep_before_promotion_11(
                                source_positions,
                                source_indices,
                                &segmentation_options(source_positions, options),
                            );
                            if let Ok(Some(first)) = first {
                                if solid_round_trips(&first.solid).is_ok() {
                                    return Ok(first);
                                }
                            }
                            // Promotion 9's switches can move a line onto a
                            // ring vertex past the import's bar (census record
                            // occt_frustum_s10_d0.05_jitter-0.1); the rebuild
                            // without them is tried before the facets.
                            let second = crate::hybrid_region_brep::hybrid_plane_cylinder_brep_before_promotion_9(
                                source_positions,
                                source_indices,
                                &segmentation_options(source_positions, options),
                            );
                            if let Ok(Some(second)) = second {
                                if solid_round_trips(&second.solid).is_ok() {
                                    return Ok(second);
                                }
                            }
                            // Then without promotion 10's switches, keeping
                            // promotion 9's, and then without either (each
                            // without promotion 11's too).
                            for with_promotion_9 in [true, false] {
                                let further = crate::hybrid_region_brep::hybrid_plane_cylinder_brep_before_promotion_10(
                                    source_positions,
                                    source_indices,
                                    &segmentation_options(source_positions, options),
                                    with_promotion_9,
                                );
                                if let Ok(Some(further)) = further {
                                    if solid_round_trips(&further.solid).is_ok() {
                                        return Ok(further);
                                    }
                                }
                            }
                            return Err(format!(
                                "{kernel_error}; the mixed rebuild's solid failed its STEP round trip: {error}"
                            ));
                        }
                    }
                    Ok(output)
                });
                match hybrid_attempt {
                    Ok(output) => {
                        let stats = &output.stats;
                        whole_carrier_scan = whole_carrier_scan.sum(stats.whole_carrier_scan);
                        if stats.split_freeform_regions
                            + stats.split_declined_regions
                            + stats.split_over_budget_regions
                            + stats.split_budget_hit_regions
                            + stats.split_band_declined_regions
                            > 0
                        {
                            messages.push(format!(
                                "freeform split: {} region(s) divided into carriers, {} tried and left as segmented, {} above the triangle budget and not tried, {} out of the hypothesis budget and left as segmented, {} declined by the normal-band pre-test",
                                stats.split_freeform_regions,
                                stats.split_declined_regions,
                                stats.split_over_budget_regions,
                                stats.split_budget_hit_regions,
                                stats.split_band_declined_regions
                            ));
                        }
                        let hybrid_report = hybrid_report(&output.stats);
                        if options.policy == ConversionPolicy::RequireFullyAnalytic
                            && hybrid_report.faceted_faces != 0
                        {
                            Err(format!(
                                "{kernel_error}; mixed rebuild retained {} faceted face(s) for {} source triangle(s)",
                                hybrid_report.faceted_faces, hybrid_report.faceted_triangles
                            ))
                        } else {
                            let reason = if hybrid_report.faceted_faces == 0 {
                                "independent segmentation reconstructed and validated a fully analytic plane/cylinder/cone/sphere shell"
                            } else {
                                "independent segmentation reconstructed exact plane/cylinder/cone/sphere regions and retained unsupported or unsafe regions as facets"
                            };
                            hybrid_demotions = output.stats.demotions;
                            Ok((
                                output.solid,
                                ConversionBackend::HybridAnalyticRebuild,
                                reason.to_owned(),
                                Some(hybrid_report),
                            ))
                        }
                    }
                    Err(hybrid_error) => Err(format!("{kernel_error}; {hybrid_error}")),
                }
            }
        };

        match analytic_attempt {
            Ok((solid, backend, reason, hybrid)) => {
                (solid, backend, reason, None, hybrid, None, None)
            }
            Err(analytic_error) => {
                let cause = format!("{direct_cause}; {analytic_error}");
                if options.policy == ConversionPolicy::RequireFullyAnalytic {
                    return Err(StlConversionError(format!(
                        "strict analytic conversion refused faceted fallback: {cause}"
                    )));
                }
                fallback_cause = Some(cause.clone());
                messages.push(format!("analytic rebuild unavailable: {cause}"));
                let faceted =
                    mesh_to_faceted_brep(source_positions, source_indices, options.weld_tolerance)
                        .map_err(|error| {
                            StlConversionError(format!("faceted mesh repair failed: {error}"))
                        })?;
                let faces_before = solid_face_count(&faceted);
                let merge_tolerance = coplanar_merge_tolerance(mesh);
                match merge_same_surface_faces(&faceted, merge_tolerance) {
                    Ok(merged) => {
                        let faces_after = solid_face_count(&merged);
                        if faces_after < faces_before {
                            messages.push(format!(
                                "coplanar faceted merge reduced faces from {faces_before} to {faces_after} (tolerance {merge_tolerance:.3e})"
                            ));
                            (
                                merged,
                                ConversionBackend::FacetedRepairCoplanarMerged,
                                "the complete source triangle set was repaired as a faceted BREP, then adjacent coplanar facets were merged without introducing curved replacement topology".to_owned(),
                                None,
                                None,
                                Some(faces_before),
                                Some(faces_after),
                            )
                        } else {
                            messages.push(format!(
                                "coplanar faceted merge found no mergeable faces (tolerance {merge_tolerance:.3e})"
                            ));
                            (
                                faceted,
                                ConversionBackend::FacetedRepair,
                                "the complete source triangle set was repaired and preserved as a faceted BREP; no adjacent coplanar facets could be merged".to_owned(),
                                None,
                                None,
                                Some(faces_before),
                                Some(faces_before),
                            )
                        }
                    }
                    Err(error) => {
                        messages.push(format!(
                            "coplanar faceted merge was unavailable; retained the validated repaired mesh: {error}"
                        ));
                        (
                            faceted,
                            ConversionBackend::FacetedRepair,
                            "the complete source triangle set was repaired and preserved as a faceted BREP; the optional coplanar merge was unavailable".to_owned(),
                            None,
                            None,
                            Some(faces_before),
                            Some(faces_before),
                        )
                    }
                }
            }
        }
    };
    let topology_build_seconds = topology_started.elapsed().as_secs_f64();

    let topology_issues = solid.validate();
    if !topology_issues.is_empty() {
        return Err(StlConversionError(format!(
            "constructed BREP failed topology validation: {topology_issues:?}"
        )));
    }

    let faces = solid_face_count(&solid);
    let detail = ComponentDetail {
        backend,
        backend_reason,
        fallback_cause,
        input_vertices,
        input_triangles,
        recognized_regions: recognition.regions.len(),
        recognized_triangles,
        unresolved_triangles: recognition.unresolved_triangles.len(),
        recognition_skipped: recognition_gate.err(),
        source_closed_manifold,
        analytic_used_repaired_mesh: repaired.is_some(),
        requested_distance_tolerance,
        effective_distance_tolerance,
        region_type_counts,
        regions,
        topology_refit,
        hybrid_rebuild,
        hybrid_demotions,
        faceted_faces_before_merge,
        faceted_faces_after_merge,
        faces,
        segmentation_seconds,
        recognition_seconds,
        recognition_work,
        whole_carrier_scan,
        topology_build_seconds,
        messages,
        refusal: None,
    };
    Ok((solid, detail))
}

/// Fold every body's detail into the document's single report. Counts are
/// TOTALS and `regions` is the concatenation; the fields that can only
/// describe one body (`backend`, `topology_refit`) are the first body's, and
/// `components` is the authoritative per-body record.
fn aggregate_report(
    components: &[Vec<usize>],
    details: Vec<ComponentDetail>,
    count: usize,
    options: &StlConversionOptions,
) -> StlConversionReport {
    let mut messages = Vec::new();
    if count > 1 {
        messages.push(format!(
            "the triangle soup holds {count} vertex-connected components; each shell was reconstructed independently before cavity assembly"
        ));
    }
    let refused = details
        .iter()
        .enumerate()
        .filter_map(|(index, detail)| detail.refusal.as_ref().map(|reason| (index, reason)))
        .collect::<Vec<_>>();
    if !refused.is_empty() {
        messages.push(format!(
            "{} of {count} bodies could not be reconstructed and are NOT in the model: {}",
            refused.len(),
            refused
                .iter()
                .map(|(index, reason)| format!(
                    "body {} (from source triangle {}): {reason}",
                    index + 1,
                    components[*index][0]
                ))
                .collect::<Vec<_>>()
                .join("; ")
        ));
    }
    for (index, detail) in details.iter().enumerate() {
        for message in &detail.messages {
            messages.push(if count > 1 {
                format!("body {}: {message}", index + 1)
            } else {
                message.clone()
            });
        }
    }

    // The document's backend is its first BUILT body's; the caller refuses
    // the import before this when no body was built.
    let first = details
        .iter()
        .find(|detail| detail.refusal.is_none())
        .unwrap_or(&details[0]);
    let backend_reason = if count == 1 {
        first.backend_reason.clone()
    } else if details
        .iter()
        .all(|detail| detail.backend == first.backend)
    {
        format!(
            "{count} components were reconstructed separately; each: {}",
            first.backend_reason
        )
    } else {
        format!(
            "{count} components were reconstructed separately: {}",
            details
                .iter()
                .enumerate()
                .map(|(index, detail)| format!("body {} — {}", index + 1, detail.backend_reason))
                .collect::<Vec<_>>()
                .join("; ")
        )
    };
    let fallback_cause = details
        .iter()
        .enumerate()
        .find_map(|(index, detail)| {
            detail.fallback_cause.as_ref().map(|cause| {
                if count > 1 {
                    format!("body {}: {cause}", index + 1)
                } else {
                    cause.clone()
                }
            })
        });
    let recognition_skipped = details
        .iter()
        .enumerate()
        .map(|(index, detail)| {
            detail
                .recognition_skipped
                .as_ref()
                .map(|reason| (index, reason))
        })
        .collect::<Option<Vec<_>>>()
        .map(|skipped| {
            if count == 1 || skipped.iter().all(|(_, reason)| *reason == skipped[0].1) {
                skipped[0].1.clone()
            } else {
                skipped
                    .iter()
                    .map(|(index, reason)| format!("body {}: {reason}", index + 1))
                    .collect::<Vec<_>>()
                    .join("; ")
            }
        });

    let mut region_type_counts = BTreeMap::new();
    for detail in &details {
        for (name, count) in &detail.region_type_counts {
            *region_type_counts.entry(name.clone()).or_insert(0) += count;
        }
    }
    let hybrid_rebuild = details
        .iter()
        .any(|detail| detail.hybrid_rebuild.is_some())
        .then(|| {
            details
                .iter()
                .filter_map(|detail| detail.hybrid_rebuild)
                .fold(HybridConversionReport::default(), add_hybrid_reports)
        });
    let faceted_faces_before_merge = sum_optional(&details, |detail| detail.faceted_faces_before_merge);
    let faceted_faces_after_merge = sum_optional(&details, |detail| detail.faceted_faces_after_merge);

    let component_reports = components
        .iter()
        .zip(&details)
        .enumerate()
        .map(|(index, (triangles, detail))| ComponentConversionReport {
            index,
            first_triangle: triangles[0],
            input_vertices: detail.input_vertices,
            input_triangles: detail.input_triangles,
            backend: detail.backend,
            backend_reason: detail.backend_reason.clone(),
            fallback_cause: detail.fallback_cause.clone(),
            recognition_skipped: detail.recognition_skipped.clone(),
            recognized_regions: detail.recognized_regions,
            recognized_triangles: detail.recognized_triangles,
            unresolved_triangles: detail.unresolved_triangles,
            source_closed_manifold: detail.source_closed_manifold,
            analytic_used_repaired_mesh: detail.analytic_used_repaired_mesh,
            hybrid_rebuild: detail.hybrid_rebuild,
            hybrid_demotions: detail.hybrid_demotions.clone(),
            faceted_faces_before_merge: detail.faceted_faces_before_merge,
            faceted_faces_after_merge: detail.faceted_faces_after_merge,
            faces: detail.faces,
            refusal: detail.refusal.clone(),
            source_name: None,
        })
        .collect();

    StlConversionReport {
        backend: first.backend,
        backend_reason,
        fallback_cause,
        input_vertices: details.iter().map(|detail| detail.input_vertices).sum(),
        input_triangles: details.iter().map(|detail| detail.input_triangles).sum(),
        recognized_regions: details.iter().map(|detail| detail.recognized_regions).sum(),
        recognized_triangles: details
            .iter()
            .map(|detail| detail.recognized_triangles)
            .sum(),
        unresolved_triangles: details
            .iter()
            .map(|detail| detail.unresolved_triangles)
            .sum(),
        recognition_skipped,
        source_closed_manifold: details.iter().all(|detail| detail.source_closed_manifold),
        analytic_used_repaired_mesh: details
            .iter()
            .any(|detail| detail.analytic_used_repaired_mesh),
        requested_distance_tolerance: first.requested_distance_tolerance,
        coordinate_precision_tolerance: options.coordinate_precision_tolerance,
        effective_distance_tolerance: first.effective_distance_tolerance,
        region_type_counts,
        regions: details
            .iter()
            .flat_map(|detail| detail.regions.iter().cloned())
            .collect(),
        topology_refit: details
            .iter()
            .find_map(|detail| detail.topology_refit.clone()),
        hybrid_rebuild,
        hybrid_demotions: details
            .iter()
            .flat_map(|detail| detail.hybrid_demotions.iter().cloned())
            .collect(),
        components: component_reports,
        exported_step_bytes: 0,
        exported_advanced_faces: 0,
        faceted_faces_before_merge,
        faceted_faces_after_merge,
        roundtrip_solids: 0,
        manifold_audit_issues: Vec::new(),
        timings: ConversionTimings {
            segmentation_seconds: details
                .iter()
                .map(|detail| detail.segmentation_seconds)
                .sum(),
            recognition_seconds: details
                .iter()
                .map(|detail| detail.recognition_seconds)
                .sum(),
            topology_build_seconds: details
                .iter()
                .map(|detail| detail.topology_build_seconds)
                .sum(),
            step_export_seconds: 0.0,
            step_validation_seconds: 0.0,
            total_seconds: 0.0,
        },
        recognition_work: details.iter().fold(RecognitionWorkReport::default(), |sum, detail| {
            RecognitionWorkReport {
                hypotheses: sum.hypotheses + detail.recognition_work.hypotheses,
                rounds: sum.rounds + detail.recognition_work.rounds,
                seeded_components: sum.seeded_components + detail.recognition_work.seeded_components,
            }
        }),
        whole_carrier_scan: details
            .iter()
            .fold(WholeCarrierScanReport::default(), |sum, detail| sum.sum(detail.whole_carrier_scan)),
        messages,
    }
}

fn sum_optional(
    details: &[ComponentDetail],
    read: impl Fn(&ComponentDetail) -> Option<usize>,
) -> Option<usize> {
    details
        .iter()
        .any(|detail| read(detail).is_some())
        .then(|| details.iter().filter_map(read).sum())
}

fn add_hybrid_reports(
    total: HybridConversionReport,
    body: HybridConversionReport,
) -> HybridConversionReport {
    HybridConversionReport {
        total_faces: total.total_faces + body.total_faces,
        analytic_plane_faces: total.analytic_plane_faces + body.analytic_plane_faces,
        analytic_plane_triangles: total.analytic_plane_triangles + body.analytic_plane_triangles,
        analytic_cylinder_faces: total.analytic_cylinder_faces + body.analytic_cylinder_faces,
        analytic_cylinder_triangles: total.analytic_cylinder_triangles
            + body.analytic_cylinder_triangles,
        analytic_cone_faces: total.analytic_cone_faces + body.analytic_cone_faces,
        analytic_cone_triangles: total.analytic_cone_triangles + body.analytic_cone_triangles,
        analytic_sphere_faces: total.analytic_sphere_faces + body.analytic_sphere_faces,
        analytic_sphere_triangles: total.analytic_sphere_triangles + body.analytic_sphere_triangles,
        analytic_torus_faces: total.analytic_torus_faces + body.analytic_torus_faces,
        analytic_torus_triangles: total.analytic_torus_triangles + body.analytic_torus_triangles,
        faceted_faces: total.faceted_faces + body.faceted_faces,
        faceted_triangles: total.faceted_triangles + body.faceted_triangles,
        demoted_regions: total.demoted_regions + body.demoted_regions,
        demoted_triangles: total.demoted_triangles + body.demoted_triangles,
        segmentation_plane_regions: total.segmentation_plane_regions
            + body.segmentation_plane_regions,
        segmentation_cylinder_regions: total.segmentation_cylinder_regions
            + body.segmentation_cylinder_regions,
        segmentation_cone_regions: total.segmentation_cone_regions + body.segmentation_cone_regions,
        segmentation_sphere_regions: total.segmentation_sphere_regions
            + body.segmentation_sphere_regions,
        segmentation_torus_regions: total.segmentation_torus_regions
            + body.segmentation_torus_regions,
        segmentation_unsupported_regions: total.segmentation_unsupported_regions
            + body.segmentation_unsupported_regions,
    }
}

/// The triangle indices of each vertex-connected component of `mesh`, each
/// component's own triangles in source order and the components themselves
/// ordered by the lowest source triangle they hold — so the bodies of one file
/// always come out in the same order, and so do their names.
///
/// Vertices are welded by EXACT position first, the canonical-bits weld the
/// STL reader's zero-tolerance path uses (`-0.0` and `0.0` are one point), so
/// two triangles that meet at the same coordinate join even when the file gave
/// that point two indices — a 3MF build gives every instance its own vertex
/// range, and an OBJ may repeat a corner per object.
///
/// Connectivity is by shared VERTEX, not by shared edge. Two closed shells
/// that touch at a single point are therefore ONE component, and the shell
/// validator refuses them exactly as it does today.
fn triangle_components(mesh: &Mesh) -> Vec<Vec<usize>> {
    fn find(parent: &mut [usize], mut node: usize) -> usize {
        while parent[node] != node {
            parent[node] = parent[parent[node]];
            node = parent[node];
        }
        node
    }

    let bits = |value: f64| if value == 0.0 { 0_u64 } else { value.to_bits() };
    let mut position_ids = HashMap::<[u64; 3], usize>::new();
    let mut vertex_position = Vec::with_capacity(mesh.vertices.len());
    for point in &mesh.vertices {
        let key = [bits(point.x), bits(point.y), bits(point.z)];
        let next = position_ids.len();
        vertex_position.push(*position_ids.entry(key).or_insert(next));
    }

    let mut parent = (0..position_ids.len()).collect::<Vec<_>>();
    for triangle in &mesh.triangles {
        let first = vertex_position[triangle[0] as usize];
        for &corner in &triangle[1..] {
            let (left, right) = (
                find(&mut parent, first),
                find(&mut parent, vertex_position[corner as usize]),
            );
            if left != right {
                parent[left] = right;
            }
        }
    }

    let mut slots = HashMap::<usize, usize>::new();
    let mut components = Vec::<Vec<usize>>::new();
    for (index, triangle) in mesh.triangles.iter().enumerate() {
        let root = find(&mut parent, vertex_position[triangle[0] as usize]);
        let slot = match slots.get(&root) {
            Some(&slot) => slot,
            None => {
                components.push(Vec::new());
                slots.insert(root, components.len() - 1);
                components.len() - 1
            }
        };
        components[slot].push(index);
    }
    components
}

/// One component's buffers, rebased onto its own vertices.
struct ComponentMesh {
    mesh: Mesh,
    positions: Vec<f64>,
    indices: Option<Vec<u32>>,
}

/// Cut `triangles` out of the whole input as a standalone mesh and matching
/// source buffers. The recognition mesh and the source buffers describe the
/// same triangles in the same order (`validate_source_buffers` proves it), so
/// one triangle-index list rebases both. An unindexed source stays a soup.
fn component_mesh(
    mesh: &Mesh,
    positions: &[f64],
    indices: Option<&[u32]>,
    triangles: &[usize],
) -> ComponentMesh {
    let mut vertex_map = HashMap::<u32, u32>::new();
    let mut vertices = Vec::new();
    let mut component_triangles = Vec::with_capacity(triangles.len());
    for &triangle in triangles {
        let mut corners = [0_u32; 3];
        for (corner, &index) in mesh.triangles[triangle].iter().enumerate() {
            corners[corner] = *vertex_map.entry(index).or_insert_with(|| {
                vertices.push(mesh.vertices[index as usize]);
                vertices.len() as u32 - 1
            });
        }
        component_triangles.push(corners);
    }
    let mut component = Mesh::new(vertices, component_triangles);
    if let Some(normals) = &mesh.vertex_normals {
        if normals.len() == mesh.vertices.len() {
            let mut component_normals = vec![Vec3::default(); component.vertices.len()];
            for (&source, &target) in &vertex_map {
                component_normals[target as usize] = normals[source as usize];
            }
            component.vertex_normals = Some(component_normals);
        }
    }
    if !mesh.source_metadata.is_empty() {
        let local = triangles
            .iter()
            .enumerate()
            .map(|(local, &source)| (source, local))
            .collect::<HashMap<_, _>>();
        component.source_metadata = mesh
            .source_metadata
            .iter()
            .filter_map(|metadata| {
                let triangle_indices = metadata
                    .triangle_indices
                    .iter()
                    .filter_map(|source| local.get(source).copied())
                    .collect::<Vec<_>>();
                (!triangle_indices.is_empty()).then(|| crate::SourceMetadata {
                    triangle_indices,
                    ..metadata.clone()
                })
            })
            .collect();
    }

    let (component_positions, component_indices) = match indices {
        Some(indices) => {
            let mut source_map = HashMap::<u32, u32>::new();
            let mut component_positions = Vec::new();
            let mut component_indices = Vec::with_capacity(triangles.len() * 3);
            for &triangle in triangles {
                for &index in &indices[triangle * 3..triangle * 3 + 3] {
                    let mapped = *source_map.entry(index).or_insert_with(|| {
                        let base = index as usize * 3;
                        component_positions.extend_from_slice(&positions[base..base + 3]);
                        component_positions.len() as u32 / 3 - 1
                    });
                    component_indices.push(mapped);
                }
            }
            (component_positions, Some(component_indices))
        }
        None => {
            let mut component_positions = Vec::with_capacity(triangles.len() * 9);
            for &triangle in triangles {
                component_positions.extend_from_slice(&positions[triangle * 9..triangle * 9 + 9]);
            }
            (component_positions, None)
        }
    };
    ComponentMesh {
        mesh: component,
        positions: component_positions,
        indices: component_indices,
    }
}

fn validate_source_buffers(
    mesh: &Mesh,
    positions: &[f64],
    indices: Option<&[u32]>,
) -> Result<(), StlConversionError> {
    if positions.is_empty() || !positions.len().is_multiple_of(3) {
        return Err(StlConversionError(
            "source position buffer must contain complete non-empty xyz triples".to_owned(),
        ));
    }
    if positions.iter().any(|value| !value.is_finite()) {
        return Err(StlConversionError(
            "source position buffer contains a non-finite coordinate".to_owned(),
        ));
    }
    let source_triangles = match indices {
        Some(indices) => {
            if !indices.len().is_multiple_of(3) {
                return Err(StlConversionError(
                    "source index buffer must contain complete triangles".to_owned(),
                ));
            }
            if indices
                .iter()
                .any(|&index| index as usize >= positions.len() / 3)
            {
                return Err(StlConversionError(
                    "source index buffer references a missing position".to_owned(),
                ));
            }
            indices.len() / 3
        }
        None => {
            if !positions.len().is_multiple_of(9) {
                return Err(StlConversionError(
                    "unindexed source positions must be a triangle soup".to_owned(),
                ));
            }
            positions.len() / 9
        }
    };
    if source_triangles != mesh.triangles.len() {
        return Err(StlConversionError(format!(
            "source buffers contain {source_triangles} triangles but recognition mesh contains {}",
            mesh.triangles.len()
        )));
    }
    Ok(())
}

/// Recover only small coplanar feature-bounded components that the generic
/// pass skipped because its minimum support deliberately protects curved
/// model selection. A two-triangle plane is fully determined without giving
/// tiny cylinder/torus hypotheses authority over output topology.
fn complete_small_planar_regions(
    mesh: &Mesh,
    options: &RecognitionOptions,
    regions: &mut Vec<SurfaceRegion>,
    unresolved: &mut Vec<usize>,
) -> Result<usize, StlConversionError> {
    if unresolved.len() < 2 {
        return Ok(0);
    }
    let analyzed = mesh
        .analyze(&MeshAnalysisOptions {
            feature_angle: options.feature_angle,
            ..MeshAnalysisOptions::default()
        })
        .map_err(|error| {
            StlConversionError(format!("plane completion analysis failed: {error}"))
        })?;
    let allowed = unresolved.iter().copied().collect::<BTreeSet<_>>();
    let mut visited = BTreeSet::new();
    let mut accepted = BTreeSet::new();
    let mut completed = 0;
    let mut plane_options = options.clone();
    plane_options.minimum_support = 2;

    for &seed in unresolved.iter() {
        if !visited.insert(seed) {
            continue;
        }
        let mut component = Vec::new();
        let mut queue = VecDeque::from([seed]);
        while let Some(triangle) = queue.pop_front() {
            component.push(triangle);
            let data = &analyzed.triangles[triangle];
            for edge in 0..3 {
                if data.feature_edges[edge] {
                    continue;
                }
                if let Some(neighbor) = data.neighbors[edge] {
                    if allowed.contains(&neighbor) && visited.insert(neighbor) {
                        queue.push_back(neighbor);
                    }
                }
            }
        }
        component.sort_unstable();
        if component.len() < 2 {
            continue;
        }
        let Ok(fit) = reconstruct_surface(
            mesh,
            &component,
            &SurfaceHint::KnownType {
                surface_type: SurfaceType::Plane,
            },
            &plane_options,
        ) else {
            continue;
        };
        if fit.metrics.support_triangles != component.len()
            || !matches!(fit.surface, AnalyticSurface::Plane(_))
        {
            continue;
        }
        accepted.extend(component.iter().copied());
        regions.push(SurfaceRegion {
            surface: fit.surface,
            orientation: fit.orientation,
            triangle_indices: component,
            metrics: fit.metrics,
            confidence: fit.confidence,
            diagnostics: fit.diagnostics,
        });
        completed += 1;
    }
    unresolved.retain(|triangle| !accepted.contains(triangle));
    Ok(completed)
}

fn region_report(region: &SurfaceRegion) -> ConversionRegionReport {
    fit_fields(
        region.surface,
        region.orientation,
        &region.metrics,
        region.confidence,
        &region.diagnostics,
    )
}

fn refit_report(fit: &SurfaceFitResult) -> ConversionRegionReport {
    fit_fields(
        fit.surface,
        fit.orientation,
        &fit.metrics,
        fit.confidence,
        &fit.diagnostics,
    )
}

fn fit_fields(
    surface: AnalyticSurface,
    orientation: i8,
    metrics: &crate::FitMetrics,
    confidence: f64,
    diagnostics: &crate::FitDiagnostics,
) -> ConversionRegionReport {
    ConversionRegionReport {
        surface_type: surface.surface_type(),
        surface,
        support_triangles: metrics.support_triangles,
        supported_area: metrics.supported_area,
        rms_error: metrics.rms_error,
        max_error: metrics.max_error,
        rms_normal_error_radians: metrics.rms_normal_error,
        max_normal_error_radians: metrics.max_normal_error,
        confidence,
        orientation,
        reason: diagnostics.reason.clone(),
        phase_timings: diagnostics.phase_timings,
    }
}

fn disjoint_complete_partition(regions: &[SurfaceRegion], triangle_count: usize) -> bool {
    let mut seen = BTreeSet::new();
    regions.iter().all(|region| {
        region
            .triangle_indices
            .iter()
            .all(|&triangle| triangle < triangle_count && seen.insert(triangle))
    }) && seen.len() == triangle_count
}

/// A source mesh the repair closed, with the buffers every downstream lane
/// reads bound to it.
pub(crate) struct RepairedMesh {
    mesh: Mesh,
    pub(crate) positions: Vec<f64>,
    pub(crate) indices: Vec<u32>,
    message: String,
}

/// Repair a mesh that is not a closed two-manifold, and hand it back only
/// when the repair actually closed it — a mesh too broken to close keeps the
/// refusal it has always had, and a file whose repair would CHANGE a closed
/// mesh never reaches here.
pub(crate) fn repaired_closed_mesh(
    source_positions: &[f64],
    source_indices: Option<&[u32]>,
    options: &StlConversionOptions,
) -> Option<RepairedMesh> {
    // A vertex sitting on the interior of a neighbour's edge (a T-junction)
    // leaves three edges used once, which no boundary cap can close: split
    // the long edge at it first, on the file's own vertex.
    let owned_indices;
    let stitched_indices = match source_indices {
        Some(indices) => indices,
        None => {
            owned_indices = (0..source_positions.len() as u32 / 3).collect::<Vec<_>>();
            &owned_indices
        }
    };
    let stitch_tolerance = if options.weld_tolerance > 0.0 {
        options.weld_tolerance
    } else {
        mesh_diagonal_of(source_positions) * crate::stl::DEFAULT_RELATIVE_WELD_TOLERANCE
    };
    let (stitched, stitch) =
        t_junctions::stitch_t_junctions(source_positions, stitched_indices, stitch_tolerance);
    let (positions, indices, report) =
        repair_triangle_soup(source_positions, Some(&stitched), options.weld_tolerance).ok()?;
    let vertices = positions
        .chunks_exact(3)
        .map(|point| Vec3::new(point[0], point[1], point[2]))
        .collect::<Vec<_>>();
    let triangles = indices
        .chunks_exact(3)
        .map(|triangle| [triangle[0], triangle[1], triangle[2]])
        .collect::<Vec<_>>();
    let mesh = Mesh::new(vertices, triangles);
    if !closed_manifold(&mesh) {
        return None;
    }
    let message = format!(
        "the source mesh is not a closed two-manifold; the analytic lanes ran on the repaired mesh \
         ({}{} welded vertices, {} triangles: {} dropped as degenerate or duplicate, {} surplus \
         sheet(s) pruned, {} reoriented to agree with their neighbours, {} boundary loop(s) \
         capped with {} triangle(s))",
        if stitch.stitched_edges > 0 {
            format!(
                "{} T-junction edge(s) split at a vertex on their interior, {} triangle(s) added; ",
                stitch.stitched_edges, stitch.added_triangles
            )
        } else {
            String::new()
        },
        report.welded_vertices,
        report.triangles,
        report.dropped_triangles,
        report.pruned_triangles,
        report.reoriented_triangles,
        report.capped_loops,
        report.cap_triangles,
    );
    Some(RepairedMesh {
        mesh,
        positions,
        indices,
        message,
    })
}

/// Bounding-box diagonal of a flat xyz buffer.
fn mesh_diagonal_of(positions: &[f64]) -> f64 {
    let mut low = [f64::INFINITY; 3];
    let mut high = [f64::NEG_INFINITY; 3];
    for point in positions.chunks_exact(3) {
        for axis in 0..3 {
            low[axis] = low[axis].min(point[axis]);
            high[axis] = high[axis].max(point[axis]);
        }
    }
    (0..3).map(|axis| (high[axis] - low[axis]).powi(2)).sum::<f64>().sqrt()
}

fn closed_manifold(mesh: &Mesh) -> bool {
    closed_triangles(mesh.triangles.iter().copied())
}

fn closed_triangles(triangles: impl Iterator<Item = [u32; 3]>) -> bool {
    let mut uses = BTreeMap::<(u32, u32), (usize, i32)>::new();
    for triangle in triangles {
        if triangle[0] == triangle[1] || triangle[1] == triangle[2] || triangle[2] == triangle[0] {
            return false;
        }
        for edge in [
            (triangle[0], triangle[1]),
            (triangle[1], triangle[2]),
            (triangle[2], triangle[0]),
        ] {
            let key = if edge.0 < edge.1 {
                (edge.0, edge.1)
            } else {
                (edge.1, edge.0)
            };
            let entry = uses.entry(key).or_default();
            entry.0 += 1;
            entry.1 += if edge == key { 1 } else { -1 };
        }
    }
    !uses.is_empty()
        && uses
            .values()
            .all(|&(count, sense)| count == 2 && sense == 0)
}

struct DirectAnalyticBuild {
    solid: Result<brep_kernel::BrepSolid, StlConversionError>,
    backend: ConversionBackend,
    reason: String,
    topology_refit: Option<ConversionRegionReport>,
}

fn direct_analytic_solid(
    mesh: &Mesh,
    regions: &[SurfaceRegion],
    options: &RecognitionOptions,
) -> Option<DirectAnalyticBuild> {
    if regions.len() == 1 {
        return match regions[0].surface {
            AnalyticSurface::Sphere(sphere) => Some(DirectAnalyticBuild {
                solid: make_sphere_brep(
                    kernel_vec(sphere.center),
                    sphere.radius,
                    kernel_vec(Vec3::new(0.0, 0.0, 1.0)),
                )
                .map_err(StlConversionError),
                backend: ConversionBackend::RansacSphere,
                reason: "RANSAC proved complete closed spherical coverage; exported an exact analytic sphere".to_owned(),
                topology_refit: None,
            }),
            AnalyticSurface::Torus(torus) if torus.major_radius > torus.minor_radius => Some(DirectAnalyticBuild {
                solid: make_torus_brep(
                    kernel_vec(torus.center),
                    kernel_vec(torus.axis),
                    torus.major_radius,
                    torus.minor_radius,
                )
                .map_err(StlConversionError),
                backend: ConversionBackend::RansacTorus,
                reason: "RANSAC proved complete closed ring-torus coverage; exported an exact analytic torus".to_owned(),
                topology_refit: None,
            }),
            _ => None,
        };
    }

    let curved = regions
        .iter()
        .filter(|region| !matches!(region.surface, AnalyticSurface::Plane(_)))
        .collect::<Vec<_>>();
    let planes = regions
        .iter()
        .filter_map(|region| match region.surface {
            AnalyticSurface::Plane(plane) => Some(plane),
            _ => None,
        })
        .collect::<Vec<_>>();
    if curved.len() != 1 {
        return None;
    }
    // A finite cylinder/cone strip sampled at only a handful of axial levels
    // can be represented to roundoff by the very-large-radius limit of a
    // torus. Planar cap topology removes that ambiguity. In that narrowly
    // gated case, ask the production recognizer for a topology-informed
    // known-type refit and retain all of its ordinary residual/normal gates.
    let topology_refit;
    let mut topology_refit_report = None;
    let curved = if let AnalyticSurface::Torus(torus) = curved[0].surface {
        let scale = mesh_diagonal(mesh);
        let collapsed = torus.major_radius.min(torus.minor_radius) > 20.0 * scale;
        let forced_type = match planes.len() {
            2 if collapsed => Some(SurfaceType::Cylinder),
            1 if collapsed => Some(SurfaceType::Cone),
            _ => None,
        };
        if let Some(surface_type) = forced_type {
            topology_refit = reconstruct_surface(
                mesh,
                &curved[0].triangle_indices,
                &SurfaceHint::KnownType { surface_type },
                options,
            )
            .ok()?;
            topology_refit_report = Some(refit_report(&topology_refit));
            &topology_refit.surface
        } else {
            &curved[0].surface
        }
    } else {
        &curved[0].surface
    };
    match *curved {
        AnalyticSurface::Cylinder(cylinder) if planes.len() == 2 => {
            let (low, high) = axial_range(mesh, cylinder.axis_origin, cylinder.axis)?;
            let tolerance = conversion_tolerance(mesh, options);
            if high - low <= tolerance
                || !caps_match(
                    &planes,
                    cylinder.axis_origin,
                    cylinder.axis,
                    &[low, high],
                    tolerance,
                )
            {
                return None;
            }
            let base = cylinder.axis_origin + cylinder.axis * low;
            Some(DirectAnalyticBuild {
                solid: make_cylinder_brep(
                    kernel_vec(base),
                    kernel_vec(cylinder.axis),
                    cylinder.radius,
                    high - low,
                )
                .map_err(StlConversionError),
                backend: ConversionBackend::RansacCappedCylinder,
                reason: if topology_refit_report.is_some() {
                    "two-cap topology disambiguated a large-radius torus limit; the production known-type cylinder refit passed all gates and supplied the exact capped-cylinder parameters".to_owned()
                } else {
                    "RANSAC proved one cylindrical wall plus two matching planar caps; exported an exact capped cylinder".to_owned()
                },
                topology_refit: topology_refit_report,
            })
        }
        AnalyticSurface::Cone(cone) if planes.len() == 1 || planes.len() == 2 => {
            let (low, high) = axial_range(mesh, cone.apex, cone.axis)?;
            let tolerance = conversion_tolerance(mesh, options);
            if low < -tolerance || high - low <= tolerance {
                return None;
            }
            let expected_caps = if low <= tolerance {
                vec![high]
            } else {
                vec![low, high]
            };
            if planes.len() != expected_caps.len()
                || !caps_match(&planes, cone.apex, cone.axis, &expected_caps, tolerance)
            {
                return None;
            }
            let radius_bottom = low.max(0.0) * cone.half_angle.tan();
            let radius_top = high * cone.half_angle.tan();
            if radius_top <= tolerance || (low > tolerance && radius_bottom <= tolerance) {
                return None;
            }
            let (base, build_axis, build_bottom, build_top) = if low <= tolerance {
                // The kernel's capped-cone constructor requires a positive
                // bottom radius. Build a pointed cone from its wide end back
                // toward the apex.
                (
                    cone.apex + cone.axis * high,
                    cone.axis * -1.0,
                    radius_top,
                    0.0,
                )
            } else {
                (
                    cone.apex + cone.axis * low,
                    cone.axis,
                    radius_bottom,
                    radius_top,
                )
            };
            Some(DirectAnalyticBuild {
                solid: make_cone_brep(
                    kernel_vec(base),
                    kernel_vec(build_axis),
                    build_bottom,
                    build_top,
                    high - low.max(0.0),
                )
                .map_err(StlConversionError),
                backend: ConversionBackend::RansacCappedCone,
                reason: if topology_refit_report.is_some() {
                    "cone-cap topology disambiguated a large-radius torus limit; the production known-type cone refit passed all gates and supplied the exact capped-cone parameters".to_owned()
                } else {
                    "RANSAC proved one conical wall and matching planar cap topology; exported an exact capped cone".to_owned()
                },
                topology_refit: topology_refit_report,
            })
        }
        _ => None,
    }
}

fn axial_range(mesh: &Mesh, origin: Vec3, axis: Vec3) -> Option<(f64, f64)> {
    let mut low = f64::INFINITY;
    let mut high = f64::NEG_INFINITY;
    for &point in &mesh.vertices {
        let height = (point - origin).dot(axis);
        low = low.min(height);
        high = high.max(height);
    }
    (low.is_finite() && high.is_finite()).then_some((low, high))
}

fn caps_match(
    planes: &[crate::PlaneSurface],
    origin: Vec3,
    axis: Vec3,
    expected_heights: &[f64],
    tolerance: f64,
) -> bool {
    let mut actual = Vec::with_capacity(planes.len());
    for plane in planes {
        if plane.normal.dot(axis).abs() < 1.0 - 1.0e-6 {
            return false;
        }
        actual.push((plane.origin - origin).dot(axis));
    }
    actual.sort_by(f64::total_cmp);
    let mut expected = expected_heights.to_vec();
    expected.sort_by(f64::total_cmp);
    actual.len() == expected.len()
        && actual
            .iter()
            .zip(expected)
            .all(|(actual, expected)| (*actual - expected).abs() <= tolerance)
}

fn mesh_tolerance(mesh: &Mesh) -> f64 {
    let mut low = mesh.vertices[0];
    let mut high = mesh.vertices[0];
    for &point in &mesh.vertices[1..] {
        low.x = low.x.min(point.x);
        low.y = low.y.min(point.y);
        low.z = low.z.min(point.z);
        high.x = high.x.max(point.x);
        high.y = high.y.max(point.y);
        high.z = high.z.max(point.z);
    }
    (high - low).length().max(1.0) * 1.0e-5
}

fn conversion_tolerance(mesh: &Mesh, options: &RecognitionOptions) -> f64 {
    mesh_tolerance(mesh)
        .max(options.distance_tolerance + options.relative_tolerance * mesh_diagonal(mesh))
}

fn mesh_diagonal(mesh: &Mesh) -> f64 {
    let mut low = mesh.vertices[0];
    let mut high = mesh.vertices[0];
    for &point in &mesh.vertices[1..] {
        low.x = low.x.min(point.x);
        low.y = low.y.min(point.y);
        low.z = low.z.min(point.z);
        high.x = high.x.max(point.x);
        high.y = high.y.max(point.y);
        high.z = high.z.max(point.z);
    }
    (high - low).length()
}

fn coplanar_merge_tolerance(mesh: &Mesh) -> f64 {
    (mesh_diagonal(mesh) * 1.0e-9).max(1.0e-12)
}

fn solid_face_count(solid: &brep_kernel::BrepSolid) -> usize {
    solid.shells.iter().map(|shell| shell.faces.len()).sum()
}

/// Most analytic regions a whole primitive can have: a capped cylinder is a
/// wall and two caps; a capped cone a wall and one or two caps; a sphere or
/// ring torus is one region.
const MAX_WHOLE_PRIMITIVE_REGIONS: usize = 3;

pub(crate) fn segmentation_options(positions: &[f64], options: &StlConversionOptions) -> SegmentOptions {
    SegmentOptions {
        deflection_angle_deg: options.kernel_deflection_angle_degrees,
        fit_tolerance: options.kernel_fit_tolerance,
        normal_tolerance_deg: options.kernel_normal_tolerance_degrees,
        // The conversion buffers have already been welded by the STL reader
        // or mesh repair. Preserve that indexed topology: the kernel's default
        // weld (diagonal * 1e-6) is wider than the STL reader's (1e-9), and can
        // merge distinct vertices before the hybrid builder consumes the IDs.
        weld_tolerance: if options.weld_tolerance > 0.0 {
            options.weld_tolerance
        } else {
            let mut low = [f64::INFINITY; 3];
            let mut high = [f64::NEG_INFINITY; 3];
            for point in positions.chunks_exact(3) {
                for axis in 0..3 {
                    low[axis] = low[axis].min(point[axis]);
                    high[axis] = high[axis].max(point[axis]);
                }
            }
            let diagonal = (0..3)
                .map(|axis| (high[axis] - low[axis]).powi(2))
                .sum::<f64>()
                .sqrt();
            (diagonal * crate::stl::DEFAULT_RELATIVE_WELD_TOLERANCE).max(f64::MIN_POSITIVE)
        },
        ..SegmentOptions::default()
    }
}

/// The kernel segmentation that decides whether RANSAC recognition and the
/// kernel region rebuilder can pay for themselves.
/// Lane J row 12, promoted ON 2026-10-16: BREP_RECOG_SEGMENT_CARRIER=0
/// restores recognition without the segmentation's carriers.
/// Promoted ON 2026-10-31 (owner; BREP_HYBRID_ROUNDTRIP_FALLBACK=0 restores
/// the old path): the mixed
/// rebuild's solid is exported and imported alone before it is taken, and a
/// solid that fails takes the faceted fallback instead of failing the whole
/// conversion. Nine of the census's ten lost rows are countersinks whose
/// rebuilt solid the STEP import refuses ("pcurve fit refused": a trim
/// misses its stations by up to 5e-2 out of sample), and the tenth
/// (kernel_pointed_cone_s10_d0.05_jitter-1.0) imports with an edge used
/// four times.
fn hybrid_roundtrip_fallback_enabled() -> bool {
    brep_kernel::switch!(live "BREP_HYBRID_ROUNDTRIP_FALLBACK", true)
}

/// [`hybrid_roundtrip_fallback_enabled`]: the solid's own STEP imports
/// and every imported solid validates.
fn solid_round_trips(solid: &brep_kernel::BrepSolid) -> Result<(), String> {
    let text = export_step(std::slice::from_ref(solid), "round-trip", "millimeter", "2026-01-01T00:00:00Z")
        .map_err(|error| format!("export: {error}"))?;
    let imported = import_step(&text).map_err(|error| error.to_string())?;
    match imported.iter().map(|solid| solid.validate()).find(|issues| !issues.is_empty()) {
        Some(issues) => Err(format!("imported solid invalid: {issues:?}")),
        None => Ok(()),
    }
}

fn segment_carrier_enabled() -> bool {
    brep_kernel::switch!(live "BREP_RECOG_SEGMENT_CARRIER", true)
}

/// Lane J row 12: the recognition tolerance is raised to the segmentation's
/// own measured maximum vertex deviation, measured against the
/// SEGMENTATION's carrier. RANSAC's least-squares refit of the same kind on
/// the same component is a different model, and its maximum lands just above
/// that tolerance about as often as below (a jittered torus: 2.973e-3 against
/// 2.972e-3), after which generic extraction shreds the component with tens
/// of thousands of hypotheses. Every analytic region is therefore offered as
/// a candidate for the component it covers.
///
/// That carrier passes the distance gate by construction — the tolerance was
/// measured on it — so the distance gate certifies nothing here. The
/// independent check is row 11's local residual scan on the carrier's own
/// vertex residuals: a region whose scan reads above its false-alarm
/// threshold (a flat or dimple the carrier was fitted across) is not offered.
fn segmentation_candidates(mesh: &Mesh, segmentation: &MeshSegmentation) -> Vec<ComponentCandidate> {
    if segmentation.triangle_count != mesh.triangles.len()
        || segmentation.triangle_region_ids.len() != mesh.triangles.len()
    {
        return Vec::new();
    }
    let mut members = vec![Vec::new(); segmentation.regions.len()];
    for (triangle, &region) in segmentation.triangle_region_ids.iter().enumerate() {
        if let Some(list) = members.get_mut(region as usize) {
            list.push(triangle);
        }
    }
    segmentation
        .regions
        .iter()
        .zip(members)
        .filter_map(|(region, triangles)| {
            let (surface, parameters) = carrier_surface(&region.carrier)?;
            if triangles.is_empty() || !surface.is_valid() {
                return None;
            }
            let indices: Vec<u32> = triangles.iter().flat_map(|&t| mesh.triangles[t]).collect();
            let (statistic, threshold) = crate::hybrid_whole_freeform::carrier_local_scan(
                &indices,
                |v| surface.signed_distance(mesh.vertices[v as usize]),
                parameters,
            );
            if std::env::var_os("BREP_DEBUG_SPLIT").is_some() {
                eprintln!(
                    "[candidate] region {} {} tris {} local {statistic:.2} threshold {threshold:.2} {}",
                    region.id,
                    region.carrier.kind(),
                    triangles.len(),
                    if statistic <= threshold { "offered" } else { "declined" }
                );
            }
            (statistic <= threshold).then_some(ComponentCandidate { triangle_indices: triangles, surface })
        })
        .collect()
}

/// Lane J row 13: the direct analytic builders take RANSAC's own regions as
/// they stand. Once the recognition tolerance has been raised to the
/// segmentation's measured deviation, the distance gate those regions passed
/// is the tolerance the noise set, so a small flat on a torus tube (h =
/// 0.015, 2.5x the jitter amplitude) passes it. Row 11's local residual scan
/// reads every region's own vertex residuals; a region whose scan reads
/// above its false-alarm threshold, with residuals that pass the
/// independence test the threshold assumes, keeps the body off the direct
/// builders. A region whose own largest residual is within `requested`
/// (the encoding distance tolerance, before the segmentation's deviation
/// raised it) is not scanned: the requested gate certifies it, and on an
/// exact mesh the residuals are roundoff (census r13: a clean torus at
/// 1.4e-15), which the scale-free scan reads as flats. A scan that abstains
/// (`carrier_scan_verdict`) keeps the status quo.
fn whole_fits_pass_the_local_scan(
    mesh: &Mesh,
    regions: &[SurfaceRegion],
    requested: f64,
    tally: &mut WholeCarrierScanReport,
) -> bool {
    if !crate::hybrid_whole_freeform::whole_carrier_scan_enabled() {
        return true;
    }
    let mut passes = true;
    for region in regions.iter().filter(|region| region.metrics.max_error > requested) {
        let surface = &region.surface;
        let indices: Vec<u32> = region
            .triangle_indices
            .iter()
            .flat_map(|&t| mesh.triangles[t])
            .collect();
        let reading = crate::hybrid_whole_freeform::carrier_scan_verdict(
            &indices,
            |v| surface.signed_distance(mesh.vertices[v as usize]),
            analytic_parameters(surface),
        );
        if std::env::var_os("BREP_DEBUG_SPLIT").is_some() {
            eprintln!(
                "[whole-fit] {} tris {} local {:.2} threshold {:.2} independence {:.3} bound {:.3} edges {} {:?}",
                surface.surface_type().name(),
                region.triangle_indices.len(),
                reading.statistic,
                reading.threshold,
                reading.independence,
                reading.bound,
                reading.outside_edges,
                reading.verdict
            );
        }
        tally.add(reading.verdict);
        if reading.verdict == crate::hybrid_whole_freeform::ScanVerdict::Declined {
            passes = false;
            break;
        }
    }
    passes
}

/// A RANSAC surface's parameter count, as `carrier_surface` counts them.
fn analytic_parameters(surface: &AnalyticSurface) -> usize {
    match surface {
        AnalyticSurface::Plane(_) => 3,
        AnalyticSurface::Cylinder(_) => 5,
        AnalyticSurface::Cone(_) => 6,
        AnalyticSurface::Sphere(_) => 4,
        AnalyticSurface::Torus(_) => 7,
    }
}

/// A segmentation carrier as a RANSAC surface, with its parameter count.
fn carrier_surface(carrier: &RegionCarrier) -> Option<(AnalyticSurface, usize)> {
    let v = |p: brep_kernel::Vec3| crate::brep::vec3_from_kernel(p);
    Some(match *carrier {
        RegionCarrier::Plane { origin, normal } => {
            (AnalyticSurface::Plane(PlaneSurface { origin: v(origin), normal: v(normal) }), 3)
        }
        RegionCarrier::Cylinder { axis_point, axis_dir, radius, .. } => (
            AnalyticSurface::Cylinder(CylinderSurface { axis_origin: v(axis_point), axis: v(axis_dir), radius }),
            5,
        ),
        RegionCarrier::Cone { apex, axis_dir, half_angle_rad, .. } => (
            AnalyticSurface::Cone(ConeSurface { apex: v(apex), axis: v(axis_dir), half_angle: half_angle_rad }),
            6,
        ),
        RegionCarrier::Sphere { center, radius, .. } => {
            (AnalyticSurface::Sphere(SphereSurface { center: v(center), radius }), 4)
        }
        RegionCarrier::Torus { center, axis_dir, major_radius, minor_radius, .. } => (
            AnalyticSurface::Torus(TorusSurface { center: v(center), axis: v(axis_dir), major_radius, minor_radius }),
            7,
        ),
        RegionCarrier::Freeform => return None,
    })
}

fn gate_segmentation(
    positions: &[f64],
    indices: Option<&[u32]>,
    options: &StlConversionOptions,
) -> Result<MeshSegmentation, String> {
    let owned_indices;
    let indices = match indices {
        Some(indices) => indices,
        None => {
            owned_indices = (0..positions.len() as u32 / 3).collect::<Vec<_>>();
            &owned_indices
        }
    };
    segment_mesh_faces(positions, indices, &segmentation_options(positions, options))
        .map_err(|error| format!("kernel segmentation failed: {error}"))
}

/// Every triangle assigned, every region on an analytic carrier.
fn segmentation_is_complete(segmentation: &MeshSegmentation) -> bool {
    !segmentation
        .triangle_region_ids
        .contains(&UNASSIGNED_REGION)
        && segmentation
            .regions
            .iter()
            .all(|region| !matches!(region.carrier, RegionCarrier::Freeform))
}

/// Whether RANSAC recognition can feed a conversion lane.
///
/// Its only consumers are the exact sphere / torus / capped cylinder /
/// capped cone lanes, which need a closed mesh whose every triangle lies on
/// one of at most [`MAX_WHOLE_PRIMITIVE_REGIONS`] analytic regions. The
/// kernel segmentation provides the initial eligibility test. A separate
/// geometric check can rescue a fragmented whole primitive. `Err` here records
/// why the region-count test alone did not establish eligibility.
fn recognition_gate(segmentation: &Result<MeshSegmentation, String>) -> Result<(), String> {
    let segmentation = segmentation.as_ref().map_err(Clone::clone)?;
    let unassigned = segmentation
        .triangle_region_ids
        .iter()
        .filter(|id| **id == UNASSIGNED_REGION)
        .count();
    let unsupported = segmentation
        .regions
        .iter()
        .filter(|region| matches!(region.carrier, RegionCarrier::Freeform))
        .count();
    if unassigned > 0 || unsupported > 0 {
        return Err(format!(
            "kernel segmentation left {unassigned} triangle(s) unassigned and {unsupported} region(s) without an analytic carrier, so no whole-primitive lane can fire"
        ));
    }
    if segmentation.regions.len() > MAX_WHOLE_PRIMITIVE_REGIONS {
        return Err(format!(
            "kernel segmentation found {} analytic regions; a whole primitive has at most {MAX_WHOLE_PRIMITIVE_REGIONS}",
            segmentation.regions.len()
        ));
    }
    Ok(())
}

fn try_kernel_analytic(
    positions: &[f64],
    indices: Option<&[u32]>,
    options: &StlConversionOptions,
) -> Result<brep_kernel::BrepSolid, String> {
    let owned_indices;
    let indices = match indices {
        Some(indices) => indices,
        None => {
            owned_indices = (0..positions.len() as u32 / 3).collect::<Vec<_>>();
            &owned_indices
        }
    };
    let segmentation_options = segmentation_options(positions, options);
    let segmentation = segment_mesh_faces(positions, indices, &segmentation_options)?;
    if segmentation
        .triangle_region_ids
        .contains(&UNASSIGNED_REGION)
    {
        return Err("independent kernel segmentation left triangles unassigned".to_owned());
    }
    if let Some(region) = segmentation.regions.iter().find(|region| {
        matches!(
            region.carrier,
            RegionCarrier::Freeform | RegionCarrier::Sphere { .. } | RegionCarrier::Torus { .. }
        )
    }) {
        return Err(format!(
            "independent kernel segmentation produced unsupported {} region {}",
            region.carrier.kind(),
            region.id
        ));
    }
    mesh_regions_to_brep(positions, indices, &segmentation_options)
}

fn try_hybrid_analytic(
    positions: &[f64],
    indices: Option<&[u32]>,
    options: &StlConversionOptions,
) -> Result<crate::hybrid_region_brep::HybridBrepOutput, String> {
    crate::hybrid_region_brep::hybrid_plane_cylinder_brep(
        positions,
        indices,
        &segmentation_options(positions, options),
    )
}

fn hybrid_report(stats: &crate::hybrid_region_brep::HybridBrepStats) -> HybridConversionReport {
    HybridConversionReport {
        total_faces: stats.total_faces,
        analytic_plane_faces: stats.analytic_plane_faces,
        analytic_plane_triangles: stats.analytic_plane_triangles,
        analytic_cylinder_faces: stats.analytic_cylinder_faces,
        analytic_cylinder_triangles: stats.analytic_cylinder_triangles,
        analytic_cone_faces: stats.analytic_cone_faces,
        analytic_cone_triangles: stats.analytic_cone_triangles,
        analytic_sphere_faces: stats.analytic_sphere_faces,
        analytic_sphere_triangles: stats.analytic_sphere_triangles,
        analytic_torus_faces: stats.analytic_torus_faces,
        analytic_torus_triangles: stats.analytic_torus_triangles,
        faceted_faces: stats.faceted_faces,
        faceted_triangles: stats.faceted_triangles,
        demoted_regions: stats.demoted_regions,
        demoted_triangles: stats.demoted_triangles,
        segmentation_plane_regions: stats.segmentation_plane_regions,
        segmentation_cylinder_regions: stats.segmentation_cylinder_regions,
        segmentation_cone_regions: stats.segmentation_cone_regions,
        segmentation_sphere_regions: stats.segmentation_sphere_regions,
        segmentation_torus_regions: stats.segmentation_torus_regions,
        segmentation_unsupported_regions: stats.segmentation_unsupported_regions,
    }
}

fn kernel_vec(value: Vec3) -> brep_kernel::Vec3 {
    brep_kernel::Vec3::new(value.x, value.y, value.z)
}