kcl-lib 0.2.142

KittyCAD Language implementation and tools
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
1205
1206
1207
1208
1209
1210
1211
1212
1213
1214
1215
1216
1217
1218
1219
1220
1221
1222
1223
1224
1225
1226
1227
1228
1229
1230
1231
1232
1233
1234
1235
1236
1237
1238
1239
1240
1241
1242
1243
1244
1245
1246
1247
1248
1249
1250
1251
1252
1253
1254
1255
1256
1257
1258
1259
1260
1261
1262
1263
1264
1265
1266
1267
1268
1269
1270
1271
1272
1273
1274
1275
1276
1277
1278
1279
1280
1281
1282
1283
1284
1285
1286
1287
1288
1289
1290
1291
1292
1293
1294
1295
1296
1297
1298
1299
1300
1301
1302
1303
1304
1305
1306
1307
1308
1309
1310
1311
1312
1313
1314
1315
1316
1317
1318
1319
1320
1321
1322
1323
1324
1325
1326
1327
1328
1329
1330
1331
1332
1333
1334
1335
1336
1337
1338
1339
1340
1341
1342
1343
1344
1345
1346
1347
1348
1349
1350
1351
1352
1353
1354
1355
1356
1357
1358
1359
1360
1361
1362
1363
1364
1365
1366
1367
1368
1369
1370
1371
1372
1373
1374
1375
1376
1377
1378
1379
1380
1381
1382
1383
1384
1385
1386
1387
1388
1389
1390
1391
1392
1393
1394
1395
1396
1397
1398
1399
1400
1401
1402
1403
1404
1405
1406
1407
1408
1409
1410
1411
1412
1413
1414
1415
1416
1417
1418
1419
1420
1421
1422
1423
1424
1425
1426
1427
1428
1429
1430
1431
1432
1433
1434
1435
1436
1437
1438
1439
1440
1441
1442
1443
1444
1445
1446
1447
1448
1449
1450
1451
1452
1453
1454
1455
1456
1457
1458
1459
1460
1461
1462
1463
1464
1465
1466
1467
1468
1469
1470
1471
1472
1473
1474
1475
1476
1477
1478
1479
1480
1481
1482
1483
1484
1485
1486
1487
1488
1489
1490
1491
1492
1493
1494
1495
1496
1497
1498
1499
1500
1501
1502
1503
1504
1505
1506
1507
1508
1509
1510
1511
1512
1513
1514
1515
1516
1517
1518
1519
1520
1521
1522
1523
1524
1525
1526
1527
1528
1529
1530
1531
1532
1533
1534
1535
1536
1537
1538
1539
1540
1541
1542
1543
1544
1545
1546
1547
1548
1549
1550
1551
1552
1553
1554
1555
1556
1557
1558
1559
1560
1561
1562
1563
1564
1565
1566
1567
1568
1569
1570
1571
1572
1573
1574
1575
1576
1577
1578
1579
1580
1581
1582
1583
1584
1585
1586
1587
1588
1589
1590
1591
1592
1593
1594
1595
1596
1597
1598
1599
1600
1601
1602
1603
1604
1605
1606
1607
1608
1609
1610
1611
1612
1613
1614
1615
1616
1617
1618
1619
1620
1621
1622
1623
1624
1625
1626
1627
1628
1629
1630
1631
1632
1633
1634
1635
1636
1637
1638
1639
1640
1641
1642
1643
1644
1645
1646
1647
1648
1649
1650
1651
1652
1653
1654
1655
1656
1657
1658
1659
1660
1661
1662
1663
1664
1665
1666
1667
1668
1669
1670
1671
1672
1673
1674
1675
1676
1677
1678
1679
1680
1681
1682
1683
1684
1685
1686
1687
1688
1689
1690
1691
1692
1693
1694
1695
1696
1697
1698
1699
1700
1701
1702
1703
1704
1705
1706
1707
1708
1709
1710
1711
1712
1713
1714
1715
1716
1717
1718
1719
1720
1721
1722
1723
1724
1725
1726
1727
1728
1729
1730
1731
1732
1733
1734
1735
1736
1737
1738
1739
1740
1741
1742
1743
1744
1745
1746
1747
1748
1749
1750
1751
1752
1753
1754
1755
1756
1757
1758
1759
1760
1761
1762
1763
1764
1765
1766
1767
1768
1769
1770
1771
1772
1773
1774
1775
1776
1777
1778
1779
1780
1781
1782
1783
1784
1785
1786
1787
1788
1789
1790
1791
1792
1793
1794
1795
1796
1797
1798
1799
1800
1801
1802
1803
1804
1805
1806
1807
1808
1809
1810
1811
1812
1813
1814
1815
1816
1817
1818
1819
1820
1821
1822
1823
1824
1825
1826
1827
1828
1829
1830
1831
1832
1833
1834
1835
1836
1837
1838
1839
1840
1841
1842
1843
1844
1845
1846
1847
1848
1849
1850
1851
1852
1853
1854
1855
1856
1857
1858
1859
1860
1861
1862
1863
1864
1865
1866
1867
1868
1869
1870
1871
1872
1873
1874
1875
1876
1877
1878
1879
1880
1881
1882
1883
1884
1885
1886
1887
1888
1889
1890
1891
1892
1893
1894
1895
1896
1897
1898
1899
1900
1901
1902
1903
1904
1905
1906
1907
1908
1909
1910
1911
1912
1913
1914
1915
1916
1917
1918
1919
1920
1921
1922
1923
1924
1925
1926
1927
1928
1929
1930
1931
1932
1933
1934
1935
1936
1937
1938
1939
1940
1941
1942
1943
1944
1945
1946
1947
1948
1949
1950
1951
1952
1953
1954
1955
1956
1957
1958
1959
1960
1961
1962
1963
1964
1965
1966
1967
1968
1969
1970
1971
1972
1973
1974
1975
1976
1977
1978
1979
1980
1981
1982
1983
1984
1985
1986
1987
1988
1989
1990
1991
1992
1993
1994
1995
1996
1997
1998
1999
2000
2001
2002
2003
2004
2005
2006
2007
2008
2009
2010
2011
2012
2013
2014
2015
2016
2017
2018
2019
2020
2021
2022
2023
2024
2025
2026
2027
2028
2029
2030
2031
2032
2033
2034
2035
2036
2037
2038
2039
2040
2041
2042
2043
2044
2045
2046
2047
2048
2049
2050
2051
2052
2053
2054
2055
2056
2057
2058
2059
2060
2061
2062
2063
2064
2065
2066
2067
2068
2069
2070
2071
2072
2073
2074
2075
2076
2077
2078
2079
2080
2081
2082
2083
2084
2085
2086
2087
2088
2089
2090
2091
2092
2093
2094
2095
2096
2097
2098
2099
2100
2101
2102
2103
2104
2105
2106
2107
2108
2109
2110
2111
2112
2113
2114
2115
2116
2117
2118
2119
2120
2121
2122
2123
2124
2125
2126
2127
2128
2129
2130
2131
2132
2133
2134
2135
2136
2137
2138
2139
2140
2141
2142
2143
2144
2145
2146
2147
2148
2149
2150
2151
2152
2153
2154
2155
2156
2157
2158
2159
2160
2161
2162
2163
2164
2165
2166
2167
2168
2169
2170
2171
2172
2173
2174
2175
2176
2177
2178
2179
2180
2181
2182
2183
2184
2185
2186
2187
2188
2189
2190
2191
2192
2193
2194
2195
2196
2197
2198
2199
2200
2201
2202
2203
2204
2205
2206
2207
2208
2209
2210
2211
2212
2213
2214
2215
2216
2217
2218
2219
2220
2221
2222
2223
2224
2225
2226
2227
2228
2229
2230
2231
2232
2233
2234
2235
2236
2237
2238
2239
2240
2241
2242
2243
2244
2245
2246
2247
2248
2249
2250
2251
2252
2253
2254
2255
2256
2257
2258
2259
2260
2261
2262
2263
2264
2265
2266
2267
2268
2269
2270
2271
2272
2273
2274
2275
2276
2277
2278
2279
2280
2281
2282
2283
2284
2285
2286
2287
2288
2289
2290
2291
2292
2293
2294
2295
2296
2297
2298
2299
2300
2301
2302
2303
2304
2305
2306
2307
2308
2309
2310
2311
2312
2313
2314
2315
2316
2317
2318
2319
2320
2321
2322
2323
2324
2325
2326
2327
2328
2329
2330
2331
2332
2333
2334
2335
2336
2337
2338
2339
2340
2341
2342
2343
2344
2345
2346
2347
2348
2349
2350
2351
2352
2353
2354
2355
2356
2357
2358
2359
2360
2361
2362
2363
2364
2365
2366
2367
2368
2369
2370
2371
2372
2373
2374
2375
2376
2377
2378
2379
2380
2381
2382
2383
2384
2385
2386
2387
2388
2389
2390
2391
2392
2393
2394
2395
2396
2397
2398
2399
2400
2401
2402
2403
2404
2405
2406
2407
2408
2409
2410
2411
2412
2413
2414
2415
2416
2417
2418
2419
2420
2421
2422
2423
2424
2425
2426
2427
2428
2429
2430
2431
2432
2433
2434
2435
2436
2437
2438
2439
2440
2441
2442
2443
2444
2445
2446
2447
2448
2449
2450
2451
2452
2453
2454
2455
2456
2457
2458
2459
2460
2461
2462
2463
2464
2465
2466
2467
2468
2469
2470
2471
2472
2473
2474
2475
2476
2477
2478
2479
2480
2481
2482
2483
2484
2485
2486
2487
2488
2489
2490
2491
2492
2493
2494
2495
2496
2497
2498
2499
2500
2501
2502
2503
2504
2505
2506
2507
2508
2509
2510
2511
2512
2513
2514
2515
2516
2517
2518
2519
2520
2521
2522
2523
2524
2525
2526
2527
2528
2529
2530
2531
2532
2533
2534
2535
2536
2537
2538
2539
2540
2541
2542
2543
2544
2545
2546
2547
2548
2549
2550
2551
2552
2553
2554
2555
2556
2557
2558
2559
2560
2561
2562
2563
2564
2565
2566
2567
2568
2569
2570
2571
2572
2573
2574
2575
2576
2577
2578
2579
2580
2581
2582
2583
2584
2585
2586
2587
2588
2589
2590
2591
2592
2593
2594
2595
2596
2597
2598
2599
2600
2601
2602
2603
2604
2605
2606
2607
2608
2609
2610
2611
2612
2613
2614
2615
2616
2617
2618
2619
2620
2621
2622
2623
2624
2625
2626
2627
2628
2629
2630
2631
2632
2633
2634
2635
2636
2637
2638
2639
2640
2641
2642
2643
2644
2645
2646
2647
2648
2649
2650
2651
2652
2653
2654
2655
2656
2657
2658
2659
2660
2661
2662
2663
2664
2665
2666
2667
2668
2669
2670
2671
2672
2673
2674
2675
2676
2677
2678
2679
2680
2681
2682
2683
2684
2685
2686
2687
2688
2689
2690
2691
2692
2693
2694
2695
2696
2697
2698
2699
2700
2701
2702
2703
2704
2705
2706
2707
2708
2709
2710
2711
2712
2713
2714
2715
2716
2717
2718
2719
2720
2721
2722
2723
2724
2725
2726
2727
2728
2729
2730
2731
2732
2733
2734
2735
2736
2737
2738
2739
2740
2741
2742
2743
2744
2745
2746
2747
2748
2749
2750
2751
2752
2753
2754
2755
2756
2757
2758
2759
2760
2761
2762
2763
2764
2765
2766
2767
2768
2769
2770
2771
2772
2773
2774
2775
2776
2777
2778
2779
2780
2781
2782
2783
2784
2785
2786
2787
2788
2789
2790
2791
2792
2793
2794
2795
2796
2797
2798
2799
2800
2801
2802
2803
2804
2805
2806
2807
2808
2809
2810
2811
2812
2813
2814
2815
2816
2817
2818
2819
2820
2821
2822
2823
2824
2825
2826
2827
2828
2829
2830
2831
2832
2833
2834
2835
2836
2837
2838
2839
2840
2841
2842
2843
2844
2845
2846
2847
2848
2849
2850
2851
2852
2853
2854
2855
2856
2857
2858
2859
2860
2861
2862
2863
2864
2865
2866
2867
2868
2869
2870
2871
2872
2873
2874
2875
2876
2877
2878
2879
2880
2881
2882
2883
2884
2885
2886
2887
2888
2889
2890
2891
2892
2893
2894
2895
2896
2897
2898
2899
2900
2901
2902
2903
2904
2905
2906
2907
2908
2909
2910
2911
2912
2913
2914
2915
2916
2917
2918
2919
2920
2921
2922
2923
2924
2925
2926
2927
2928
2929
2930
2931
2932
2933
2934
2935
2936
2937
2938
2939
2940
2941
2942
2943
2944
2945
2946
2947
2948
2949
2950
2951
2952
2953
2954
2955
2956
2957
2958
2959
2960
2961
2962
2963
2964
2965
2966
2967
2968
2969
2970
2971
2972
2973
2974
2975
2976
2977
2978
2979
2980
2981
2982
2983
2984
2985
2986
2987
2988
2989
2990
2991
2992
2993
2994
2995
2996
2997
2998
2999
3000
3001
3002
3003
3004
3005
3006
3007
3008
3009
3010
3011
3012
3013
3014
3015
3016
3017
3018
3019
3020
3021
3022
3023
3024
3025
3026
3027
3028
3029
3030
3031
3032
3033
3034
3035
3036
3037
3038
3039
3040
3041
3042
3043
3044
3045
3046
3047
3048
3049
3050
3051
3052
3053
3054
3055
3056
3057
3058
3059
3060
3061
3062
3063
3064
3065
3066
3067
3068
3069
3070
3071
3072
3073
3074
3075
3076
3077
3078
3079
3080
3081
3082
3083
3084
3085
3086
3087
3088
3089
3090
3091
3092
3093
3094
3095
3096
3097
3098
3099
3100
3101
3102
3103
3104
3105
3106
3107
3108
3109
3110
3111
3112
3113
3114
3115
3116
3117
3118
3119
3120
3121
3122
3123
3124
3125
3126
3127
3128
3129
3130
3131
3132
3133
3134
3135
3136
3137
3138
3139
3140
3141
3142
3143
3144
3145
3146
3147
3148
3149
3150
3151
3152
3153
3154
3155
3156
3157
3158
3159
3160
3161
3162
3163
3164
3165
3166
3167
3168
3169
3170
3171
3172
3173
3174
3175
3176
3177
3178
3179
3180
3181
3182
3183
3184
3185
3186
3187
3188
3189
3190
3191
3192
3193
3194
3195
3196
3197
3198
3199
3200
3201
3202
3203
3204
3205
3206
3207
3208
3209
3210
3211
3212
3213
3214
3215
3216
3217
3218
3219
3220
3221
3222
3223
3224
3225
3226
3227
3228
3229
3230
3231
3232
3233
3234
3235
3236
3237
3238
3239
3240
3241
3242
3243
3244
3245
3246
3247
3248
3249
3250
3251
3252
3253
3254
3255
3256
3257
3258
3259
3260
3261
3262
3263
3264
3265
3266
3267
3268
3269
3270
3271
3272
3273
3274
3275
3276
3277
3278
3279
3280
3281
3282
3283
3284
3285
3286
3287
3288
3289
3290
3291
3292
3293
3294
3295
3296
3297
3298
3299
3300
3301
3302
3303
3304
3305
3306
3307
3308
3309
3310
3311
3312
3313
3314
3315
3316
3317
3318
3319
3320
3321
3322
3323
3324
3325
3326
3327
3328
3329
3330
3331
3332
3333
3334
3335
3336
3337
3338
3339
3340
3341
3342
3343
3344
3345
3346
3347
3348
3349
3350
3351
3352
3353
3354
3355
3356
3357
3358
3359
3360
3361
3362
3363
3364
3365
3366
3367
3368
3369
3370
3371
3372
3373
3374
3375
3376
3377
3378
3379
3380
3381
3382
3383
3384
3385
3386
3387
3388
3389
3390
3391
3392
3393
3394
3395
3396
3397
3398
3399
3400
3401
3402
3403
3404
3405
3406
3407
3408
3409
3410
3411
3412
3413
3414
3415
3416
3417
3418
3419
3420
3421
3422
3423
3424
3425
3426
3427
3428
3429
3430
3431
3432
3433
3434
3435
3436
3437
3438
3439
3440
3441
3442
3443
3444
3445
3446
3447
3448
3449
3450
3451
3452
3453
3454
3455
3456
3457
3458
3459
3460
3461
3462
3463
3464
3465
3466
3467
3468
3469
3470
3471
3472
3473
3474
3475
3476
3477
3478
3479
3480
3481
3482
3483
3484
3485
3486
3487
3488
3489
3490
3491
3492
3493
3494
3495
3496
3497
3498
3499
3500
3501
3502
3503
3504
3505
3506
3507
3508
3509
3510
3511
3512
3513
3514
3515
3516
3517
3518
3519
3520
3521
3522
3523
3524
3525
3526
3527
3528
3529
3530
3531
3532
3533
3534
3535
3536
3537
3538
3539
3540
3541
3542
3543
3544
3545
3546
3547
3548
3549
3550
3551
3552
3553
3554
3555
3556
3557
3558
3559
3560
3561
3562
3563
3564
3565
3566
3567
3568
3569
3570
3571
3572
3573
3574
3575
3576
3577
3578
3579
3580
3581
3582
3583
3584
3585
3586
3587
3588
3589
3590
3591
3592
3593
3594
3595
3596
3597
3598
3599
3600
3601
3602
3603
3604
3605
3606
3607
3608
3609
3610
3611
3612
3613
3614
3615
3616
3617
3618
3619
3620
3621
3622
3623
3624
3625
3626
3627
3628
3629
3630
3631
3632
3633
3634
3635
3636
3637
3638
3639
3640
3641
3642
3643
3644
3645
3646
3647
3648
3649
3650
3651
3652
3653
3654
3655
3656
3657
3658
3659
3660
3661
3662
3663
3664
3665
3666
3667
3668
3669
3670
3671
3672
3673
3674
3675
3676
3677
3678
3679
3680
3681
3682
3683
3684
3685
3686
3687
3688
3689
3690
3691
3692
3693
3694
3695
3696
3697
3698
3699
3700
3701
3702
3703
3704
3705
3706
3707
3708
3709
3710
3711
3712
3713
3714
3715
3716
3717
3718
3719
3720
3721
3722
3723
3724
3725
3726
3727
3728
3729
3730
3731
3732
3733
3734
3735
3736
3737
3738
3739
3740
3741
3742
3743
3744
3745
3746
3747
3748
3749
3750
3751
3752
3753
3754
3755
3756
3757
3758
3759
3760
3761
3762
3763
3764
3765
3766
3767
3768
3769
3770
3771
3772
3773
3774
3775
3776
3777
3778
3779
3780
3781
3782
3783
3784
3785
3786
3787
3788
3789
3790
3791
3792
3793
3794
3795
3796
3797
3798
3799
3800
3801
3802
3803
3804
3805
3806
3807
3808
3809
3810
3811
3812
3813
3814
3815
3816
3817
3818
3819
3820
3821
3822
3823
3824
3825
3826
3827
3828
3829
3830
3831
3832
3833
3834
3835
3836
3837
3838
3839
3840
3841
3842
3843
3844
3845
3846
3847
3848
3849
3850
3851
3852
3853
3854
3855
3856
3857
3858
3859
3860
3861
3862
3863
3864
3865
3866
3867
3868
3869
3870
3871
3872
3873
3874
3875
3876
3877
3878
3879
3880
3881
3882
3883
3884
3885
3886
3887
3888
3889
3890
3891
3892
3893
3894
3895
3896
3897
3898
3899
3900
3901
3902
3903
3904
3905
3906
3907
3908
3909
3910
3911
3912
3913
3914
3915
3916
3917
3918
3919
3920
3921
3922
3923
3924
3925
3926
3927
3928
3929
3930
3931
3932
3933
3934
3935
3936
3937
3938
3939
3940
3941
3942
3943
3944
3945
3946
3947
3948
3949
3950
3951
3952
3953
3954
3955
3956
3957
3958
3959
3960
3961
3962
3963
3964
3965
3966
3967
3968
3969
3970
3971
3972
3973
3974
3975
3976
3977
3978
3979
3980
3981
3982
3983
3984
3985
3986
3987
3988
3989
3990
3991
3992
3993
3994
3995
3996
3997
3998
3999
4000
4001
4002
4003
4004
4005
4006
4007
4008
4009
4010
4011
4012
4013
4014
4015
4016
4017
4018
4019
4020
4021
4022
4023
4024
4025
4026
4027
4028
4029
4030
4031
4032
4033
4034
4035
4036
4037
4038
4039
4040
4041
4042
4043
4044
4045
4046
4047
4048
4049
4050
4051
4052
4053
4054
4055
4056
4057
4058
4059
4060
4061
4062
4063
4064
4065
4066
4067
4068
4069
4070
4071
4072
4073
4074
4075
4076
4077
4078
4079
4080
4081
4082
4083
4084
4085
4086
4087
4088
4089
4090
4091
4092
4093
4094
4095
4096
4097
4098
4099
4100
4101
4102
4103
4104
4105
4106
4107
4108
4109
4110
4111
4112
4113
4114
4115
4116
4117
4118
4119
4120
4121
4122
4123
4124
4125
4126
4127
4128
4129
4130
4131
4132
4133
4134
4135
4136
4137
4138
4139
4140
4141
4142
4143
4144
4145
4146
4147
4148
4149
4150
4151
4152
4153
4154
4155
4156
4157
4158
4159
4160
4161
4162
4163
4164
4165
4166
4167
4168
4169
4170
4171
4172
4173
4174
4175
4176
4177
4178
4179
4180
4181
4182
4183
4184
4185
4186
4187
4188
4189
4190
4191
4192
4193
4194
4195
4196
4197
4198
4199
4200
4201
4202
4203
4204
4205
4206
4207
4208
4209
4210
4211
4212
4213
4214
4215
4216
4217
4218
4219
4220
4221
4222
4223
4224
4225
4226
4227
4228
4229
4230
4231
4232
4233
4234
4235
4236
4237
4238
4239
4240
4241
4242
4243
4244
4245
4246
4247
4248
4249
4250
4251
4252
4253
4254
4255
4256
4257
4258
4259
4260
4261
4262
4263
4264
4265
4266
4267
4268
4269
4270
4271
4272
4273
4274
4275
4276
4277
4278
4279
4280
4281
4282
4283
4284
4285
4286
4287
4288
4289
4290
4291
4292
4293
4294
4295
4296
4297
4298
4299
4300
4301
4302
4303
4304
4305
4306
4307
4308
4309
4310
4311
4312
4313
4314
4315
4316
4317
4318
4319
4320
4321
4322
4323
4324
4325
4326
4327
4328
4329
4330
4331
4332
4333
4334
4335
4336
4337
4338
4339
4340
4341
4342
4343
4344
4345
4346
4347
4348
4349
4350
4351
4352
4353
4354
4355
4356
4357
4358
4359
4360
4361
4362
4363
4364
4365
4366
4367
4368
4369
4370
4371
4372
4373
4374
4375
4376
4377
4378
4379
4380
4381
4382
4383
4384
4385
4386
4387
4388
4389
4390
4391
4392
4393
4394
4395
4396
4397
4398
4399
4400
4401
4402
4403
4404
4405
4406
4407
4408
4409
4410
4411
4412
4413
4414
4415
4416
4417
4418
4419
4420
4421
4422
4423
4424
4425
4426
4427
4428
4429
4430
4431
4432
4433
4434
4435
4436
4437
4438
4439
4440
4441
4442
4443
4444
4445
4446
4447
4448
4449
4450
4451
4452
4453
4454
4455
4456
4457
4458
4459
4460
4461
4462
4463
4464
4465
4466
4467
4468
4469
4470
4471
4472
4473
4474
4475
4476
4477
4478
4479
4480
4481
4482
4483
4484
4485
4486
4487
4488
4489
4490
4491
4492
4493
4494
4495
4496
4497
4498
4499
4500
4501
4502
4503
4504
4505
4506
4507
4508
4509
4510
4511
4512
4513
4514
4515
4516
4517
4518
4519
4520
4521
4522
4523
4524
4525
4526
4527
4528
4529
4530
4531
4532
4533
4534
4535
4536
4537
4538
4539
4540
4541
4542
4543
4544
4545
4546
4547
4548
4549
4550
4551
4552
4553
4554
4555
4556
4557
4558
4559
4560
4561
4562
4563
4564
4565
4566
4567
4568
4569
4570
4571
4572
4573
4574
4575
4576
4577
4578
4579
4580
4581
4582
4583
4584
4585
4586
4587
4588
4589
4590
4591
4592
4593
4594
4595
4596
4597
4598
4599
4600
4601
4602
4603
4604
4605
4606
4607
4608
4609
4610
4611
4612
4613
4614
4615
4616
4617
4618
4619
4620
4621
4622
4623
4624
4625
4626
4627
4628
4629
4630
4631
4632
4633
4634
4635
4636
4637
4638
4639
4640
4641
4642
4643
4644
4645
4646
4647
4648
4649
4650
4651
4652
4653
4654
4655
4656
4657
4658
4659
4660
4661
4662
4663
4664
4665
4666
4667
4668
4669
4670
4671
4672
4673
4674
4675
4676
4677
4678
4679
4680
4681
4682
4683
4684
4685
4686
4687
4688
4689
4690
4691
4692
4693
4694
4695
4696
4697
4698
4699
4700
4701
4702
4703
4704
4705
4706
4707
4708
4709
4710
4711
4712
4713
4714
4715
4716
4717
4718
4719
4720
4721
4722
4723
4724
4725
4726
4727
4728
4729
4730
4731
4732
4733
4734
4735
4736
4737
4738
4739
4740
4741
4742
4743
4744
4745
4746
4747
4748
4749
4750
4751
4752
4753
4754
4755
4756
4757
4758
4759
4760
4761
4762
4763
4764
4765
4766
4767
4768
4769
4770
4771
4772
4773
4774
4775
4776
4777
4778
4779
4780
4781
4782
4783
4784
4785
4786
4787
4788
4789
4790
4791
4792
4793
4794
4795
4796
4797
4798
4799
4800
4801
4802
4803
4804
4805
4806
4807
4808
4809
4810
4811
4812
4813
4814
4815
4816
4817
4818
4819
4820
4821
4822
4823
4824
4825
4826
4827
4828
4829
4830
4831
4832
4833
4834
4835
4836
4837
4838
4839
4840
4841
4842
4843
4844
4845
4846
4847
4848
4849
4850
4851
4852
4853
4854
4855
4856
4857
4858
4859
4860
4861
4862
4863
4864
4865
4866
4867
4868
4869
4870
4871
4872
4873
4874
4875
4876
4877
4878
4879
4880
4881
4882
4883
4884
4885
4886
4887
4888
4889
4890
4891
4892
4893
4894
4895
4896
4897
4898
4899
4900
4901
4902
4903
4904
4905
4906
4907
4908
4909
4910
4911
4912
4913
4914
4915
4916
4917
4918
4919
4920
4921
4922
4923
4924
4925
4926
4927
4928
4929
4930
4931
4932
4933
4934
4935
4936
4937
4938
4939
4940
4941
4942
4943
4944
4945
4946
4947
4948
4949
4950
4951
4952
4953
4954
4955
4956
4957
4958
4959
4960
4961
4962
4963
4964
4965
4966
4967
4968
4969
4970
4971
4972
4973
4974
4975
4976
4977
4978
4979
4980
4981
4982
4983
4984
4985
4986
4987
4988
4989
4990
4991
4992
4993
4994
4995
4996
4997
4998
4999
5000
5001
5002
5003
5004
5005
5006
5007
5008
5009
5010
5011
5012
5013
5014
5015
5016
5017
5018
5019
5020
5021
5022
5023
5024
5025
5026
5027
5028
5029
5030
5031
5032
5033
5034
5035
5036
5037
5038
5039
5040
5041
5042
5043
5044
5045
5046
5047
5048
5049
5050
5051
5052
5053
5054
5055
5056
5057
5058
5059
5060
5061
5062
5063
5064
5065
5066
5067
5068
5069
5070
5071
5072
5073
5074
5075
5076
5077
5078
5079
5080
5081
5082
5083
5084
5085
5086
5087
5088
5089
5090
5091
5092
5093
5094
5095
5096
5097
5098
5099
5100
5101
5102
5103
5104
5105
5106
5107
5108
5109
5110
5111
5112
5113
5114
5115
5116
5117
5118
5119
5120
5121
5122
5123
5124
5125
5126
5127
5128
5129
5130
5131
5132
5133
5134
5135
5136
5137
5138
5139
5140
5141
5142
5143
5144
5145
5146
5147
5148
5149
5150
5151
5152
5153
5154
5155
5156
5157
5158
5159
5160
5161
5162
5163
5164
5165
5166
5167
5168
5169
5170
5171
5172
5173
use std::f64::consts::TAU;

