brepkit-wasm 3.2.15

WebAssembly bindings for brepkit — browser-native B-Rep solid modeling
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
//! Reproducer tests for gridfinity-layout-tool dual-kernel failures.
//!
//! These tests reproduce the scenarios from issues #258, #259, #260 using
//! WASM contract tests via `execute_batch()`. Tests that reproduce known
//! bugs are marked `#[ignore]` with a comment linking to the issue.
//!
//! # Categories
//!
//! - **A**: Compound boolean crash reproducers (#258)
//! - **B**: Volume / bounding box regression reproducers (#260)
//!
//! Tessellation reproducers (#259) live in
//! `crates/operations/src/tessellate.rs` since `tessellateSolid` is not
//! in the batch dispatcher.
//!
//! # Solid Handle Numbering
//!
//! Solid handles are arena indices, NOT batch result indices.
//! Ops that create new solids: `makeBox`, `makeCylinder`, `makeSphere`,
//! `makeCone`, `makeTorus`, `copyAndTransformSolid`, `copySolid`,
//! `fuse`, `cut`, `intersect`, `compoundCut`, `fillet`, `chamfer`,
//! `extrude`, `revolve`, `sweep`, `loft`, `loftSmooth`, `shell`, `pipe`.
//!
//! Ops that do NOT create new solids (return same handle or a float):
//! `transform`, `volume`, `surfaceArea`, `boundingBox`, `centerOfMass`.

#![allow(
    clippy::unwrap_used,
    clippy::expect_used,
    clippy::panic,
    clippy::cast_possible_wrap,
    clippy::manual_assert,
    clippy::vec_init_then_push,
    clippy::print_stdout,
    clippy::print_stderr
)]

use crate::kernel::BrepKernel;

/// Parse the batch result JSON and return the parsed array.
fn parse_batch(result: &str) -> serde_json::Value {
    serde_json::from_str(result).expect("batch result should be valid JSON")
}

/// Check that batch result at `idx` has an `"ok"` field (not an error).
fn assert_ok(parsed: &serde_json::Value, idx: usize) {
    assert!(
        parsed[idx].get("ok").is_some(),
        "expected ok at index {idx}, got: {}",
        parsed[idx]
    );
}

/// Check that batch result at `idx` completed without crash.
fn assert_no_crash(parsed: &serde_json::Value, idx: usize, msg: &str) {
    assert!(
        parsed[idx].get("ok").is_some() || parsed[idx].get("error").is_some(),
        "{msg}: got: {}",
        parsed[idx]
    );
}

/// Extract the `"ok"` value as f64 (volume, area, etc.).
fn ok_f64(parsed: &serde_json::Value, idx: usize) -> f64 {
    parsed[idx]["ok"]
        .as_f64()
        .unwrap_or_else(|| panic!("expected ok f64 at index {idx}, got: {}", parsed[idx]))
}

/// Extract bounding box as `[min_x, min_y, min_z, max_x, max_y, max_z]`.
fn ok_bbox(parsed: &serde_json::Value, idx: usize) -> [f64; 6] {
    let arr = parsed[idx]["ok"]
        .as_array()
        .unwrap_or_else(|| panic!("expected ok array at index {idx}, got: {}", parsed[idx]));
    assert_eq!(arr.len(), 6, "bbox should have 6 elements");
    let mut out = [0.0; 6];
    for (i, v) in arr.iter().enumerate() {
        out[i] = v.as_f64().unwrap();
    }
    out
}

/// Build a row-major translation matrix JSON fragment.
///
/// `Mat4` is row-major: `rows[i][j] = elems[i*4+j]`.
/// Translation goes at `[0][3], [1][3], [2][3]` (flat indices 3, 7, 11).
fn translate_matrix(x: f64, y: f64, z: f64) -> String {
    format!("[1,0,0,{x}, 0,1,0,{y}, 0,0,1,{z}, 0,0,0,1]")
}

// ═══════════════════════════════════════════════════════════════════════
// Category A: Compound Boolean Crash Reproducers (#258)
//
// These reproduce scenarios where compound booleans with 3+ tools cause
// RefCell aliasing panics in the WASM layer. The test passes if the
// operation completes without panic (returning an error is also acceptable).
// ═══════════════════════════════════════════════════════════════════════

/// 4 cylinder magnet sockets cut from a baseplate.
///
/// Solids: 0=box, 1=cylinder, 2-5=copies, 6=compoundCut result
#[test]
fn compound_cut_4_cylinders() {
    let mut k = BrepKernel::new();
    let result = k.execute_batch(
        r#"[
        {"op": "makeBox", "args": {"width": 42, "height": 42, "depth": 5}},
        {"op": "makeCylinder", "args": {"radius": 3.0, "height": 10.0}},
        {"op": "copyAndTransformSolid", "args": {"solid": 1, "matrix": [1,0,0,5, 0,1,0,5, 0,0,1,-2.5, 0,0,0,1]}},
        {"op": "copyAndTransformSolid", "args": {"solid": 1, "matrix": [1,0,0,37, 0,1,0,5, 0,0,1,-2.5, 0,0,0,1]}},
        {"op": "copyAndTransformSolid", "args": {"solid": 1, "matrix": [1,0,0,5, 0,1,0,37, 0,0,1,-2.5, 0,0,0,1]}},
        {"op": "copyAndTransformSolid", "args": {"solid": 1, "matrix": [1,0,0,37, 0,1,0,37, 0,0,1,-2.5, 0,0,0,1]}},
        {"op": "compoundCut", "args": {"target": 0, "tools": [2, 3, 4, 5]}}
    ]"#,
    );
    let parsed = parse_batch(&result);
    assert_no_crash(&parsed, 6, "compoundCut with 4 cylinders should not crash");
}

/// 4 box cutouts from each wall side.
///
/// Solids: 0=target, 1=x-template, 2-3=x-cutouts, 4=y-template,
///         5-6=y-cutouts, 7=compoundCut result
#[test]
fn compound_cut_wall_cutouts() {
    let mut k = BrepKernel::new();
    let result = k.execute_batch(
        r#"[
        {"op": "makeBox", "args": {"width": 20, "height": 20, "depth": 10}},
        {"op": "makeBox", "args": {"width": 5, "height": 22, "depth": 5}},
        {"op": "copyAndTransformSolid", "args": {"solid": 1, "matrix": [1,0,0,-2, 0,1,0,-1, 0,0,1,2.5, 0,0,0,1]}},
        {"op": "copyAndTransformSolid", "args": {"solid": 1, "matrix": [1,0,0,17, 0,1,0,-1, 0,0,1,2.5, 0,0,0,1]}},
        {"op": "makeBox", "args": {"width": 22, "height": 5, "depth": 5}},
        {"op": "copyAndTransformSolid", "args": {"solid": 4, "matrix": [1,0,0,-1, 0,1,0,-2, 0,0,1,2.5, 0,0,0,1]}},
        {"op": "copyAndTransformSolid", "args": {"solid": 4, "matrix": [1,0,0,-1, 0,1,0,17, 0,0,1,2.5, 0,0,0,1]}},
        {"op": "compoundCut", "args": {"target": 0, "tools": [2, 3, 5, 6]}}
    ]"#,
    );
    let parsed = parse_batch(&result);
    assert_no_crash(&parsed, 7, "compoundCut with wall cutouts should not crash");
}

/// Mixed insert shapes: cylinder + 2 boxes.
///
/// Solids: 0=target, 1=cylinder, 2=cyl-copy, 3=box-template,
///         4-5=box-copies, 6=compoundCut result
#[test]
fn compound_cut_inserts_mixed() {
    let mut k = BrepKernel::new();
    let result = k.execute_batch(
        r#"[
        {"op": "makeBox", "args": {"width": 30, "height": 30, "depth": 8}},
        {"op": "makeCylinder", "args": {"radius": 2.0, "height": 12.0}},
        {"op": "copyAndTransformSolid", "args": {"solid": 1, "matrix": [1,0,0,15, 0,1,0,15, 0,0,1,-2, 0,0,0,1]}},
        {"op": "makeBox", "args": {"width": 4, "height": 4, "depth": 12}},
        {"op": "copyAndTransformSolid", "args": {"solid": 3, "matrix": [1,0,0,5, 0,1,0,5, 0,0,1,-2, 0,0,0,1]}},
        {"op": "copyAndTransformSolid", "args": {"solid": 3, "matrix": [1,0,0,22, 0,1,0,22, 0,0,1,-2, 0,0,0,1]}},
        {"op": "compoundCut", "args": {"target": 0, "tools": [2, 4, 5]}}
    ]"#,
    );
    let parsed = parse_batch(&result);
    assert_no_crash(
        &parsed,
        6,
        "compoundCut with mixed inserts should not crash",
    );
}

/// 6 dividers via sequential cuts (3 in X + 3 in Y).
///
/// Solids: 0=target, 1=x-template, 2-4=x-dividers, 5=y-template,
///         6-8=y-dividers, 9-14=cut results
#[test]
fn sequential_cut_many_dividers() {
    let mut k = BrepKernel::new();
    let result = k.execute_batch(
        r#"[
        {"op": "makeBox", "args": {"width": 40, "height": 40, "depth": 10}},
        {"op": "makeBox", "args": {"width": 1, "height": 42, "depth": 12}},
        {"op": "copyAndTransformSolid", "args": {"solid": 1, "matrix": [1,0,0,9.5, 0,1,0,-1, 0,0,1,-1, 0,0,0,1]}},
        {"op": "copyAndTransformSolid", "args": {"solid": 1, "matrix": [1,0,0,19.5, 0,1,0,-1, 0,0,1,-1, 0,0,0,1]}},
        {"op": "copyAndTransformSolid", "args": {"solid": 1, "matrix": [1,0,0,29.5, 0,1,0,-1, 0,0,1,-1, 0,0,0,1]}},
        {"op": "makeBox", "args": {"width": 42, "height": 1, "depth": 12}},
        {"op": "copyAndTransformSolid", "args": {"solid": 5, "matrix": [1,0,0,-1, 0,1,0,9.5, 0,0,1,-1, 0,0,0,1]}},
        {"op": "copyAndTransformSolid", "args": {"solid": 5, "matrix": [1,0,0,-1, 0,1,0,19.5, 0,0,1,-1, 0,0,0,1]}},
        {"op": "copyAndTransformSolid", "args": {"solid": 5, "matrix": [1,0,0,-1, 0,1,0,29.5, 0,0,1,-1, 0,0,0,1]}},
        {"op": "cut", "args": {"solidA": 0, "solidB": 2}},
        {"op": "cut", "args": {"solidA": 9, "solidB": 3}},
        {"op": "cut", "args": {"solidA": 10, "solidB": 4}},
        {"op": "cut", "args": {"solidA": 11, "solidB": 6}},
        {"op": "cut", "args": {"solidA": 12, "solidB": 7}},
        {"op": "cut", "args": {"solidA": 13, "solidB": 8}}
    ]"#,
    );
    let parsed = parse_batch(&result);
    for i in 9..=14 {
        assert_no_crash(&parsed, i, &format!("sequential cut step {i}"));
    }
}