use indexmap::IndexSet;
use kittycad_modeling_cmds::units::UnitLength;

use crate::execution::types::adjust_length;
use crate::frontend::api::Number;
use crate::frontend::api::Object;
use crate::frontend::api::ObjectId;
use crate::frontend::api::ObjectKind;
use crate::frontend::sketch::Constraint;
use crate::frontend::sketch::Segment;
use crate::frontend::sketch::SegmentCtor;
use crate::pretty::NumericSuffix;

#[cfg(all(feature = "artifact-graph", test))]
mod tests;

// Epsilon constants for geometric calculations
const EPSILON_PARALLEL: f64 = 1e-10;
const EPSILON_POINT_ON_SEGMENT: f64 = 1e-6;

/// Length unit for a numeric suffix (length variants only). Non-length suffixes default to millimeters.
fn suffix_to_unit(suffix: NumericSuffix) -> UnitLength {
    match suffix {
        NumericSuffix::Mm => UnitLength::Millimeters,
        NumericSuffix::Cm => UnitLength::Centimeters,
        NumericSuffix::M => UnitLength::Meters,
        NumericSuffix::Inch => UnitLength::Inches,
        NumericSuffix::Ft => UnitLength::Feet,
        NumericSuffix::Yd => UnitLength::Yards,
        _ => UnitLength::Millimeters,
    }
}

/// Convert a length `Number` to f64 in the target unit. Use when normalizing geometry into a single unit.
fn number_to_unit(n: &Number, target_unit: UnitLength) -> f64 {
    adjust_length(suffix_to_unit(n.units), n.value, target_unit).0
}

/// Convert a length in the given unit to a `Number` in the target suffix.
fn unit_to_number(value: f64, source_unit: UnitLength, target_suffix: NumericSuffix) -> Number {
    let (value, _) = adjust_length(source_unit, value, suffix_to_unit(target_suffix));
    Number {
        value,
        units: target_suffix,
    }
}

/// Convert trim line points from millimeters into the current/default unit.
fn normalize_trim_points_to_unit(points: &[Coords2d], default_unit: UnitLength) -> Vec<Coords2d> {
    points
        .iter()
        .map(|point| Coords2d {
            x: adjust_length(UnitLength::Millimeters, point.x, default_unit).0,
            y: adjust_length(UnitLength::Millimeters, point.y, default_unit).0,
        })
        .collect()
}

/// 2D coordinates in the trim internal unit (current/default length unit).
#[derive(Debug, Clone, Copy)]
pub struct Coords2d {
    pub x: f64,
    pub y: f64,
}

/// Which endpoint of a line segment to get coordinates for
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum LineEndpoint {
    Start,
    End,
}

/// Which point of an arc segment to get coordinates for
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum ArcPoint {
    Start,
    End,
    Center,
}

/// Which point of a circle segment to get coordinates for
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum CirclePoint {
    Start,
    Center,
}

/// Direction along a segment for finding trim terminations
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum TrimDirection {
    Left,
    Right,
}

// Manual serde implementation for Coords2d to serialize as [x, y] array
// This matches TypeScript's Coords2d type which is [number, number]

// A trim spawn is the intersection point of the trim line (drawn by the user) and a segment.
// We travel in both directions along the segment from the trim spawn to determine how to implement the trim.

/// Item from advancing to the next trim spawn (intersection), like an iterator item from `Iterator::next()`.
#[derive(Debug, Clone)]
pub enum TrimItem {
    Spawn {
        trim_spawn_seg_id: ObjectId,
        trim_spawn_coords: Coords2d,
        next_index: usize,
    },
    None {
        next_index: usize,
    },
}

/// Trim termination types
///
/// Trim termination is the term used to figure out each end of a segment after a trim spawn has been found.
/// When a trim spawn is found, we travel in both directions to find this termination. It can be:
/// (1) the end of a segment (floating end), (2) an intersection with another segment, or
/// (3) a coincident point where another segment is coincident with the segment we're traveling along.
#[derive(Debug, Clone)]
pub enum TrimTermination {
    SegEndPoint {
        trim_termination_coords: Coords2d,
    },
    Intersection {
        trim_termination_coords: Coords2d,
        intersecting_seg_id: ObjectId,
    },
    TrimSpawnSegmentCoincidentWithAnotherSegmentPoint {
        trim_termination_coords: Coords2d,
        intersecting_seg_id: ObjectId,
        other_segment_point_id: ObjectId,
    },
}

/// Trim terminations for both sides
#[derive(Debug, Clone)]
pub struct TrimTerminations {
    pub left_side: TrimTermination,
    pub right_side: TrimTermination,
}

/// Specifies where a constraint should attach when migrating during split operations
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum AttachToEndpoint {
    Start,
    End,
    Segment,
}

/// Specifies which endpoint of a segment was changed
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum EndpointChanged {
    Start,
    End,
}

/// Coincident data for split segment operations
#[derive(Debug, Clone)]
pub struct CoincidentData {
    pub intersecting_seg_id: ObjectId,
    pub intersecting_endpoint_point_id: Option<ObjectId>,
    pub existing_point_segment_constraint_id: Option<ObjectId>,
}

/// Constraint to migrate during split operations
#[derive(Debug, Clone)]
pub struct ConstraintToMigrate {
    pub constraint_id: ObjectId,
    pub other_entity_id: ObjectId,
    /// True if the coincident constraint is between two points (point–point).
    /// False if it is between a point and a line/arc/segment (point-segment coincident).
    pub is_point_point: bool,
    pub attach_to_endpoint: AttachToEndpoint,
}

/// Semantic trim plan produced by analysis/planning before lowering to frontend operations.
#[derive(Debug, Clone)]
pub enum TrimPlan {
    DeleteSegment {
        segment_id: ObjectId,
    },
    TailCut {
        segment_id: ObjectId,
        endpoint_changed: EndpointChanged,
        ctor: SegmentCtor,
        segment_or_point_to_make_coincident_to: ObjectId,
        intersecting_endpoint_point_id: Option<ObjectId>,
        constraint_ids_to_delete: Vec<ObjectId>,
    },
    ReplaceCircleWithArc {
        circle_id: ObjectId,
        arc_start_coords: Coords2d,
        arc_end_coords: Coords2d,
        arc_start_termination: Box<TrimTermination>,
        arc_end_termination: Box<TrimTermination>,
    },
    SplitSegment {
        segment_id: ObjectId,
        left_trim_coords: Coords2d,
        right_trim_coords: Coords2d,
        original_end_coords: Coords2d,
        left_side: Box<TrimTermination>,
        right_side: Box<TrimTermination>,
        left_side_coincident_data: CoincidentData,
        right_side_coincident_data: CoincidentData,
        constraints_to_migrate: Vec<ConstraintToMigrate>,
        constraints_to_delete: Vec<ObjectId>,
    },
}

fn lower_trim_plan(plan: &TrimPlan) -> Vec<TrimOperation> {
    match plan {
        TrimPlan::DeleteSegment { segment_id } => vec![TrimOperation::SimpleTrim {
            segment_to_trim_id: *segment_id,
        }],
        TrimPlan::TailCut {
            segment_id,
            endpoint_changed,
            ctor,
            segment_or_point_to_make_coincident_to,
            intersecting_endpoint_point_id,
            constraint_ids_to_delete,
        } => {
            let mut ops = vec![
                TrimOperation::EditSegment {
                    segment_id: *segment_id,
                    ctor: ctor.clone(),
                    endpoint_changed: *endpoint_changed,
                },
                TrimOperation::AddCoincidentConstraint {
                    segment_id: *segment_id,
                    endpoint_changed: *endpoint_changed,
                    segment_or_point_to_make_coincident_to: *segment_or_point_to_make_coincident_to,
                    intersecting_endpoint_point_id: *intersecting_endpoint_point_id,
                },
            ];
            if !constraint_ids_to_delete.is_empty() {
                ops.push(TrimOperation::DeleteConstraints {
                    constraint_ids: constraint_ids_to_delete.clone(),
                });
            }
            ops
        }
        TrimPlan::ReplaceCircleWithArc {
            circle_id,
            arc_start_coords,
            arc_end_coords,
            arc_start_termination,
            arc_end_termination,
        } => vec![TrimOperation::ReplaceCircleWithArc {
            circle_id: *circle_id,
            arc_start_coords: *arc_start_coords,
            arc_end_coords: *arc_end_coords,
            arc_start_termination: arc_start_termination.clone(),
            arc_end_termination: arc_end_termination.clone(),
        }],
        TrimPlan::SplitSegment {
            segment_id,
            left_trim_coords,
            right_trim_coords,
            original_end_coords,
            left_side,
            right_side,
            left_side_coincident_data,
            right_side_coincident_data,
            constraints_to_migrate,
            constraints_to_delete,
        } => vec![TrimOperation::SplitSegment {
            segment_id: *segment_id,
            left_trim_coords: *left_trim_coords,
            right_trim_coords: *right_trim_coords,
            original_end_coords: *original_end_coords,
            left_side: left_side.clone(),
            right_side: right_side.clone(),
            left_side_coincident_data: left_side_coincident_data.clone(),
            right_side_coincident_data: right_side_coincident_data.clone(),
            constraints_to_migrate: constraints_to_migrate.clone(),
            constraints_to_delete: constraints_to_delete.clone(),
        }],
    }
}

fn trim_plan_modifies_geometry(plan: &TrimPlan) -> bool {
    matches!(
        plan,
        TrimPlan::DeleteSegment { .. }
            | TrimPlan::TailCut { .. }
            | TrimPlan::ReplaceCircleWithArc { .. }
            | TrimPlan::SplitSegment { .. }
    )
}

fn rewrite_object_id(id: ObjectId, rewrite_map: &std::collections::HashMap<ObjectId, ObjectId>) -> ObjectId {
    rewrite_map.get(&id).copied().unwrap_or(id)
}

fn rewrite_constraint_segment(
    segment: crate::frontend::sketch::ConstraintSegment,
    rewrite_map: &std::collections::HashMap<ObjectId, ObjectId>,
) -> crate::frontend::sketch::ConstraintSegment {
    match segment {
        crate::frontend::sketch::ConstraintSegment::Segment(id) => {
            crate::frontend::sketch::ConstraintSegment::Segment(rewrite_object_id(id, rewrite_map))
        }
        crate::frontend::sketch::ConstraintSegment::Origin(origin) => {
            crate::frontend::sketch::ConstraintSegment::Origin(origin)
        }
    }
}

fn rewrite_constraint_segments(
    segments: &[crate::frontend::sketch::ConstraintSegment],
    rewrite_map: &std::collections::HashMap<ObjectId, ObjectId>,
) -> Vec<crate::frontend::sketch::ConstraintSegment> {
    segments
        .iter()
        .copied()
        .map(|segment| rewrite_constraint_segment(segment, rewrite_map))
        .collect()
}

fn constraint_segments_reference_any(
    segments: &[crate::frontend::sketch::ConstraintSegment],
    ids: &std::collections::HashSet<ObjectId>,
) -> bool {
    segments.iter().any(|segment| match segment {
        crate::frontend::sketch::ConstraintSegment::Segment(id) => ids.contains(id),
        crate::frontend::sketch::ConstraintSegment::Origin(_) => false,
    })
}

fn rewrite_constraint_with_map(
    constraint: &Constraint,
    rewrite_map: &std::collections::HashMap<ObjectId, ObjectId>,
) -> Option<Constraint> {
    match constraint {
        Constraint::Coincident(coincident) => Some(Constraint::Coincident(crate::frontend::sketch::Coincident {
            segments: rewrite_constraint_segments(&coincident.segments, rewrite_map),
        })),
        Constraint::Distance(distance) => Some(Constraint::Distance(crate::frontend::sketch::Distance {
            points: rewrite_constraint_segments(&distance.points, rewrite_map),
            distance: distance.distance,
            source: distance.source.clone(),
        })),
        Constraint::HorizontalDistance(distance) => {
            Some(Constraint::HorizontalDistance(crate::frontend::sketch::Distance {
                points: rewrite_constraint_segments(&distance.points, rewrite_map),
                distance: distance.distance,
                source: distance.source.clone(),
            }))
        }
        Constraint::VerticalDistance(distance) => {
            Some(Constraint::VerticalDistance(crate::frontend::sketch::Distance {
                points: rewrite_constraint_segments(&distance.points, rewrite_map),
                distance: distance.distance,
                source: distance.source.clone(),
            }))
        }
        Constraint::Radius(radius) => Some(Constraint::Radius(crate::frontend::sketch::Radius {
            arc: rewrite_object_id(radius.arc, rewrite_map),
            radius: radius.radius,
            source: radius.source.clone(),
        })),
        Constraint::Diameter(diameter) => Some(Constraint::Diameter(crate::frontend::sketch::Diameter {
            arc: rewrite_object_id(diameter.arc, rewrite_map),
            diameter: diameter.diameter,
            source: diameter.source.clone(),
        })),
        Constraint::EqualRadius(equal_radius) => Some(Constraint::EqualRadius(crate::frontend::sketch::EqualRadius {
            input: equal_radius
                .input
                .iter()
                .map(|id| rewrite_object_id(*id, rewrite_map))
                .collect(),
        })),
        Constraint::Tangent(tangent) => Some(Constraint::Tangent(crate::frontend::sketch::Tangent {
            input: tangent
                .input
                .iter()
                .map(|id| rewrite_object_id(*id, rewrite_map))
                .collect(),
        })),
        Constraint::Parallel(parallel) => Some(Constraint::Parallel(crate::frontend::sketch::Parallel {
            lines: parallel
                .lines
                .iter()
                .map(|id| rewrite_object_id(*id, rewrite_map))
                .collect(),
        })),
        Constraint::Perpendicular(perpendicular) => {
            Some(Constraint::Perpendicular(crate::frontend::sketch::Perpendicular {
                lines: perpendicular
                    .lines
                    .iter()
                    .map(|id| rewrite_object_id(*id, rewrite_map))
                    .collect(),
            }))
        }
        Constraint::Horizontal(horizontal) => Some(Constraint::Horizontal(crate::frontend::sketch::Horizontal {
            line: rewrite_object_id(horizontal.line, rewrite_map),
        })),
        Constraint::Vertical(vertical) => Some(Constraint::Vertical(crate::frontend::sketch::Vertical {
            line: rewrite_object_id(vertical.line, rewrite_map),
        })),
        _ => None,
    }
}

#[derive(Debug, Clone)]
#[allow(clippy::large_enum_variant)]
pub enum TrimOperation {
    SimpleTrim {
        segment_to_trim_id: ObjectId,
    },
    EditSegment {
        segment_id: ObjectId,
        ctor: SegmentCtor,
        endpoint_changed: EndpointChanged,
    },
    AddCoincidentConstraint {
        segment_id: ObjectId,
        endpoint_changed: EndpointChanged,
        segment_or_point_to_make_coincident_to: ObjectId,
        intersecting_endpoint_point_id: Option<ObjectId>,
    },
    SplitSegment {
        segment_id: ObjectId,
        left_trim_coords: Coords2d,
        right_trim_coords: Coords2d,
        original_end_coords: Coords2d,
        left_side: Box<TrimTermination>,
        right_side: Box<TrimTermination>,
        left_side_coincident_data: CoincidentData,
        right_side_coincident_data: CoincidentData,
        constraints_to_migrate: Vec<ConstraintToMigrate>,
        constraints_to_delete: Vec<ObjectId>,
    },
    ReplaceCircleWithArc {
        circle_id: ObjectId,
        arc_start_coords: Coords2d,
        arc_end_coords: Coords2d,
        arc_start_termination: Box<TrimTermination>,
        arc_end_termination: Box<TrimTermination>,
    },
    DeleteConstraints {
        constraint_ids: Vec<ObjectId>,
    },
}

/// Helper to check if a point is on a line segment (within epsilon distance)
///
/// Returns the point if it's on the segment, None otherwise.
pub fn is_point_on_line_segment(
    point: Coords2d,
    segment_start: Coords2d,
    segment_end: Coords2d,
    epsilon: f64,
) -> Option<Coords2d> {
    let dx = segment_end.x - segment_start.x;
    let dy = segment_end.y - segment_start.y;
    let segment_length_sq = dx * dx + dy * dy;

    if segment_length_sq < EPSILON_PARALLEL {
        // Segment is degenerate, i.e it's practically a point
        let dist_sq = (point.x - segment_start.x) * (point.x - segment_start.x)
            + (point.y - segment_start.y) * (point.y - segment_start.y);
        if dist_sq <= epsilon * epsilon {
            return Some(point);
        }
        return None;
    }

    let point_dx = point.x - segment_start.x;
    let point_dy = point.y - segment_start.y;
    let projection_param = (point_dx * dx + point_dy * dy) / segment_length_sq;

    // Check if point projects onto the segment
    if !(0.0..=1.0).contains(&projection_param) {
        return None;
    }

    // Calculate the projected point on the segment
    let projected_point = Coords2d {
        x: segment_start.x + projection_param * dx,
        y: segment_start.y + projection_param * dy,
    };

    // Check if the distance from point to projected point is within epsilon
    let dist_dx = point.x - projected_point.x;
    let dist_dy = point.y - projected_point.y;
    let distance_sq = dist_dx * dist_dx + dist_dy * dist_dy;

    if distance_sq <= epsilon * epsilon {
        Some(point)
    } else {
        None
    }
}

/// Helper to calculate intersection point of two line segments
///
/// Returns the intersection point if segments intersect, None otherwise.
pub fn line_segment_intersection(
    line1_start: Coords2d,
    line1_end: Coords2d,
    line2_start: Coords2d,
    line2_end: Coords2d,
    epsilon: f64,
) -> Option<Coords2d> {
    // First check if any endpoints are on the other segment
    if let Some(point) = is_point_on_line_segment(line1_start, line2_start, line2_end, epsilon) {
        return Some(point);
    }

    if let Some(point) = is_point_on_line_segment(line1_end, line2_start, line2_end, epsilon) {
        return Some(point);
    }

    if let Some(point) = is_point_on_line_segment(line2_start, line1_start, line1_end, epsilon) {
        return Some(point);
    }

    if let Some(point) = is_point_on_line_segment(line2_end, line1_start, line1_end, epsilon) {
        return Some(point);
    }

    // Then check for actual line segment intersection
    let x1 = line1_start.x;
    let y1 = line1_start.y;
    let x2 = line1_end.x;
    let y2 = line1_end.y;
    let x3 = line2_start.x;
    let y3 = line2_start.y;
    let x4 = line2_end.x;
    let y4 = line2_end.y;

    let denominator = (x1 - x2) * (y3 - y4) - (y1 - y2) * (x3 - x4);
    if denominator.abs() < EPSILON_PARALLEL {
        // Lines are parallel
        return None;
    }

    let t = ((x1 - x3) * (y3 - y4) - (y1 - y3) * (x3 - x4)) / denominator;
    let u = -((x1 - x2) * (y1 - y3) - (y1 - y2) * (x1 - x3)) / denominator;

    // Check if intersection is within both segments
    if (0.0..=1.0).contains(&t) && (0.0..=1.0).contains(&u) {
        let x = x1 + t * (x2 - x1);
        let y = y1 + t * (y2 - y1);
        return Some(Coords2d { x, y });
    }

    None
}

/// Helper to calculate the parametric position of a point on a line segment
///
/// Returns t where t=0 at segmentStart, t=1 at segmentEnd.
/// t can be < 0 or > 1 if the point projects outside the segment.
pub fn project_point_onto_segment(point: Coords2d, segment_start: Coords2d, segment_end: Coords2d) -> f64 {
    let dx = segment_end.x - segment_start.x;
    let dy = segment_end.y - segment_start.y;
    let segment_length_sq = dx * dx + dy * dy;

    if segment_length_sq < EPSILON_PARALLEL {
        // Segment is degenerate
        return 0.0;
    }

    let point_dx = point.x - segment_start.x;
    let point_dy = point.y - segment_start.y;

    (point_dx * dx + point_dy * dy) / segment_length_sq
}

/// Helper to calculate the perpendicular distance from a point to a line segment
///
/// Returns the distance from the point to the closest point on the segment.
pub fn perpendicular_distance_to_segment(point: Coords2d, segment_start: Coords2d, segment_end: Coords2d) -> f64 {
    let dx = segment_end.x - segment_start.x;
    let dy = segment_end.y - segment_start.y;
    let segment_length_sq = dx * dx + dy * dy;

    if segment_length_sq < EPSILON_PARALLEL {
        // Segment is degenerate, return distance to point
        let dist_dx = point.x - segment_start.x;
        let dist_dy = point.y - segment_start.y;
        return (dist_dx * dist_dx + dist_dy * dist_dy).sqrt();
    }

    // Vector from segment start to point
    let point_dx = point.x - segment_start.x;
    let point_dy = point.y - segment_start.y;

    // Project point onto segment
    let t = (point_dx * dx + point_dy * dy) / segment_length_sq;

    // Clamp t to [0, 1] to get closest point on segment
    let clamped_t = t.clamp(0.0, 1.0);
    let closest_point = Coords2d {
        x: segment_start.x + clamped_t * dx,
        y: segment_start.y + clamped_t * dy,
    };

    // Calculate distance
    let dist_dx = point.x - closest_point.x;
    let dist_dy = point.y - closest_point.y;
    (dist_dx * dist_dx + dist_dy * dist_dy).sqrt()
}

/// Helper to check if a point is on an arc segment (CCW from start to end)
///
/// Returns true if the point is on the arc, false otherwise.
pub fn is_point_on_arc(point: Coords2d, center: Coords2d, start: Coords2d, end: Coords2d, epsilon: f64) -> bool {
    // Calculate radius
    let radius = ((start.x - center.x) * (start.x - center.x) + (start.y - center.y) * (start.y - center.y)).sqrt();

    // Check if point is on the circle (within epsilon)
    let dist_from_center =
        ((point.x - center.x) * (point.x - center.x) + (point.y - center.y) * (point.y - center.y)).sqrt();
    if (dist_from_center - radius).abs() > epsilon {
        return false;
    }

    // Calculate angles
    let start_angle = libm::atan2(start.y - center.y, start.x - center.x);
    let end_angle = libm::atan2(end.y - center.y, end.x - center.x);
    let point_angle = libm::atan2(point.y - center.y, point.x - center.x);

    // Normalize angles to [0, 2Ï€]
    let normalize_angle = |angle: f64| -> f64 {
        if !angle.is_finite() {
            return angle;
        }
        let mut normalized = angle;
        while normalized < 0.0 {
            normalized += TAU;
        }
        while normalized >= TAU {
            normalized -= TAU;
        }
        normalized
    };

    let normalized_start = normalize_angle(start_angle);
    let normalized_end = normalize_angle(end_angle);
    let normalized_point = normalize_angle(point_angle);

    // Check if point is on the arc going CCW from start to end
    // Since arcs always travel CCW, we need to check if the point angle
    // is between start and end when going CCW
    if normalized_start < normalized_end {
        // No wrap around
        normalized_point >= normalized_start && normalized_point <= normalized_end
    } else {
        // Wrap around (e.g., start at 350°, end at 10°)
        normalized_point >= normalized_start || normalized_point <= normalized_end
    }
}

/// Helper to calculate intersection between a line segment and an arc
///
/// Returns the intersection point if found, None otherwise.
pub fn line_arc_intersection(
    line_start: Coords2d,
    line_end: Coords2d,
    arc_center: Coords2d,
    arc_start: Coords2d,
    arc_end: Coords2d,
    epsilon: f64,
) -> Option<Coords2d> {
    // Calculate radius
    let radius = ((arc_start.x - arc_center.x) * (arc_start.x - arc_center.x)
        + (arc_start.y - arc_center.y) * (arc_start.y - arc_center.y))
        .sqrt();

    // Translate line to origin (center at 0,0)
    let translated_line_start = Coords2d {
        x: line_start.x - arc_center.x,
        y: line_start.y - arc_center.y,
    };
    let translated_line_end = Coords2d {
        x: line_end.x - arc_center.x,
        y: line_end.y - arc_center.y,
    };

    // Line equation: p = lineStart + t * (lineEnd - lineStart)
    let dx = translated_line_end.x - translated_line_start.x;
    let dy = translated_line_end.y - translated_line_start.y;

    // Circle equation: x² + y² = r²
    // Substitute line equation into circle equation
    // (x0 + t*dx)² + (y0 + t*dy)² = r²
    // Expand: x0² + 2*x0*t*dx + t²*dx² + y0² + 2*y0*t*dy + t²*dy² = r²
    // Rearrange: t²*(dx² + dy²) + 2*t*(x0*dx + y0*dy) + (x0² + y0² - r²) = 0

    let a = dx * dx + dy * dy;
    let b = 2.0 * (translated_line_start.x * dx + translated_line_start.y * dy);
    let c = translated_line_start.x * translated_line_start.x + translated_line_start.y * translated_line_start.y
        - radius * radius;

    let discriminant = b * b - 4.0 * a * c;

    if discriminant < 0.0 {
        // No intersection
        return None;
    }

    if a.abs() < EPSILON_PARALLEL {
        // Line segment is degenerate
        let dist_from_center = (translated_line_start.x * translated_line_start.x
            + translated_line_start.y * translated_line_start.y)
            .sqrt();
        if (dist_from_center - radius).abs() <= epsilon {
            // Point is on circle, check if it's on the arc
            let point = line_start;
            if is_point_on_arc(point, arc_center, arc_start, arc_end, epsilon) {
                return Some(point);
            }
        }
        return None;
    }

    let sqrt_discriminant = discriminant.sqrt();
    let t1 = (-b - sqrt_discriminant) / (2.0 * a);
    let t2 = (-b + sqrt_discriminant) / (2.0 * a);

    // Check both intersection points
    let mut candidates: Vec<(f64, Coords2d)> = Vec::new();
    if (0.0..=1.0).contains(&t1) {
        let point = Coords2d {
            x: line_start.x + t1 * (line_end.x - line_start.x),
            y: line_start.y + t1 * (line_end.y - line_start.y),
        };
        candidates.push((t1, point));
    }
    if (0.0..=1.0).contains(&t2) && (t2 - t1).abs() > epsilon {
        let point = Coords2d {
            x: line_start.x + t2 * (line_end.x - line_start.x),
            y: line_start.y + t2 * (line_end.y - line_start.y),
        };
        candidates.push((t2, point));
    }

    // Check which candidates are on the arc
    for (_t, point) in candidates {
        if is_point_on_arc(point, arc_center, arc_start, arc_end, epsilon) {
            return Some(point);
        }
    }

    None
}

/// Helper to calculate intersection points between a line segment and a circle.
///
/// Returns intersections as `(t, point)` where `t` is the line parametric position:
/// `point = line_start + t * (line_end - line_start)`, with `0 <= t <= 1`.
pub fn line_circle_intersections(
    line_start: Coords2d,
    line_end: Coords2d,
    circle_center: Coords2d,
    radius: f64,
    epsilon: f64,
) -> Vec<(f64, Coords2d)> {
    // Translate line to origin (center at 0,0)
    let translated_line_start = Coords2d {
        x: line_start.x - circle_center.x,
        y: line_start.y - circle_center.y,
    };
    let translated_line_end = Coords2d {
        x: line_end.x - circle_center.x,
        y: line_end.y - circle_center.y,
    };

    let dx = translated_line_end.x - translated_line_start.x;
    let dy = translated_line_end.y - translated_line_start.y;
    let a = dx * dx + dy * dy;
    let b = 2.0 * (translated_line_start.x * dx + translated_line_start.y * dy);
    let c = translated_line_start.x * translated_line_start.x + translated_line_start.y * translated_line_start.y
        - radius * radius;

    if a.abs() < EPSILON_PARALLEL {
        return Vec::new();
    }

    let discriminant = b * b - 4.0 * a * c;
    if discriminant < 0.0 {
        return Vec::new();
    }

    let sqrt_discriminant = discriminant.sqrt();
    let mut intersections = Vec::new();

    let t1 = (-b - sqrt_discriminant) / (2.0 * a);
    if (0.0..=1.0).contains(&t1) {
        intersections.push((
            t1,
            Coords2d {
                x: line_start.x + t1 * (line_end.x - line_start.x),
                y: line_start.y + t1 * (line_end.y - line_start.y),
            },
        ));
    }

    let t2 = (-b + sqrt_discriminant) / (2.0 * a);
    if (0.0..=1.0).contains(&t2) && (t2 - t1).abs() > epsilon {
        intersections.push((
            t2,
            Coords2d {
                x: line_start.x + t2 * (line_end.x - line_start.x),
                y: line_start.y + t2 * (line_end.y - line_start.y),
            },
        ));
    }

    intersections.sort_by(|a, b| a.0.partial_cmp(&b.0).unwrap_or(std::cmp::Ordering::Equal));
    intersections
}

/// Parametric position of a point on a circle, measured CCW from the circle start point.
///
/// Returns `t` in `[0, 1)` where:
/// - `t = 0` at circle start
/// - increasing `t` moves CCW
pub fn project_point_onto_circle(point: Coords2d, center: Coords2d, start: Coords2d) -> f64 {
    let normalize_angle = |angle: f64| -> f64 {
        if !angle.is_finite() {
            return angle;
        }
        let mut normalized = angle;
        while normalized < 0.0 {
            normalized += TAU;
        }
        while normalized >= TAU {
            normalized -= TAU;
        }
        normalized
    };

    let start_angle = normalize_angle(libm::atan2(start.y - center.y, start.x - center.x));
    let point_angle = normalize_angle(libm::atan2(point.y - center.y, point.x - center.x));
    let delta_ccw = (point_angle - start_angle).rem_euclid(TAU);
    delta_ccw / TAU
}

fn is_point_on_circle(point: Coords2d, center: Coords2d, radius: f64, epsilon: f64) -> bool {
    let dist = ((point.x - center.x) * (point.x - center.x) + (point.y - center.y) * (point.y - center.y)).sqrt();
    (dist - radius).abs() <= epsilon
}

/// Helper to calculate the parametric position of a point on an arc
/// Returns t where t=0 at start, t=1 at end, based on CCW angle
pub fn project_point_onto_arc(point: Coords2d, arc_center: Coords2d, arc_start: Coords2d, arc_end: Coords2d) -> f64 {
    // Calculate angles
    let start_angle = libm::atan2(arc_start.y - arc_center.y, arc_start.x - arc_center.x);
    let end_angle = libm::atan2(arc_end.y - arc_center.y, arc_end.x - arc_center.x);
    let point_angle = libm::atan2(point.y - arc_center.y, point.x - arc_center.x);

    // Normalize angles to [0, 2Ï€]
    let normalize_angle = |angle: f64| -> f64 {
        if !angle.is_finite() {
            return angle;
        }
        let mut normalized = angle;
        while normalized < 0.0 {
            normalized += TAU;
        }
        while normalized >= TAU {
            normalized -= TAU;
        }
        normalized
    };

    let normalized_start = normalize_angle(start_angle);
    let normalized_end = normalize_angle(end_angle);
    let normalized_point = normalize_angle(point_angle);

    // Calculate arc length (CCW)
    let arc_length = if normalized_start < normalized_end {
        normalized_end - normalized_start
    } else {
        // Wrap around
        TAU - normalized_start + normalized_end
    };

    if arc_length < EPSILON_PARALLEL {
        // Arc is degenerate (full circle or very small)
        return 0.0;
    }

    // Calculate point's position along arc (CCW from start)
    let point_arc_length = if normalized_start < normalized_end {
        if normalized_point >= normalized_start && normalized_point <= normalized_end {
            normalized_point - normalized_start
        } else {
            // Point is not on the arc, return closest endpoint
            let dist_to_start = (normalized_point - normalized_start)
                .abs()
                .min(TAU - (normalized_point - normalized_start).abs());
            let dist_to_end = (normalized_point - normalized_end)
                .abs()
                .min(TAU - (normalized_point - normalized_end).abs());
            return if dist_to_start < dist_to_end { 0.0 } else { 1.0 };
        }
    } else {
        // Wrap around case
        if normalized_point >= normalized_start || normalized_point <= normalized_end {
            if normalized_point >= normalized_start {
                normalized_point - normalized_start
            } else {
                TAU - normalized_start + normalized_point
            }
        } else {
            // Point is not on the arc
            let dist_to_start = (normalized_point - normalized_start)
                .abs()
                .min(TAU - (normalized_point - normalized_start).abs());
            let dist_to_end = (normalized_point - normalized_end)
                .abs()
                .min(TAU - (normalized_point - normalized_end).abs());
            return if dist_to_start < dist_to_end { 0.0 } else { 1.0 };
        }
    };

    // Return parametric position
    point_arc_length / arc_length
}

/// Helper to calculate all intersections between two arcs (via circle-circle intersection).
///
/// Returns all valid points that lie on both arcs (0, 1, or 2).
pub fn arc_arc_intersections(
    arc1_center: Coords2d,
    arc1_start: Coords2d,
    arc1_end: Coords2d,
    arc2_center: Coords2d,
    arc2_start: Coords2d,
    arc2_end: Coords2d,
    epsilon: f64,
) -> Vec<Coords2d> {
    // Calculate radii
    let r1 = ((arc1_start.x - arc1_center.x) * (arc1_start.x - arc1_center.x)
        + (arc1_start.y - arc1_center.y) * (arc1_start.y - arc1_center.y))
        .sqrt();
    let r2 = ((arc2_start.x - arc2_center.x) * (arc2_start.x - arc2_center.x)
        + (arc2_start.y - arc2_center.y) * (arc2_start.y - arc2_center.y))
        .sqrt();

    // Distance between centers
    let dx = arc2_center.x - arc1_center.x;
    let dy = arc2_center.y - arc1_center.y;
    let d = (dx * dx + dy * dy).sqrt();

    // Check if circles intersect
    if d > r1 + r2 + epsilon || d < (r1 - r2).abs() - epsilon {
        // No intersection
        return Vec::new();
    }

    // Check for degenerate cases
    if d < EPSILON_PARALLEL {
        // Concentric circles - no intersection (or infinite if same radius, but we treat as none)
        return Vec::new();
    }

    // Calculate intersection points
    // Using the formula from: https://mathworld.wolfram.com/Circle-CircleIntersection.html
    let a = (r1 * r1 - r2 * r2 + d * d) / (2.0 * d);
    let h_sq = r1 * r1 - a * a;

    // If h_sq is negative, no intersection
    if h_sq < 0.0 {
        return Vec::new();
    }

    let h = h_sq.sqrt();

    // If h is NaN, no intersection
    if h.is_nan() {
        return Vec::new();
    }

    // Unit vector from arc1Center to arc2Center
    let ux = dx / d;
    let uy = dy / d;

    // Perpendicular vector (rotated 90 degrees)
    let px = -uy;
    let py = ux;

    // Midpoint on the line connecting centers
    let mid_point = Coords2d {
        x: arc1_center.x + a * ux,
        y: arc1_center.y + a * uy,
    };

    // Two intersection points
    let intersection1 = Coords2d {
        x: mid_point.x + h * px,
        y: mid_point.y + h * py,
    };
    let intersection2 = Coords2d {
        x: mid_point.x - h * px,
        y: mid_point.y - h * py,
    };

    // Check which intersection point(s) are on both arcs
    let mut candidates: Vec<Coords2d> = Vec::new();

    if is_point_on_arc(intersection1, arc1_center, arc1_start, arc1_end, epsilon)
        && is_point_on_arc(intersection1, arc2_center, arc2_start, arc2_end, epsilon)
    {
        candidates.push(intersection1);
    }

    if (intersection1.x - intersection2.x).abs() > epsilon || (intersection1.y - intersection2.y).abs() > epsilon {
        // Only check second point if it's different from the first
        if is_point_on_arc(intersection2, arc1_center, arc1_start, arc1_end, epsilon)
            && is_point_on_arc(intersection2, arc2_center, arc2_start, arc2_end, epsilon)
        {
            candidates.push(intersection2);
        }
    }

    candidates
}

/// Helper to calculate one intersection between two arcs (if any).
///
/// This is kept for compatibility with existing call sites/tests that expect
/// a single optional intersection.
pub fn arc_arc_intersection(
    arc1_center: Coords2d,
    arc1_start: Coords2d,
    arc1_end: Coords2d,
    arc2_center: Coords2d,
    arc2_start: Coords2d,
    arc2_end: Coords2d,
    epsilon: f64,
) -> Option<Coords2d> {
    arc_arc_intersections(
        arc1_center,
        arc1_start,
        arc1_end,
        arc2_center,
        arc2_start,
        arc2_end,
        epsilon,
    )
    .first()
    .copied()
}

/// Helper to calculate intersections between a full circle and an arc.
///
/// Returns all valid intersection points on the arc (0, 1, or 2).
pub fn circle_arc_intersections(
    circle_center: Coords2d,
    circle_radius: f64,
    arc_center: Coords2d,
    arc_start: Coords2d,
    arc_end: Coords2d,
    epsilon: f64,
) -> Vec<Coords2d> {
    let r1 = circle_radius;
    let r2 = ((arc_start.x - arc_center.x) * (arc_start.x - arc_center.x)
        + (arc_start.y - arc_center.y) * (arc_start.y - arc_center.y))
        .sqrt();

    let dx = arc_center.x - circle_center.x;
    let dy = arc_center.y - circle_center.y;
    let d = (dx * dx + dy * dy).sqrt();

    if d > r1 + r2 + epsilon || d < (r1 - r2).abs() - epsilon || d < EPSILON_PARALLEL {
        return Vec::new();
    }

    let a = (r1 * r1 - r2 * r2 + d * d) / (2.0 * d);
    let h_sq = r1 * r1 - a * a;
    if h_sq < 0.0 {
        return Vec::new();
    }
    let h = h_sq.sqrt();
    if h.is_nan() {
        return Vec::new();
    }

    let ux = dx / d;
    let uy = dy / d;
    let px = -uy;
    let py = ux;
    let mid_point = Coords2d {
        x: circle_center.x + a * ux,
        y: circle_center.y + a * uy,
    };

    let intersection1 = Coords2d {
        x: mid_point.x + h * px,
        y: mid_point.y + h * py,
    };
    let intersection2 = Coords2d {
        x: mid_point.x - h * px,
        y: mid_point.y - h * py,
    };

    let mut intersections = Vec::new();
    if is_point_on_arc(intersection1, arc_center, arc_start, arc_end, epsilon) {
        intersections.push(intersection1);
    }
    if ((intersection1.x - intersection2.x).abs() > epsilon || (intersection1.y - intersection2.y).abs() > epsilon)
        && is_point_on_arc(intersection2, arc_center, arc_start, arc_end, epsilon)
    {
        intersections.push(intersection2);
    }
    intersections
}

/// Helper to calculate intersections between two full circles.
///
/// Returns 0, 1 (tangent), or 2 intersection points.
pub fn circle_circle_intersections(
    circle1_center: Coords2d,
    circle1_radius: f64,
    circle2_center: Coords2d,
    circle2_radius: f64,
    epsilon: f64,
) -> Vec<Coords2d> {
    let dx = circle2_center.x - circle1_center.x;
    let dy = circle2_center.y - circle1_center.y;
    let d = (dx * dx + dy * dy).sqrt();

    if d > circle1_radius + circle2_radius + epsilon
        || d < (circle1_radius - circle2_radius).abs() - epsilon
        || d < EPSILON_PARALLEL
    {
        return Vec::new();
    }

    let a = (circle1_radius * circle1_radius - circle2_radius * circle2_radius + d * d) / (2.0 * d);
    let h_sq = circle1_radius * circle1_radius - a * a;
    if h_sq < 0.0 {
        return Vec::new();
    }

    let h = if h_sq <= epsilon { 0.0 } else { h_sq.sqrt() };
    if h.is_nan() {
        return Vec::new();
    }

    let ux = dx / d;
    let uy = dy / d;
    let px = -uy;
    let py = ux;

    let mid_point = Coords2d {
        x: circle1_center.x + a * ux,
        y: circle1_center.y + a * uy,
    };

    let intersection1 = Coords2d {
        x: mid_point.x + h * px,
        y: mid_point.y + h * py,
    };
    let intersection2 = Coords2d {
        x: mid_point.x - h * px,
        y: mid_point.y - h * py,
    };

    let mut intersections = vec![intersection1];
    if (intersection1.x - intersection2.x).abs() > epsilon || (intersection1.y - intersection2.y).abs() > epsilon {
        intersections.push(intersection2);
    }
    intersections
}

/// Helper to extract coordinates from a point object in JSON format
// Native type helper - get point coordinates from ObjectId
fn get_point_coords_from_native(objects: &[Object], point_id: ObjectId, default_unit: UnitLength) -> Option<Coords2d> {
    let point_obj = objects.get(point_id.0)?;

    // Check if it's a Point segment
    let ObjectKind::Segment { segment } = &point_obj.kind else {
        return None;
    };

    let Segment::Point(point) = segment else {
        return None;
    };

    // Extract position coordinates in the trim internal unit
    Some(Coords2d {
        x: number_to_unit(&point.position.x, default_unit),
        y: number_to_unit(&point.position.y, default_unit),
    })
}

// Legacy JSON helper (will be removed)
/// Helper to get point coordinates from a Line segment by looking up the point object (native types)
pub fn get_position_coords_for_line(
    segment_obj: &Object,
    which: LineEndpoint,
    objects: &[Object],
    default_unit: UnitLength,
) -> Option<Coords2d> {
    let ObjectKind::Segment { segment } = &segment_obj.kind else {
        return None;
    };

    let Segment::Line(line) = segment else {
        return None;
    };

    // Get the point ID from the segment
    let point_id = match which {
        LineEndpoint::Start => line.start,
        LineEndpoint::End => line.end,
    };

    get_point_coords_from_native(objects, point_id, default_unit)
}

/// Helper to check if a point is coincident with a segment (line or arc) via constraints (native types)
fn is_point_coincident_with_segment_native(point_id: ObjectId, segment_id: ObjectId, objects: &[Object]) -> bool {
    // Find coincident constraints
    for obj in objects {
        let ObjectKind::Constraint { constraint } = &obj.kind else {
            continue;
        };

        let Constraint::Coincident(coincident) = constraint else {
            continue;
        };

        // Check if both pointId and segmentId are in the segments array
        let has_point = coincident.contains_segment(point_id);
        let has_segment = coincident.contains_segment(segment_id);

        if has_point && has_segment {
            return true;
        }
    }
    false
}

/// Helper to get point coordinates from an Arc segment by looking up the point object (native types)
pub fn get_position_coords_from_arc(
    segment_obj: &Object,
    which: ArcPoint,
    objects: &[Object],
    default_unit: UnitLength,
) -> Option<Coords2d> {
    let ObjectKind::Segment { segment } = &segment_obj.kind else {
        return None;
    };

    let Segment::Arc(arc) = segment else {
        return None;
    };

    // Get the point ID from the segment
    let point_id = match which {
        ArcPoint::Start => arc.start,
        ArcPoint::End => arc.end,
        ArcPoint::Center => arc.center,
    };

    get_point_coords_from_native(objects, point_id, default_unit)
}

/// Helper to get point coordinates from a Circle segment by looking up the point object (native types)
pub fn get_position_coords_from_circle(
    segment_obj: &Object,
    which: CirclePoint,
    objects: &[Object],
    default_unit: UnitLength,
) -> Option<Coords2d> {
    let ObjectKind::Segment { segment } = &segment_obj.kind else {
        return None;
    };

    let Segment::Circle(circle) = segment else {
        return None;
    };

    let point_id = match which {
        CirclePoint::Start => circle.start,
        CirclePoint::Center => circle.center,
    };

    get_point_coords_from_native(objects, point_id, default_unit)
}

/// Internal normalized curve kind used by trim.
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
enum CurveKind {
    Line,
    Circular,
}

/// Internal curve domain used by trim.
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
enum CurveDomain {
    Open,
    Closed,
}

/// Internal normalized curve representation loaded from a scene segment.
#[derive(Debug, Clone, Copy)]
struct CurveHandle {
    segment_id: ObjectId,
    kind: CurveKind,
    domain: CurveDomain,
    start: Coords2d,
    end: Coords2d,
    center: Option<Coords2d>,
    radius: Option<f64>,
}

impl CurveHandle {
    fn project_for_trim(self, point: Coords2d) -> Result<f64, String> {
        match (self.kind, self.domain) {
            (CurveKind::Line, CurveDomain::Open) => Ok(project_point_onto_segment(point, self.start, self.end)),
            (CurveKind::Circular, CurveDomain::Open) => {
                let center = self
                    .center
                    .ok_or_else(|| format!("Curve {} missing center for arc projection", self.segment_id.0))?;
                Ok(project_point_onto_arc(point, center, self.start, self.end))
            }
            (CurveKind::Circular, CurveDomain::Closed) => {
                let center = self
                    .center
                    .ok_or_else(|| format!("Curve {} missing center for circle projection", self.segment_id.0))?;
                Ok(project_point_onto_circle(point, center, self.start))
            }
            (CurveKind::Line, CurveDomain::Closed) => Err(format!(
                "Invalid curve state: line {} cannot be closed",
                self.segment_id.0
            )),
        }
    }
}

/// Load a normalized curve handle from a segment object.
fn load_curve_handle(
    segment_obj: &Object,
    objects: &[Object],
    default_unit: UnitLength,
) -> Result<CurveHandle, String> {
    let ObjectKind::Segment { segment } = &segment_obj.kind else {
        return Err("Object is not a segment".to_owned());
    };

    match segment {
        Segment::Line(_) => {
            let start = get_position_coords_for_line(segment_obj, LineEndpoint::Start, objects, default_unit)
                .ok_or_else(|| format!("Could not get line start for segment {}", segment_obj.id.0))?;
            let end = get_position_coords_for_line(segment_obj, LineEndpoint::End, objects, default_unit)
                .ok_or_else(|| format!("Could not get line end for segment {}", segment_obj.id.0))?;
            Ok(CurveHandle {
                segment_id: segment_obj.id,
                kind: CurveKind::Line,
                domain: CurveDomain::Open,
                start,
                end,
                center: None,
                radius: None,
            })
        }
        Segment::Arc(_) => {
            let start = get_position_coords_from_arc(segment_obj, ArcPoint::Start, objects, default_unit)
                .ok_or_else(|| format!("Could not get arc start for segment {}", segment_obj.id.0))?;
            let end = get_position_coords_from_arc(segment_obj, ArcPoint::End, objects, default_unit)
                .ok_or_else(|| format!("Could not get arc end for segment {}", segment_obj.id.0))?;
            let center = get_position_coords_from_arc(segment_obj, ArcPoint::Center, objects, default_unit)
                .ok_or_else(|| format!("Could not get arc center for segment {}", segment_obj.id.0))?;
            let radius =
                ((start.x - center.x) * (start.x - center.x) + (start.y - center.y) * (start.y - center.y)).sqrt();
            Ok(CurveHandle {
                segment_id: segment_obj.id,
                kind: CurveKind::Circular,
                domain: CurveDomain::Open,
                start,
                end,
                center: Some(center),
                radius: Some(radius),
            })
        }
        Segment::Circle(_) => {
            let start = get_position_coords_from_circle(segment_obj, CirclePoint::Start, objects, default_unit)
                .ok_or_else(|| format!("Could not get circle start for segment {}", segment_obj.id.0))?;
            let center = get_position_coords_from_circle(segment_obj, CirclePoint::Center, objects, default_unit)
                .ok_or_else(|| format!("Could not get circle center for segment {}", segment_obj.id.0))?;
            let radius =
                ((start.x - center.x) * (start.x - center.x) + (start.y - center.y) * (start.y - center.y)).sqrt();
            Ok(CurveHandle {
                segment_id: segment_obj.id,
                kind: CurveKind::Circular,
                domain: CurveDomain::Closed,
                start,
                // Closed curves have no true "end"; keep current trim semantics by mirroring start.
                end: start,
                center: Some(center),
                radius: Some(radius),
            })
        }
        Segment::Point(_) => Err(format!(
            "Point segment {} cannot be used as trim curve",
            segment_obj.id.0
        )),
    }
}

fn project_point_onto_curve(curve: CurveHandle, point: Coords2d) -> Result<f64, String> {
    curve.project_for_trim(point)
}

fn curve_contains_point(curve: CurveHandle, point: Coords2d, epsilon: f64) -> bool {
    match (curve.kind, curve.domain) {
        (CurveKind::Line, CurveDomain::Open) => {
            let t = project_point_onto_segment(point, curve.start, curve.end);
            (0.0..=1.0).contains(&t) && perpendicular_distance_to_segment(point, curve.start, curve.end) <= epsilon
        }
        (CurveKind::Circular, CurveDomain::Open) => curve
            .center
            .is_some_and(|center| is_point_on_arc(point, center, curve.start, curve.end, epsilon)),
        (CurveKind::Circular, CurveDomain::Closed) => curve.center.is_some_and(|center| {
            let radius = curve
                .radius
                .unwrap_or_else(|| ((curve.start.x - center.x).powi(2) + (curve.start.y - center.y).powi(2)).sqrt());
            is_point_on_circle(point, center, radius, epsilon)
        }),
        (CurveKind::Line, CurveDomain::Closed) => false,
    }
}

fn curve_line_segment_intersections(
    curve: CurveHandle,
    line_start: Coords2d,
    line_end: Coords2d,
    epsilon: f64,
) -> Vec<(f64, Coords2d)> {
    match (curve.kind, curve.domain) {
        (CurveKind::Line, CurveDomain::Open) => {
            line_segment_intersection(line_start, line_end, curve.start, curve.end, epsilon)
                .map(|intersection| {
                    (
                        project_point_onto_segment(intersection, line_start, line_end),
                        intersection,
                    )
                })
                .into_iter()
                .collect()
        }
        (CurveKind::Circular, CurveDomain::Open) => curve
            .center
            .and_then(|center| line_arc_intersection(line_start, line_end, center, curve.start, curve.end, epsilon))
            .map(|intersection| {
                (
                    project_point_onto_segment(intersection, line_start, line_end),
                    intersection,
                )
            })
            .into_iter()
            .collect(),
        (CurveKind::Circular, CurveDomain::Closed) => {
            let Some(center) = curve.center else {
                return Vec::new();
            };
            let radius = curve
                .radius
                .unwrap_or_else(|| ((curve.start.x - center.x).powi(2) + (curve.start.y - center.y).powi(2)).sqrt());
            line_circle_intersections(line_start, line_end, center, radius, epsilon)
        }
        (CurveKind::Line, CurveDomain::Closed) => Vec::new(),
    }
}