/// Compound cut with 5 cylinders (slot pattern).
///
/// Solids: 0=box, 1=cylinder, 2-6=copies, 7=compoundCut result
#[test]
fn compound_cut_slotted() {
    let mut k = BrepKernel::new();
    let result = k.execute_batch(
        r#"[
        {"op": "makeBox", "args": {"width": 30, "height": 10, "depth": 5}},
        {"op": "makeCylinder", "args": {"radius": 1.0, "height": 8.0}},
        {"op": "copyAndTransformSolid", "args": {"solid": 1, "matrix": [1,0,0,5, 0,1,0,5, 0,0,1,-1.5, 0,0,0,1]}},
        {"op": "copyAndTransformSolid", "args": {"solid": 1, "matrix": [1,0,0,10, 0,1,0,5, 0,0,1,-1.5, 0,0,0,1]}},
        {"op": "copyAndTransformSolid", "args": {"solid": 1, "matrix": [1,0,0,15, 0,1,0,5, 0,0,1,-1.5, 0,0,0,1]}},
        {"op": "copyAndTransformSolid", "args": {"solid": 1, "matrix": [1,0,0,20, 0,1,0,5, 0,0,1,-1.5, 0,0,0,1]}},
        {"op": "copyAndTransformSolid", "args": {"solid": 1, "matrix": [1,0,0,25, 0,1,0,5, 0,0,1,-1.5, 0,0,0,1]}},
        {"op": "compoundCut", "args": {"target": 0, "tools": [2, 3, 4, 5, 6]}}
    ]"#,
    );
    let parsed = parse_batch(&result);
    assert_no_crash(&parsed, 7, "compoundCut with 5 slot cylinders");
}

/// Honeycomb pattern: many cylinder tools.
///
/// Solids: 0=box, 1=cylinder, 2-10=copies, 11=compoundCut result
#[test]
fn compound_cut_honeycomb() {
    let mut k = BrepKernel::new();
    let mut ops: Vec<String> = vec![
        r#"{"op": "makeBox", "args": {"width": 30, "height": 30, "depth": 3}}"#.to_string(),
        r#"{"op": "makeCylinder", "args": {"radius": 2.0, "height": 6.0}}"#.to_string(),
    ];
    let mut tool_handles = Vec::new();
    let mut handle = 2u32;
    for row in 0..3 {
        for col in 0..3 {
            let x = 5.0 + col as f64 * 10.0;
            let y = 5.0 + row as f64 * 10.0;
            let mat = translate_matrix(x, y, -1.5);
            ops.push(format!(
                r#"{{"op": "copyAndTransformSolid", "args": {{"solid": 1, "matrix": {mat}}}}}"#
            ));
            tool_handles.push(handle);
            handle += 1;
        }
    }
    let tools_json = serde_json::to_string(&tool_handles).unwrap();
    ops.push(format!(
        r#"{{"op": "compoundCut", "args": {{"target": 0, "tools": {tools_json}}}}}"#
    ));
    let json = format!("[{}]", ops.join(","));

    let result = k.execute_batch(&json);
    let parsed = parse_batch(&result);
    let last_idx = ops.len() - 1;
    assert_no_crash(&parsed, last_idx, "compoundCut with 9 honeycomb cylinders");
}

/// Fillet first, then compound cut — the fillet introduces torus faces.
///
/// Uses `solidEdges` to get edge handles, then fillets the first edge.
/// Split into batches because fillet may fail, shifting handles.
#[test]
fn fillet_then_compound_cut() {
    let mut k = BrepKernel::new();
    // Batch 1: create box + query edges + fillet first edge.
    let r1 = k.execute_batch(
        r#"[
        {"op": "makeBox", "args": {"width": 20, "height": 20, "depth": 10}},
        {"op": "solidEdges", "args": {"solid": 0}}
    ]"#,
    );
    let p1 = parse_batch(&r1);
    assert_ok(&p1, 1);
    let edges = p1[1]["ok"]
        .as_array()
        .expect("solidEdges should return array");
    assert!(!edges.is_empty(), "box should have edges");
    // Fillet the first edge.
    let edge0 = edges[0].as_u64().unwrap();
    let r2 = k.execute_batch(&format!(
        r#"[{{"op": "fillet", "args": {{"solid": 0, "radius": 1.0, "edges": [{edge0}]}}}}]"#
    ));
    let p2 = parse_batch(&r2);
    if p2[0].get("error").is_some() {
        return; // Fillet failed — skip compound cut.
    }
    // Batch 3: cylinder tools + compoundCut on the filleted solid (handle 1).
    let r3 = k.execute_batch(
        r#"[
        {"op": "makeCylinder", "args": {"radius": 2.0, "height": 14.0}},
        {"op": "copyAndTransformSolid", "args": {"solid": 2, "matrix": [1,0,0,5, 0,1,0,5, 0,0,1,-2, 0,0,0,1]}},
        {"op": "copyAndTransformSolid", "args": {"solid": 2, "matrix": [1,0,0,15, 0,1,0,5, 0,0,1,-2, 0,0,0,1]}},
        {"op": "copyAndTransformSolid", "args": {"solid": 2, "matrix": [1,0,0,10, 0,1,0,15, 0,0,1,-2, 0,0,0,1]}},
        {"op": "compoundCut", "args": {"target": 1, "tools": [3, 4, 5]}}
    ]"#,
    );
    let p3 = parse_batch(&r3);
    assert_no_crash(&p3, 4, "fillet + compoundCut");
}

/// Sequential 5-cylinder cuts (not compound — one at a time).
///
/// Solids: 0=box, 1=cylinder, 2-6=copies, 7-11=cut results
#[test]
fn sequential_cut_5_cylinders() {
    let mut k = BrepKernel::new();
    let result = k.execute_batch(
        r#"[
        {"op": "makeBox", "args": {"width": 20, "height": 20, "depth": 8}},
        {"op": "makeCylinder", "args": {"radius": 1.5, "height": 12.0}},
        {"op": "copyAndTransformSolid", "args": {"solid": 1, "matrix": [1,0,0,4, 0,1,0,10, 0,0,1,-2, 0,0,0,1]}},
        {"op": "copyAndTransformSolid", "args": {"solid": 1, "matrix": [1,0,0,8, 0,1,0,10, 0,0,1,-2, 0,0,0,1]}},
        {"op": "copyAndTransformSolid", "args": {"solid": 1, "matrix": [1,0,0,12, 0,1,0,10, 0,0,1,-2, 0,0,0,1]}},
        {"op": "copyAndTransformSolid", "args": {"solid": 1, "matrix": [1,0,0,16, 0,1,0,10, 0,0,1,-2, 0,0,0,1]}},
        {"op": "copyAndTransformSolid", "args": {"solid": 1, "matrix": [1,0,0,10, 0,1,0,10, 0,0,1,-2, 0,0,0,1]}},
        {"op": "cut", "args": {"solidA": 0, "solidB": 2}},
        {"op": "cut", "args": {"solidA": 7, "solidB": 3}},
        {"op": "cut", "args": {"solidA": 8, "solidB": 4}},
        {"op": "cut", "args": {"solidA": 9, "solidB": 5}},
        {"op": "cut", "args": {"solidA": 10, "solidB": 6}}
    ]"#,
    );
    let parsed = parse_batch(&result);
    for i in 7..=11 {
        assert_no_crash(&parsed, i, &format!("sequential cut step {i}"));
    }
}

/// Fuse two boxes, then compound-cut the result.
///
/// Solids: 0=box1, 1=box2, 2=box2-copy (translated), 3=fused,
///         4=cylinder, 5-6=cyl-copies, 7=compoundCut result
#[test]
fn compound_cut_after_fuse() {
    let mut k = BrepKernel::new();
    let result = k.execute_batch(
        r#"[
        {"op": "makeBox", "args": {"width": 10, "height": 10, "depth": 10}},
        {"op": "makeBox", "args": {"width": 10, "height": 10, "depth": 10}},
        {"op": "copyAndTransformSolid", "args": {"solid": 1, "matrix": [1,0,0,5, 0,1,0,0, 0,0,1,0, 0,0,0,1]}},
        {"op": "fuse", "args": {"solidA": 0, "solidB": 2}},
        {"op": "makeCylinder", "args": {"radius": 1.5, "height": 14.0}},
        {"op": "copyAndTransformSolid", "args": {"solid": 4, "matrix": [1,0,0,5, 0,1,0,5, 0,0,1,-2, 0,0,0,1]}},
        {"op": "copyAndTransformSolid", "args": {"solid": 4, "matrix": [1,0,0,10, 0,1,0,5, 0,0,1,-2, 0,0,0,1]}},
        {"op": "compoundCut", "args": {"target": 3, "tools": [5, 6]}}
    ]"#,
    );
    let parsed = parse_batch(&result);
    assert_no_crash(&parsed, 7, "fuse + compoundCut");
}

/// Fuse many boxes at once via `fuseAll` (mix of overlapping + disjoint).
///
/// Exercises both `fuse_all` paths: boxes 0 and 2 overlap (pairwise boolean
/// reduction) while box 3 is far away (disjoint-merge fast path).
///
/// Solids: 0=box, 2=overlapping copy, 3=disjoint copy, 4=fuseAll result.
#[test]
fn fuse_all_mixed_overlap_and_disjoint() {
    let mut k = BrepKernel::new();
    let result = k.execute_batch(
        r#"[
        {"op": "makeBox", "args": {"width": 10, "height": 10, "depth": 10}},
        {"op": "makeBox", "args": {"width": 10, "height": 10, "depth": 10}},
        {"op": "copyAndTransformSolid", "args": {"solid": 1, "matrix": [1,0,0,5, 0,1,0,0, 0,0,1,0, 0,0,0,1]}},
        {"op": "copyAndTransformSolid", "args": {"solid": 1, "matrix": [1,0,0,50, 0,1,0,0, 0,0,1,0, 0,0,0,1]}},
        {"op": "fuseAll", "args": {"solids": [0, 2, 3]}}
    ]"#,
    );
    let parsed = parse_batch(&result);
    assert_no_crash(&parsed, 4, "fuseAll mix of overlapping and disjoint boxes");
    assert_ok(&parsed, 4);

    let handle = parsed[4]["ok"]
        .as_u64()
        .expect("fuseAll should return a solid handle") as u32;
    let counts = k
        .get_entity_counts(handle)
        .expect("fuseAll result should be a valid solid");
    assert_eq!(
        counts.len(),
        3,
        "entity counts are [faces, edges, vertices]"
    );
    assert!(
        counts[0] > 0 && counts[1] > 0 && counts[2] > 0,
        "fused solid should be non-empty, got {counts:?}"
    );
}