fn curve_polyline_intersections(curve: CurveHandle, polyline: &[Coords2d], epsilon: f64) -> Vec<(Coords2d, usize)> {
    let mut intersections = Vec::new();

    for i in 0..polyline.len().saturating_sub(1) {
        let p1 = polyline[i];
        let p2 = polyline[i + 1];
        for (_, intersection) in curve_line_segment_intersections(curve, p1, p2, epsilon) {
            intersections.push((intersection, i));
        }
    }

    intersections
}

fn curve_curve_intersections(curve: CurveHandle, other: CurveHandle, epsilon: f64) -> Vec<Coords2d> {
    match (curve.kind, curve.domain, other.kind, other.domain) {
        (CurveKind::Line, CurveDomain::Open, CurveKind::Line, CurveDomain::Open) => {
            line_segment_intersection(curve.start, curve.end, other.start, other.end, epsilon)
                .into_iter()
                .collect()
        }
        (CurveKind::Line, CurveDomain::Open, CurveKind::Circular, CurveDomain::Open) => other
            .center
            .and_then(|other_center| {
                line_arc_intersection(curve.start, curve.end, other_center, other.start, other.end, epsilon)
            })
            .into_iter()
            .collect(),
        (CurveKind::Line, CurveDomain::Open, CurveKind::Circular, CurveDomain::Closed) => {
            let Some(other_center) = other.center else {
                return Vec::new();
            };
            let other_radius = other.radius.unwrap_or_else(|| {
                ((other.start.x - other_center.x).powi(2) + (other.start.y - other_center.y).powi(2)).sqrt()
            });
            line_circle_intersections(curve.start, curve.end, other_center, other_radius, epsilon)
                .into_iter()
                .map(|(_, point)| point)
                .collect()
        }
        (CurveKind::Circular, CurveDomain::Open, CurveKind::Line, CurveDomain::Open) => curve
            .center
            .and_then(|curve_center| {
                line_arc_intersection(other.start, other.end, curve_center, curve.start, curve.end, epsilon)
            })
            .into_iter()
            .collect(),
        (CurveKind::Circular, CurveDomain::Open, CurveKind::Circular, CurveDomain::Open) => {
            let (Some(curve_center), Some(other_center)) = (curve.center, other.center) else {
                return Vec::new();
            };
            arc_arc_intersections(
                curve_center,
                curve.start,
                curve.end,
                other_center,
                other.start,
                other.end,
                epsilon,
            )
        }
        (CurveKind::Circular, CurveDomain::Open, CurveKind::Circular, CurveDomain::Closed) => {
            let (Some(curve_center), Some(other_center)) = (curve.center, other.center) else {
                return Vec::new();
            };
            let other_radius = other.radius.unwrap_or_else(|| {
                ((other.start.x - other_center.x).powi(2) + (other.start.y - other_center.y).powi(2)).sqrt()
            });
            circle_arc_intersections(
                other_center,
                other_radius,
                curve_center,
                curve.start,
                curve.end,
                epsilon,
            )
        }
        (CurveKind::Circular, CurveDomain::Closed, CurveKind::Line, CurveDomain::Open) => {
            let Some(curve_center) = curve.center else {
                return Vec::new();
            };
            let curve_radius = curve.radius.unwrap_or_else(|| {
                ((curve.start.x - curve_center.x).powi(2) + (curve.start.y - curve_center.y).powi(2)).sqrt()
            });
            line_circle_intersections(other.start, other.end, curve_center, curve_radius, epsilon)
                .into_iter()
                .map(|(_, point)| point)
                .collect()
        }
        (CurveKind::Circular, CurveDomain::Closed, CurveKind::Circular, CurveDomain::Open) => {
            let (Some(curve_center), Some(other_center)) = (curve.center, other.center) else {
                return Vec::new();
            };
            let curve_radius = curve.radius.unwrap_or_else(|| {
                ((curve.start.x - curve_center.x).powi(2) + (curve.start.y - curve_center.y).powi(2)).sqrt()
            });
            circle_arc_intersections(
                curve_center,
                curve_radius,
                other_center,
                other.start,
                other.end,
                epsilon,
            )
        }
        (CurveKind::Circular, CurveDomain::Closed, CurveKind::Circular, CurveDomain::Closed) => {
            let (Some(curve_center), Some(other_center)) = (curve.center, other.center) else {
                return Vec::new();
            };
            let curve_radius = curve.radius.unwrap_or_else(|| {
                ((curve.start.x - curve_center.x).powi(2) + (curve.start.y - curve_center.y).powi(2)).sqrt()
            });
            let other_radius = other.radius.unwrap_or_else(|| {
                ((other.start.x - other_center.x).powi(2) + (other.start.y - other_center.y).powi(2)).sqrt()
            });
            circle_circle_intersections(curve_center, curve_radius, other_center, other_radius, epsilon)
        }
        _ => Vec::new(),
    }
}

fn segment_endpoint_points(
    segment_obj: &Object,
    objects: &[Object],
    default_unit: UnitLength,
) -> Vec<(ObjectId, Coords2d)> {
    let ObjectKind::Segment { segment } = &segment_obj.kind else {
        return Vec::new();
    };

    match segment {
        Segment::Line(line) => {
            let mut points = Vec::new();
            if let Some(start) = get_position_coords_for_line(segment_obj, LineEndpoint::Start, objects, default_unit) {
                points.push((line.start, start));
            }
            if let Some(end) = get_position_coords_for_line(segment_obj, LineEndpoint::End, objects, default_unit) {
                points.push((line.end, end));
            }
            points
        }
        Segment::Arc(arc) => {
            let mut points = Vec::new();
            if let Some(start) = get_position_coords_from_arc(segment_obj, ArcPoint::Start, objects, default_unit) {
                points.push((arc.start, start));
            }
            if let Some(end) = get_position_coords_from_arc(segment_obj, ArcPoint::End, objects, default_unit) {
                points.push((arc.end, end));
            }
            points
        }
        _ => Vec::new(),
    }
}

/// Find the next trim spawn (intersection) between trim line and scene segments
///
/// When a user draws a trim line, we loop over each pairs of points of the trim line,
/// until we find an intersection, this intersection is called the trim spawn (to differentiate from
/// segment-segment intersections which are also important for trimming).
/// Below the dashes are segments and the periods are points on the trim line.
///
/// ```
///          /
///         /
///        /    .
/// ------/-------x--------
///      /       .       
///     /       .       
///    /           .   
/// ```
///
/// When we find a trim spawn we stop looping but save the index as we process each trim spawn one at a time.
/// The loop that processes each spawn one at a time is managed by `execute_trim_loop` (or `execute_trim_loop_with_context`).
///
/// Loops through polyline segments starting from startIndex and checks for intersections
/// with all scene segments (both Line and Arc). Returns the first intersection found.
///
/// **Units:** Trim line points are expected in millimeters at the API boundary. Callers should
/// normalize points to the current/default length unit before calling this function (the
/// trim loop does this for you). Segment positions read from `objects` are converted to that same
/// unit internally.
pub fn get_next_trim_spawn(
    points: &[Coords2d],
    start_index: usize,
    objects: &[Object],
    default_unit: UnitLength,
) -> TrimItem {
    let scene_curves: Vec<CurveHandle> = objects
        .iter()
        .filter_map(|obj| load_curve_handle(obj, objects, default_unit).ok())
        .collect();

    // Loop through polyline segments starting from startIndex
    for i in start_index..points.len().saturating_sub(1) {
        let p1 = points[i];
        let p2 = points[i + 1];

        // Check this polyline segment against all scene segments
        for curve in &scene_curves {
            let intersections = curve_line_segment_intersections(*curve, p1, p2, EPSILON_POINT_ON_SEGMENT);
            if let Some((_, intersection)) = intersections.first() {
                return TrimItem::Spawn {
                    trim_spawn_seg_id: curve.segment_id,
                    trim_spawn_coords: *intersection,
                    next_index: i,
                };
            }
        }
    }

    // No intersection found
    TrimItem::None {
        next_index: points.len().saturating_sub(1),
    }
}

/**
 * For the trim spawn segment and the intersection point on that segment,
 * finds the "trim terminations" in both directions (left and right from the intersection point).
 * A trim termination is the point where trimming should stop in each direction.
 *
 * The function searches for candidates in each direction and selects the closest one,
 * with the following priority when distances are equal: coincident > intersection > endpoint.
 *
 * ## segEndPoint: The segment's own endpoint
 *
 *   ========0
 * OR
 *   ========0
 *            \
 *             \
 *
 *  Returns this when:
 *  - No other candidates are found between the intersection point and the segment end
 *  - An intersection is found at the segment's own endpoint (even if due to numerical precision)
 *  - An intersection is found at another segment's endpoint (without a coincident constraint)
 *  - The closest candidate is the segment's own endpoint
 *
 * ## intersection: Intersection with another segment's body
 *            /
 *           /
 *  ========X=====
 *         /
 *        /
 *
 *  Returns this when:
 *  - A geometric intersection is found with another segment's body (not at an endpoint)
 *  - The intersection is not at our own segment's endpoint
 *  - The intersection is not at the other segment's endpoint (which would be segEndPoint)
 *
 * ## trimSpawnSegmentCoincidentWithAnotherSegmentPoint: Another segment's endpoint coincident with our segment
 *
 *  ========0=====
 *         /
 *        /
 *
 *  Returns this when:
 *  - Another segment's endpoint has a coincident constraint with our trim spawn segment
 *  - The endpoint's perpendicular distance to our segment is within epsilon
 *  - The endpoint is geometrically on our segment (between start and end)
 *  - This takes priority over intersections when distances are equal (within epsilon)
 *
 * ## Fallback
 *  If no candidates are found in a direction, defaults to "segEndPoint".
 * */
/// Find trim terminations for both sides of a trim spawn
///
/// For the trim spawn segment and the intersection point on that segment,
/// finds the "trim terminations" in both directions (left and right from the intersection point).
/// A trim termination is the point where trimming should stop in each direction.
pub fn get_trim_spawn_terminations(
    trim_spawn_seg_id: ObjectId,
    trim_spawn_coords: &[Coords2d],
    objects: &[Object],
    default_unit: UnitLength,
) -> Result<TrimTerminations, String> {
    // Find the trim spawn segment
    let trim_spawn_seg = objects.iter().find(|obj| obj.id == trim_spawn_seg_id);

    let trim_spawn_seg = match trim_spawn_seg {
        Some(seg) => seg,
        None => {
            return Err(format!("Trim spawn segment {} not found", trim_spawn_seg_id.0));
        }
    };

    let trim_curve = load_curve_handle(trim_spawn_seg, objects, default_unit).map_err(|e| {
        format!(
            "Failed to load trim spawn segment {} as normalized curve: {}",
            trim_spawn_seg_id.0, e
        )
    })?;

    // Find intersection point between polyline and trim spawn segment
    // trimSpawnCoords is a polyline, so we check each segment
    // We need to find ALL intersections and use a consistent one to avoid
    // different results for different trim lines in the same area
    let all_intersections = curve_polyline_intersections(trim_curve, trim_spawn_coords, EPSILON_POINT_ON_SEGMENT);

    // Use the intersection that's closest to the middle of the polyline
    // This ensures consistent results regardless of which segment intersects first
    let intersection_point = if all_intersections.is_empty() {
        return Err("Could not find intersection point between polyline and trim spawn segment".to_string());
    } else {
        // Find the middle of the polyline
        let mid_index = (trim_spawn_coords.len() - 1) / 2;
        let mid_point = trim_spawn_coords[mid_index];

        // Find the intersection closest to the middle
        let mut min_dist = f64::INFINITY;
        let mut closest_intersection = all_intersections[0].0;

        for (intersection, _) in &all_intersections {
            let dist = ((intersection.x - mid_point.x) * (intersection.x - mid_point.x)
                + (intersection.y - mid_point.y) * (intersection.y - mid_point.y))
                .sqrt();
            if dist < min_dist {
                min_dist = dist;
                closest_intersection = *intersection;
            }
        }

        closest_intersection
    };

    // Project intersection point onto segment to get parametric position
    let intersection_t = project_point_onto_curve(trim_curve, intersection_point)?;

    // Find terminations on both sides
    let left_termination = find_termination_in_direction(
        trim_spawn_seg,
        trim_curve,
        intersection_t,
        TrimDirection::Left,
        objects,
        default_unit,
    )?;

    let right_termination = find_termination_in_direction(
        trim_spawn_seg,
        trim_curve,
        intersection_t,
        TrimDirection::Right,
        objects,
        default_unit,
    )?;

    Ok(TrimTerminations {
        left_side: left_termination,
        right_side: right_termination,
    })
}

/// Helper to find trim termination in a given direction from the intersection point
///
/// This is called by `get_trim_spawn_terminations` for each direction (left and right).
/// It searches for candidates in the specified direction and selects the closest one,
/// with the following priority when distances are equal: coincident > intersection > endpoint.
///
/// ## segEndPoint: The segment's own endpoint
///
/// ```
///   ========0
/// OR
///   ========0
///            \
///             \
/// ```
///
/// Returns this when:
/// - No other candidates are found between the intersection point and the segment end
/// - An intersection is found at the segment's own endpoint (even if due to numerical precision)
/// - An intersection is found at another segment's endpoint (without a coincident constraint)
/// - The closest candidate is the segment's own endpoint
///
/// ## intersection: Intersection with another segment's body
/// ```
///            /
///           /
///  ========X=====
///         /
///        /
/// ```
///
/// Returns this when:
/// - A geometric intersection is found with another segment's body (not at an endpoint)
/// - The intersection is not at our own segment's endpoint
/// - The intersection is not at the other segment's endpoint (which would be segEndPoint)
///
/// ## trimSpawnSegmentCoincidentWithAnotherSegmentPoint: Another segment's endpoint coincident with our segment
///
/// ```
///  ========0=====
///         /
///        /
/// ```
///
/// Returns this when:
/// - Another segment's endpoint has a coincident constraint with our trim spawn segment
/// - The endpoint's perpendicular distance to our segment is within epsilon
/// - The endpoint is geometrically on our segment (between start and end)
/// - This takes priority over intersections when distances are equal (within epsilon)
///
/// ## Fallback
/// If no candidates are found in a direction, defaults to "segEndPoint".
fn find_termination_in_direction(
    trim_spawn_seg: &Object,
    trim_curve: CurveHandle,
    intersection_t: f64,
    direction: TrimDirection,
    objects: &[Object],
    default_unit: UnitLength,
) -> Result<TrimTermination, String> {
    // Use native types
    let ObjectKind::Segment { segment } = &trim_spawn_seg.kind else {
        return Err("Trim spawn segment is not a segment".to_string());
    };

    // Collect all candidate points: intersections, coincident points, and endpoints
    #[derive(Debug, Clone, Copy, PartialEq, Eq, PartialOrd, Ord)]
    enum CandidateType {
        Intersection,
        Coincident,
        Endpoint,
    }

    #[derive(Debug, Clone)]
    struct Candidate {
        t: f64,
        point: Coords2d,
        candidate_type: CandidateType,
        segment_id: Option<ObjectId>,
        point_id: Option<ObjectId>,
    }

    let mut candidates: Vec<Candidate> = Vec::new();

    // Add segment endpoints using native types
    match segment {
        Segment::Line(line) => {
            candidates.push(Candidate {
                t: 0.0,
                point: trim_curve.start,
                candidate_type: CandidateType::Endpoint,
                segment_id: None,
                point_id: Some(line.start),
            });
            candidates.push(Candidate {
                t: 1.0,
                point: trim_curve.end,
                candidate_type: CandidateType::Endpoint,
                segment_id: None,
                point_id: Some(line.end),
            });
        }
        Segment::Arc(arc) => {
            // For arcs, endpoints are at t=0 and t=1 conceptually
            candidates.push(Candidate {
                t: 0.0,
                point: trim_curve.start,
                candidate_type: CandidateType::Endpoint,
                segment_id: None,
                point_id: Some(arc.start),
            });
            candidates.push(Candidate {
                t: 1.0,
                point: trim_curve.end,
                candidate_type: CandidateType::Endpoint,
                segment_id: None,
                point_id: Some(arc.end),
            });
        }
        Segment::Circle(_) => {
            // Circles have no endpoints for trim termination purposes.
        }
        _ => {}
    }

    // Get trim spawn segment ID for comparison
    let trim_spawn_seg_id = trim_spawn_seg.id;

    // Find intersections and coincident endpoint candidates against all other segments.
    for other_seg in objects.iter() {
        let other_id = other_seg.id;
        if other_id == trim_spawn_seg_id {
            continue;
        }

        if let Ok(other_curve) = load_curve_handle(other_seg, objects, default_unit) {
            for intersection in curve_curve_intersections(trim_curve, other_curve, EPSILON_POINT_ON_SEGMENT) {
                let Ok(t) = project_point_onto_curve(trim_curve, intersection) else {
                    continue;
                };
                candidates.push(Candidate {
                    t,
                    point: intersection,
                    candidate_type: CandidateType::Intersection,
                    segment_id: Some(other_id),
                    point_id: None,
                });
            }
        }

        for (other_point_id, other_point) in segment_endpoint_points(other_seg, objects, default_unit) {
            if !is_point_coincident_with_segment_native(other_point_id, trim_spawn_seg_id, objects) {
                continue;
            }
            if !curve_contains_point(trim_curve, other_point, EPSILON_POINT_ON_SEGMENT) {
                continue;
            }
            let Ok(t) = project_point_onto_curve(trim_curve, other_point) else {
                continue;
            };
            candidates.push(Candidate {
                t,
                point: other_point,
                candidate_type: CandidateType::Coincident,
                segment_id: Some(other_id),
                point_id: Some(other_point_id),
            });
        }
    }

    let is_circle_segment = trim_curve.domain == CurveDomain::Closed;

    // Filter candidates to exclude the intersection point itself and those on the wrong side.
    // Use a slightly larger epsilon to account for numerical precision variations.
    let intersection_epsilon = EPSILON_POINT_ON_SEGMENT * 10.0; // 0.0001mm
    let direction_distance = |candidate_t: f64| -> f64 {
        if is_circle_segment {
            match direction {
                TrimDirection::Left => (intersection_t - candidate_t).rem_euclid(1.0),
                TrimDirection::Right => (candidate_t - intersection_t).rem_euclid(1.0),
            }
        } else {
            (candidate_t - intersection_t).abs()
        }
    };
    let filtered_candidates: Vec<Candidate> = candidates
        .into_iter()
        .filter(|candidate| {
            let dist_from_intersection = if is_circle_segment {
                let ccw = (candidate.t - intersection_t).rem_euclid(1.0);
                let cw = (intersection_t - candidate.t).rem_euclid(1.0);
                ccw.min(cw)
            } else {
                (candidate.t - intersection_t).abs()
            };
            if dist_from_intersection < intersection_epsilon {
                return false; // Too close to intersection point
            }

            if is_circle_segment {
                direction_distance(candidate.t) > intersection_epsilon
            } else {
                match direction {
                    TrimDirection::Left => candidate.t < intersection_t,
                    TrimDirection::Right => candidate.t > intersection_t,
                }
            }
        })
        .collect();

    // Sort candidates by distance from intersection (closest first)
    // When distances are equal, prioritize: coincident > intersection > endpoint
    let mut sorted_candidates = filtered_candidates;
    sorted_candidates.sort_by(|a, b| {
        let dist_a = direction_distance(a.t);
        let dist_b = direction_distance(b.t);
        let dist_diff = dist_a - dist_b;
        if dist_diff.abs() > EPSILON_POINT_ON_SEGMENT {
            dist_diff.partial_cmp(&0.0).unwrap_or(std::cmp::Ordering::Equal)
        } else {
            // Distances are effectively equal - prioritize by type
            let type_priority = |candidate_type: CandidateType| -> i32 {
                match candidate_type {
                    CandidateType::Coincident => 0,
                    CandidateType::Intersection => 1,
                    CandidateType::Endpoint => 2,
                }
            };
            type_priority(a.candidate_type).cmp(&type_priority(b.candidate_type))
        }
    });

    // Find the first valid trim termination
    let closest_candidate = match sorted_candidates.first() {
        Some(c) => c,
        None => {
            if is_circle_segment {
                return Err("No trim termination candidate found for circle".to_string());
            }
            // No trim termination found, default to segment endpoint
            let endpoint = match direction {
                TrimDirection::Left => trim_curve.start,
                TrimDirection::Right => trim_curve.end,
            };
            return Ok(TrimTermination::SegEndPoint {
                trim_termination_coords: endpoint,
            });
        }
    };

    // Check if the closest candidate is an intersection that is actually another segment's endpoint
    // According to test case: if another segment's endpoint is on our segment (even without coincident constraint),
    // we should return segEndPoint, not intersection
    if !is_circle_segment
        && closest_candidate.candidate_type == CandidateType::Intersection
        && let Some(seg_id) = closest_candidate.segment_id
    {
        let intersecting_seg = objects.iter().find(|obj| obj.id == seg_id);

        if let Some(intersecting_seg) = intersecting_seg {
            // Use a larger epsilon for checking if intersection is at another segment's endpoint
            let endpoint_epsilon = EPSILON_POINT_ON_SEGMENT * 1000.0; // 0.001mm
            let is_other_seg_endpoint = segment_endpoint_points(intersecting_seg, objects, default_unit)
                .into_iter()
                .any(|(_, endpoint)| {
                    let dist_to_endpoint = ((closest_candidate.point.x - endpoint.x).powi(2)
                        + (closest_candidate.point.y - endpoint.y).powi(2))
                    .sqrt();
                    dist_to_endpoint < endpoint_epsilon
                });

            // If the intersection point is another segment's endpoint (even without coincident constraint),
            // return segEndPoint instead of intersection
            if is_other_seg_endpoint {
                let endpoint = match direction {
                    TrimDirection::Left => trim_curve.start,
                    TrimDirection::Right => trim_curve.end,
                };
                return Ok(TrimTermination::SegEndPoint {
                    trim_termination_coords: endpoint,
                });
            }
        }

        // Also check if intersection is at our arc's endpoint
        let endpoint_t = match direction {
            TrimDirection::Left => 0.0,
            TrimDirection::Right => 1.0,
        };
        let endpoint = match direction {
            TrimDirection::Left => trim_curve.start,
            TrimDirection::Right => trim_curve.end,
        };
        let dist_to_endpoint_param = (closest_candidate.t - endpoint_t).abs();
        let dist_to_endpoint_coords = ((closest_candidate.point.x - endpoint.x)
            * (closest_candidate.point.x - endpoint.x)
            + (closest_candidate.point.y - endpoint.y) * (closest_candidate.point.y - endpoint.y))
            .sqrt();

        let is_at_endpoint =
            dist_to_endpoint_param < EPSILON_POINT_ON_SEGMENT || dist_to_endpoint_coords < EPSILON_POINT_ON_SEGMENT;

        if is_at_endpoint {
            // Intersection is at our endpoint -> segEndPoint
            return Ok(TrimTermination::SegEndPoint {
                trim_termination_coords: endpoint,
            });
        }
    }

    // Check if the closest candidate is an intersection at an endpoint
    let endpoint_t_for_return = match direction {
        TrimDirection::Left => 0.0,
        TrimDirection::Right => 1.0,
    };
    if !is_circle_segment && closest_candidate.candidate_type == CandidateType::Intersection {
        let dist_to_endpoint = (closest_candidate.t - endpoint_t_for_return).abs();
        if dist_to_endpoint < EPSILON_POINT_ON_SEGMENT {
            // Intersection is at endpoint - check if there's a coincident constraint
            // or if it's just a numerical precision issue
            let endpoint = match direction {
                TrimDirection::Left => trim_curve.start,
                TrimDirection::Right => trim_curve.end,
            };
            return Ok(TrimTermination::SegEndPoint {
                trim_termination_coords: endpoint,
            });
        }
    }

    // Check if the closest candidate is an endpoint at the trim spawn segment's endpoint
    let endpoint = match direction {
        TrimDirection::Left => trim_curve.start,
        TrimDirection::Right => trim_curve.end,
    };
    if !is_circle_segment && closest_candidate.candidate_type == CandidateType::Endpoint {
        let dist_to_endpoint = (closest_candidate.t - endpoint_t_for_return).abs();
        if dist_to_endpoint < EPSILON_POINT_ON_SEGMENT {
            // This is our own endpoint, return it
            return Ok(TrimTermination::SegEndPoint {
                trim_termination_coords: endpoint,
            });
        }
    }

    // Return appropriate termination type
    if closest_candidate.candidate_type == CandidateType::Coincident {
        // Even if at endpoint, return coincident type because it's a constraint-based termination
        Ok(TrimTermination::TrimSpawnSegmentCoincidentWithAnotherSegmentPoint {
            trim_termination_coords: closest_candidate.point,
            intersecting_seg_id: closest_candidate
                .segment_id
                .ok_or_else(|| "Missing segment_id for coincident".to_string())?,
            other_segment_point_id: closest_candidate
                .point_id
                .ok_or_else(|| "Missing point_id for coincident".to_string())?,
        })
    } else if closest_candidate.candidate_type == CandidateType::Intersection {
        Ok(TrimTermination::Intersection {
            trim_termination_coords: closest_candidate.point,
            intersecting_seg_id: closest_candidate
                .segment_id
                .ok_or_else(|| "Missing segment_id for intersection".to_string())?,
        })
    } else {
        if is_circle_segment {
            return Err("Circle trim termination unexpectedly resolved to endpoint".to_string());
        }
        // endpoint
        Ok(TrimTermination::SegEndPoint {
            trim_termination_coords: closest_candidate.point,
        })
    }
}