/// Full pipeline: box + fuse + fillet + compoundCut.
///
/// Uses `solidEdges` to get edge handles for the fillet step.
/// Split into batches because fillet may fail, shifting handles.
#[test]
fn batch_fuse_cut_fillet_compound() {
    let mut k = BrepKernel::new();
    // Batch 1: create two boxes, fuse them.
    // Solids: 0=box1, 1=box2, 2=box2-copy (translated), 3=fused
    let r1 = k.execute_batch(
        r#"[
        {"op": "makeBox", "args": {"width": 10, "height": 10, "depth": 10}},
        {"op": "makeBox", "args": {"width": 10, "height": 10, "depth": 5}},
        {"op": "copyAndTransformSolid", "args": {"solid": 1, "matrix": [1,0,0,0, 0,1,0,0, 0,0,1,10, 0,0,0,1]}},
        {"op": "fuse", "args": {"solidA": 0, "solidB": 2}},
        {"op": "solidEdges", "args": {"solid": 3}}
    ]"#,
    );
    let p1 = parse_batch(&r1);
    assert_ok(&p1, 3); // fuse succeeded
    assert_ok(&p1, 4); // solidEdges succeeded
    let edges = p1[4]["ok"]
        .as_array()
        .expect("solidEdges should return array");
    assert!(!edges.is_empty(), "fused solid should have edges");
    let edge0 = edges[0].as_u64().unwrap();

    // Batch 2: fillet first edge.
    // Solids: 4=filleted
    let r2 = k.execute_batch(&format!(
        r#"[{{"op": "fillet", "args": {{"solid": 3, "radius": 0.5, "edges": [{edge0}]}}}}]"#
    ));
    let p2 = parse_batch(&r2);
    if p2[0].get("error").is_some() {
        return; // Fillet failed — skip compound cut.
    }

    // Batch 3: cylinder tools + compoundCut on filleted solid (handle 4).
    // Solids: 5=cylinder, 6-8=cyl-copies, 9=compoundCut
    let r3 = k.execute_batch(
        r#"[
        {"op": "makeCylinder", "args": {"radius": 1.0, "height": 20.0}},
        {"op": "copyAndTransformSolid", "args": {"solid": 5, "matrix": [1,0,0,5, 0,1,0,5, 0,0,1,-2, 0,0,0,1]}},
        {"op": "copyAndTransformSolid", "args": {"solid": 5, "matrix": [1,0,0,3, 0,1,0,3, 0,0,1,-2, 0,0,0,1]}},
        {"op": "copyAndTransformSolid", "args": {"solid": 5, "matrix": [1,0,0,7, 0,1,0,7, 0,0,1,-2, 0,0,0,1]}},
        {"op": "compoundCut", "args": {"target": 4, "tools": [6, 7, 8]}}
    ]"#,
    );
    let p3 = parse_batch(&r3);
    assert_no_crash(&p3, 4, "full pipeline (fuse+fillet+compoundCut)");
}

/// Compound cut with several tools, then measure.
///
/// Solids: 0=box, 1=cylinder, 2-5=copies, 6=compoundCut result
#[test]
fn compound_cut_then_measure() {
    let mut k = BrepKernel::new();
    let result = k.execute_batch(
        r#"[
        {"op": "makeBox", "args": {"width": 20, "height": 20, "depth": 5}},
        {"op": "makeCylinder", "args": {"radius": 2.0, "height": 8.0}},
        {"op": "copyAndTransformSolid", "args": {"solid": 1, "matrix": [1,0,0,5, 0,1,0,5, 0,0,1,-1.5, 0,0,0,1]}},
        {"op": "copyAndTransformSolid", "args": {"solid": 1, "matrix": [1,0,0,15, 0,1,0,5, 0,0,1,-1.5, 0,0,0,1]}},
        {"op": "copyAndTransformSolid", "args": {"solid": 1, "matrix": [1,0,0,5, 0,1,0,15, 0,0,1,-1.5, 0,0,0,1]}},
        {"op": "copyAndTransformSolid", "args": {"solid": 1, "matrix": [1,0,0,15, 0,1,0,15, 0,0,1,-1.5, 0,0,0,1]}},
        {"op": "compoundCut", "args": {"target": 0, "tools": [2, 3, 4, 5]}},
        {"op": "volume", "args": {"solid": 6}},
        {"op": "boundingBox", "args": {"solid": 6}}
    ]"#,
    );
    let parsed = parse_batch(&result);
    // If compoundCut succeeded, volume and bbox should also succeed.
    if parsed[6].get("ok").is_some() {
        assert_ok(&parsed, 7);
        assert_ok(&parsed, 8);
        let vol = ok_f64(&parsed, 7);
        assert!(
            vol > 0.0 && vol < 2000.0,
            "volume should be positive and less than original (2000): {vol}"
        );
    }
}

// ═══════════════════════════════════════════════════════════════════════
// Category B: Volume / BBox Regression Reproducers (#260)
//
// These test geometric accuracy after boolean operations.
// ═══════════════════════════════════════════════════════════════════════

/// Sequential cylinder cuts: volume should be analytically predictable.
///
/// Solids: 0=box, 1=cylinder, 2-4=copies, 5-7=cut results
#[test]
fn sequential_booleans_volume_accuracy() {
    let mut k = BrepKernel::new();
    let result = k.execute_batch(
        r#"[
        {"op": "makeBox", "args": {"width": 10, "height": 10, "depth": 10}},
        {"op": "volume", "args": {"solid": 0}},
        {"op": "makeCylinder", "args": {"radius": 1.0, "height": 14.0}},
        {"op": "copyAndTransformSolid", "args": {"solid": 1, "matrix": [1,0,0,2, 0,1,0,5, 0,0,1,-2, 0,0,0,1]}},
        {"op": "copyAndTransformSolid", "args": {"solid": 1, "matrix": [1,0,0,5, 0,1,0,5, 0,0,1,-2, 0,0,0,1]}},
        {"op": "copyAndTransformSolid", "args": {"solid": 1, "matrix": [1,0,0,8, 0,1,0,5, 0,0,1,-2, 0,0,0,1]}},
        {"op": "cut", "args": {"solidA": 0, "solidB": 2}},
        {"op": "cut", "args": {"solidA": 5, "solidB": 3}},
        {"op": "cut", "args": {"solidA": 6, "solidB": 4}},
        {"op": "volume", "args": {"solid": 7}}
    ]"#,
    );
    let parsed = parse_batch(&result);
    for i in 6..=8 {
        assert_ok(&parsed, i);
    }
    let original_vol = ok_f64(&parsed, 1);
    let result_vol = ok_f64(&parsed, 9);
    // Each cylinder removes π * r² * h_inside = π * 1 * 10 ≈ 31.4 from the box.
    let expected = original_vol - 3.0 * std::f64::consts::PI * 1.0 * 10.0;
    let rel_error = ((result_vol - expected) / expected).abs();
    assert!(
        rel_error < 0.05,
        "volume after 3 cylinder cuts: got {result_vol:.1}, expected {expected:.1}, \
         error {:.1}% (issue #260)",
        rel_error * 100.0
    );
}

/// Fillet should not change the bounding box of a box.
///
/// Uses `solidEdges` to get edge handles for the fillet.
#[test]
fn fillet_box_bbox_unchanged() {
    let mut k = BrepKernel::new();
    // Get box bbox and edge handles.
    let r1 = k.execute_batch(
        r#"[
        {"op": "makeBox", "args": {"width": 10, "height": 10, "depth": 10}},
        {"op": "boundingBox", "args": {"solid": 0}},
        {"op": "solidEdges", "args": {"solid": 0}}
    ]"#,
    );
    let p1 = parse_batch(&r1);
    assert_ok(&p1, 1); // boundingBox
    assert_ok(&p1, 2); // solidEdges
    let bbox_before = ok_bbox(&p1, 1);
    let edges = p1[2]["ok"]
        .as_array()
        .expect("solidEdges should return array");
    assert!(!edges.is_empty(), "box should have edges");
    let edge0 = edges[0].as_u64().unwrap();

    // Fillet first edge + get bbox.
    let r2 = k.execute_batch(&format!(
        r#"[
        {{"op": "fillet", "args": {{"solid": 0, "radius": 1.0, "edges": [{edge0}]}}}},
        {{"op": "boundingBox", "args": {{"solid": 1}}}}
    ]"#
    ));
    let p2 = parse_batch(&r2);

    // Fillet might fail — only check bbox if it succeeded.
    if p2[0].get("ok").is_some() {
        assert_ok(&p2, 1);
        let bbox_after = ok_bbox(&p2, 1);
        let tol = 0.01;
        for i in 0..6 {
            assert!(
                (bbox_before[i] - bbox_after[i]).abs() < tol,
                "bbox[{i}] shifted after fillet: {:.3} → {:.3} (issue #260)",
                bbox_before[i],
                bbox_after[i]
            );
        }
    }
}

/// Cylinder cut from center: outer bounding box should not change.
///
/// Solids: 0=box, 1=cylinder, 2=cyl-copy, 3=cut result
#[test]
fn compound_cut_bbox_accurate() {
    let mut k = BrepKernel::new();
    let result = k.execute_batch(
        r#"[
        {"op": "makeBox", "args": {"width": 20, "height": 20, "depth": 10}},
        {"op": "boundingBox", "args": {"solid": 0}},
        {"op": "makeCylinder", "args": {"radius": 2.0, "height": 14.0}},
        {"op": "copyAndTransformSolid", "args": {"solid": 1, "matrix": [1,0,0,10, 0,1,0,10, 0,0,1,-2, 0,0,0,1]}},
        {"op": "cut", "args": {"solidA": 0, "solidB": 2}},
        {"op": "boundingBox", "args": {"solid": 3}}
    ]"#,
    );
    let parsed = parse_batch(&result);
    assert_ok(&parsed, 1); // boundingBox on original box
    let bbox_before = ok_bbox(&parsed, 1);

    if parsed[4].get("ok").is_some() {
        assert_ok(&parsed, 5); // boundingBox on cut result
        let bbox_after = ok_bbox(&parsed, 5);
        let tol = 0.1;
        for i in 0..6 {
            assert!(
                (bbox_before[i] - bbox_after[i]).abs() < tol,
                "bbox[{i}] shifted after cylinder cut: {:.3} → {:.3} (issue #260)",
                bbox_before[i],
                bbox_after[i]
            );
        }
    }
}