/// Execute the core trim loop.
/// This function handles the iteration through trim points, finding intersections,
/// and determining strategies. It calls the provided callback to execute operations.
///
/// The callback receives:
/// - The strategy (list of operations to execute)
/// - The current scene graph delta
///
/// The callback should return:
/// - The updated scene graph delta after executing operations
#[cfg(test)]
#[allow(dead_code)]
pub(crate) async fn execute_trim_loop<F, Fut>(
    points: &[Coords2d],
    default_unit: UnitLength,
    initial_scene_graph_delta: crate::frontend::api::SceneGraphDelta,
    mut execute_operations: F,
) -> Result<(crate::frontend::api::SourceDelta, crate::frontend::api::SceneGraphDelta), String>
where
    F: FnMut(Vec<TrimOperation>, crate::frontend::api::SceneGraphDelta) -> Fut,
    Fut: std::future::Future<
            Output = Result<(crate::frontend::api::SourceDelta, crate::frontend::api::SceneGraphDelta), String>,
        >,
{
    // Trim line points are expected in millimeters and normalized to the current unit here.
    let normalized_points = normalize_trim_points_to_unit(points, default_unit);
    let points = normalized_points.as_slice();

    let mut start_index = 0;
    let max_iterations = 1000;
    let mut iteration_count = 0;
    let mut last_result: Option<(crate::frontend::api::SourceDelta, crate::frontend::api::SceneGraphDelta)> = Some((
        crate::frontend::api::SourceDelta { text: String::new() },
        initial_scene_graph_delta.clone(),
    ));
    let mut invalidates_ids = false;
    let mut current_scene_graph_delta = initial_scene_graph_delta;
    let circle_delete_fallback_strategy =
        |error: &str, segment_id: ObjectId, scene_objects: &[Object]| -> Option<Vec<TrimOperation>> {
            if !error.contains("No trim termination candidate found for circle") {
                return None;
            }
            let is_circle = scene_objects
                .iter()
                .find(|obj| obj.id == segment_id)
                .is_some_and(|obj| {
                    matches!(
                        obj.kind,
                        ObjectKind::Segment {
                            segment: Segment::Circle(_)
                        }
                    )
                });
            if is_circle {
                Some(vec![TrimOperation::SimpleTrim {
                    segment_to_trim_id: segment_id,
                }])
            } else {
                None
            }
        };

    while start_index < points.len().saturating_sub(1) && iteration_count < max_iterations {
        iteration_count += 1;

        // Get next trim result
        let next_trim_spawn = get_next_trim_spawn(
            points,
            start_index,
            &current_scene_graph_delta.new_graph.objects,
            default_unit,
        );

        match &next_trim_spawn {
            TrimItem::None { next_index } => {
                let old_start_index = start_index;
                start_index = *next_index;

                // Fail-safe: if start_index didn't advance, force it to advance
                if start_index <= old_start_index {
                    start_index = old_start_index + 1;
                }

                // Early exit if we've reached the end
                if start_index >= points.len().saturating_sub(1) {
                    break;
                }
                continue;
            }
            TrimItem::Spawn {
                trim_spawn_seg_id,
                trim_spawn_coords,
                next_index,
                ..
            } => {
                // Get terminations
                let terminations = match get_trim_spawn_terminations(
                    *trim_spawn_seg_id,
                    points,
                    &current_scene_graph_delta.new_graph.objects,
                    default_unit,
                ) {
                    Ok(terms) => terms,
                    Err(e) => {
                        crate::logln!("Error getting trim spawn terminations: {}", e);
                        if let Some(strategy) = circle_delete_fallback_strategy(
                            &e,
                            *trim_spawn_seg_id,
                            &current_scene_graph_delta.new_graph.objects,
                        ) {
                            match execute_operations(strategy, current_scene_graph_delta.clone()).await {
                                Ok((source_delta, scene_graph_delta)) => {
                                    last_result = Some((source_delta, scene_graph_delta.clone()));
                                    invalidates_ids = invalidates_ids || scene_graph_delta.invalidates_ids;
                                    current_scene_graph_delta = scene_graph_delta;
                                }
                                Err(exec_err) => {
                                    crate::logln!(
                                        "Error executing circle-delete fallback trim operation: {}",
                                        exec_err
                                    );
                                }
                            }

                            let old_start_index = start_index;
                            start_index = *next_index;
                            if start_index <= old_start_index {
                                start_index = old_start_index + 1;
                            }
                            continue;
                        }

                        let old_start_index = start_index;
                        start_index = *next_index;
                        if start_index <= old_start_index {
                            start_index = old_start_index + 1;
                        }
                        continue;
                    }
                };

                // Get trim strategy
                let trim_spawn_segment = current_scene_graph_delta
                    .new_graph
                    .objects
                    .iter()
                    .find(|obj| obj.id == *trim_spawn_seg_id)
                    .ok_or_else(|| format!("Trim spawn segment {} not found", trim_spawn_seg_id.0))?;

                let plan = match build_trim_plan(
                    *trim_spawn_seg_id,
                    *trim_spawn_coords,
                    trim_spawn_segment,
                    &terminations.left_side,
                    &terminations.right_side,
                    &current_scene_graph_delta.new_graph.objects,
                    default_unit,
                ) {
                    Ok(plan) => plan,
                    Err(e) => {
                        crate::logln!("Error determining trim strategy: {}", e);
                        let old_start_index = start_index;
                        start_index = *next_index;
                        if start_index <= old_start_index {
                            start_index = old_start_index + 1;
                        }
                        continue;
                    }
                };
                let strategy = lower_trim_plan(&plan);

                // Keep processing the same trim polyline segment after geometry-changing ops.
                // This allows a single stroke to trim multiple intersected segments.
                let geometry_was_modified = trim_plan_modifies_geometry(&plan);

                // Execute operations via callback
                match execute_operations(strategy, current_scene_graph_delta.clone()).await {
                    Ok((source_delta, scene_graph_delta)) => {
                        last_result = Some((source_delta, scene_graph_delta.clone()));
                        invalidates_ids = invalidates_ids || scene_graph_delta.invalidates_ids;
                        current_scene_graph_delta = scene_graph_delta;
                    }
                    Err(e) => {
                        crate::logln!("Error executing trim operations: {}", e);
                        // Continue to next segment
                    }
                }

                // Move to next segment
                let old_start_index = start_index;
                start_index = *next_index;

                // Fail-safe: if start_index didn't advance, force it to advance
                if start_index <= old_start_index && !geometry_was_modified {
                    start_index = old_start_index + 1;
                }
            }
        }
    }

    if iteration_count >= max_iterations {
        return Err(format!("Reached max iterations ({})", max_iterations));
    }

    // Return the last result
    last_result.ok_or_else(|| "No trim operations were executed".to_string())
}

/// Result of executing trim flow
#[cfg(all(feature = "artifact-graph", test))]
#[derive(Debug, Clone)]
pub struct TrimFlowResult {
    pub kcl_code: String,
    pub invalidates_ids: bool,
}

/// Execute a complete trim flow from KCL code to KCL code.
/// This is a high-level function that sets up the frontend state and executes the trim loop.
///
/// This function:
/// 1. Parses the input KCL code
/// 2. Sets up ExecutorContext and FrontendState
/// 3. Executes the initial code to get the scene graph
/// 4. Runs the trim loop using `execute_trim_loop`
/// 5. Returns the resulting KCL code
///
/// This is designed for testing and simple use cases. For more complex scenarios
/// (like WASM with batching), use `execute_trim_loop` directly with a custom callback.
///
/// Note: This function is only available for non-WASM builds (tests) and uses
/// a mock executor context so tests can run without an engine token.
#[cfg(all(not(target_arch = "wasm32"), feature = "artifact-graph", test))]
pub(crate) async fn execute_trim_flow(
    kcl_code: &str,
    trim_points: &[Coords2d],
    sketch_id: ObjectId,
) -> Result<TrimFlowResult, String> {
    use crate::ExecutorContext;
    use crate::Program;
    use crate::execution::MockConfig;
    use crate::frontend::FrontendState;
    use crate::frontend::api::Version;

    // Parse KCL code
    let parse_result = Program::parse(kcl_code).map_err(|e| format!("Failed to parse KCL: {}", e))?;
    let (program_opt, errors) = parse_result;
    if !errors.is_empty() {
        return Err(format!("Failed to parse KCL: {:?}", errors));
    }
    let program = program_opt.ok_or_else(|| "No AST produced".to_string())?;

    let mock_ctx = ExecutorContext::new_mock(None).await;

    // Use a guard to ensure context is closed even on error
    let result = async {
        let mut frontend = FrontendState::new();

        // Set the program
        frontend.program = program.clone();

        let exec_outcome = mock_ctx
            .run_mock(&program, &MockConfig::default())
            .await
            .map_err(|e| format!("Failed to execute program: {}", e.error.message()))?;

        let exec_outcome = frontend.update_state_after_exec(exec_outcome, false);
        #[allow(unused_mut)] // mut is needed when artifact-graph feature is enabled
        let mut initial_scene_graph = frontend.scene_graph.clone();

        // If scene graph is empty, try to get objects from exec_outcome.scene_objects
        // (this is only available when artifact-graph feature is enabled)
        #[cfg(feature = "artifact-graph")]
        if initial_scene_graph.objects.is_empty() && !exec_outcome.scene_objects.is_empty() {
            initial_scene_graph.objects = exec_outcome.scene_objects.clone();
        }

        // Get the sketch ID from the scene graph
        // First try sketch_mode, then try to find a sketch object, then fall back to provided sketch_id
        let actual_sketch_id = if let Some(sketch_mode) = initial_scene_graph.sketch_mode {
            sketch_mode
        } else {
            // Try to find a sketch object in the scene graph
            initial_scene_graph
                .objects
                .iter()
                .find(|obj| matches!(obj.kind, crate::frontend::api::ObjectKind::Sketch { .. }))
                .map(|obj| obj.id)
                .unwrap_or(sketch_id) // Fall back to provided sketch_id
        };

        let version = Version(0);
        let initial_scene_graph_delta = crate::frontend::api::SceneGraphDelta {
            new_graph: initial_scene_graph,
            new_objects: vec![],
            invalidates_ids: false,
            exec_outcome,
        };

        // Execute the trim loop with a callback that executes operations using SketchApi
        // We need to use a different approach since we can't easily capture mutable references in closures
        // Instead, we'll use a helper that takes the necessary parameters
        // Use mock_ctx for operations (SketchApi methods require mock context)
        let (source_delta, scene_graph_delta) = execute_trim_loop_with_context(
            trim_points,
            initial_scene_graph_delta,
            &mut frontend,
            &mock_ctx,
            version,
            actual_sketch_id,
        )
        .await?;

        // Return the source delta text - this should contain the full updated KCL code
        // If it's empty, that means no operations were executed, which is an error
        if source_delta.text.is_empty() {
            return Err("No trim operations were executed - source delta is empty".to_string());
        }

        Ok(TrimFlowResult {
            kcl_code: source_delta.text,
            invalidates_ids: scene_graph_delta.invalidates_ids,
        })
    }
    .await;

    // Clean up context regardless of success or failure
    mock_ctx.close().await;

    result
}

/// Execute the trim loop with a context struct that provides access to FrontendState.
/// This is a convenience wrapper that inlines the loop to avoid borrow checker issues with closures.
/// The core loop logic is duplicated here, but this allows direct access to frontend and ctx.
///
/// Trim line points are expected in millimeters and are normalized to the current/default unit.
pub async fn execute_trim_loop_with_context(
    points: &[Coords2d],
    initial_scene_graph_delta: crate::frontend::api::SceneGraphDelta,
    frontend: &mut crate::frontend::FrontendState,
    ctx: &crate::ExecutorContext,
    version: crate::frontend::api::Version,
    sketch_id: ObjectId,
) -> Result<(crate::frontend::api::SourceDelta, crate::frontend::api::SceneGraphDelta), String> {
    // Trim line points are expected in millimeters and normalized to the current unit here.
    let default_unit = frontend.default_length_unit();
    let normalized_points = normalize_trim_points_to_unit(points, default_unit);

    // We inline the loop logic here to avoid borrow checker issues with closures capturing mutable references
    // This duplicates the loop from execute_trim_loop, but allows us to access frontend and ctx directly
    let mut current_scene_graph_delta = initial_scene_graph_delta.clone();
    let mut last_result: Option<(crate::frontend::api::SourceDelta, crate::frontend::api::SceneGraphDelta)> = Some((
        crate::frontend::api::SourceDelta { text: String::new() },
        initial_scene_graph_delta.clone(),
    ));
    let mut invalidates_ids = false;
    let mut start_index = 0;
    let max_iterations = 1000;
    let mut iteration_count = 0;
    let circle_delete_fallback_strategy =
        |error: &str, segment_id: ObjectId, scene_objects: &[Object]| -> Option<Vec<TrimOperation>> {
            if !error.contains("No trim termination candidate found for circle") {
                return None;
            }
            let is_circle = scene_objects
                .iter()
                .find(|obj| obj.id == segment_id)
                .is_some_and(|obj| {
                    matches!(
                        obj.kind,
                        ObjectKind::Segment {
                            segment: Segment::Circle(_)
                        }
                    )
                });
            if is_circle {
                Some(vec![TrimOperation::SimpleTrim {
                    segment_to_trim_id: segment_id,
                }])
            } else {
                None
            }
        };

    let points = normalized_points.as_slice();

    while start_index < points.len().saturating_sub(1) && iteration_count < max_iterations {
        iteration_count += 1;

        // Get next trim result
        let next_trim_spawn = get_next_trim_spawn(
            points,
            start_index,
            &current_scene_graph_delta.new_graph.objects,
            default_unit,
        );

        match &next_trim_spawn {
            TrimItem::None { next_index } => {
                let old_start_index = start_index;
                start_index = *next_index;
                if start_index <= old_start_index {
                    start_index = old_start_index + 1;
                }
                if start_index >= points.len().saturating_sub(1) {
                    break;
                }
                continue;
            }
            TrimItem::Spawn {
                trim_spawn_seg_id,
                trim_spawn_coords,
                next_index,
                ..
            } => {
                // Get terminations
                let terminations = match get_trim_spawn_terminations(
                    *trim_spawn_seg_id,
                    points,
                    &current_scene_graph_delta.new_graph.objects,
                    default_unit,
                ) {
                    Ok(terms) => terms,
                    Err(e) => {
                        crate::logln!("Error getting trim spawn terminations: {}", e);
                        if let Some(strategy) = circle_delete_fallback_strategy(
                            &e,
                            *trim_spawn_seg_id,
                            &current_scene_graph_delta.new_graph.objects,
                        ) {
                            match execute_trim_operations_simple(
                                strategy.clone(),
                                &current_scene_graph_delta,
                                frontend,
                                ctx,
                                version,
                                sketch_id,
                            )
                            .await
                            {
                                Ok((source_delta, scene_graph_delta)) => {
                                    invalidates_ids = invalidates_ids || scene_graph_delta.invalidates_ids;
                                    last_result = Some((source_delta, scene_graph_delta.clone()));
                                    current_scene_graph_delta = scene_graph_delta;
                                }
                                Err(exec_err) => {
                                    crate::logln!(
                                        "Error executing circle-delete fallback trim operation: {}",
                                        exec_err
                                    );
                                }
                            }

                            let old_start_index = start_index;
                            start_index = *next_index;
                            if start_index <= old_start_index {
                                start_index = old_start_index + 1;
                            }
                            continue;
                        }

                        let old_start_index = start_index;
                        start_index = *next_index;
                        if start_index <= old_start_index {
                            start_index = old_start_index + 1;
                        }
                        continue;
                    }
                };

                // Get trim strategy
                let trim_spawn_segment = current_scene_graph_delta
                    .new_graph
                    .objects
                    .iter()
                    .find(|obj| obj.id == *trim_spawn_seg_id)
                    .ok_or_else(|| format!("Trim spawn segment {} not found", trim_spawn_seg_id.0))?;

                let plan = match build_trim_plan(
                    *trim_spawn_seg_id,
                    *trim_spawn_coords,
                    trim_spawn_segment,
                    &terminations.left_side,
                    &terminations.right_side,
                    &current_scene_graph_delta.new_graph.objects,
                    default_unit,
                ) {
                    Ok(plan) => plan,
                    Err(e) => {
                        crate::logln!("Error determining trim strategy: {}", e);
                        let old_start_index = start_index;
                        start_index = *next_index;
                        if start_index <= old_start_index {
                            start_index = old_start_index + 1;
                        }
                        continue;
                    }
                };
                let strategy = lower_trim_plan(&plan);

                // Keep processing the same trim polyline segment after geometry-changing ops.
                // This allows a single stroke to trim multiple intersected segments.
                let geometry_was_modified = trim_plan_modifies_geometry(&plan);

                // Execute operations
                match execute_trim_operations_simple(
                    strategy.clone(),
                    &current_scene_graph_delta,
                    frontend,
                    ctx,
                    version,
                    sketch_id,
                )
                .await
                {
                    Ok((source_delta, scene_graph_delta)) => {
                        invalidates_ids = invalidates_ids || scene_graph_delta.invalidates_ids;
                        last_result = Some((source_delta, scene_graph_delta.clone()));
                        current_scene_graph_delta = scene_graph_delta;
                    }
                    Err(e) => {
                        crate::logln!("Error executing trim operations: {}", e);
                    }
                }

                // Move to next segment
                let old_start_index = start_index;
                start_index = *next_index;
                if start_index <= old_start_index && !geometry_was_modified {
                    start_index = old_start_index + 1;
                }
            }
        }
    }

    if iteration_count >= max_iterations {
        return Err(format!("Reached max iterations ({})", max_iterations));
    }

    let (source_delta, mut scene_graph_delta) =
        last_result.ok_or_else(|| "No trim operations were executed".to_string())?;
    // Set invalidates_ids if any operation invalidated IDs
    scene_graph_delta.invalidates_ids = invalidates_ids;
    Ok((source_delta, scene_graph_delta))
}

/// Determine the trim strategy based on the terminations found on both sides
///
/// Once we have the termination of both sides, we have all the information we need to come up with a trim strategy.
/// In the below x is the trim spawn.
///
/// ## When both sides are the end of a segment
///
/// ```
/// o - -----x - -----o
/// ```
///
/// This is the simplest and we just delete the segment. This includes when the ends of the segment have
/// coincident constraints, as the delete API cascade deletes these constraints
///
/// ## When one side is the end of the segment and the other side is either an intersection or has another segment endpoint coincident with it
///
/// ```
///        /
/// -------/---x--o
///      /
/// ```
/// OR
/// ```
/// ----o---x---o
///    /
///   /
/// ```
///
/// In both of these cases, we need to edit one end of the segment to be the location of the
/// intersection/coincident point of this other segment though:
/// - If it's an intersection, we need to create a point-segment coincident constraint
/// ```
///        /
/// -------o
///      /
/// ```
/// - If it's a coincident endpoint, we need to create a point-point coincident constraint
///
/// ```
/// ----o
///    /
///   /
/// ```
///
/// ## When both sides are either intersections or coincident endpoints
///
/// ```
///        /
/// -------/---x----o------
///      /         |
/// ```
///
/// We need to split the segment in two, which basically means editing the existing segment to be one side
/// of the split, and adding a new segment for the other side of the split. And then there is lots of
/// complications around how to migrate constraints applied to each side of the segment, to list a couple
/// of considerations:
/// - Coincident constraints on either side need to be migrated to the correct side
/// - Angle based constraints (parallel, perpendicular, horizontal, vertical), need to be applied to both sides of the trim
/// - If the segment getting split is an arc, and there's a constraints applied to an arc's center, this should be applied to both arcs after they are split.
pub(crate) fn build_trim_plan(
    trim_spawn_id: ObjectId,
    trim_spawn_coords: Coords2d,
    trim_spawn_segment: &Object,
    left_side: &TrimTermination,
    right_side: &TrimTermination,
    objects: &[Object],
    default_unit: UnitLength,
) -> Result<TrimPlan, String> {
    // Simple trim: both sides are endpoints
    if matches!(left_side, TrimTermination::SegEndPoint { .. })
        && matches!(right_side, TrimTermination::SegEndPoint { .. })
    {
        return Ok(TrimPlan::DeleteSegment {
            segment_id: trim_spawn_id,
        });
    }

    // Helper to check if a side is an intersection or coincident
    let is_intersect_or_coincident = |side: &TrimTermination| -> bool {
        matches!(
            side,
            TrimTermination::Intersection { .. }
                | TrimTermination::TrimSpawnSegmentCoincidentWithAnotherSegmentPoint { .. }
        )
    };

    let left_side_needs_tail_cut = is_intersect_or_coincident(left_side) && !is_intersect_or_coincident(right_side);
    let right_side_needs_tail_cut = is_intersect_or_coincident(right_side) && !is_intersect_or_coincident(left_side);

    // Validate trim spawn segment using native types
    let ObjectKind::Segment { segment } = &trim_spawn_segment.kind else {
        return Err("Trim spawn segment is not a segment".to_string());
    };

    let (_segment_type, ctor) = match segment {
        Segment::Line(line) => ("Line", &line.ctor),
        Segment::Arc(arc) => ("Arc", &arc.ctor),
        Segment::Circle(circle) => ("Circle", &circle.ctor),
        _ => {
            return Err("Trim spawn segment is not a Line, Arc, or Circle".to_string());
        }
    };

    // Extract units from the existing ctor's start point
    let units = match ctor {
        SegmentCtor::Line(line_ctor) => match &line_ctor.start.x {
            crate::frontend::api::Expr::Var(v) | crate::frontend::api::Expr::Number(v) => v.units,
            _ => NumericSuffix::Mm,
        },
        SegmentCtor::Arc(arc_ctor) => match &arc_ctor.start.x {
            crate::frontend::api::Expr::Var(v) | crate::frontend::api::Expr::Number(v) => v.units,
            _ => NumericSuffix::Mm,
        },
        SegmentCtor::Circle(circle_ctor) => match &circle_ctor.start.x {
            crate::frontend::api::Expr::Var(v) | crate::frontend::api::Expr::Number(v) => v.units,
            _ => NumericSuffix::Mm,
        },
        _ => NumericSuffix::Mm,
    };

    // Helper to find distance constraints that reference a segment (via owned points)
    let find_distance_constraints_for_segment = |segment_id: ObjectId| -> Vec<ObjectId> {
        let mut constraint_ids = Vec::new();
        for obj in objects {
            let ObjectKind::Constraint { constraint } = &obj.kind else {
                continue;
            };

            let Constraint::Distance(distance) = constraint else {
                continue;
            };

            // Only delete distance constraints where BOTH points are owned by this segment.
            // Distance constraints that reference points on other segments should be preserved,
            // as they define relationships between this segment and other geometry that remain valid
            // even when this segment is trimmed. Only constraints that measure distances between
            // points on the same segment (e.g., segment length constraints) should be deleted.
            let points_owned_by_segment: Vec<bool> = distance
                .point_ids()
                .map(|point_id| {
                    if let Some(point_obj) = objects.iter().find(|o| o.id == point_id)
                        && let ObjectKind::Segment { segment } = &point_obj.kind
                        && let Segment::Point(point) = segment
                        && let Some(owner_id) = point.owner
                    {
                        return owner_id == segment_id;
                    }
                    false
                })
                .collect();

            // Only include if ALL points are owned by this segment
            if points_owned_by_segment.len() == 2 && points_owned_by_segment.iter().all(|&owned| owned) {
                constraint_ids.push(obj.id);
            }
        }
        constraint_ids
    };

    // Helper to find existing point-segment coincident constraint (using native types)
    let find_existing_point_segment_coincident =
        |trim_seg_id: ObjectId, intersecting_seg_id: ObjectId| -> CoincidentData {
            // If the intersecting id itself is a point, try a fast lookup using it directly
            let lookup_by_point_id = |point_id: ObjectId| -> Option<CoincidentData> {
                for obj in objects {
                    let ObjectKind::Constraint { constraint } = &obj.kind else {
                        continue;
                    };

                    let Constraint::Coincident(coincident) = constraint else {
                        continue;
                    };

                    let involves_trim_seg = coincident.segment_ids().any(|id| id == trim_seg_id || id == point_id);
                    let involves_point = coincident.contains_segment(point_id);

                    if involves_trim_seg && involves_point {
                        return Some(CoincidentData {
                            intersecting_seg_id,
                            intersecting_endpoint_point_id: Some(point_id),
                            existing_point_segment_constraint_id: Some(obj.id),
                        });
                    }
                }
                None
            };

            // Collect trim endpoints using native types
            let trim_seg = objects.iter().find(|obj| obj.id == trim_seg_id);

            let mut trim_endpoint_ids: Vec<ObjectId> = Vec::new();
            if let Some(seg) = trim_seg
                && let ObjectKind::Segment { segment } = &seg.kind
            {
                match segment {
                    Segment::Line(line) => {
                        trim_endpoint_ids.push(line.start);
                        trim_endpoint_ids.push(line.end);
                    }
                    Segment::Arc(arc) => {
                        trim_endpoint_ids.push(arc.start);
                        trim_endpoint_ids.push(arc.end);
                    }
                    _ => {}
                }
            }

            let intersecting_obj = objects.iter().find(|obj| obj.id == intersecting_seg_id);

            if let Some(obj) = intersecting_obj
                && let ObjectKind::Segment { segment } = &obj.kind
                && let Segment::Point(_) = segment
                && let Some(found) = lookup_by_point_id(intersecting_seg_id)
            {
                return found;
            }

            // Collect intersecting endpoint IDs using native types
            let mut intersecting_endpoint_ids: Vec<ObjectId> = Vec::new();
            if let Some(obj) = intersecting_obj
                && let ObjectKind::Segment { segment } = &obj.kind
            {
                match segment {
                    Segment::Line(line) => {
                        intersecting_endpoint_ids.push(line.start);
                        intersecting_endpoint_ids.push(line.end);
                    }
                    Segment::Arc(arc) => {
                        intersecting_endpoint_ids.push(arc.start);
                        intersecting_endpoint_ids.push(arc.end);
                    }
                    _ => {}
                }
            }

            // Also include the intersecting_seg_id itself (it might already be a point id)
            intersecting_endpoint_ids.push(intersecting_seg_id);

            // Search for constraints involving trim segment (or trim endpoints) and intersecting endpoints/points
            for obj in objects {
                let ObjectKind::Constraint { constraint } = &obj.kind else {
                    continue;
                };

                let Constraint::Coincident(coincident) = constraint else {
                    continue;
                };

                let constraint_segment_ids: Vec<ObjectId> = coincident.get_segments();

                // Check if constraint involves the trim segment itself OR any trim endpoint
                let involves_trim_seg = constraint_segment_ids.contains(&trim_seg_id)
                    || trim_endpoint_ids.iter().any(|&id| constraint_segment_ids.contains(&id));

                if !involves_trim_seg {
                    continue;
                }

                // Check if any intersecting endpoint/point is involved
                if let Some(&intersecting_endpoint_id) = intersecting_endpoint_ids
                    .iter()
                    .find(|&&id| constraint_segment_ids.contains(&id))
                {
                    return CoincidentData {
                        intersecting_seg_id,
                        intersecting_endpoint_point_id: Some(intersecting_endpoint_id),
                        existing_point_segment_constraint_id: Some(obj.id),
                    };
                }
            }

            // No existing constraint found
            CoincidentData {
                intersecting_seg_id,
                intersecting_endpoint_point_id: None,
                existing_point_segment_constraint_id: None,
            }
        };

    // Helper to find point-segment coincident constraints on an endpoint (using native types)
    let find_point_segment_coincident_constraints = |endpoint_point_id: ObjectId| -> Vec<serde_json::Value> {
        let mut constraints: Vec<serde_json::Value> = Vec::new();
        for obj in objects {
            let ObjectKind::Constraint { constraint } = &obj.kind else {
                continue;
            };

            let Constraint::Coincident(coincident) = constraint else {
                continue;
            };

            // Check if this constraint involves the endpoint
            if !coincident.contains_segment(endpoint_point_id) {
                continue;
            }

            // Find the other entity
            let other_segment_id = coincident.segment_ids().find(|&seg_id| seg_id != endpoint_point_id);

            if let Some(other_id) = other_segment_id
                && let Some(other_obj) = objects.iter().find(|o| o.id == other_id)
            {
                // Check if other is a segment (not a point)
                if matches!(&other_obj.kind, ObjectKind::Segment { segment } if !matches!(segment, Segment::Point(_))) {
                    constraints.push(serde_json::json!({
                        "constraintId": obj.id.0,
                        "segmentOrPointId": other_id.0,
                    }));
                }
            }
        }
        constraints
    };

    // Helper to find point-point coincident constraints on an endpoint (using native types)
    // Returns constraint IDs
    let find_point_point_coincident_constraints = |endpoint_point_id: ObjectId| -> Vec<ObjectId> {
        let mut constraint_ids = Vec::new();
        for obj in objects {
            let ObjectKind::Constraint { constraint } = &obj.kind else {
                continue;
            };

            let Constraint::Coincident(coincident) = constraint else {
                continue;
            };

            // Check if this constraint involves the endpoint
            if !coincident.contains_segment(endpoint_point_id) {
                continue;
            }

            // Check if this is a point-point constraint (all segments are points)
            let is_point_point = coincident.segment_ids().all(|seg_id| {
                if let Some(seg_obj) = objects.iter().find(|o| o.id == seg_id) {
                    matches!(&seg_obj.kind, ObjectKind::Segment { segment } if matches!(segment, Segment::Point(_)))
                } else {
                    false
                }
            });

            if is_point_point {
                constraint_ids.push(obj.id);
            }
        }
        constraint_ids
    };

    // Helper to find point-segment coincident constraints on an endpoint (using native types)
    // Returns constraint IDs
    let find_point_segment_coincident_constraint_ids = |endpoint_point_id: ObjectId| -> Vec<ObjectId> {
        let mut constraint_ids = Vec::new();
        for obj in objects {
            let ObjectKind::Constraint { constraint } = &obj.kind else {
                continue;
            };

            let Constraint::Coincident(coincident) = constraint else {
                continue;
            };

            // Check if this constraint involves the endpoint
            if !coincident.contains_segment(endpoint_point_id) {
                continue;
            }

            // Find the other entity
            let other_segment_id = coincident.segment_ids().find(|&seg_id| seg_id != endpoint_point_id);

            if let Some(other_id) = other_segment_id
                && let Some(other_obj) = objects.iter().find(|o| o.id == other_id)
            {
                // Check if other is a segment (not a point) - this is a point-segment constraint
                if matches!(&other_obj.kind, ObjectKind::Segment { segment } if !matches!(segment, Segment::Point(_))) {
                    constraint_ids.push(obj.id);
                }
            }
        }
        constraint_ids
    };

    // Cut tail: one side intersects, one is endpoint
    if left_side_needs_tail_cut || right_side_needs_tail_cut {
        let side = if left_side_needs_tail_cut {
            left_side
        } else {
            right_side
        };

        let intersection_coords = match side {
            TrimTermination::Intersection {
                trim_termination_coords,
                ..
            }
            | TrimTermination::TrimSpawnSegmentCoincidentWithAnotherSegmentPoint {
                trim_termination_coords,
                ..
            } => *trim_termination_coords,
            TrimTermination::SegEndPoint { .. } => {
                return Err("Logic error: side should not be segEndPoint here".to_string());
            }
        };

        let endpoint_to_change = if left_side_needs_tail_cut {
            EndpointChanged::End
        } else {
            EndpointChanged::Start
        };

        let intersecting_seg_id = match side {
            TrimTermination::Intersection {
                intersecting_seg_id, ..
            }
            | TrimTermination::TrimSpawnSegmentCoincidentWithAnotherSegmentPoint {
                intersecting_seg_id, ..
            } => *intersecting_seg_id,
            TrimTermination::SegEndPoint { .. } => {
                return Err("Logic error".to_string());
            }
        };

        let mut coincident_data = if matches!(
            side,
            TrimTermination::TrimSpawnSegmentCoincidentWithAnotherSegmentPoint { .. }
        ) {
            let point_id = match side {
                TrimTermination::TrimSpawnSegmentCoincidentWithAnotherSegmentPoint {
                    other_segment_point_id, ..
                } => *other_segment_point_id,
                _ => return Err("Logic error".to_string()),
            };
            let mut data = find_existing_point_segment_coincident(trim_spawn_id, intersecting_seg_id);
            data.intersecting_endpoint_point_id = Some(point_id);
            data
        } else {
            find_existing_point_segment_coincident(trim_spawn_id, intersecting_seg_id)
        };

        // Find the endpoint that will be trimmed using native types
        let trim_seg = objects.iter().find(|obj| obj.id == trim_spawn_id);

        let endpoint_point_id = if let Some(seg) = trim_seg {
            let ObjectKind::Segment { segment } = &seg.kind else {
                return Err("Trim spawn segment is not a segment".to_string());
            };
            match segment {
                Segment::Line(line) => {
                    if endpoint_to_change == EndpointChanged::Start {
                        Some(line.start)
                    } else {
                        Some(line.end)
                    }
                }
                Segment::Arc(arc) => {
                    if endpoint_to_change == EndpointChanged::Start {
                        Some(arc.start)
                    } else {
                        Some(arc.end)
                    }
                }
                _ => None,
            }
        } else {
            None
        };

        if let (Some(endpoint_id), Some(existing_constraint_id)) =
            (endpoint_point_id, coincident_data.existing_point_segment_constraint_id)
        {
            let constraint_involves_trimmed_endpoint = objects
                .iter()
                .find(|obj| obj.id == existing_constraint_id)
                .and_then(|obj| match &obj.kind {
                    ObjectKind::Constraint {
                        constraint: Constraint::Coincident(coincident),
                    } => Some(coincident.contains_segment(endpoint_id) || coincident.contains_segment(trim_spawn_id)),
                    _ => None,
                })
                .unwrap_or(false);

            if !constraint_involves_trimmed_endpoint {
                coincident_data.existing_point_segment_constraint_id = None;
                coincident_data.intersecting_endpoint_point_id = None;
            }
        }

        // Find point-point and point-segment constraints to delete
        let coincident_end_constraint_to_delete_ids = if let Some(point_id) = endpoint_point_id {
            let mut constraint_ids = find_point_point_coincident_constraints(point_id);
            // Also find point-segment constraints where the point is the endpoint being trimmed
            constraint_ids.extend(find_point_segment_coincident_constraint_ids(point_id));
            constraint_ids
        } else {
            Vec::new()
        };

        // Edit the segment - create new ctor with updated endpoint
        let new_ctor = match ctor {
            SegmentCtor::Line(line_ctor) => {
                // Convert to segment units only; rounding happens at final conversion to output if needed.
                let new_point = crate::frontend::sketch::Point2d {
                    x: crate::frontend::api::Expr::Var(unit_to_number(intersection_coords.x, default_unit, units)),
                    y: crate::frontend::api::Expr::Var(unit_to_number(intersection_coords.y, default_unit, units)),
                };
                if endpoint_to_change == EndpointChanged::Start {
                    SegmentCtor::Line(crate::frontend::sketch::LineCtor {
                        start: new_point,
                        end: line_ctor.end.clone(),
                        construction: line_ctor.construction,
                    })
                } else {
                    SegmentCtor::Line(crate::frontend::sketch::LineCtor {
                        start: line_ctor.start.clone(),
                        end: new_point,
                        construction: line_ctor.construction,
                    })
                }
            }
            SegmentCtor::Arc(arc_ctor) => {
                // Convert to segment units only; rounding happens at final conversion to output if needed.
                let new_point = crate::frontend::sketch::Point2d {
                    x: crate::frontend::api::Expr::Var(unit_to_number(intersection_coords.x, default_unit, units)),
                    y: crate::frontend::api::Expr::Var(unit_to_number(intersection_coords.y, default_unit, units)),
                };
                if endpoint_to_change == EndpointChanged::Start {
                    SegmentCtor::Arc(crate::frontend::sketch::ArcCtor {
                        start: new_point,
                        end: arc_ctor.end.clone(),
                        center: arc_ctor.center.clone(),
                        construction: arc_ctor.construction,
                    })
                } else {
                    SegmentCtor::Arc(crate::frontend::sketch::ArcCtor {
                        start: arc_ctor.start.clone(),
                        end: new_point,
                        center: arc_ctor.center.clone(),
                        construction: arc_ctor.construction,
                    })
                }
            }
            _ => {
                return Err("Unsupported segment type for edit".to_string());
            }
        };

        // Delete old constraints
        let mut all_constraint_ids_to_delete: Vec<ObjectId> = Vec::new();
        if let Some(constraint_id) = coincident_data.existing_point_segment_constraint_id {
            all_constraint_ids_to_delete.push(constraint_id);
        }
        all_constraint_ids_to_delete.extend(coincident_end_constraint_to_delete_ids);

        // Delete distance constraints that reference this segment
        // When trimming an endpoint, the distance constraint no longer makes sense
        let distance_constraint_ids = find_distance_constraints_for_segment(trim_spawn_id);
        all_constraint_ids_to_delete.extend(distance_constraint_ids);

        return Ok(TrimPlan::TailCut {
            segment_id: trim_spawn_id,
            endpoint_changed: endpoint_to_change,
            ctor: new_ctor,
            segment_or_point_to_make_coincident_to: intersecting_seg_id,
            intersecting_endpoint_point_id: coincident_data.intersecting_endpoint_point_id,
            constraint_ids_to_delete: all_constraint_ids_to_delete,
        });
    }

    // Circle trim: both sides must terminate on intersections/coincident points.
    // A circle cannot be "split" into two circles; it is converted into a single arc.
    if matches!(segment, Segment::Circle(_)) {
        let left_side_intersects = is_intersect_or_coincident(left_side);
        let right_side_intersects = is_intersect_or_coincident(right_side);
        if !(left_side_intersects && right_side_intersects) {
            return Err(format!(
                "Unsupported circle trim termination combination: left={:?} right={:?}",
                left_side, right_side
            ));
        }

        let left_trim_coords = match left_side {
            TrimTermination::SegEndPoint {
                trim_termination_coords,
            }
            | TrimTermination::Intersection {
                trim_termination_coords,
                ..
            }
            | TrimTermination::TrimSpawnSegmentCoincidentWithAnotherSegmentPoint {
                trim_termination_coords,
                ..
            } => *trim_termination_coords,
        };
        let right_trim_coords = match right_side {
            TrimTermination::SegEndPoint {
                trim_termination_coords,
            }
            | TrimTermination::Intersection {
                trim_termination_coords,
                ..
            }
            | TrimTermination::TrimSpawnSegmentCoincidentWithAnotherSegmentPoint {
                trim_termination_coords,
                ..
            } => *trim_termination_coords,
        };

        // If both sides resolve to essentially the same trim point (e.g., tangent-only hit),
        // deleting the circle matches expected trim behavior better than creating a zero-length arc.
        let trim_points_coincident = ((left_trim_coords.x - right_trim_coords.x)
            * (left_trim_coords.x - right_trim_coords.x)
            + (left_trim_coords.y - right_trim_coords.y) * (left_trim_coords.y - right_trim_coords.y))
            .sqrt()
            <= EPSILON_POINT_ON_SEGMENT * 10.0;
        if trim_points_coincident {
            return Ok(TrimPlan::DeleteSegment {
                segment_id: trim_spawn_id,
            });
        }

        let circle_center_coords =
            get_position_coords_from_circle(trim_spawn_segment, CirclePoint::Center, objects, default_unit)
                .ok_or_else(|| {
                    format!(
                        "Could not get center coordinates for circle segment {}",
                        trim_spawn_id.0
                    )
                })?;

        // The trim removes the side containing the trim spawn. Keep the opposite side.
        let spawn_on_left_to_right = is_point_on_arc(
            trim_spawn_coords,
            circle_center_coords,
            left_trim_coords,
            right_trim_coords,
            EPSILON_POINT_ON_SEGMENT,
        );
        let (arc_start_coords, arc_end_coords, arc_start_termination, arc_end_termination) = if spawn_on_left_to_right {
            (
                right_trim_coords,
                left_trim_coords,
                Box::new(right_side.clone()),
                Box::new(left_side.clone()),
            )
        } else {
            (
                left_trim_coords,
                right_trim_coords,
                Box::new(left_side.clone()),
                Box::new(right_side.clone()),
            )
        };

        return Ok(TrimPlan::ReplaceCircleWithArc {
            circle_id: trim_spawn_id,
            arc_start_coords,
            arc_end_coords,
            arc_start_termination,
            arc_end_termination,
        });
    }

    // Split segment: both sides intersect
    let left_side_intersects = is_intersect_or_coincident(left_side);
    let right_side_intersects = is_intersect_or_coincident(right_side);

    if left_side_intersects && right_side_intersects {
        // This is the most complex case - split segment
        // Get coincident data for both sides
        let left_intersecting_seg_id = match left_side {
            TrimTermination::Intersection {
                intersecting_seg_id, ..
            }
            | TrimTermination::TrimSpawnSegmentCoincidentWithAnotherSegmentPoint {
                intersecting_seg_id, ..
            } => *intersecting_seg_id,
            TrimTermination::SegEndPoint { .. } => {
                return Err("Logic error: left side should not be segEndPoint".to_string());
            }
        };

        let right_intersecting_seg_id = match right_side {
            TrimTermination::Intersection {
                intersecting_seg_id, ..
            }
            | TrimTermination::TrimSpawnSegmentCoincidentWithAnotherSegmentPoint {
                intersecting_seg_id, ..
            } => *intersecting_seg_id,
            TrimTermination::SegEndPoint { .. } => {
                return Err("Logic error: right side should not be segEndPoint".to_string());
            }
        };

        let left_coincident_data = if matches!(
            left_side,
            TrimTermination::TrimSpawnSegmentCoincidentWithAnotherSegmentPoint { .. }
        ) {
            let point_id = match left_side {
                TrimTermination::TrimSpawnSegmentCoincidentWithAnotherSegmentPoint {
                    other_segment_point_id, ..
                } => *other_segment_point_id,
                _ => return Err("Logic error".to_string()),
            };
            let mut data = find_existing_point_segment_coincident(trim_spawn_id, left_intersecting_seg_id);
            data.intersecting_endpoint_point_id = Some(point_id);
            data
        } else {
            find_existing_point_segment_coincident(trim_spawn_id, left_intersecting_seg_id)
        };

        let right_coincident_data = if matches!(
            right_side,
            TrimTermination::TrimSpawnSegmentCoincidentWithAnotherSegmentPoint { .. }
        ) {
            let point_id = match right_side {
                TrimTermination::TrimSpawnSegmentCoincidentWithAnotherSegmentPoint {
                    other_segment_point_id, ..
                } => *other_segment_point_id,
                _ => return Err("Logic error".to_string()),
            };
            let mut data = find_existing_point_segment_coincident(trim_spawn_id, right_intersecting_seg_id);
            data.intersecting_endpoint_point_id = Some(point_id);
            data
        } else {
            find_existing_point_segment_coincident(trim_spawn_id, right_intersecting_seg_id)
        };

        // Find the endpoints of the segment being split using native types
        let (original_start_point_id, original_end_point_id) = match segment {
            Segment::Line(line) => (Some(line.start), Some(line.end)),
            Segment::Arc(arc) => (Some(arc.start), Some(arc.end)),
            _ => (None, None),
        };

        // Get the original end point coordinates before editing using native types
        let original_end_point_coords = match segment {
            Segment::Line(_) => {
                get_position_coords_for_line(trim_spawn_segment, LineEndpoint::End, objects, default_unit)
            }
            Segment::Arc(_) => get_position_coords_from_arc(trim_spawn_segment, ArcPoint::End, objects, default_unit),
            _ => None,
        };

        let Some(original_end_coords) = original_end_point_coords else {
            return Err(
                "Could not get original end point coordinates before editing - this is required for split trim"
                    .to_string(),
            );
        };

        // Calculate trim coordinates for both sides
        let left_trim_coords = match left_side {
            TrimTermination::SegEndPoint {
                trim_termination_coords,
            }
            | TrimTermination::Intersection {
                trim_termination_coords,
                ..
            }
            | TrimTermination::TrimSpawnSegmentCoincidentWithAnotherSegmentPoint {
                trim_termination_coords,
                ..
            } => *trim_termination_coords,
        };

        let right_trim_coords = match right_side {
            TrimTermination::SegEndPoint {
                trim_termination_coords,
            }
            | TrimTermination::Intersection {
                trim_termination_coords,
                ..
            }
            | TrimTermination::TrimSpawnSegmentCoincidentWithAnotherSegmentPoint {
                trim_termination_coords,
                ..
            } => *trim_termination_coords,
        };

        // Check if the split point is at the original end point
        let dist_to_original_end = ((right_trim_coords.x - original_end_coords.x)
            * (right_trim_coords.x - original_end_coords.x)
            + (right_trim_coords.y - original_end_coords.y) * (right_trim_coords.y - original_end_coords.y))
            .sqrt();
        if dist_to_original_end < EPSILON_POINT_ON_SEGMENT {
            return Err(
                "Split point is at original end point - this should be handled as cutTail, not split".to_string(),
            );
        }

        // For now, implement a simplified version that creates the split operation
        // The full constraint migration logic is very complex and can be refined during testing
        let mut constraints_to_migrate: Vec<ConstraintToMigrate> = Vec::new();
        let mut constraints_to_delete_set: IndexSet<ObjectId> = IndexSet::new();

        // Add existing point-segment constraints from terminations to delete list
        if let Some(constraint_id) = left_coincident_data.existing_point_segment_constraint_id {
            constraints_to_delete_set.insert(constraint_id);
        }
        if let Some(constraint_id) = right_coincident_data.existing_point_segment_constraint_id {
            constraints_to_delete_set.insert(constraint_id);
        }

        // Find point-point constraints on end endpoint to migrate
        if let Some(end_id) = original_end_point_id {
            let end_point_point_constraint_ids = find_point_point_coincident_constraints(end_id);
            for constraint_id in end_point_point_constraint_ids {
                // Identify the other point in the coincident constraint
                let other_point_id_opt = objects.iter().find_map(|obj| {
                    if obj.id != constraint_id {
                        return None;
                    }
                    let ObjectKind::Constraint { constraint } = &obj.kind else {
                        return None;
                    };
                    let Constraint::Coincident(coincident) = constraint else {
                        return None;
                    };
                    coincident.segment_ids().find(|&seg_id| seg_id != end_id)
                });

                if let Some(other_point_id) = other_point_id_opt {
                    constraints_to_delete_set.insert(constraint_id);
                    // Migrate as point-point constraint to the new end endpoint
                    constraints_to_migrate.push(ConstraintToMigrate {
                        constraint_id,
                        other_entity_id: other_point_id,
                        is_point_point: true,
                        attach_to_endpoint: AttachToEndpoint::End,
                    });
                }
            }
        }

        // Find point-segment constraints on end endpoint to migrate
        if let Some(end_id) = original_end_point_id {
            let end_point_segment_constraints = find_point_segment_coincident_constraints(end_id);
            for constraint_json in end_point_segment_constraints {
                if let Some(constraint_id_usize) = constraint_json
                    .get("constraintId")
                    .and_then(|v| v.as_u64())
                    .map(|id| id as usize)
                {
                    let constraint_id = ObjectId(constraint_id_usize);
                    constraints_to_delete_set.insert(constraint_id);
                    // Add to migrate list (simplified)
                    if let Some(other_id_usize) = constraint_json
                        .get("segmentOrPointId")
                        .and_then(|v| v.as_u64())
                        .map(|id| id as usize)
                    {
                        constraints_to_migrate.push(ConstraintToMigrate {
                            constraint_id,
                            other_entity_id: ObjectId(other_id_usize),
                            is_point_point: false,
                            attach_to_endpoint: AttachToEndpoint::End,
                        });
                    }
                }
            }
        }

        // Find point-segment constraints where the point is geometrically at the original end point
        // These should migrate to [newSegmentEndPointId, pointId] (point-point), not [pointId, newSegmentId] (point-segment)
        // We need to find these by checking all point-segment constraints involving the segment ID
        // and checking if the point is at the original end point
        if let Some(end_id) = original_end_point_id {
            for obj in objects {
                let ObjectKind::Constraint { constraint } = &obj.kind else {
                    continue;
                };

                let Constraint::Coincident(coincident) = constraint else {
                    continue;
                };

                // Only consider constraints that involve the segment ID but NOT the endpoint IDs directly
                // Note: We want to find constraints like [pointId, segmentId] where pointId is a point
                // that happens to be at the endpoint geometrically, but the constraint doesn't reference
                // the endpoint ID directly
                if !coincident.contains_segment(trim_spawn_id) {
                    continue;
                }
                // Skip constraints that involve endpoint IDs directly (those are handled by endpoint constraint migration)
                // But we still want to find constraints where a point (not an endpoint ID) is at the endpoint
                if let (Some(start_id), Some(end_id_val)) = (original_start_point_id, Some(end_id))
                    && coincident.segment_ids().any(|id| id == start_id || id == end_id_val)
                {
                    continue; // Skip constraints that involve endpoint IDs directly
                }

                // Find the other entity (should be a point)
                let other_id = coincident.segment_ids().find(|&seg_id| seg_id != trim_spawn_id);

                if let Some(other_id) = other_id {
                    // Check if the other entity is a point
                    if let Some(other_obj) = objects.iter().find(|o| o.id == other_id) {
                        let ObjectKind::Segment { segment: other_segment } = &other_obj.kind else {
                            continue;
                        };

                        let Segment::Point(point) = other_segment else {
                            continue;
                        };

                        // Get point coordinates in the trim internal unit
                        let point_coords = Coords2d {
                            x: number_to_unit(&point.position.x, default_unit),
                            y: number_to_unit(&point.position.y, default_unit),
                        };

                        // Check if point is at original end point (geometrically)
                        // Use post-solve coordinates for original end point if available, otherwise use the coordinates we have
                        let original_end_point_post_solve_coords = if let Some(end_id) = original_end_point_id {
                            if let Some(end_point_obj) = objects.iter().find(|o| o.id == end_id) {
                                if let ObjectKind::Segment {
                                    segment: Segment::Point(end_point),
                                } = &end_point_obj.kind
                                {
                                    Some(Coords2d {
                                        x: number_to_unit(&end_point.position.x, default_unit),
                                        y: number_to_unit(&end_point.position.y, default_unit),
                                    })
                                } else {
                                    None
                                }
                            } else {
                                None
                            }
                        } else {
                            None
                        };

                        let reference_coords = original_end_point_post_solve_coords.unwrap_or(original_end_coords);
                        let dist_to_original_end = ((point_coords.x - reference_coords.x)
                            * (point_coords.x - reference_coords.x)
                            + (point_coords.y - reference_coords.y) * (point_coords.y - reference_coords.y))
                            .sqrt();

                        if dist_to_original_end < EPSILON_POINT_ON_SEGMENT {
                            // Point is at the original end point - migrate as point-point constraint
                            // Check if there's already a point-point constraint between this point and the original end point
                            let has_point_point_constraint = find_point_point_coincident_constraints(end_id)
                                .iter()
                                .any(|&constraint_id| {
                                    if let Some(constraint_obj) = objects.iter().find(|o| o.id == constraint_id) {
                                        if let ObjectKind::Constraint {
                                            constraint: Constraint::Coincident(coincident),
                                        } = &constraint_obj.kind
                                        {
                                            coincident.contains_segment(other_id)
                                        } else {
                                            false
                                        }
                                    } else {
                                        false
                                    }
                                });

                            if !has_point_point_constraint {
                                // No existing point-point constraint - migrate as point-point constraint
                                constraints_to_migrate.push(ConstraintToMigrate {
                                    constraint_id: obj.id,
                                    other_entity_id: other_id,
                                    is_point_point: true, // Convert to point-point constraint
                                    attach_to_endpoint: AttachToEndpoint::End, // Attach to new segment's end
                                });
                            }
                            // Always delete the old point-segment constraint (whether we migrate or not)
                            constraints_to_delete_set.insert(obj.id);
                        }
                    }
                }
            }
        }

        // Find point-segment constraints on the segment body (not at endpoints)
        // These are constraints [pointId, segmentId] where the point is on the segment body
        // They should be migrated to [pointId, newSegmentId] if the point is after the split point
        let split_point = right_trim_coords; // Use right trim coords as split point
        let segment_start_coords = match segment {
            Segment::Line(_) => {
                get_position_coords_for_line(trim_spawn_segment, LineEndpoint::Start, objects, default_unit)
            }
            Segment::Arc(_) => get_position_coords_from_arc(trim_spawn_segment, ArcPoint::Start, objects, default_unit),
            _ => None,
        };
        let segment_end_coords = match segment {
            Segment::Line(_) => {
                get_position_coords_for_line(trim_spawn_segment, LineEndpoint::End, objects, default_unit)
            }
            Segment::Arc(_) => get_position_coords_from_arc(trim_spawn_segment, ArcPoint::End, objects, default_unit),
            _ => None,
        };
        let segment_center_coords = match segment {
            Segment::Line(_) => None,
            Segment::Arc(_) => {
                get_position_coords_from_arc(trim_spawn_segment, ArcPoint::Center, objects, default_unit)
            }
            _ => None,
        };

        if let (Some(start_coords), Some(end_coords)) = (segment_start_coords, segment_end_coords) {
            // Calculate split point parametric position
            let split_point_t_opt = match segment {
                Segment::Line(_) => Some(project_point_onto_segment(split_point, start_coords, end_coords)),
                Segment::Arc(_) => segment_center_coords
                    .map(|center| project_point_onto_arc(split_point, center, start_coords, end_coords)),
                _ => None,
            };

            if let Some(split_point_t) = split_point_t_opt {
                // Find all coincident constraints involving the segment
                for obj in objects {
                    let ObjectKind::Constraint { constraint } = &obj.kind else {
                        continue;
                    };

                    let Constraint::Coincident(coincident) = constraint else {
                        continue;
                    };

                    // Check if constraint involves the segment being split
                    if !coincident.contains_segment(trim_spawn_id) {
                        continue;
                    }

                    // Skip if constraint also involves endpoint IDs directly (those are handled separately)
                    if let (Some(start_id), Some(end_id)) = (original_start_point_id, original_end_point_id)
                        && coincident.segment_ids().any(|id| id == start_id || id == end_id)
                    {
                        continue;
                    }

                    // Find the other entity in the constraint
                    let other_id = coincident.segment_ids().find(|&seg_id| seg_id != trim_spawn_id);

                    if let Some(other_id) = other_id {
                        // Check if the other entity is a point
                        if let Some(other_obj) = objects.iter().find(|o| o.id == other_id) {
                            let ObjectKind::Segment { segment: other_segment } = &other_obj.kind else {
                                continue;
                            };

                            let Segment::Point(point) = other_segment else {
                                continue;
                            };

                            // Get point coordinates in the trim internal unit
                            let point_coords = Coords2d {
                                x: number_to_unit(&point.position.x, default_unit),
                                y: number_to_unit(&point.position.y, default_unit),
                            };

                            // Project the point onto the segment to get its parametric position
                            let point_t = match segment {
                                Segment::Line(_) => project_point_onto_segment(point_coords, start_coords, end_coords),
                                Segment::Arc(_) => {
                                    if let Some(center) = segment_center_coords {
                                        project_point_onto_arc(point_coords, center, start_coords, end_coords)
                                    } else {
                                        continue; // Skip this constraint if no center
                                    }
                                }
                                _ => continue, // Skip non-line/arc segments
                            };

                            // Check if point is at the original end point (skip if so - already handled above)
                            // Use post-solve coordinates for original end point if available
                            let original_end_point_post_solve_coords = if let Some(end_id) = original_end_point_id {
                                if let Some(end_point_obj) = objects.iter().find(|o| o.id == end_id) {
                                    if let ObjectKind::Segment {
                                        segment: Segment::Point(end_point),
                                    } = &end_point_obj.kind
                                    {
                                        Some(Coords2d {
                                            x: number_to_unit(&end_point.position.x, default_unit),
                                            y: number_to_unit(&end_point.position.y, default_unit),
                                        })
                                    } else {
                                        None
                                    }
                                } else {
                                    None
                                }
                            } else {
                                None
                            };

                            let reference_coords = original_end_point_post_solve_coords.unwrap_or(original_end_coords);
                            let dist_to_original_end = ((point_coords.x - reference_coords.x)
                                * (point_coords.x - reference_coords.x)
                                + (point_coords.y - reference_coords.y) * (point_coords.y - reference_coords.y))
                                .sqrt();

                            if dist_to_original_end < EPSILON_POINT_ON_SEGMENT {
                                // This should have been handled in the first loop, but if we find it here,
                                // make sure it's deleted (it might have been missed due to filtering)
                                // Also check if we should migrate it as point-point constraint
                                let has_point_point_constraint = if let Some(end_id) = original_end_point_id {
                                    find_point_point_coincident_constraints(end_id)
                                        .iter()
                                        .any(|&constraint_id| {
                                            if let Some(constraint_obj) = objects.iter().find(|o| o.id == constraint_id)
                                            {
                                                if let ObjectKind::Constraint {
                                                    constraint: Constraint::Coincident(coincident),
                                                } = &constraint_obj.kind
                                                {
                                                    coincident.contains_segment(other_id)
                                                } else {
                                                    false
                                                }
                                            } else {
                                                false
                                            }
                                        })
                                } else {
                                    false
                                };

                                if !has_point_point_constraint {
                                    // No existing point-point constraint - migrate as point-point constraint
                                    constraints_to_migrate.push(ConstraintToMigrate {
                                        constraint_id: obj.id,
                                        other_entity_id: other_id,
                                        is_point_point: true, // Convert to point-point constraint
                                        attach_to_endpoint: AttachToEndpoint::End, // Attach to new segment's end
                                    });
                                }
                                // Always delete the old point-segment constraint
                                constraints_to_delete_set.insert(obj.id);
                                continue; // Already handled as point-point constraint migration above
                            }

                            // Check if point is at the current start endpoint (skip if so - handled separately)
                            let dist_to_start = ((point_coords.x - start_coords.x) * (point_coords.x - start_coords.x)
                                + (point_coords.y - start_coords.y) * (point_coords.y - start_coords.y))
                                .sqrt();
                            let is_at_start = (point_t - 0.0).abs() < EPSILON_POINT_ON_SEGMENT
                                || dist_to_start < EPSILON_POINT_ON_SEGMENT;

                            if is_at_start {
                                continue; // Handled by endpoint constraint migration
                            }

                            // Check if point is at the split point (don't migrate - would pull halves together)
                            let dist_to_split = (point_t - split_point_t).abs();
                            if dist_to_split < EPSILON_POINT_ON_SEGMENT * 100.0 {
                                continue; // Too close to split point
                            }

                            // If point is after split point (closer to end), migrate to new segment
                            if point_t > split_point_t {
                                constraints_to_migrate.push(ConstraintToMigrate {
                                    constraint_id: obj.id,
                                    other_entity_id: other_id,
                                    is_point_point: false, // Keep as point-segment, but replace the segment
                                    attach_to_endpoint: AttachToEndpoint::Segment, // Replace old segment with new segment
                                });
                                constraints_to_delete_set.insert(obj.id);
                            }
                        }
                    }
                }
            } // End of if let Some(split_point_t)
        } // End of if let (Some(start_coords), Some(end_coords))

        // Find distance constraints that reference the segment being split
        // These need to be deleted and re-added with new endpoints after split
        // BUT: For arcs, we need to exclude distance constraints that reference the center point
        // (those will be migrated separately in the execution code)
        let distance_constraint_ids_for_split = find_distance_constraints_for_segment(trim_spawn_id);

        // Get the center point ID if this is an arc, so we can exclude center point constraints
        let arc_center_point_id: Option<ObjectId> = match segment {
            Segment::Arc(arc) => Some(arc.center),
            _ => None,
        };

        for constraint_id in distance_constraint_ids_for_split {
            // Skip if this is a center point constraint for an arc (will be migrated separately)
            if let Some(center_id) = arc_center_point_id {
                // Check if this constraint references the center point
                if let Some(constraint_obj) = objects.iter().find(|o| o.id == constraint_id)
                    && let ObjectKind::Constraint { constraint } = &constraint_obj.kind
                    && let Constraint::Distance(distance) = constraint
                    && distance.contains_point(center_id)
                {
                    // This is a center point constraint - skip deletion, it will be migrated
                    continue;
                }
            }

            constraints_to_delete_set.insert(constraint_id);
        }

        // Find angle constraints (Parallel, Perpendicular, Horizontal, Vertical) that reference the segment being split
        // Note: We don't delete these - they still apply to the original (trimmed) segment
        // We'll add new constraints for the new segment in the execution code

        // Catch-all: Find any remaining point-segment constraints involving the segment
        // that we might have missed (e.g., due to coordinate precision issues)
        // This ensures we don't leave orphaned constraints
        for obj in objects {
            let ObjectKind::Constraint { constraint } = &obj.kind else {
                continue;
            };

            let Constraint::Coincident(coincident) = constraint else {
                continue;
            };

            // Only consider constraints that involve the segment ID
            if !coincident.contains_segment(trim_spawn_id) {
                continue;
            }

            // Skip if already marked for deletion
            if constraints_to_delete_set.contains(&obj.id) {
                continue;
            }

            // Skip if this constraint involves an endpoint directly (handled separately)
            // BUT: if the other entity is a point that's at the original end point geometrically,
            // we still want to handle it here even if it's not the same point object
            // So we'll check this after we verify the other entity is a point and check its coordinates

            // Find the other entity (should be a point)
            let other_id = coincident.segment_ids().find(|&seg_id| seg_id != trim_spawn_id);

            if let Some(other_id) = other_id {
                // Check if the other entity is a point
                if let Some(other_obj) = objects.iter().find(|o| o.id == other_id) {
                    let ObjectKind::Segment { segment: other_segment } = &other_obj.kind else {
                        continue;
                    };

                    let Segment::Point(point) = other_segment else {
                        continue;
                    };

                    // Skip if this constraint involves an endpoint directly (handled separately)
                    // BUT: if the point is at the original end point geometrically, we still want to handle it
                    let _is_endpoint_constraint =
                        if let (Some(start_id), Some(end_id)) = (original_start_point_id, original_end_point_id) {
                            coincident.segment_ids().any(|id| id == start_id || id == end_id)
                        } else {
                            false
                        };

                    // Get point coordinates in the trim internal unit
                    let point_coords = Coords2d {
                        x: number_to_unit(&point.position.x, default_unit),
                        y: number_to_unit(&point.position.y, default_unit),
                    };

                    // Check if point is at original end point (with relaxed tolerance for catch-all)
                    let original_end_point_post_solve_coords = if let Some(end_id) = original_end_point_id {
                        if let Some(end_point_obj) = objects.iter().find(|o| o.id == end_id) {
                            if let ObjectKind::Segment {
                                segment: Segment::Point(end_point),
                            } = &end_point_obj.kind
                            {
                                Some(Coords2d {
                                    x: number_to_unit(&end_point.position.x, default_unit),
                                    y: number_to_unit(&end_point.position.y, default_unit),
                                })
                            } else {
                                None
                            }
                        } else {
                            None
                        }
                    } else {
                        None
                    };

                    let reference_coords = original_end_point_post_solve_coords.unwrap_or(original_end_coords);
                    let dist_to_original_end = ((point_coords.x - reference_coords.x)
                        * (point_coords.x - reference_coords.x)
                        + (point_coords.y - reference_coords.y) * (point_coords.y - reference_coords.y))
                        .sqrt();

                    // Use a slightly more relaxed tolerance for catch-all to catch edge cases
                    // Also handle endpoint constraints that might have been missed
                    let is_at_original_end = dist_to_original_end < EPSILON_POINT_ON_SEGMENT * 2.0;

                    if is_at_original_end {
                        // Point is at or very close to original end point - delete the constraint
                        // Check if we should migrate it as point-point constraint
                        let has_point_point_constraint = if let Some(end_id) = original_end_point_id {
                            find_point_point_coincident_constraints(end_id)
                                .iter()
                                .any(|&constraint_id| {
                                    if let Some(constraint_obj) = objects.iter().find(|o| o.id == constraint_id) {
                                        if let ObjectKind::Constraint {
                                            constraint: Constraint::Coincident(coincident),
                                        } = &constraint_obj.kind
                                        {
                                            coincident.contains_segment(other_id)
                                        } else {
                                            false
                                        }
                                    } else {
                                        false
                                    }
                                })
                        } else {
                            false
                        };

                        if !has_point_point_constraint {
                            // No existing point-point constraint - migrate as point-point constraint
                            constraints_to_migrate.push(ConstraintToMigrate {
                                constraint_id: obj.id,
                                other_entity_id: other_id,
                                is_point_point: true, // Convert to point-point constraint
                                attach_to_endpoint: AttachToEndpoint::End, // Attach to new segment's end
                            });
                        }
                        // Always delete the old point-segment constraint
                        constraints_to_delete_set.insert(obj.id);
                    }
                }
            }
        }

        // Create split segment operation
        let constraints_to_delete: Vec<ObjectId> = constraints_to_delete_set.iter().copied().collect();
        let plan = TrimPlan::SplitSegment {
            segment_id: trim_spawn_id,
            left_trim_coords,
            right_trim_coords,
            original_end_coords,
            left_side: Box::new(left_side.clone()),
            right_side: Box::new(right_side.clone()),
            left_side_coincident_data: CoincidentData {
                intersecting_seg_id: left_intersecting_seg_id,
                intersecting_endpoint_point_id: left_coincident_data.intersecting_endpoint_point_id,
                existing_point_segment_constraint_id: left_coincident_data.existing_point_segment_constraint_id,
            },
            right_side_coincident_data: CoincidentData {
                intersecting_seg_id: right_intersecting_seg_id,
                intersecting_endpoint_point_id: right_coincident_data.intersecting_endpoint_point_id,
                existing_point_segment_constraint_id: right_coincident_data.existing_point_segment_constraint_id,
            },
            constraints_to_migrate,
            constraints_to_delete,
        };

        return Ok(plan);
    }

    // Only three strategy cases should exist: simple trim (endpoint/endpoint),
    // tail cut (intersection+endpoint), or split (intersection+intersection).
    // If we get here, trim termination pairing was unexpected or a new variant
    // was added without updating the strategy mapping.
    Err(format!(
        "Unsupported trim termination combination: left={:?} right={:?}",
        left_side, right_side
    ))
}