// ═══════════════════════════════════════════════════════════════════════
// Category C: Face explosion regression (#270)
//
// These test that sequential booleans with fillet/fuse/cut do not cause
// face count explosion.
// ═══════════════════════════════════════════════════════════════════════

/// Fillet + fuse lip: volume should be reasonable.
///
/// Reproduces the gridfinity stacking lip scenario from #270:
/// makeBox → fillet edge → fuse lip shape → measure volume.
/// Exercises the NURBS/torus surface path that caused face explosion.
///
/// Solids: 0=box, 1=filleted, 2=lip_box, 3=fused
#[test]
fn gridfinity_lip_fillet_fuse_volume() {
    let mut k = BrepKernel::new();

    // Batch 1: create box + query edges.
    let r1 = k.execute_batch(
        r#"[
        {"op": "makeBox", "args": {"width": 42, "height": 42, "depth": 7}},
        {"op": "solidEdges", "args": {"solid": 0}}
    ]"#,
    );
    let p1 = parse_batch(&r1);
    assert_ok(&p1, 0);
    assert_ok(&p1, 1);
    let edges = p1[1]["ok"]
        .as_array()
        .expect("solidEdges should return array");
    assert!(!edges.is_empty(), "box should have edges");
    let edge0 = edges[0].as_u64().unwrap();

    // Fillet first edge — assert success.
    let r2 = k.execute_batch(&format!(
        r#"[{{"op": "fillet", "args": {{"solid": 0, "radius": 0.8, "edges": [{edge0}]}}}}]"#
    ));
    let p2 = parse_batch(&r2);
    assert_ok(&p2, 0);
    let filleted_handle = p2[0]["ok"].as_u64().unwrap();

    // Create lip shape, fuse, then measure volume.
    let r3 = k.execute_batch(&format!(
        r#"[
        {{"op": "makeBox", "args": {{"width": 44, "height": 44, "depth": 2}}}},
        {{"op": "transform", "args": {{"solid": 2, "matrix": [1,0,0,-1, 0,1,0,-1, 0,0,1,7, 0,0,0,1]}}}},
        {{"op": "fuse", "args": {{"solidA": {filleted_handle}, "solidB": 2}}}},
        {{"op": "volume", "args": {{"solid": 3}}}}
    ]"#,
    ));
    let p3 = parse_batch(&r3);
    assert_ok(&p3, 2);
    let vol = ok_f64(&p3, 3);
    // Box 42×42×7 = 12348, lip 44×44×2 = 3872, adjacent at z=7.
    // Expected ≈ 16220 minus fillet material.
    assert!(
        vol > 10000.0 && vol < 20000.0,
        "gridfinity lip fuse volume should be ~16000: got {vol:.0} (issue #270)"
    );
}

// ═══════════════════════════════════════════════════════════════════════
// Category D: Lip Topology Reproducers (stacking lip parity)
//
// These reproduce the exact geometry from `buildTopShapeLoft()` in
// gridfinity-layout-tool's boxBuilder.ts. The stacking lip is built as:
//   1. Ruled loft of rounded-rectangle sections (outer frustum)
//   2. Same but inset by wall thickness (inner frustum)
//   3. Boolean cut (outer - inner) → hollow ring
//   4. Fillet peak edges at Z_PEAK
//
// Gridfinity spec constants (mm):
//   Grid size: 42, clearance: 0.5 → outer = 41.5 × 41.5
//   Corner radius: 4.0
//   Lip profile: 0.7mm small taper + 1.8mm vertical + 1.9mm big taper = 4.4mm
//   Wall (taper width): 2.6mm (= 0.7 + 1.9)
//   Top fillet: 0.6mm
// ═══════════════════════════════════════════════════════════════════════

// Gridfinity lip constants
const OUTER_DIM: f64 = 41.5; // 1×1 bin: 42 - 0.5 clearance
const CORNER_R: f64 = 4.0; // socket corner radius
const WALL: f64 = 2.6; // LIP_TAPER_WIDTH = 0.7 + 1.9
const _LIP_EXT: f64 = 1.2; // lip extension below base
const Z_EXT: f64 = -1.2; // -LIP_EXTENSION
const Z_BASE: f64 = 0.0;
const Z_TAPER1: f64 = 0.7; // LIP_SMALL_TAPER
const Z_VERT: f64 = 2.5; // 0.7 + 1.8 (LIP_VERTICAL_PART)
const Z_PEAK: f64 = 4.4; // LIP_HEIGHT
const INSET_BOTTOM: f64 = 2.6; // LIP_TAPER_WIDTH
const INSET_MID: f64 = 1.9; // LIP_BIG_TAPER
const INSET_TOP: f64 = 0.0;
const TOP_FILLET: f64 = 0.6;
const WALL_THICKNESS: f64 = 1.6; // shell thickness for box
const WALL_HEIGHT: f64 = 21.0; // 3 height units

/// Build a rounded-rectangle face centered at origin on the XY plane at
/// height `z`, with given width, depth, and corner radius.
///
/// The wire goes counterclockwise (normal = +Z) with 4 line edges and
/// 4 quarter-circle arc edges.
fn make_rounded_rect_face(k: &mut BrepKernel, w: f64, d: f64, r: f64, z: f64) -> u32 {
    let hw = w / 2.0;
    let hd = d / 2.0;
    let r = r.min(hw).min(hd).max(0.05); // clamp to valid range

    // 8 tangent points (CCW from bottom-right)
    let pts: [(f64, f64); 8] = [
        (hw, -(hd - r)),  // 0: start of right edge (bottom)
        (hw, hd - r),     // 1: end of right edge (top)
        (hw - r, hd),     // 2: end of top-right arc / start of top edge
        (-(hw - r), hd),  // 3: end of top edge
        (-hw, hd - r),    // 4: end of top-left arc / start of left edge
        (-hw, -(hd - r)), // 5: end of left edge
        (-(hw - r), -hd), // 6: end of bottom-left arc / start of bottom edge
        (hw - r, -hd),    // 7: end of bottom edge
    ];

    // Corner arc centers
    let centers: [(f64, f64); 4] = [
        (hw - r, hd - r),       // top-right
        (-(hw - r), hd - r),    // top-left
        (-(hw - r), -(hd - r)), // bottom-left
        (hw - r, -(hd - r)),    // bottom-right
    ];

    // Build edges: line, arc, line, arc, line, arc, line, arc
    let mut edges = Vec::with_capacity(8);

    // Right side line: pts[0] → pts[1]
    edges.push(
        k.make_line_edge(pts[0].0, pts[0].1, z, pts[1].0, pts[1].1, z)
            .unwrap(),
    );
    // Top-right arc: pts[1] → pts[2], center = centers[0]
    edges.push(
        k.make_circle_arc_3d(
            pts[1].0,
            pts[1].1,
            z,
            pts[2].0,
            pts[2].1,
            z,
            centers[0].0,
            centers[0].1,
            z,
            0.0,
            0.0,
            1.0,
        )
        .unwrap(),
    );
    // Top side line: pts[2] → pts[3]
    edges.push(
        k.make_line_edge(pts[2].0, pts[2].1, z, pts[3].0, pts[3].1, z)
            .unwrap(),
    );
    // Top-left arc: pts[3] → pts[4], center = centers[1]
    edges.push(
        k.make_circle_arc_3d(
            pts[3].0,
            pts[3].1,
            z,
            pts[4].0,
            pts[4].1,
            z,
            centers[1].0,
            centers[1].1,
            z,
            0.0,
            0.0,
            1.0,
        )
        .unwrap(),
    );
    // Left side line: pts[4] → pts[5]
    edges.push(
        k.make_line_edge(pts[4].0, pts[4].1, z, pts[5].0, pts[5].1, z)
            .unwrap(),
    );
    // Bottom-left arc: pts[5] → pts[6], center = centers[2]
    edges.push(
        k.make_circle_arc_3d(
            pts[5].0,
            pts[5].1,
            z,
            pts[6].0,
            pts[6].1,
            z,
            centers[2].0,
            centers[2].1,
            z,
            0.0,
            0.0,
            1.0,
        )
        .unwrap(),
    );
    // Bottom side line: pts[6] → pts[7]
    edges.push(
        k.make_line_edge(pts[6].0, pts[6].1, z, pts[7].0, pts[7].1, z)
            .unwrap(),
    );
    // Bottom-right arc: pts[7] → pts[0], center = centers[3]
    edges.push(
        k.make_circle_arc_3d(
            pts[7].0,
            pts[7].1,
            z,
            pts[0].0,
            pts[0].1,
            z,
            centers[3].0,
            centers[3].1,
            z,
            0.0,
            0.0,
            1.0,
        )
        .unwrap(),
    );

    // Wire → face
    let wire = k.make_wire(edges, true).unwrap();
    k.make_face_from_wire(wire).unwrap()
}

/// Section dimensions at a given profile height.
fn section_dims(inset: f64) -> (f64, f64, f64) {
    let w = OUTER_DIM - 2.0 * inset;
    let d = OUTER_DIM - 2.0 * inset;
    let r = (CORNER_R - inset).max(0.1);
    (w, d, r)
}

/// Build the outer lip sections and return face handles.
///
/// The outer frustum is a rectangular tube FLUSH with the bin wall
/// (inset = 0) — it must coincide with the body's outer wall so the lip
/// fuses onto the body. (An earlier version tapered the outer profile,
/// which left the lip narrower than the wall and disjoint from the body, so
/// the fuse dropped it.) Only the INNER sections taper to form the stacking
/// ledge. Two sections (bottom extension + peak) suffice for a flush tube.
fn make_outer_sections(k: &mut BrepKernel) -> Vec<u32> {
    let mut faces = Vec::new();
    let sections: [(f64, f64); 2] = [(Z_EXT, 0.0), (Z_PEAK, 0.0)];
    for &(z, inset) in &sections {
        let (w, d, r) = section_dims(inset);
        faces.push(make_rounded_rect_face(k, w, d, r, z));
    }
    faces
}

/// Build 5 inner sections (outer + WALL inset) and return face handles.
///
/// When `z_offset` is non-zero, shifts all Z heights to avoid coplanar caps.
fn make_inner_sections_offset(k: &mut BrepKernel, z_offset: f64) -> Vec<u32> {
    let mut faces = Vec::new();
    let sections: [(f64, f64); 5] = [
        (Z_EXT + z_offset, INSET_BOTTOM + WALL),
        (Z_BASE + z_offset, INSET_BOTTOM + WALL),
        (Z_TAPER1 + z_offset, INSET_MID + WALL),
        (Z_VERT + z_offset, INSET_MID + WALL),
        (Z_PEAK + z_offset, INSET_TOP + WALL),
    ];
    for &(z, inset) in &sections {
        let (w, d, r) = section_dims(inset);
        faces.push(make_rounded_rect_face(k, w, d, r, z));
    }
    faces
}