/// Execute the trim operations determined by the trim strategy
///
/// Once we have a trim strategy, it then needs to be executed. This function is separate just to keep
/// one phase just collecting info (`build_trim_plan` + `lower_trim_plan`), and the other actually mutating things.
///
/// This function takes the list of trim operations from `lower_trim_plan` and executes them, which may include:
/// - Deleting segments (SimpleTrim)
/// - Editing segment endpoints (EditSegment)
/// - Adding coincident constraints (AddCoincidentConstraint)
/// - Splitting segments (SplitSegment)
/// - Migrating constraints (MigrateConstraint)
pub(crate) async fn execute_trim_operations_simple(
    strategy: Vec<TrimOperation>,
    current_scene_graph_delta: &crate::frontend::api::SceneGraphDelta,
    frontend: &mut crate::frontend::FrontendState,
    ctx: &crate::ExecutorContext,
    version: crate::frontend::api::Version,
    sketch_id: ObjectId,
) -> Result<(crate::frontend::api::SourceDelta, crate::frontend::api::SceneGraphDelta), String> {
    use crate::frontend::SketchApi;
    use crate::frontend::sketch::Constraint;
    use crate::frontend::sketch::ExistingSegmentCtor;
    use crate::frontend::sketch::SegmentCtor;

    let default_unit = frontend.default_length_unit();

    let mut op_index = 0;
    let mut last_result: Option<(crate::frontend::api::SourceDelta, crate::frontend::api::SceneGraphDelta)> = None;
    let mut invalidates_ids = false;

    while op_index < strategy.len() {
        let mut consumed_ops = 1;
        let operation_result = match &strategy[op_index] {
            TrimOperation::SimpleTrim { segment_to_trim_id } => {
                // Delete the segment
                frontend
                    .delete_objects(
                        ctx,
                        version,
                        sketch_id,
                        Vec::new(),                // constraint_ids
                        vec![*segment_to_trim_id], // segment_ids
                    )
                    .await
                    .map_err(|e| format!("Failed to delete segment: {}", e.error.message()))
            }
            TrimOperation::EditSegment {
                segment_id,
                ctor,
                endpoint_changed,
            } => {
                // Try to batch tail-cut sequence: EditSegment + AddCoincidentConstraint (+ DeleteConstraints)
                // This matches the batching logic in kcl-wasm-lib/src/api.rs
                if op_index + 1 < strategy.len() {
                    if let TrimOperation::AddCoincidentConstraint {
                        segment_id: coincident_seg_id,
                        endpoint_changed: coincident_endpoint_changed,
                        segment_or_point_to_make_coincident_to,
                        intersecting_endpoint_point_id,
                    } = &strategy[op_index + 1]
                    {
                        if segment_id == coincident_seg_id && endpoint_changed == coincident_endpoint_changed {
                            // This is a tail-cut sequence - batch it!
                            let mut delete_constraint_ids: Vec<ObjectId> = Vec::new();
                            consumed_ops = 2;

                            if op_index + 2 < strategy.len()
                                && let TrimOperation::DeleteConstraints { constraint_ids } = &strategy[op_index + 2]
                            {
                                delete_constraint_ids = constraint_ids.to_vec();
                                consumed_ops = 3;
                            }

                            // Use ctor directly
                            let segment_ctor = ctor.clone();

                            // Get endpoint point id from current scene graph (IDs stay the same after edit)
                            let edited_segment = current_scene_graph_delta
                                .new_graph
                                .objects
                                .iter()
                                .find(|obj| obj.id == *segment_id)
                                .ok_or_else(|| format!("Failed to find segment {} for tail-cut batch", segment_id.0))?;

                            let endpoint_point_id = match &edited_segment.kind {
                                crate::frontend::api::ObjectKind::Segment { segment } => match segment {
                                    crate::frontend::sketch::Segment::Line(line) => {
                                        if *endpoint_changed == EndpointChanged::Start {
                                            line.start
                                        } else {
                                            line.end
                                        }
                                    }
                                    crate::frontend::sketch::Segment::Arc(arc) => {
                                        if *endpoint_changed == EndpointChanged::Start {
                                            arc.start
                                        } else {
                                            arc.end
                                        }
                                    }
                                    _ => {
                                        return Err("Unsupported segment type for tail-cut batch".to_string());
                                    }
                                },
                                _ => {
                                    return Err("Edited object is not a segment (tail-cut batch)".to_string());
                                }
                            };

                            let coincident_segments = if let Some(point_id) = intersecting_endpoint_point_id {
                                vec![endpoint_point_id.into(), (*point_id).into()]
                            } else {
                                vec![
                                    endpoint_point_id.into(),
                                    (*segment_or_point_to_make_coincident_to).into(),
                                ]
                            };

                            let constraint = Constraint::Coincident(crate::frontend::sketch::Coincident {
                                segments: coincident_segments,
                            });

                            let segment_to_edit = ExistingSegmentCtor {
                                id: *segment_id,
                                ctor: segment_ctor,
                            };

                            // Batch the operations - this is the key optimization!
                            // Note: consumed_ops is set above (2 or 3), and we'll use it after the match
                            frontend
                                .batch_tail_cut_operations(
                                    ctx,
                                    version,
                                    sketch_id,
                                    vec![segment_to_edit],
                                    vec![constraint],
                                    delete_constraint_ids,
                                )
                                .await
                                .map_err(|e| format!("Failed to batch tail-cut operations: {}", e.error.message()))
                        } else {
                            // Not same segment/endpoint - execute EditSegment normally
                            let segment_to_edit = ExistingSegmentCtor {
                                id: *segment_id,
                                ctor: ctor.clone(),
                            };

                            frontend
                                .edit_segments(ctx, version, sketch_id, vec![segment_to_edit])
                                .await
                                .map_err(|e| format!("Failed to edit segment: {}", e.error.message()))
                        }
                    } else {
                        // Not followed by AddCoincidentConstraint - execute EditSegment normally
                        let segment_to_edit = ExistingSegmentCtor {
                            id: *segment_id,
                            ctor: ctor.clone(),
                        };

                        frontend
                            .edit_segments(ctx, version, sketch_id, vec![segment_to_edit])
                            .await
                            .map_err(|e| format!("Failed to edit segment: {}", e.error.message()))
                    }
                } else {
                    // No following op to batch with - execute EditSegment normally
                    let segment_to_edit = ExistingSegmentCtor {
                        id: *segment_id,
                        ctor: ctor.clone(),
                    };

                    frontend
                        .edit_segments(ctx, version, sketch_id, vec![segment_to_edit])
                        .await
                        .map_err(|e| format!("Failed to edit segment: {}", e.error.message()))
                }
            }
            TrimOperation::AddCoincidentConstraint {
                segment_id,
                endpoint_changed,
                segment_or_point_to_make_coincident_to,
                intersecting_endpoint_point_id,
            } => {
                // Find the edited segment to get the endpoint point ID
                let edited_segment = current_scene_graph_delta
                    .new_graph
                    .objects
                    .iter()
                    .find(|obj| obj.id == *segment_id)
                    .ok_or_else(|| format!("Failed to find edited segment {}", segment_id.0))?;

                // Get the endpoint ID after editing
                let new_segment_endpoint_point_id = match &edited_segment.kind {
                    crate::frontend::api::ObjectKind::Segment { segment } => match segment {
                        crate::frontend::sketch::Segment::Line(line) => {
                            if *endpoint_changed == EndpointChanged::Start {
                                line.start
                            } else {
                                line.end
                            }
                        }
                        crate::frontend::sketch::Segment::Arc(arc) => {
                            if *endpoint_changed == EndpointChanged::Start {
                                arc.start
                            } else {
                                arc.end
                            }
                        }
                        _ => {
                            return Err("Unsupported segment type for addCoincidentConstraint".to_string());
                        }
                    },
                    _ => {
                        return Err("Edited object is not a segment".to_string());
                    }
                };

                // Determine coincident segments
                let coincident_segments = if let Some(point_id) = intersecting_endpoint_point_id {
                    vec![new_segment_endpoint_point_id.into(), (*point_id).into()]
                } else {
                    vec![
                        new_segment_endpoint_point_id.into(),
                        (*segment_or_point_to_make_coincident_to).into(),
                    ]
                };

                let constraint = Constraint::Coincident(crate::frontend::sketch::Coincident {
                    segments: coincident_segments,
                });

                frontend
                    .add_constraint(ctx, version, sketch_id, constraint)
                    .await
                    .map_err(|e| format!("Failed to add constraint: {}", e.error.message()))
            }
            TrimOperation::DeleteConstraints { constraint_ids } => {
                // Delete constraints
                let constraint_object_ids: Vec<ObjectId> = constraint_ids.to_vec();

                frontend
                    .delete_objects(
                        ctx,
                        version,
                        sketch_id,
                        constraint_object_ids,
                        Vec::new(), // segment_ids
                    )
                    .await
                    .map_err(|e| format!("Failed to delete constraints: {}", e.error.message()))
            }
            TrimOperation::ReplaceCircleWithArc {
                circle_id,
                arc_start_coords,
                arc_end_coords,
                arc_start_termination,
                arc_end_termination,
            } => {
                // Replace a circle with a single arc and re-attach coincident constraints.
                let original_circle = current_scene_graph_delta
                    .new_graph
                    .objects
                    .iter()
                    .find(|obj| obj.id == *circle_id)
                    .ok_or_else(|| format!("Failed to find original circle {}", circle_id.0))?;

                let (original_circle_start_id, original_circle_center_id, circle_ctor) = match &original_circle.kind {
                    crate::frontend::api::ObjectKind::Segment { segment } => match segment {
                        crate::frontend::sketch::Segment::Circle(circle) => match &circle.ctor {
                            SegmentCtor::Circle(circle_ctor) => (circle.start, circle.center, circle_ctor.clone()),
                            _ => return Err("Circle does not have a Circle ctor".to_string()),
                        },
                        _ => return Err("Original segment is not a circle".to_string()),
                    },
                    _ => return Err("Original object is not a segment".to_string()),
                };

                let units = match &circle_ctor.start.x {
                    crate::frontend::api::Expr::Var(v) | crate::frontend::api::Expr::Number(v) => v.units,
                    _ => crate::pretty::NumericSuffix::Mm,
                };

                let coords_to_point_expr = |coords: Coords2d| crate::frontend::sketch::Point2d {
                    x: crate::frontend::api::Expr::Var(unit_to_number(coords.x, default_unit, units)),
                    y: crate::frontend::api::Expr::Var(unit_to_number(coords.y, default_unit, units)),
                };

                let arc_ctor = SegmentCtor::Arc(crate::frontend::sketch::ArcCtor {
                    start: coords_to_point_expr(*arc_start_coords),
                    end: coords_to_point_expr(*arc_end_coords),
                    center: circle_ctor.center.clone(),
                    construction: circle_ctor.construction,
                });

                let (_add_source_delta, add_scene_graph_delta) = frontend
                    .add_segment(ctx, version, sketch_id, arc_ctor, None)
                    .await
                    .map_err(|e| format!("Failed to add arc while replacing circle: {}", e.error.message()))?;
                invalidates_ids = invalidates_ids || add_scene_graph_delta.invalidates_ids;

                let new_arc_id = *add_scene_graph_delta
                    .new_objects
                    .iter()
                    .find(|&id| {
                        add_scene_graph_delta
                            .new_graph
                            .objects
                            .iter()
                            .find(|o| o.id == *id)
                            .is_some_and(|obj| {
                                matches!(
                                    &obj.kind,
                                    crate::frontend::api::ObjectKind::Segment { segment }
                                        if matches!(segment, crate::frontend::sketch::Segment::Arc(_))
                                )
                            })
                    })
                    .ok_or_else(|| "Failed to find newly created arc segment".to_string())?;

                let new_arc_obj = add_scene_graph_delta
                    .new_graph
                    .objects
                    .iter()
                    .find(|obj| obj.id == new_arc_id)
                    .ok_or_else(|| format!("New arc segment not found {}", new_arc_id.0))?;
                let (new_arc_start_id, new_arc_end_id, new_arc_center_id) = match &new_arc_obj.kind {
                    crate::frontend::api::ObjectKind::Segment { segment } => match segment {
                        crate::frontend::sketch::Segment::Arc(arc) => (arc.start, arc.end, arc.center),
                        _ => return Err("New segment is not an arc".to_string()),
                    },
                    _ => return Err("New arc object is not a segment".to_string()),
                };

                let constraint_segments_for =
                    |arc_endpoint_id: ObjectId,
                     term: &TrimTermination|
                     -> Result<Vec<crate::frontend::sketch::ConstraintSegment>, String> {
                        match term {
                            TrimTermination::Intersection {
                                intersecting_seg_id, ..
                            } => Ok(vec![arc_endpoint_id.into(), (*intersecting_seg_id).into()]),
                            TrimTermination::TrimSpawnSegmentCoincidentWithAnotherSegmentPoint {
                                other_segment_point_id,
                                ..
                            } => Ok(vec![arc_endpoint_id.into(), (*other_segment_point_id).into()]),
                            TrimTermination::SegEndPoint { .. } => {
                                Err("Circle replacement endpoint cannot terminate at seg endpoint".to_string())
                            }
                        }
                    };

                let start_constraint = Constraint::Coincident(crate::frontend::sketch::Coincident {
                    segments: constraint_segments_for(new_arc_start_id, arc_start_termination)?,
                });
                let (_c1_source_delta, c1_scene_graph_delta) = frontend
                    .add_constraint(ctx, version, sketch_id, start_constraint)
                    .await
                    .map_err(|e| format!("Failed to add start coincident on replaced arc: {}", e.error.message()))?;
                invalidates_ids = invalidates_ids || c1_scene_graph_delta.invalidates_ids;

                let end_constraint = Constraint::Coincident(crate::frontend::sketch::Coincident {
                    segments: constraint_segments_for(new_arc_end_id, arc_end_termination)?,
                });
                let (_c2_source_delta, c2_scene_graph_delta) = frontend
                    .add_constraint(ctx, version, sketch_id, end_constraint)
                    .await
                    .map_err(|e| format!("Failed to add end coincident on replaced arc: {}", e.error.message()))?;
                invalidates_ids = invalidates_ids || c2_scene_graph_delta.invalidates_ids;

                let mut termination_point_ids: Vec<ObjectId> = Vec::new();
                for term in [arc_start_termination, arc_end_termination] {
                    if let TrimTermination::TrimSpawnSegmentCoincidentWithAnotherSegmentPoint {
                        other_segment_point_id,
                        ..
                    } = term.as_ref()
                    {
                        termination_point_ids.push(*other_segment_point_id);
                    }
                }

                // Migrate constraints that reference the original circle segment or points.
                // This preserves authored constraints (e.g. radius/tangent/coincident) when
                // a trim converts a circle into an arc.
                let rewrite_map = std::collections::HashMap::from([
                    (*circle_id, new_arc_id),
                    (original_circle_center_id, new_arc_center_id),
                    (original_circle_start_id, new_arc_start_id),
                ]);
                let rewrite_ids: std::collections::HashSet<ObjectId> = rewrite_map.keys().copied().collect();

                let mut migrated_constraints: Vec<Constraint> = Vec::new();
                for obj in &current_scene_graph_delta.new_graph.objects {
                    let crate::frontend::api::ObjectKind::Constraint { constraint } = &obj.kind else {
                        continue;
                    };

                    match constraint {
                        Constraint::Coincident(coincident) => {
                            if !constraint_segments_reference_any(&coincident.segments, &rewrite_ids) {
                                continue;
                            }

                            // If the original coincident is circle<->point for a point that is
                            // already used as a trim termination, endpoint coincident constraints
                            // already preserve that relationship.
                            if coincident.contains_segment(*circle_id)
                                && coincident
                                    .segment_ids()
                                    .filter(|id| *id != *circle_id)
                                    .any(|id| termination_point_ids.contains(&id))
                            {
                                continue;
                            }

                            let Some(Constraint::Coincident(migrated_coincident)) =
                                rewrite_constraint_with_map(constraint, &rewrite_map)
                            else {
                                continue;
                            };

                            // Skip redundant migration when a previous point-segment circle
                            // coincident would become point-segment arc coincident at an arc
                            // endpoint that is already handled by explicit endpoint constraints.
                            let migrated_ids: Vec<ObjectId> = migrated_coincident
                                .segments
                                .iter()
                                .filter_map(|segment| match segment {
                                    crate::frontend::sketch::ConstraintSegment::Segment(id) => Some(*id),
                                    crate::frontend::sketch::ConstraintSegment::Origin(_) => None,
                                })
                                .collect();
                            if migrated_ids.contains(&new_arc_id)
                                && (migrated_ids.contains(&new_arc_start_id) || migrated_ids.contains(&new_arc_end_id))
                            {
                                continue;
                            }

                            migrated_constraints.push(Constraint::Coincident(migrated_coincident));
                        }
                        Constraint::Distance(distance) => {
                            if !constraint_segments_reference_any(&distance.points, &rewrite_ids) {
                                continue;
                            }
                            if let Some(migrated) = rewrite_constraint_with_map(constraint, &rewrite_map) {
                                migrated_constraints.push(migrated);
                            }
                        }
                        Constraint::HorizontalDistance(distance) => {
                            if !constraint_segments_reference_any(&distance.points, &rewrite_ids) {
                                continue;
                            }
                            if let Some(migrated) = rewrite_constraint_with_map(constraint, &rewrite_map) {
                                migrated_constraints.push(migrated);
                            }
                        }
                        Constraint::VerticalDistance(distance) => {
                            if !constraint_segments_reference_any(&distance.points, &rewrite_ids) {
                                continue;
                            }
                            if let Some(migrated) = rewrite_constraint_with_map(constraint, &rewrite_map) {
                                migrated_constraints.push(migrated);
                            }
                        }
                        Constraint::Radius(radius) => {
                            if radius.arc == *circle_id
                                && let Some(migrated) = rewrite_constraint_with_map(constraint, &rewrite_map)
                            {
                                migrated_constraints.push(migrated);
                            }
                        }
                        Constraint::Diameter(diameter) => {
                            if diameter.arc == *circle_id
                                && let Some(migrated) = rewrite_constraint_with_map(constraint, &rewrite_map)
                            {
                                migrated_constraints.push(migrated);
                            }
                        }
                        Constraint::EqualRadius(equal_radius) => {
                            if equal_radius.input.contains(circle_id)
                                && let Some(migrated) = rewrite_constraint_with_map(constraint, &rewrite_map)
                            {
                                migrated_constraints.push(migrated);
                            }
                        }
                        Constraint::Tangent(tangent) => {
                            if tangent.input.contains(circle_id)
                                && let Some(migrated) = rewrite_constraint_with_map(constraint, &rewrite_map)
                            {
                                migrated_constraints.push(migrated);
                            }
                        }
                        _ => {}
                    }
                }

                for constraint in migrated_constraints {
                    let (_source_delta, migrated_scene_graph_delta) = frontend
                        .add_constraint(ctx, version, sketch_id, constraint)
                        .await
                        .map_err(|e| format!("Failed to migrate circle constraint to arc: {}", e.error.message()))?;
                    invalidates_ids = invalidates_ids || migrated_scene_graph_delta.invalidates_ids;
                }

                frontend
                    .delete_objects(ctx, version, sketch_id, Vec::new(), vec![*circle_id])
                    .await
                    .map_err(|e| format!("Failed to delete circle after arc replacement: {}", e.error.message()))
            }
            TrimOperation::SplitSegment {
                segment_id,
                left_trim_coords,
                right_trim_coords,
                original_end_coords,
                left_side,
                right_side,
                constraints_to_migrate,
                constraints_to_delete,
                ..
            } => {
                // SplitSegment is a complex multi-step operation
                // Ported from kcl-wasm-lib/src/api.rs execute_trim function

                // Step 1: Find and validate original segment
                let original_segment = current_scene_graph_delta
                    .new_graph
                    .objects
                    .iter()
                    .find(|obj| obj.id == *segment_id)
                    .ok_or_else(|| format!("Failed to find original segment {}", segment_id.0))?;

                // Extract point IDs from original segment
                let (original_segment_start_point_id, original_segment_end_point_id, original_segment_center_point_id) =
                    match &original_segment.kind {
                        crate::frontend::api::ObjectKind::Segment { segment } => match segment {
                            crate::frontend::sketch::Segment::Line(line) => (Some(line.start), Some(line.end), None),
                            crate::frontend::sketch::Segment::Arc(arc) => {
                                (Some(arc.start), Some(arc.end), Some(arc.center))
                            }
                            _ => (None, None, None),
                        },
                        _ => (None, None, None),
                    };

                // Store center point constraints to migrate BEFORE edit_segments modifies the scene graph
                let mut center_point_constraints_to_migrate: Vec<(Constraint, ObjectId)> = Vec::new();
                if let Some(original_center_id) = original_segment_center_point_id {
                    for obj in &current_scene_graph_delta.new_graph.objects {
                        let crate::frontend::api::ObjectKind::Constraint { constraint } = &obj.kind else {
                            continue;
                        };

                        // Find coincident constraints that reference the original center point
                        if let Constraint::Coincident(coincident) = constraint
                            && coincident.contains_segment(original_center_id)
                        {
                            center_point_constraints_to_migrate.push((constraint.clone(), original_center_id));
                        }

                        // Find distance constraints that reference the original center point
                        if let Constraint::Distance(distance) = constraint
                            && distance.contains_point(original_center_id)
                        {
                            center_point_constraints_to_migrate.push((constraint.clone(), original_center_id));
                        }
                    }
                }

                // Extract segment and ctor
                let (_segment_type, original_ctor) = match &original_segment.kind {
                    crate::frontend::api::ObjectKind::Segment { segment } => match segment {
                        crate::frontend::sketch::Segment::Line(line) => ("Line", line.ctor.clone()),
                        crate::frontend::sketch::Segment::Arc(arc) => ("Arc", arc.ctor.clone()),
                        _ => {
                            return Err("Original segment is not a Line or Arc".to_string());
                        }
                    },
                    _ => {
                        return Err("Original object is not a segment".to_string());
                    }
                };

                // Extract units from the existing ctor
                let units = match &original_ctor {
                    SegmentCtor::Line(line_ctor) => match &line_ctor.start.x {
                        crate::frontend::api::Expr::Var(v) | crate::frontend::api::Expr::Number(v) => v.units,
                        _ => crate::pretty::NumericSuffix::Mm,
                    },
                    SegmentCtor::Arc(arc_ctor) => match &arc_ctor.start.x {
                        crate::frontend::api::Expr::Var(v) | crate::frontend::api::Expr::Number(v) => v.units,
                        _ => crate::pretty::NumericSuffix::Mm,
                    },
                    _ => crate::pretty::NumericSuffix::Mm,
                };

                // Helper to convert Coords2d (current trim unit) to Point2d in segment units.
                // No rounding here; rounding happens at final conversion to output if needed.
                let coords_to_point =
                    |coords: Coords2d| -> crate::frontend::sketch::Point2d<crate::frontend::api::Number> {
                        crate::frontend::sketch::Point2d {
                            x: unit_to_number(coords.x, default_unit, units),
                            y: unit_to_number(coords.y, default_unit, units),
                        }
                    };

                // Convert Point2d<Number> to Point2d<Expr> for SegmentCtor
                let point_to_expr = |point: crate::frontend::sketch::Point2d<crate::frontend::api::Number>| -> crate::frontend::sketch::Point2d<crate::frontend::api::Expr> {
                    crate::frontend::sketch::Point2d {
                        x: crate::frontend::api::Expr::Var(point.x),
                        y: crate::frontend::api::Expr::Var(point.y),
                    }
                };

                // Step 2: Create new segment (right side) first to get its IDs
                let new_segment_ctor = match &original_ctor {
                    SegmentCtor::Line(line_ctor) => SegmentCtor::Line(crate::frontend::sketch::LineCtor {
                        start: point_to_expr(coords_to_point(*right_trim_coords)),
                        end: point_to_expr(coords_to_point(*original_end_coords)),
                        construction: line_ctor.construction,
                    }),
                    SegmentCtor::Arc(arc_ctor) => SegmentCtor::Arc(crate::frontend::sketch::ArcCtor {
                        start: point_to_expr(coords_to_point(*right_trim_coords)),
                        end: point_to_expr(coords_to_point(*original_end_coords)),
                        center: arc_ctor.center.clone(),
                        construction: arc_ctor.construction,
                    }),
                    _ => {
                        return Err("Unsupported segment type for new segment".to_string());
                    }
                };

                let (_add_source_delta, add_scene_graph_delta) = frontend
                    .add_segment(ctx, version, sketch_id, new_segment_ctor, None)
                    .await
                    .map_err(|e| format!("Failed to add new segment: {}", e.error.message()))?;

                // Step 3: Find the newly created segment
                let new_segment_id = *add_scene_graph_delta
                    .new_objects
                    .iter()
                    .find(|&id| {
                        if let Some(obj) = add_scene_graph_delta.new_graph.objects.iter().find(|o| o.id == *id) {
                            matches!(
                                &obj.kind,
                                crate::frontend::api::ObjectKind::Segment { segment }
                                    if matches!(segment, crate::frontend::sketch::Segment::Line(_) | crate::frontend::sketch::Segment::Arc(_))
                            )
                        } else {
                            false
                        }
                    })
                    .ok_or_else(|| "Failed to find newly created segment".to_string())?;

                let new_segment = add_scene_graph_delta
                    .new_graph
                    .objects
                    .iter()
                    .find(|o| o.id == new_segment_id)
                    .ok_or_else(|| format!("New segment not found with id {}", new_segment_id.0))?;

                // Extract endpoint IDs
                let (new_segment_start_point_id, new_segment_end_point_id, new_segment_center_point_id) =
                    match &new_segment.kind {
                        crate::frontend::api::ObjectKind::Segment { segment } => match segment {
                            crate::frontend::sketch::Segment::Line(line) => (line.start, line.end, None),
                            crate::frontend::sketch::Segment::Arc(arc) => (arc.start, arc.end, Some(arc.center)),
                            _ => {
                                return Err("New segment is not a Line or Arc".to_string());
                            }
                        },
                        _ => {
                            return Err("New segment is not a segment".to_string());
                        }
                    };

                // Step 4: Edit the original segment (trim left side)
                let edited_ctor = match &original_ctor {
                    SegmentCtor::Line(line_ctor) => SegmentCtor::Line(crate::frontend::sketch::LineCtor {
                        start: line_ctor.start.clone(),
                        end: point_to_expr(coords_to_point(*left_trim_coords)),
                        construction: line_ctor.construction,
                    }),
                    SegmentCtor::Arc(arc_ctor) => SegmentCtor::Arc(crate::frontend::sketch::ArcCtor {
                        start: arc_ctor.start.clone(),
                        end: point_to_expr(coords_to_point(*left_trim_coords)),
                        center: arc_ctor.center.clone(),
                        construction: arc_ctor.construction,
                    }),
                    _ => {
                        return Err("Unsupported segment type for split".to_string());
                    }
                };

                let (_edit_source_delta, edit_scene_graph_delta) = frontend
                    .edit_segments(
                        ctx,
                        version,
                        sketch_id,
                        vec![ExistingSegmentCtor {
                            id: *segment_id,
                            ctor: edited_ctor,
                        }],
                    )
                    .await
                    .map_err(|e| format!("Failed to edit segment: {}", e.error.message()))?;
                // Track invalidates_ids from edit_segments call
                invalidates_ids = invalidates_ids || edit_scene_graph_delta.invalidates_ids;

                // Get left endpoint ID from edited segment
                let edited_segment = edit_scene_graph_delta
                    .new_graph
                    .objects
                    .iter()
                    .find(|obj| obj.id == *segment_id)
                    .ok_or_else(|| format!("Failed to find edited segment {}", segment_id.0))?;

                let left_side_endpoint_point_id = match &edited_segment.kind {
                    crate::frontend::api::ObjectKind::Segment { segment } => match segment {
                        crate::frontend::sketch::Segment::Line(line) => line.end,
                        crate::frontend::sketch::Segment::Arc(arc) => arc.end,
                        _ => {
                            return Err("Edited segment is not a Line or Arc".to_string());
                        }
                    },
                    _ => {
                        return Err("Edited segment is not a segment".to_string());
                    }
                };

                // Step 5: Prepare constraints for batch
                let mut batch_constraints = Vec::new();

                // Left constraint
                let left_intersecting_seg_id = match &**left_side {
                    TrimTermination::Intersection {
                        intersecting_seg_id, ..
                    }
                    | TrimTermination::TrimSpawnSegmentCoincidentWithAnotherSegmentPoint {
                        intersecting_seg_id, ..
                    } => *intersecting_seg_id,
                    _ => {
                        return Err("Left side is not an intersection or coincident".to_string());
                    }
                };
                let left_coincident_segments = match &**left_side {
                    TrimTermination::TrimSpawnSegmentCoincidentWithAnotherSegmentPoint {
                        other_segment_point_id,
                        ..
                    } => {
                        vec![left_side_endpoint_point_id.into(), (*other_segment_point_id).into()]
                    }
                    _ => {
                        vec![left_side_endpoint_point_id.into(), left_intersecting_seg_id.into()]
                    }
                };
                batch_constraints.push(Constraint::Coincident(crate::frontend::sketch::Coincident {
                    segments: left_coincident_segments,
                }));

                // Right constraint - need to check if intersection is at endpoint
                let right_intersecting_seg_id = match &**right_side {
                    TrimTermination::Intersection {
                        intersecting_seg_id, ..
                    }
                    | TrimTermination::TrimSpawnSegmentCoincidentWithAnotherSegmentPoint {
                        intersecting_seg_id, ..
                    } => *intersecting_seg_id,
                    _ => {
                        return Err("Right side is not an intersection or coincident".to_string());
                    }
                };

                let mut intersection_point_id: Option<ObjectId> = None;
                if matches!(&**right_side, TrimTermination::Intersection { .. }) {
                    let intersecting_seg = edit_scene_graph_delta
                        .new_graph
                        .objects
                        .iter()
                        .find(|obj| obj.id == right_intersecting_seg_id);

                    if let Some(seg) = intersecting_seg {
                        let endpoint_epsilon = 1e-3; // In current trim unit
                        let right_trim_coords_value = *right_trim_coords;

                        if let crate::frontend::api::ObjectKind::Segment { segment } = &seg.kind {
                            match segment {
                                crate::frontend::sketch::Segment::Line(_) => {
                                    if let (Some(start_coords), Some(end_coords)) = (
                                        crate::frontend::trim::get_position_coords_for_line(
                                            seg,
                                            crate::frontend::trim::LineEndpoint::Start,
                                            &edit_scene_graph_delta.new_graph.objects,
                                            default_unit,
                                        ),
                                        crate::frontend::trim::get_position_coords_for_line(
                                            seg,
                                            crate::frontend::trim::LineEndpoint::End,
                                            &edit_scene_graph_delta.new_graph.objects,
                                            default_unit,
                                        ),
                                    ) {
                                        let dist_to_start = ((right_trim_coords_value.x - start_coords.x)
                                            * (right_trim_coords_value.x - start_coords.x)
                                            + (right_trim_coords_value.y - start_coords.y)
                                                * (right_trim_coords_value.y - start_coords.y))
                                            .sqrt();
                                        if dist_to_start < endpoint_epsilon {
                                            if let crate::frontend::sketch::Segment::Line(line) = segment {
                                                intersection_point_id = Some(line.start);
                                            }
                                        } else {
                                            let dist_to_end = ((right_trim_coords_value.x - end_coords.x)
                                                * (right_trim_coords_value.x - end_coords.x)
                                                + (right_trim_coords_value.y - end_coords.y)
                                                    * (right_trim_coords_value.y - end_coords.y))
                                                .sqrt();
                                            if dist_to_end < endpoint_epsilon
                                                && let crate::frontend::sketch::Segment::Line(line) = segment
                                            {
                                                intersection_point_id = Some(line.end);
                                            }
                                        }
                                    }
                                }
                                crate::frontend::sketch::Segment::Arc(_) => {
                                    if let (Some(start_coords), Some(end_coords)) = (
                                        crate::frontend::trim::get_position_coords_from_arc(
                                            seg,
                                            crate::frontend::trim::ArcPoint::Start,
                                            &edit_scene_graph_delta.new_graph.objects,
                                            default_unit,
                                        ),
                                        crate::frontend::trim::get_position_coords_from_arc(
                                            seg,
                                            crate::frontend::trim::ArcPoint::End,
                                            &edit_scene_graph_delta.new_graph.objects,
                                            default_unit,
                                        ),
                                    ) {
                                        let dist_to_start = ((right_trim_coords_value.x - start_coords.x)
                                            * (right_trim_coords_value.x - start_coords.x)
                                            + (right_trim_coords_value.y - start_coords.y)
                                                * (right_trim_coords_value.y - start_coords.y))
                                            .sqrt();
                                        if dist_to_start < endpoint_epsilon {
                                            if let crate::frontend::sketch::Segment::Arc(arc) = segment {
                                                intersection_point_id = Some(arc.start);
                                            }
                                        } else {
                                            let dist_to_end = ((right_trim_coords_value.x - end_coords.x)
                                                * (right_trim_coords_value.x - end_coords.x)
                                                + (right_trim_coords_value.y - end_coords.y)
                                                    * (right_trim_coords_value.y - end_coords.y))
                                                .sqrt();
                                            if dist_to_end < endpoint_epsilon
                                                && let crate::frontend::sketch::Segment::Arc(arc) = segment
                                            {
                                                intersection_point_id = Some(arc.end);
                                            }
                                        }
                                    }
                                }
                                _ => {}
                            }
                        }
                    }
                }

                let right_coincident_segments = if let Some(point_id) = intersection_point_id {
                    vec![new_segment_start_point_id.into(), point_id.into()]
                } else if let TrimTermination::TrimSpawnSegmentCoincidentWithAnotherSegmentPoint {
                    other_segment_point_id,
                    ..
                } = &**right_side
                {
                    vec![new_segment_start_point_id.into(), (*other_segment_point_id).into()]
                } else {
                    vec![new_segment_start_point_id.into(), right_intersecting_seg_id.into()]
                };
                batch_constraints.push(Constraint::Coincident(crate::frontend::sketch::Coincident {
                    segments: right_coincident_segments,
                }));

                // Migrate constraints
                let mut points_constrained_to_new_segment_start = std::collections::HashSet::new();
                let mut points_constrained_to_new_segment_end = std::collections::HashSet::new();

                if let TrimTermination::TrimSpawnSegmentCoincidentWithAnotherSegmentPoint {
                    other_segment_point_id,
                    ..
                } = &**right_side
                {
                    points_constrained_to_new_segment_start.insert(other_segment_point_id);
                }

                for constraint_to_migrate in constraints_to_migrate.iter() {
                    if constraint_to_migrate.attach_to_endpoint == AttachToEndpoint::End
                        && constraint_to_migrate.is_point_point
                    {
                        points_constrained_to_new_segment_end.insert(constraint_to_migrate.other_entity_id);
                    }
                }

                for constraint_to_migrate in constraints_to_migrate.iter() {
                    // Skip migrating point-segment constraints if the point is already constrained
                    if constraint_to_migrate.attach_to_endpoint == AttachToEndpoint::Segment
                        && (points_constrained_to_new_segment_start.contains(&constraint_to_migrate.other_entity_id)
                            || points_constrained_to_new_segment_end.contains(&constraint_to_migrate.other_entity_id))
                    {
                        continue; // Skip redundant constraint
                    }

                    let constraint_segments = if constraint_to_migrate.attach_to_endpoint == AttachToEndpoint::Segment {
                        vec![constraint_to_migrate.other_entity_id.into(), new_segment_id.into()]
                    } else {
                        let target_endpoint_id = if constraint_to_migrate.attach_to_endpoint == AttachToEndpoint::Start
                        {
                            new_segment_start_point_id
                        } else {
                            new_segment_end_point_id
                        };
                        vec![target_endpoint_id.into(), constraint_to_migrate.other_entity_id.into()]
                    };
                    batch_constraints.push(Constraint::Coincident(crate::frontend::sketch::Coincident {
                        segments: constraint_segments,
                    }));
                }

                // Find distance constraints that reference both endpoints of the original segment
                let mut distance_constraints_to_re_add: Vec<(
                    crate::frontend::api::Number,
                    crate::frontend::sketch::ConstraintSource,
                )> = Vec::new();
                if let (Some(original_start_id), Some(original_end_id)) =
                    (original_segment_start_point_id, original_segment_end_point_id)
                {
                    for obj in &edit_scene_graph_delta.new_graph.objects {
                        let crate::frontend::api::ObjectKind::Constraint { constraint } = &obj.kind else {
                            continue;
                        };

                        let Constraint::Distance(distance) = constraint else {
                            continue;
                        };

                        let references_start = distance.contains_point(original_start_id);
                        let references_end = distance.contains_point(original_end_id);

                        if references_start && references_end {
                            distance_constraints_to_re_add.push((distance.distance, distance.source.clone()));
                        }
                    }
                }

                // Re-add distance constraints
                if let Some(original_start_id) = original_segment_start_point_id {
                    for (distance_value, source) in distance_constraints_to_re_add {
                        batch_constraints.push(Constraint::Distance(crate::frontend::sketch::Distance {
                            points: vec![original_start_id.into(), new_segment_end_point_id.into()],
                            distance: distance_value,
                            source,
                        }));
                    }
                }

                // Migrate center point constraints for arcs
                if let Some(new_center_id) = new_segment_center_point_id {
                    for (constraint, original_center_id) in center_point_constraints_to_migrate {
                        let center_rewrite_map = std::collections::HashMap::from([(original_center_id, new_center_id)]);
                        if let Some(rewritten) = rewrite_constraint_with_map(&constraint, &center_rewrite_map)
                            && matches!(rewritten, Constraint::Coincident(_) | Constraint::Distance(_))
                        {
                            batch_constraints.push(rewritten);
                        }
                    }
                }

                // Re-add angle constraints (Parallel, Perpendicular, Horizontal, Vertical)
                let angle_rewrite_map = std::collections::HashMap::from([(*segment_id, new_segment_id)]);
                for obj in &edit_scene_graph_delta.new_graph.objects {
                    let crate::frontend::api::ObjectKind::Constraint { constraint } = &obj.kind else {
                        continue;
                    };

                    let should_migrate = match constraint {
                        Constraint::Parallel(parallel) => parallel.lines.contains(segment_id),
                        Constraint::Perpendicular(perpendicular) => perpendicular.lines.contains(segment_id),
                        Constraint::Horizontal(horizontal) => horizontal.line == *segment_id,
                        Constraint::Vertical(vertical) => vertical.line == *segment_id,
                        _ => false,
                    };

                    if should_migrate
                        && let Some(migrated_constraint) = rewrite_constraint_with_map(constraint, &angle_rewrite_map)
                        && matches!(
                            migrated_constraint,
                            Constraint::Parallel(_)
                                | Constraint::Perpendicular(_)
                                | Constraint::Horizontal(_)
                                | Constraint::Vertical(_)
                        )
                    {
                        batch_constraints.push(migrated_constraint);
                    }
                }

                // Step 6: Batch all remaining operations
                let constraint_object_ids: Vec<ObjectId> = constraints_to_delete.to_vec();

                let batch_result = frontend
                    .batch_split_segment_operations(
                        ctx,
                        version,
                        sketch_id,
                        Vec::new(), // edit_segments already done
                        batch_constraints,
                        constraint_object_ids,
                        crate::frontend::sketch::NewSegmentInfo {
                            segment_id: new_segment_id,
                            start_point_id: new_segment_start_point_id,
                            end_point_id: new_segment_end_point_id,
                            center_point_id: new_segment_center_point_id,
                        },
                    )
                    .await
                    .map_err(|e| format!("Failed to batch split segment operations: {}", e.error.message()));
                // Track invalidates_ids from batch_split_segment_operations call
                if let Ok((_, ref batch_delta)) = batch_result {
                    invalidates_ids = invalidates_ids || batch_delta.invalidates_ids;
                }
                batch_result
            }
        };

        match operation_result {
            Ok((source_delta, scene_graph_delta)) => {
                // Track invalidates_ids from each operation result
                invalidates_ids = invalidates_ids || scene_graph_delta.invalidates_ids;
                last_result = Some((source_delta, scene_graph_delta.clone()));
            }
            Err(e) => {
                crate::logln!("Error executing trim operation {}: {}", op_index, e);
                // Continue to next operation
            }
        }

        op_index += consumed_ops;
    }

    let (source_delta, mut scene_graph_delta) =
        last_result.ok_or_else(|| "No operations were executed successfully".to_string())?;
    // Set invalidates_ids if any operation invalidated IDs
    scene_graph_delta.invalidates_ids = invalidates_ids;
    Ok((source_delta, scene_graph_delta))
}