/// Build 5 inner sections with same Z heights as outer (coplanar caps).
fn make_inner_sections(k: &mut BrepKernel) -> Vec<u32> {
    make_inner_sections_offset(k, 0.0)
}

/// D1: Lip ring — loft outer, loft inner, cut inner from outer.
///
/// Reproduces `buildTopShapeLoft()` without the final fillet.
/// Expected: valid solid, Euler=2, reasonable volume.
#[test]
fn gridfinity_d1_lip_ring_loft_cut() {
    let mut k = BrepKernel::new();

    let outer_faces = make_outer_sections(&mut k);
    let inner_faces = make_inner_sections(&mut k);

    // Loft outer frustum
    let outer_json = serde_json::to_string(&outer_faces).unwrap();
    let r1 = k.execute_batch(&format!(
        r#"[{{"op": "loft", "args": {{"faces": {outer_json}}}}}]"#
    ));
    let p1 = parse_batch(&r1);
    assert_ok(&p1, 0);
    let outer_solid = p1[0]["ok"].as_u64().unwrap() as u32;

    // Validate outer loft
    let oc = k.get_entity_counts(outer_solid).unwrap();
    let o_euler = (oc[2] as i64) - (oc[1] as i64) + (oc[0] as i64);
    let ov = k.validate_solid(outer_solid).unwrap();
    eprintln!(
        "D1 outer loft: F={}, E={}, V={}, euler={o_euler}, validation_issues={ov}",
        oc[0], oc[1], oc[2]
    );

    // Loft inner frustum
    let inner_json = serde_json::to_string(&inner_faces).unwrap();
    let r2 = k.execute_batch(&format!(
        r#"[{{"op": "loft", "args": {{"faces": {inner_json}}}}}]"#
    ));
    let p2 = parse_batch(&r2);
    assert_ok(&p2, 0);
    let inner_solid = p2[0]["ok"].as_u64().unwrap() as u32;

    // Validate inner loft
    let ic = k.get_entity_counts(inner_solid).unwrap();
    let i_euler = (ic[2] as i64) - (ic[1] as i64) + (ic[0] as i64);
    let iv = k.validate_solid(inner_solid).unwrap();
    eprintln!(
        "D1 inner loft: F={}, E={}, V={}, euler={i_euler}, validation_issues={iv}",
        ic[0], ic[1], ic[2]
    );

    // Cut: outer - inner → hollow ring
    let r3 = k.execute_batch(&format!(
        r#"[
        {{"op": "cut", "args": {{"solidA": {outer_solid}, "solidB": {inner_solid}}}}},
        {{"op": "volume", "args": {{"solid": {}}}}},
        {{"op": "boundingBox", "args": {{"solid": {}}}}}
    ]"#,
        outer_solid + 2, // cut result handle
        outer_solid + 2,
    ));
    let p3 = parse_batch(&r3);
    assert_ok(&p3, 0);

    // Volume should be positive and reasonable
    let vol = ok_f64(&p3, 1);
    assert!(
        vol > 100.0 && vol < 5000.0,
        "lip ring volume should be 100-5000 mm³: got {vol:.1}"
    );

    // BBox Z extent should be close to lip height (5.6 = 1.2 ext + 4.4 peak)
    let bbox = ok_bbox(&p3, 2);
    let z_extent = bbox[5] - bbox[2];
    assert!(
        (z_extent - 5.6).abs() < 1.0,
        "lip Z extent should be ~5.6mm: got {z_extent:.2}"
    );

    // Check Euler characteristic and validation via direct API
    let lip_handle = p3[0]["ok"].as_u64().unwrap() as u32;
    let lip_id = k.resolve_solid(lip_handle).unwrap();
    let val = k.validate_solid(lip_handle).unwrap();
    let counts = k.get_entity_counts(lip_handle).unwrap();
    let f = counts[0] as usize;
    let e = counts[1] as usize;
    let v = counts[2] as usize;
    let euler = (v as i64) - (e as i64) + (f as i64);
    eprintln!("D1 lip ring: F={f}, E={e}, V={v}, euler={euler}, vol={vol:.1}, val={val}");
    if let Ok(report) = brepkit_operations::validate::validate_solid(&k.topo, lip_id) {
        for issue in &report.issues {
            if issue.severity == brepkit_operations::validate::Severity::Error {
                eprintln!("  ERR: {}", issue.description);
            }
        }
    }
    // Dump boundary edge positions for debugging
    {
        use std::collections::HashMap;
        let solid_data = k.topo.solid(lip_id).unwrap();
        let shell = k.topo.shell(solid_data.outer_shell()).unwrap();
        let mut edge_face_count: HashMap<usize, usize> = HashMap::new();
        for &fid in shell.faces() {
            let face = k.topo.face(fid).unwrap();
            let wire = k.topo.wire(face.outer_wire()).unwrap();
            for oe in wire.edges() {
                *edge_face_count.entry(oe.edge().index()).or_insert(0) += 1;
            }
        }
        let boundary: Vec<usize> = edge_face_count
            .iter()
            .filter(|&(_, &c)| c == 1)
            .map(|(&e, _)| e)
            .collect();
        eprintln!("  Boundary edges: {}", boundary.len());
        for &eidx in boundary.iter().take(8) {
            if let Some(eid) = k.topo.edge_id_from_index(eidx)
                && let Ok(edge) = k.topo.edge(eid)
            {
                let s = k.topo.vertex(edge.start()).unwrap().point();
                let e = k.topo.vertex(edge.end()).unwrap().point();
                let curve = match edge.curve() {
                    brepkit_topology::edge::EdgeCurve::Line => "line",
                    brepkit_topology::edge::EdgeCurve::Circle(_) => "circle",
                    _ => "other",
                };
                eprintln!(
                    "    edge[{eidx}] {curve}: ({:.3},{:.3},{:.3}) → ({:.3},{:.3},{:.3})",
                    s.x(),
                    s.y(),
                    s.z(),
                    e.x(),
                    e.y(),
                    e.z()
                );
            }
        }
    }
    assert!(
        val == 0,
        "lip ring should have 0 validation issues: got {val}"
    );
    assert!(
        euler == 2,
        "Euler should be 2 for a valid solid: got {euler} (F={f}, E={e}, V={v})"
    );
    assert!(
        f < 200,
        "lip ring should have < 200 faces (no explosion): got {f}"
    );
}

/// D1a: Simplest concentric cut — outer box minus inner box (no loft).
///
/// If this fails, the issue is in the boolean engine itself, not loft geometry.
#[test]
fn gridfinity_d1a_concentric_box_cut() {
    let mut k = BrepKernel::new();
    // Outer box: 20×20×10, inner box: 14×14×8 centered (3mm wall)
    let result = k.execute_batch(
        r#"[
        {"op": "makeBox", "args": {"width": 20, "height": 20, "depth": 10}},
        {"op": "makeBox", "args": {"width": 14, "height": 14, "depth": 8}},
        {"op": "transform", "args": {"solid": 1, "matrix": [1,0,0,3, 0,1,0,3, 0,0,1,1, 0,0,0,1]}},
        {"op": "cut", "args": {"solidA": 0, "solidB": 1}}
    ]"#,
    );
    let parsed = parse_batch(&result);
    assert_ok(&parsed, 3);
    let solid = parsed[3]["ok"].as_u64().unwrap() as u32;
    let counts = k.get_entity_counts(solid).unwrap();
    let f = counts[0] as usize;
    let e = counts[1] as usize;
    let v = counts[2] as usize;
    let euler = (v as i64) - (e as i64) + (f as i64);
    let val = k.validate_solid(solid).unwrap();
    eprintln!("D1a concentric box cut: F={f}, E={e}, V={v}, euler={euler}, val={val}");
    // Euler=4 is correct for a solid with an internal cavity (2 shells × Euler=2)
    assert!(
        euler == 4,
        "D1a Euler should be 4 (internal cavity): got {euler}"
    );
}

/// D1a1c: Cut two concentric extruded octagons (same height).
///
/// Tests whether the boolean issue is specific to loft geometry or
/// whether it also affects simple extrusions with many coplanar caps.
#[test]
fn gridfinity_d1a1c_octagon_cut() {
    let mut k = BrepKernel::new();

    // Create octagonal faces at Z=0 centered at origin
    let outer_r = 20.75; // half of 41.5
    let inner_r = 18.15; // half of (41.5 - 2*2.6)
    let n = 8;
    let height = 5.6;

    // Build outer octagon points
    let mut outer_pts = Vec::new();
    let mut inner_pts = Vec::new();
    for i in 0..n {
        let angle = std::f64::consts::TAU * (i as f64) / (n as f64);
        outer_pts.extend_from_slice(&[outer_r * angle.cos(), outer_r * angle.sin(), 0.0]);
        inner_pts.extend_from_slice(&[inner_r * angle.cos(), inner_r * angle.sin(), 0.0]);
    }

    let outer_face = k.make_polygon(outer_pts).unwrap();
    let inner_face = k.make_polygon(inner_pts).unwrap();

    // Extrude both to same height
    let r1 = k.execute_batch(&format!(
        r#"[
        {{"op": "extrude", "args": {{"face": {outer_face}, "dz": 1.0, "distance": {height}}}}},
        {{"op": "extrude", "args": {{"face": {inner_face}, "dz": 1.0, "distance": {height}}}}},
        {{"op": "cut", "args": {{"solidA": 0, "solidB": 1}}}}
    ]"#
    ));
    let p1 = parse_batch(&r1);
    assert_ok(&p1, 2);

    let solid = p1[2]["ok"].as_u64().unwrap() as u32;
    let counts = k.get_entity_counts(solid).unwrap();
    let f = counts[0] as usize;
    let e = counts[1] as usize;
    let v = counts[2] as usize;
    let euler = (v as i64) - (e as i64) + (f as i64);
    let val = k.validate_solid(solid).unwrap();
    eprintln!("D1a1c octagon cut: F={f}, E={e}, V={v}, euler={euler}, val={val}");
    // A tube with coplanar caps should have Euler=2
    assert!(euler == 2, "D1a1c Euler should be 2: got {euler}");
}

/// D1a2: Concentric box cut with SHARED faces (coplanar bottom/top).
///
/// Tests coplanar face handling when inner box shares Z planes with outer.
#[test]
fn gridfinity_d1a2_concentric_box_coplanar() {
    let mut k = BrepKernel::new();
    // Outer box: 20×20×10, inner box: 14×14×10 centered (coplanar top & bottom)
    let result = k.execute_batch(
        r#"[
        {"op": "makeBox", "args": {"width": 20, "height": 20, "depth": 10}},
        {"op": "makeBox", "args": {"width": 14, "height": 14, "depth": 10}},
        {"op": "transform", "args": {"solid": 1, "matrix": [1,0,0,3, 0,1,0,3, 0,0,1,0, 0,0,0,1]}},
        {"op": "cut", "args": {"solidA": 0, "solidB": 1}}
    ]"#,
    );
    let parsed = parse_batch(&result);
    assert_ok(&parsed, 3);
    let solid = parsed[3]["ok"].as_u64().unwrap() as u32;
    let counts = k.get_entity_counts(solid).unwrap();
    let f = counts[0] as usize;
    let e = counts[1] as usize;
    let v = counts[2] as usize;
    let euler = (v as i64) - (e as i64) + (f as i64);
    let val = k.validate_solid(solid).unwrap();
    eprintln!("D1a2 coplanar box cut: F={f}, E={e}, V={v}, euler={euler}, val={val}");
    assert!(euler == 2, "D1a2 Euler should be 2: got {euler}");
}

/// D1b: Same as D1 but inner frustum Z-shifted by 0.1mm to avoid coplanar caps.
///
/// If D1 fails but D1b passes, the bug is in coplanar face handling.
#[test]
fn gridfinity_d1b_lip_ring_no_coplanar() {
    let mut k = BrepKernel::new();

    let outer_faces = make_outer_sections(&mut k);
    // Shift inner Z by 0.1mm — inner sticks out 0.1mm above and below outer
    let inner_faces = make_inner_sections_offset(&mut k, -0.1);

    let outer_json = serde_json::to_string(&outer_faces).unwrap();
    let r1 = k.execute_batch(&format!(
        r#"[{{"op": "loft", "args": {{"faces": {outer_json}}}}}]"#
    ));
    let p1 = parse_batch(&r1);
    assert_ok(&p1, 0);
    let outer_solid = p1[0]["ok"].as_u64().unwrap() as u32;

    let inner_json = serde_json::to_string(&inner_faces).unwrap();
    let r2 = k.execute_batch(&format!(
        r#"[{{"op": "loft", "args": {{"faces": {inner_json}}}}}]"#
    ));
    let p2 = parse_batch(&r2);
    assert_ok(&p2, 0);
    let inner_solid = p2[0]["ok"].as_u64().unwrap() as u32;

    let r3 = k.execute_batch(&format!(
        r#"[{{"op": "cut", "args": {{"solidA": {outer_solid}, "solidB": {inner_solid}}}}}]"#
    ));
    let p3 = parse_batch(&r3);
    assert_ok(&p3, 0);
    let lip_handle = p3[0]["ok"].as_u64().unwrap() as u32;

    let lv = k.validate_solid(lip_handle).unwrap();
    let counts = k.get_entity_counts(lip_handle).unwrap();
    let f = counts[0] as usize;
    let e = counts[1] as usize;
    let v = counts[2] as usize;
    let euler = (v as i64) - (e as i64) + (f as i64);

    // Count inner loops (holes in faces). The Euler-Poincaré formula for a
    // closed 2-manifold with L inner loops is V-E+F = 2+L.
    let lip_id = k.resolve_solid(lip_handle).unwrap();
    let solid_data = k.topo.solid(lip_id).unwrap();
    let shell = k.topo.shell(solid_data.outer_shell()).unwrap();
    let inner_loop_count: i64 = shell
        .faces()
        .iter()
        .map(|&fid| k.topo.face(fid).unwrap().inner_wires().len() as i64)
        .sum();
    let adjusted_euler = euler - inner_loop_count;

    eprintln!(
        "D1b no-coplanar: F={f}, E={e}, V={v}, euler={euler}, inner_loops={inner_loop_count}, adjusted_euler={adjusted_euler}, validation_issues={lv}"
    );
    assert_eq!(lv, 0, "D1b should have 0 validation issues, got {lv}");
    assert!(
        adjusted_euler == 2,
        "D1b adjusted Euler should be 2: got {adjusted_euler} (raw euler={euler}, inner_loops={inner_loop_count}, F={f}, E={e}, V={v})"
    );
}

/// D2: Lip ring + fillet — builds D1, then fillets peak edges at Z_PEAK.
///
/// Expected: Euler preserved, bbox Z unchanged from D1.
#[test]
fn gridfinity_d2_lip_ring_with_fillet() {
    let mut k = BrepKernel::new();

    let outer_faces = make_outer_sections(&mut k);
    let inner_faces = make_inner_sections(&mut k);

    // Loft + cut (same as D1)
    let outer_json = serde_json::to_string(&outer_faces).unwrap();
    let r1 = k.execute_batch(&format!(
        r#"[{{"op": "loft", "args": {{"faces": {outer_json}}}}}]"#
    ));
    let p1 = parse_batch(&r1);
    assert_ok(&p1, 0);
    let outer_solid = p1[0]["ok"].as_u64().unwrap() as u32;

    let inner_json = serde_json::to_string(&inner_faces).unwrap();
    let r2 = k.execute_batch(&format!(
        r#"[{{"op": "loft", "args": {{"faces": {inner_json}}}}}]"#
    ));
    let p2 = parse_batch(&r2);
    assert_ok(&p2, 0);
    let inner_solid = p2[0]["ok"].as_u64().unwrap() as u32;

    let r3 = k.execute_batch(&format!(
        r#"[{{"op": "cut", "args": {{"solidA": {outer_solid}, "solidB": {inner_solid}}}}}]"#
    ));
    let p3 = parse_batch(&r3);
    assert_ok(&p3, 0);
    let lip_handle = p3[0]["ok"].as_u64().unwrap() as u32;

    // Get bbox before fillet
    let r3b = k.execute_batch(&format!(
        r#"[{{"op": "boundingBox", "args": {{"solid": {lip_handle}}}}}]"#
    ));
    let p3b = parse_batch(&r3b);
    assert_ok(&p3b, 0);
    let bbox_before = ok_bbox(&p3b, 0);

    // Get edges, find those near Z_PEAK for fillet
    let r4 = k.execute_batch(&format!(
        r#"[{{"op": "solidEdges", "args": {{"solid": {lip_handle}}}}}]"#
    ));
    let p4 = parse_batch(&r4);
    assert_ok(&p4, 0);
    let edges = p4[0]["ok"]
        .as_array()
        .expect("solidEdges should return array");

    // Filter edges near Z_PEAK (z >= 3.4 and z <= 4.4)
    // We use edgeMidpoint or just try all top edges — for simplicity, try
    // fillet on all edges and check which ones are near peak.
    // Since we can't easily query edge positions via batch, fillet ALL edges
    // with a small radius — this tests the fillet path thoroughly.
    // Actually, let's just use the first few edges as a representative test.
    if edges.is_empty() {
        panic!("lip solid should have edges");
    }

    // Fillet with TOP_FILLET radius on first edge (any edge exercises the path)
    let edge0 = edges[0].as_u64().unwrap();
    let r5 = k.execute_batch(&format!(
        r#"[{{"op": "fillet", "args": {{"solid": {lip_handle}, "radius": {TOP_FILLET}, "edges": [{edge0}]}}}}]"#
    ));
    let p5 = parse_batch(&r5);

    if p5[0].get("error").is_some() {
        eprintln!(
            "D2 fillet failed (expected for known bugs): {}",
            p5[0]["error"]
        );
        return; // Fillet failure is the bug we're tracking
    }

    let filleted = p5[0]["ok"].as_u64().unwrap() as u32;

    // Check bbox unchanged
    let r6 = k.execute_batch(&format!(
        r#"[{{"op": "boundingBox", "args": {{"solid": {filleted}}}}}]"#
    ));
    let p6 = parse_batch(&r6);
    assert_ok(&p6, 0);
    let bbox_after = ok_bbox(&p6, 0);

    let tol = 0.5; // fillet should not change bbox by more than 0.5mm
    for i in 0..6 {
        assert!(
            (bbox_before[i] - bbox_after[i]).abs() < tol,
            "D2 bbox[{i}] shifted after fillet: {:.3} → {:.3} (issue #260)",
            bbox_before[i],
            bbox_after[i]
        );
    }

    eprintln!("D2 lip ring + fillet: bbox stable, fillet succeeded");
}

/// D3: Shelled box + lip ring → fuse.
///
/// Builds a hollow rounded-rectangle box (matching the tool / D4) and fuses the
/// D1 lip ring on top. Expected: analytic fuse, face count < 200.
///
/// The body was previously a sharp `makeBox`; the real tool (and D4) use a
/// rounded-rect body whose corner radius matches the lip's outer corners, so
/// the lip seats flush and the fuse stays analytic instead of falling back to
/// the mesh boolean.
#[test]
fn gridfinity_d3_shelled_box_with_lip() {
    let mut k = BrepKernel::new();

    // Build the shelled rounded-rect box body (centered at origin).
    let box_face = make_rounded_rect_face(&mut k, OUTER_DIM, OUTER_DIM, CORNER_R, 0.0);
    let r1 = k.execute_batch(&format!(
        r#"[{{"op": "extrude", "args": {{"face": {box_face}, "dz": 1.0, "distance": {WALL_HEIGHT}}}}}]"#
    ));
    let p1 = parse_batch(&r1);
    assert_ok(&p1, 0);
    let box_solid = p1[0]["ok"].as_u64().unwrap() as u32;

    // Select the +Z top face by normal (positional indexing is unreliable for
    // a rounded-rect extrude).
    let top_face = k
        .get_solid_faces(box_solid)
        .unwrap()
        .iter()
        .copied()
        .find(|&fh| {
            k.resolve_face(fh)
                .ok()
                .and_then(|fid| k.topo.face(fid).ok())
                .and_then(brepkit_topology::face::Face::effective_plane_normal)
                .is_some_and(|n| n.z() > 0.5 * n.length())
        })
        .expect("extruded box should have a +Z top face");
    let r2 = k.execute_batch(&format!(
        r#"[{{"op": "shell", "args": {{"solid": {box_solid}, "thickness": {WALL_THICKNESS}, "faces": [{top_face}]}}}}]"#
    ));
    let p2 = parse_batch(&r2);
    assert_ok(&p2, 0);
    let box_handle = p2[0]["ok"].as_u64().unwrap() as u32;

    // Build lip ring (same as D1) — at Z=0, will be translated to wallHeight
    let outer_faces = make_outer_sections(&mut k);
    let inner_faces = make_inner_sections(&mut k);

    let outer_json = serde_json::to_string(&outer_faces).unwrap();
    let r3 = k.execute_batch(&format!(
        r#"[{{"op": "loft", "args": {{"faces": {outer_json}}}}}]"#
    ));
    let p3 = parse_batch(&r3);
    assert_ok(&p3, 0);
    let outer_solid = p3[0]["ok"].as_u64().unwrap() as u32;

    let inner_json = serde_json::to_string(&inner_faces).unwrap();
    let r4 = k.execute_batch(&format!(
        r#"[{{"op": "loft", "args": {{"faces": {inner_json}}}}}]"#
    ));
    let p4 = parse_batch(&r4);
    assert_ok(&p4, 0);
    let inner_solid = p4[0]["ok"].as_u64().unwrap() as u32;

    let r5 = k.execute_batch(&format!(
        r#"[{{"op": "cut", "args": {{"solidA": {outer_solid}, "solidB": {inner_solid}}}}}]"#
    ));
    let p5 = parse_batch(&r5);
    assert_ok(&p5, 0);
    let lip_handle = p5[0]["ok"].as_u64().unwrap() as u32;

    // Translate lip to the top of the box. Both the lip sections and the
    // rounded-rect body are centered at the origin, so only a Z shift is
    // needed.
    let mat = translate_matrix(0.0, 0.0, WALL_HEIGHT);
    let r6 = k.execute_batch(&format!(
        r#"[{{"op": "transform", "args": {{"solid": {lip_handle}, "matrix": {mat}}}}}]"#
    ));
    let p6 = parse_batch(&r6);
    assert_ok(&p6, 0);

    // Check face counts before fuse
    let bc = k.get_entity_counts(box_handle).unwrap();
    let lc = k.get_entity_counts(lip_handle).unwrap();
    eprintln!("D3 before fuse: box F={}, lip F={}", bc[0], lc[0]);

    // Fuse box + lip
    let r7 = k.execute_batch(&format!(
        r#"[{{"op": "fuse", "args": {{"solidA": {box_handle}, "solidB": {lip_handle}}}}}]"#
    ));
    let p7 = parse_batch(&r7);

    if p7[0].get("error").is_some() {
        eprintln!("D3 fuse failed: {}", p7[0]["error"]);
        return;
    }

    let fused = p7[0]["ok"].as_u64().unwrap() as u32;
    let r8 = k.execute_batch(&format!(
        r#"[{{"op": "volume", "args": {{"solid": {fused}}}}}]"#
    ));
    let p8 = parse_batch(&r8);
    let vol = ok_f64(&p8, 0);
    eprintln!("D3 shelled box + lip: vol={vol:.1}");

    // Volume should be box shell volume + lip volume
    assert!(
        vol > 5000.0,
        "fused volume should be > 5000 mm³: got {vol:.1}"
    );

    let counts = k.get_entity_counts(fused).unwrap();
    let fc = counts[0] as usize;
    eprintln!("D3 face count: {fc}");
    assert!(fc < 200, "fused solid should have < 200 faces: got {fc}");
}

/// D5: Shelled box + FILLETED lip ring → fuse.
///
/// Like D4 (rounded-rectangle body matching the tool), but with a fillet on the
/// lip's peak rim before the fuse. Exercises the analytic boolean fusing a lip
/// whose rounded corners carry a fillet-derived NURBS blend at the peak.
///
/// Earlier this test built the body with a sharp `makeBox` (the real tool uses
/// a rounded-rect body, like D4) and filleted `edges[0]` — which happens to be
/// a bottom-outer corner arc *at the fuse interface*, not the peak. Both made
/// the fuse fall back to the mesh boolean. The body is now a rounded-rect (per
/// `BOX_CORNER_RADIUS`) and the fillet targets a peak rim edge.
#[test]
fn gridfinity_d5_box_with_filleted_lip() {
    let mut k = BrepKernel::new();

    // Step 1: rounded-rectangle box body (matches the tool / D4), then shell.
    let box_face = make_rounded_rect_face(&mut k, OUTER_DIM, OUTER_DIM, CORNER_R, 0.0);
    let r1 = k.execute_batch(&format!(
        r#"[{{"op": "extrude", "args": {{"face": {box_face}, "dz": 1.0, "distance": {WALL_HEIGHT}}}}}]"#
    ));
    let p1 = parse_batch(&r1);
    assert_ok(&p1, 0);
    let box_solid = p1[0]["ok"].as_u64().unwrap() as u32;

    // Select the +Z top face (positional indexing is unreliable for a
    // rounded-rect extrude — corner cylinders interleave the side faces).
    let top_face = k
        .get_solid_faces(box_solid)
        .unwrap()
        .iter()
        .copied()
        .find(|&fh| {
            k.resolve_face(fh)
                .ok()
                .and_then(|fid| k.topo.face(fid).ok())
                .and_then(brepkit_topology::face::Face::effective_plane_normal)
                .is_some_and(|n| n.z() > 0.5 * n.length())
        })
        .expect("extruded box should have a +Z top face");
    let r2 = k.execute_batch(&format!(
        r#"[{{"op": "shell", "args": {{"solid": {box_solid}, "thickness": {WALL_THICKNESS}, "faces": [{top_face}]}}}}]"#
    ));
    let p2 = parse_batch(&r2);
    assert_ok(&p2, 0);
    let box_handle = p2[0]["ok"].as_u64().unwrap() as u32;

    // Step 2: lip ring (loft outer, loft inner, cut) — same as D4.
    let outer_faces = make_outer_sections(&mut k);
    let inner_faces = make_inner_sections(&mut k);

    let outer_json = serde_json::to_string(&outer_faces).unwrap();
    let r3 = k.execute_batch(&format!(
        r#"[{{"op": "loft", "args": {{"faces": {outer_json}}}}}]"#
    ));
    let p3 = parse_batch(&r3);
    assert_ok(&p3, 0);
    let outer_solid = p3[0]["ok"].as_u64().unwrap() as u32;

    let inner_json = serde_json::to_string(&inner_faces).unwrap();
    let r4 = k.execute_batch(&format!(
        r#"[{{"op": "loft", "args": {{"faces": {inner_json}}}}}]"#
    ));
    let p4 = parse_batch(&r4);
    assert_ok(&p4, 0);
    let inner_solid = p4[0]["ok"].as_u64().unwrap() as u32;

    let r5 = k.execute_batch(&format!(
        r#"[{{"op": "cut", "args": {{"solidA": {outer_solid}, "solidB": {inner_solid}}}}}]"#
    ));
    let p5 = parse_batch(&r5);
    assert_ok(&p5, 0);
    let lip_handle = p5[0]["ok"].as_u64().unwrap() as u32;

    // The cut must produce a valid (closed, genus-0) lip.
    let pre_lc = k.get_entity_counts(lip_handle).unwrap();
    let pre_euler = (pre_lc[2] as i64) - (pre_lc[1] as i64) + (pre_lc[0] as i64);
    assert!(
        pre_euler >= 2,
        "lip solid should have euler >= 2 before fillet, got {pre_euler}"
    );

    // Step 3: fillet a PEAK rim edge (z ≈ Z_PEAK), as the tool does when
    // TOP_FILLET > 0. Select by z-bound rather than `edges[0]`, which is a
    // bottom-outer corner arc on the fuse interface.
    let r5b = k.execute_batch(&format!(
        r#"[{{"op": "solidEdges", "args": {{"solid": {lip_handle}}}}}]"#
    ));
    let p5b = parse_batch(&r5b);
    assert_ok(&p5b, 0);
    let peak_edge = p5b[0]["ok"]
        .as_array()
        .expect("edges")
        .iter()
        .filter_map(serde_json::Value::as_u64)
        .find(|&eh| {
            k.resolve_edge(eh as u32)
                .ok()
                .and_then(|eid| k.topo.edge(eid).ok())
                .is_some_and(|edge| {
                    let z0 = k
                        .topo
                        .vertex(edge.start())
                        .map(|v| v.point().z())
                        .unwrap_or(f64::NAN);
                    let z1 = k
                        .topo
                        .vertex(edge.end())
                        .map(|v| v.point().z())
                        .unwrap_or(f64::NAN);
                    z0.min(z1) >= Z_PEAK - 1.0 && z0.max(z1) >= Z_PEAK - 0.01
                })
        })
        .expect("lip should have a peak rim edge near Z_PEAK");
    let r5c = k.execute_batch(&format!(
        r#"[{{"op": "fillet", "args": {{"solid": {lip_handle}, "radius": {TOP_FILLET}, "edges": [{peak_edge}]}}}}]"#
    ));
    let p5c = parse_batch(&r5c);
    assert_ok(&p5c, 0);
    let lip_final = p5c[0]["ok"].as_u64().unwrap() as u32;

    // The filleted lip must remain a watertight, genus-0 solid (the fillet's
    // arc-runout closure plus arc-preserving reassembly keep it closed).
    let lc = k.get_entity_counts(lip_final).unwrap();
    let lip_val = k.validate_solid(lip_final).unwrap();
    let lip_euler = (lc[2] as i64) - (lc[1] as i64) + (lc[0] as i64);
    assert!(
        lip_val <= 2,
        "filleted lip should have <= 2 validation issues, got {lip_val}"
    );
    assert!(
        lip_euler >= 2,
        "filleted lip Euler characteristic should be >= 2, got {lip_euler}"
    );

    // Step 4: translate lip onto the box top and fuse.
    let mat = translate_matrix(0.0, 0.0, WALL_HEIGHT);
    let r6 = k.execute_batch(&format!(
        r#"[{{"op": "transform", "args": {{"solid": {lip_final}, "matrix": {mat}}}}}]"#
    ));
    let p6 = parse_batch(&r6);
    assert_ok(&p6, 0);

    let r7 = k.execute_batch(&format!(
        r#"[{{"op": "fuse", "args": {{"solidA": {box_handle}, "solidB": {lip_final}}}}}]"#
    ));
    let p7 = parse_batch(&r7);
    assert_ok(&p7, 0);
    let fused = p7[0]["ok"].as_u64().unwrap() as u32;

    let r8 = k.execute_batch(&format!(
        r#"[{{"op": "volume", "args": {{"solid": {fused}}}}}]"#
    ));
    let p8 = parse_batch(&r8);
    let vol = ok_f64(&p8, 0);
    let fc = k.get_entity_counts(fused).unwrap();
    let euler = (fc[2] as i64) - (fc[1] as i64) + (fc[0] as i64);
    eprintln!(
        "D5 result: F={}, E={}, V={}, euler={euler}, vol={vol:.1}",
        fc[0], fc[1], fc[2]
    );

    // An analytic fuse keeps the face count low (a mesh fallback yields >200).
    assert!(
        fc[0] < 200,
        "fused solid should have < 200 faces (mesh fallback otherwise): got {}",
        fc[0]
    );
    assert!(
        vol > 5000.0,
        "fused volume should be > 5000 mm³: got {vol:.1}"
    );
}

/// D4: Full 1×1 bin — socket + box + shell + lip + fillet.
///
/// Builds the complete bin pipeline matching gridfinity-layout-tool's
/// `generateBin()` for a 1×1 standard bin with stacking lip.
/// Expected: genus-0 manifold (adjusted Euler == 2), faces < 200, volume.
#[test]
fn gridfinity_d4_full_1x1_bin() {
    let mut k = BrepKernel::new();

    // Step 1: Build box body (rounded-rectangle extrusion)
    // First create a rounded-rect face at Z=0, then extrude up
    let box_face = make_rounded_rect_face(&mut k, OUTER_DIM, OUTER_DIM, CORNER_R, 0.0);
    let r1 = k.execute_batch(&format!(
        r#"[{{"op": "extrude", "args": {{"face": {box_face}, "dz": 1.0, "distance": {WALL_HEIGHT}}}}}]"#
    ));
    let p1 = parse_batch(&r1);
    assert_ok(&p1, 0);
    let box_solid = p1[0]["ok"].as_u64().unwrap() as u32;

    // Step 2: Shell the box (remove top face).
    // Select the top face by its outward normal (+Z). A rounded-rect extrude
    // interleaves cylindrical corner faces, so positional indexing (faces[1])
    // is unreliable here — it lands on the base face, not the top.
    let faces = k.get_solid_faces(box_solid).unwrap();
    assert!(!faces.is_empty(), "box should have faces");
    let top_face = faces
        .iter()
        .copied()
        .find(|&fh| {
            k.resolve_face(fh)
                .ok()
                .and_then(|fid| k.topo.face(fid).ok())
                .and_then(brepkit_topology::face::Face::effective_plane_normal)
                // Top face points predominantly +Z. Compare against the
                // normal's own magnitude rather than assuming unit length,
                // since `FaceSurface::Plane` normals are not normalized.
                .is_some_and(|n| n.z() > 0.5 * n.length())
        })
        .expect("extruded box should have a +Z top face");
    let r3 = k.execute_batch(&format!(
        r#"[{{"op": "shell", "args": {{"solid": {box_solid}, "thickness": {WALL_THICKNESS}, "faces": [{top_face}]}}}}]"#
    ));
    let p3 = parse_batch(&r3);
    assert_ok(&p3, 0);
    let shelled = p3[0]["ok"].as_u64().unwrap() as u32;

    // Step 3: Build lip ring (same as D1)
    let outer_faces = make_outer_sections(&mut k);
    let inner_faces = make_inner_sections(&mut k);

    let outer_json = serde_json::to_string(&outer_faces).unwrap();
    let r4 = k.execute_batch(&format!(
        r#"[{{"op": "loft", "args": {{"faces": {outer_json}}}}}]"#
    ));
    let p4 = parse_batch(&r4);
    assert_ok(&p4, 0);
    let outer_solid = p4[0]["ok"].as_u64().unwrap() as u32;

    let inner_json = serde_json::to_string(&inner_faces).unwrap();
    let r5 = k.execute_batch(&format!(
        r#"[{{"op": "loft", "args": {{"faces": {inner_json}}}}}]"#
    ));
    let p5 = parse_batch(&r5);
    assert_ok(&p5, 0);
    let inner_solid = p5[0]["ok"].as_u64().unwrap() as u32;

    let r6 = k.execute_batch(&format!(
        r#"[{{"op": "cut", "args": {{"solidA": {outer_solid}, "solidB": {inner_solid}}}}}]"#
    ));
    let p6 = parse_batch(&r6);
    assert_ok(&p6, 0);
    let lip_handle = p6[0]["ok"].as_u64().unwrap() as u32;

    // Translate lip to top of box
    let mat = translate_matrix(0.0, 0.0, WALL_HEIGHT);
    let r7 = k.execute_batch(&format!(
        r#"[{{"op": "transform", "args": {{"solid": {lip_handle}, "matrix": {mat}}}}}]"#
    ));
    let p7 = parse_batch(&r7);
    assert_ok(&p7, 0);

    // Step 4: Fuse shelled box + lip
    let r8 = k.execute_batch(&format!(
        r#"[{{"op": "fuse", "args": {{"solidA": {shelled}, "solidB": {lip_handle}}}}}]"#
    ));
    let p8 = parse_batch(&r8);

    if p8[0].get("error").is_some() {
        eprintln!("D4 fuse failed: {}", p8[0]["error"]);
        return;
    }
    let fused = p8[0]["ok"].as_u64().unwrap() as u32;

    // Step 5: Measure final solid
    let r9 = k.execute_batch(&format!(
        r#"[
        {{"op": "volume", "args": {{"solid": {fused}}}}},
        {{"op": "boundingBox", "args": {{"solid": {fused}}}}}
    ]"#
    ));
    let p9 = parse_batch(&r9);

    let vol = ok_f64(&p9, 0);
    let bbox = ok_bbox(&p9, 1);
    let counts = k.get_entity_counts(fused).unwrap();
    let f = counts[0] as usize;
    let e = counts[1] as usize;
    let v = counts[2] as usize;
    let euler = (v as i64) - (e as i64) + (f as i64);

    // Count inner loops for adjusted Euler.
    let fused_id = k.resolve_solid(fused).unwrap();
    let solid_data = k.topo.solid(fused_id).unwrap();
    let shell = k.topo.shell(solid_data.outer_shell()).unwrap();
    let inner_loop_count: i64 = shell
        .faces()
        .iter()
        .map(|&fid| k.topo.face(fid).unwrap().inner_wires().len() as i64)
        .sum();
    let adjusted_euler = euler - inner_loop_count;

    eprintln!("D4 full 1×1 bin:");
    eprintln!("  volume: {vol:.1} mm³");
    eprintln!(
        "  bbox: [{:.1}, {:.1}, {:.1}] → [{:.1}, {:.1}, {:.1}]",
        bbox[0], bbox[1], bbox[2], bbox[3], bbox[4], bbox[5]
    );
    eprintln!(
        "  faces={f}, edges={e}, verts={v}, euler={euler}, inner_loops={inner_loop_count}, adjusted_euler={adjusted_euler}"
    );

    // Assertions — adjusted Euler accounts for inner loops (holes in faces).
    assert!(
        adjusted_euler == 2,
        "Adjusted Euler should be 2: got {adjusted_euler} (raw={euler}, inner_loops={inner_loop_count})"
    );
    assert!(f < 200, "face count should be < 200: got {f}");
    assert!(vol > 5000.0, "volume should be > 5000 mm³: got {vol:.1}");

    // BBox should be approximately 41.5 × 41.5 × (21 + 4.4)
    let expected_z = WALL_HEIGHT + Z_PEAK; // 25.4mm
    let z_extent = bbox[5] - bbox[2];
    assert!(
        (z_extent - expected_z).abs() < 2.0,
        "Z extent should be ~{expected_z:.1}mm: got {z_extent:.1}"
    );
}

/// Box volume sanity check.
#[test]
fn box_volume_sanity() {
    let mut k = BrepKernel::new();
    let result = k.execute_batch(
        r#"[
        {"op": "makeBox", "args": {"width": 10, "height": 10, "depth": 10}},
        {"op": "volume", "args": {"solid": 0}}
    ]"#,
    );
    let parsed = parse_batch(&result);
    assert_ok(&parsed, 0);
    let vol = ok_f64(&parsed, 1);
    let expected = 1000.0;
    let rel_error = ((vol - expected) / expected).abs();
    assert!(
        rel_error < 0.01,
        "box volume should be 1000: got {vol:.1}, error {:.1}%",
        rel_error * 100.0
    );
}

/// Regression: a rounded-rectangle shelled body (open-top hollow) must
/// classify a point in its OPEN CAVITY as Outside, not Inside. The analytic
/// composite classifier modelled the rounded corners as `ConvexAnalytic`
/// intersection constraints (`radial_dist < radius` for every corner
/// cylinder), which the cavity centre fails (it is far from every corner) —
/// so the cavity was wrongly classified Inside, dropping a fused lip's
/// inner-cavity faces and forcing a mesh-boolean fallback. The composite now
/// bails to the exact ray-cast classifier when a cylinder/cone does not
/// contain the centroid.
#[test]
fn rounded_shelled_body_classifies_cavity_outside() {
    use brepkit_math::vec::Point3;
    let mut k = BrepKernel::new();
    let bf = make_rounded_rect_face(&mut k, OUTER_DIM, OUTER_DIM, CORNER_R, 0.0);
    let bs = parse_batch(&k.execute_batch(&format!(
        r#"[{{"op":"extrude","args":{{"face":{bf},"dz":1.0,"distance":{WALL_HEIGHT}}}}}]"#
    )))[0]["ok"]
        .as_u64()
        .unwrap() as u32;
    let tf = k
        .get_solid_faces(bs)
        .unwrap()
        .iter()
        .copied()
        .find(|&fh| {
            k.resolve_face(fh)
                .ok()
                .and_then(|fid| k.topo.face(fid).ok())
                .and_then(brepkit_topology::face::Face::effective_plane_normal)
                .is_some_and(|n| n.z() > 0.5 * n.length())
        })
        .unwrap();
    let shelled = parse_batch(&k.execute_batch(&format!(
        r#"[{{"op":"shell","args":{{"solid":{bs},"thickness":{WALL_THICKNESS},"faces":[{tf}]}}}}]"#
    )))[0]["ok"]
        .as_u64()
        .unwrap() as u32;
    let sid = k.resolve_solid(shelled).unwrap();
    let topo = &*k.topo;
    let cavity = brepkit_algo::classifier::classify_point(
        topo,
        sid,
        Point3::new(0.0, 0.0, WALL_HEIGHT / 2.0),
    )
    .unwrap();
    assert_eq!(
        cavity,
        brepkit_algo::FaceClass::Outside,
        "open-cavity centre must classify Outside, got {cavity:?}"
    );
    let wall = brepkit_algo::classifier::classify_point(
        topo,
        sid,
        Point3::new(
            OUTER_DIM / 2.0 - WALL_THICKNESS / 2.0,
            0.0,
            WALL_HEIGHT / 2.0,
        ),
    )
    .unwrap();
    assert_eq!(
        wall,
        brepkit_algo::FaceClass::Inside,
        "wall-material point must classify Inside, got {wall:?}"
    );
}