togo 0.7.2

A library for 2D geometry, providing geometric algorithms for intersection/distance between circular arcs/line segments.
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
#![allow(dead_code)]

use robust::{Coord, orient2d};

use crate::constants::{DIVISION_EPSILON, GEOMETRIC_EPSILON};
use crate::prelude::*;

use std::{fmt::Display, sync::atomic::AtomicUsize};

/// A Arcline is a sequence of connected Arc-s forming a path.
pub type Arcline = Vec<Arc>;

static ID_COUNT: AtomicUsize = AtomicUsize::new(0);

/// Tolerance for detecting collapsed/degenerate arcs (nearly line segments).
/// Uses GEOMETRIC_EPSILON for consistency with other geometric predicates.
const ARC_COLLAPSED_TOLERANCE: f64 = GEOMETRIC_EPSILON; // 1e-10

/// An arc segment (CCW) defined by start point, end point, center, and radius.
///
/// Arcs are fundamental geometric primitives.
/// <div class="warning">NOTE: Arcs are always CCW (counter-clockwise) in this library.</div>
///
/// # Fields
///
/// * `a` - Start point of the arc
/// * `b` - End point of the arc  
/// * `c` - Center point of the arc
/// * `r` - Radius of the arc (`f64::INFINITY` indicates a line segment)
/// * `id` - Non-unique identifier used for debugging and tracking segments
///
/// # Examples
///
/// ```
/// use togo::prelude::*;
///
/// let start = point(0.0, 1.0);
/// let end = point(1.0, 0.0);
/// let center = point(0.0, 0.0);
/// let radius = 1.0;
///
/// let arc = arc(start, end, center, radius);
/// ```
///
// #00001
#[derive(Debug, Copy, Clone)]
pub struct Arc {
    /// Start point of the arc.
    pub a: Point,
    /// End point of the arc.
    pub b: Point,
    /// Center point of the arc.
    pub c: Point,
    /// Radius of the arc.
    pub r: f64,
    /// non-unique id, used for debugging and
    /// checking parts coming from the same segment
    pub id: usize,
}

// Implemented because id is different in tests
impl PartialEq for Arc {
    fn eq(&self, other: &Self) -> bool {
        self.a == other.a && self.b == other.b && self.c == other.c && self.r == other.r
        //??? self.r == other.r
    }
}

impl Display for Arc {
    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
        write!(f, "[{}, {}, {}, {:.20}]", self.a, self.b, self.c, self.r)
    }
}

impl Arc {
    /// Creates a new arc with the specified parameters.
    ///
    /// # Arguments
    ///
    /// * `a` - Start point of the arc
    /// * `b` - End point of the arc
    /// * `c` - Center point of the arc
    /// * `r` - Radius of the arc (use `arcseg()` for segments)
    ///
    /// # Returns
    ///
    /// A new Arc instance with a unique internal ID
    ///
    /// <div class="warning">Arcs are always CCW (counter-clockwise) in this library!</div>
    ///
    /// # Examples
    ///
    /// ```
    /// use togo::prelude::*;
    ///
    /// // Create a quarter circle arc
    /// let arc = Arc::new(
    ///     point(1.0, 0.0),  // start
    ///     point(0.0, 1.0),  // end
    ///     point(0.0, 0.0),  // center
    ///     1.0               // radius
    /// );
    ///
    /// // Create a line segment
    /// let line = Arc::new(
    ///     point(0.0, 0.0),     // start
    ///     point(1.0, 1.0),     // end
    ///     point(0.0, 0.0),     // center (unused for lines)
    ///     f64::INFINITY        // infinite radius indicates line
    /// );
    /// ```
    #[inline]
    pub fn new(a: Point, b: Point, c: Point, r: f64) -> Self {
        let id = ID_COUNT.fetch_add(1, std::sync::atomic::Ordering::Relaxed);
        Arc { a, b, c, r, id }
    }

    /// Set the id of the arc.
    #[inline]
    pub fn id(&mut self, id: usize) {
        self.id = id;
    }

    /// Returns true if this arc represents a circular arc (finite radius).
    ///
    /// # Returns
    ///
    /// True if the radius is finite, false if it represents a line segment
    ///
    /// # Examples
    ///
    /// ```
    /// use togo::prelude::*;
    /// let arc = arc(point(0.0, 0.0), point(1.0, 0.0), point(0.5, 0.5), 1.0);
    /// assert!(arc.is_arc()); // Has finite radius
    ///
    /// let line = arcseg(point(0.0, 0.0), point(1.0, 0.0));
    /// assert!(!line.is_arc()); // Has infinite radius (line segment)
    /// ```
    #[inline]
    #[must_use]
    pub fn is_arc(&self) -> bool {
        self.r != f64::INFINITY
    }

    /// Returns true if this arc represents a line segment (infinite radius).
    ///
    /// # Returns
    ///
    /// True if the radius is infinite, false if it represents a circular arc
    ///
    /// # Examples
    ///
    /// ```
    /// use togo::prelude::*;
    /// let arc = arc(point(0.0, 0.0), point(1.0, 0.0), point(0.5, 0.5), 1.0);
    /// assert!(!arc.is_seg()); // Has finite radius
    ///
    /// let line = arcseg(point(0.0, 0.0), point(1.0, 0.0));
    /// assert!(line.is_seg()); // Has infinite radius (line segment)
    /// ```
    #[inline]
    #[must_use]
    pub fn is_seg(&self) -> bool {
        self.r == f64::INFINITY
    }

    /// Translates this arc by the given vector.
    ///
    /// # Arguments
    ///
    /// * `point` - The translation vector to apply
    ///
    /// # Examples
    ///
    /// ```
    /// use togo::prelude::*;
    ///
    /// let mut my_arc = arc(
    ///     point(0.0, 0.0),
    ///     point(1.0, 0.0),
    ///     point(0.5, 0.0),
    ///     1.0
    /// );
    /// my_arc.translate(point(10.0, 5.0));
    /// // All points are now shifted by (10, 5)
    /// ```
    #[inline]
    pub fn translate(&mut self, point: Point) {
        self.a = self.a + point;
        self.b = self.b + point;
        self.c = self.c + point;
    }

    /// Scales this arc by the given factor.
    #[inline]
    pub fn scale(&mut self, factor: f64) {
        self.a = self.a * factor;
        self.b = self.b * factor;
        self.c = self.c * factor;
        self.r *= factor;
    }

    /// Returns a reversed copy of this Arc.
    ///
    /// The reversed arc (all arcs are CCW) is not the same as original arc, but complement of the circle.
    ///
    /// # Returns
    ///
    /// A new Arc with start and end points swapped
    ///
    /// # Examples
    ///
    /// ```
    /// use togo::prelude::*;
    /// let arc = arc(point(0.0, 0.0), point(1.0, 0.0), point(0.5, 0.5), 1.0);
    /// let reversed = arc.reverse();
    /// ```
    #[inline]
    #[must_use]
    pub fn reverse(&self) -> Arc {
        arc(self.b, self.a, self.c, self.r)
    }

    #[inline]
    /// Checks if the arc contains the given point,
    /// where the point is a result of intersection.
    /// <div class="warning">This does not work for points not on the circle!</div>
    ///
    /// # Arguments
    ///
    /// * `p` - The point to check
    ///
    /// # Returns
    /// True if the point is contained within the arc, false otherwise
    ///
    /// # Examples
    ///
    /// ```
    /// use togo::prelude::*;
    /// let arc0 = arc(point(0.0, 0.0), point(1.0, 1.0), point(0.5, 0.5), 1.0);
    /// assert!(arc0.contains(point(1.0, 0.0))); // Point on the arc
    /// assert!(!arc0.contains(point(0.0, 1.0))); // Point outside the arc
    /// ```
    #[must_use]
    pub fn contains(&self, p: Point) -> bool {
        let pa = Coord {
            x: self.a.x,
            y: self.a.y,
        };
        let pb = Coord {
            x: self.b.x,
            y: self.b.y,
        };
        let pp = Coord { x: p.x, y: p.y };
        let perp = orient2d(pa, pp, pb);
        //let perp = Arc::simple_orient2d(pa, pp, pb);
        perp >= 0f64
    }

    // fn simple_orient2d(p: Coord<f64>, q: Coord<f64>, r: Coord<f64>) -> f64 {
    //     (q.x - p.x) * (r.y - q.y) - (q.y - p.y) * (r.x - q.x)
    // }
}

/// Creates a new Arc with the given parameters.
///
/// This is a convenience function equivalent to `Arc::new(a, b, c, r)`.
///
/// # Arguments
///
/// * `a` - The start point of the arc
/// * `b` - The end point of the arc  
/// * `c` - The center point of the arc
/// * `r` - The radius of the arc
///
/// # Returns
///
/// A new Arc instance
///
/// # Examples
///
/// ```
/// use togo::prelude::*;
/// let arc = arc(point(0.0, 0.0), point(1.0, 0.0), point(0.5, 0.0), 1.0);
/// assert_eq!(arc.a, point(0.0, 0.0));
/// assert_eq!(arc.b, point(1.0, 0.0));
/// assert_eq!(arc.r, 1.0);
/// ```
#[inline]
#[must_use]
pub fn arc(a: Point, b: Point, c: Point, r: f64) -> Arc {
    Arc::new(a, b, c, r)
}

/// Creates a line segment represented as an Arc with infinite radius.
///
/// This function creates an Arc that represents a straight line segment
/// between two points. The arc uses infinite radius to distinguish it
/// from curved arcs.
///
/// # Arguments
///
/// * `a` - The start point of the line segment
/// * `b` - The end point of the line segment
///
/// # Returns
///
/// An Arc representing a line segment with infinite radius
///
/// # Examples
///
/// ```
/// use togo::prelude::*;
/// let line = arcseg(point(0.0, 0.0), point(1.0, 1.0));
/// assert!(line.is_seg());
/// assert!(!line.is_arc());
/// assert_eq!(line.r, f64::INFINITY);
/// ```
#[inline]
#[must_use]
pub fn arcseg(a: Point, b: Point) -> Arc {
    arc(a, b, point(f64::INFINITY, f64::INFINITY), f64::INFINITY)
}

/// Translates an arcline by a given translation vector, returning a new arcline.
#[must_use]
pub fn arcline_translate(arcline: &Arcline, translation: Point) -> Arcline {
    let mut result: Arcline = Vec::with_capacity(arcline.len());
    for arc in arcline {
        let mut translated_arc = *arc;
        translated_arc.translate(translation);
        result.push(translated_arc);
    }
    result
}

/// Scales an arcline by a given scale factor, returning a new arcline.
#[must_use]
pub fn arcline_scale(arcline: &Arcline, scale: f64) -> Arcline {
    let mut result: Arcline = Vec::with_capacity(arcline.len());
    for arc in arcline {
        if arc.is_seg() {
            // For line segments, only scale endpoints
            let scaled_arc = arcseg(arc.a * scale, arc.b * scale);
            result.push(scaled_arc);
        } else {
            // For circular arcs, scale all components
            let mut scaled_arc = *arc;
            scaled_arc.a = scaled_arc.a * scale;
            scaled_arc.b = scaled_arc.b * scale;
            scaled_arc.c = scaled_arc.c * scale;
            scaled_arc.r = scaled_arc.r * scale.abs();
            result.push(scaled_arc);
        }
    }
    result
}

#[cfg(test)]
mod test_arc {
    use super::*;

    #[test]
    fn test_new() {
        let arc0 = Arc::new(point(1.0, 1.0), point(1.0, 3.0), point(2.0, -1.0), 1.0);
        let arc1 = arc(point(1.0, 1.0), point(1.0, 3.0), point(2.0, -1.0), 1.0);
        assert_eq!(arc0, arc1);
    }

    #[test]
    fn test_display() {
        let arc = arc(point(1.0, 1.0), point(1.0, 3.0), point(2.0, -1.0), 1.0);
        //print!("{}", arc);
        assert_eq!(
            "[[1.00000000000000000000, 1.00000000000000000000], [1.00000000000000000000, 3.00000000000000000000], [2.00000000000000000000, -1.00000000000000000000], 1.00000000000000000000]",
            format!("{}", arc)
        );
    }

    #[test]
    fn test_id_set() {
        let mut arc = arc(point(1.0, 1.0), point(1.0, 3.0), point(2.0, -1.0), 1.0);
        arc.id(42);
        assert!(arc.id == 42);
    }

    #[test]
    fn test_is_arc() {
        let arc = arcseg(point(1.0, 1.0), point(1.0, 3.0));
        assert!(arc.is_seg());
        assert!(!arc.is_arc());
    }

    #[test]
    fn test_contains_orientation() {
        // CCW quarter-circle from (1,0) to (0,1) centered at (0,0)
        let a = arc(point(1.0, 0.0), point(0.0, 1.0), point(0.0, 0.0), 1.0);
        // Point at 45 degrees should be contained
        assert!(a.contains(point(0.7071067811865476, 0.7071067811865476)));
        // Point outside arc span should not
        assert!(!a.contains(point(0.7071067811865476, -0.7071067811865476)));
        // Endpoints are considered contained (collinear => orient2d >= 0)
        assert!(a.contains(point(1.0, 0.0)));
        assert!(a.contains(point(0.0, 1.0)));
    }

    #[test]
    fn test_arcseg_creation() {
        // Test that arcseg creates a line segment (infinite radius)
        let line_arc = arcseg(point(0.0, 0.0), point(5.0, 5.0));
        assert!(line_arc.is_seg());
        assert!(!line_arc.is_arc());
        assert_eq!(line_arc.r, f64::INFINITY);
        assert_eq!(line_arc.a, point(0.0, 0.0));
        assert_eq!(line_arc.b, point(5.0, 5.0));
    }

    #[test]
    fn test_arc_reverse() {
        let original = arc(point(1.0, 0.0), point(0.0, 1.0), point(0.0, 0.0), 1.0);
        let reversed = original.reverse();

        // Check that endpoints are swapped
        assert_eq!(reversed.a, original.b);
        assert_eq!(reversed.b, original.a);
        // Center and radius should remain the same
        assert_eq!(reversed.c, original.c);
        assert_eq!(reversed.r, original.r);
    }

    #[test]
    fn test_arc_translate() {
        let mut arc = arc(point(1.0, 1.0), point(2.0, 2.0), point(1.5, 1.5), 0.5);
        let translation = point(10.0, -5.0);

        arc.translate(translation);

        // All points should be translated
        assert_eq!(arc.a, point(11.0, -4.0));
        assert_eq!(arc.b, point(12.0, -3.0));
        assert_eq!(arc.c, point(11.5, -3.5));
        // Radius should remain unchanged
        assert_eq!(arc.r, 0.5);
    }

    #[test]
    fn test_copy() {
        let arc = arcseg(point(1.0, 1.0), point(1.0, 3.0));
        let arc2 = arc;
        assert_eq!(arc, arc2);
    }

    #[test]
    fn test_reverse() {
        // Test reversing a circular arc
        let original = arc(point(1.0, 0.0), point(0.0, 1.0), point(0.0, 0.0), 1.0);
        let reversed = original.reverse();

        // Start and end points should be swapped
        assert_eq!(reversed.a, original.b);
        assert_eq!(reversed.b, original.a);

        // Center and radius should remain the same
        assert_eq!(reversed.c, original.c);
        assert_eq!(reversed.r, original.r);

        // Test the specific values
        assert_eq!(reversed.a, point(0.0, 1.0));
        assert_eq!(reversed.b, point(1.0, 0.0));
        assert_eq!(reversed.c, point(0.0, 0.0));
        assert_eq!(reversed.r, 1.0);
    }

    #[test]
    fn test_reverse_twice_returns_original() {
        // Test that reversing twice returns to the original arc
        let original = arc(point(3.0, 4.0), point(1.0, 2.0), point(2.0, 3.0), 2.5);
        let double_reversed = original.reverse().reverse();

        // Should be equal to the original (excluding ID which may differ)
        assert_eq!(double_reversed.a, original.a);
        assert_eq!(double_reversed.b, original.b);
        assert_eq!(double_reversed.c, original.c);
        assert_eq!(double_reversed.r, original.r);
    }

    #[test]
    fn test_arcline_translate_empty() {
        // Test translating an empty arcline
        let empty_arcline: Arcline = vec![];
        let translation = point(5.0, -3.0);
        let result = arcline_translate(&empty_arcline, translation);
        assert_eq!(result.len(), 0);
    }

    #[test]
    fn test_arcline_translate_single_arc() {
        // Test translating an arcline with a single arc
        let arcline = vec![arc(point(0.0, 0.0), point(2.0, 0.0), point(1.0, 0.0), 1.0)];
        let translation = point(10.0, 5.0);
        let result = arcline_translate(&arcline, translation);

        assert_eq!(result.len(), 1);
        assert_eq!(result[0].a, point(10.0, 5.0));
        assert_eq!(result[0].b, point(12.0, 5.0));
        assert_eq!(result[0].c, point(11.0, 5.0));
        assert_eq!(result[0].r, 1.0); // Radius should remain unchanged
    }

    #[test]
    fn test_arcline_translate_multiple_arcs() {
        // Test translating an arcline with multiple arcs
        let arcline = vec![
            arc(point(0.0, 0.0), point(1.0, 0.0), point(0.5, 0.0), 0.5),
            arcseg(point(1.0, 0.0), point(3.0, 2.0)), // Line segment
            arc(
                point(3.0, 2.0),
                point(3.0, 4.0),
                point(4.0, 3.0),
                1.414213562373095,
            ),
        ];
        let translation = point(-2.0, 3.0);
        let result = arcline_translate(&arcline, translation);

        assert_eq!(result.len(), 3);
    }

    #[test]
    fn test_arcline_scale_empty() {
        // Test scaling an empty arcline
        let empty_arcline: Arcline = vec![];
        let result = arcline_scale(&empty_arcline, 2.0);
        assert_eq!(result.len(), 0);
    }

    #[test]
    fn test_arcline_scale_single_arc() {
        // Test scaling an arcline with a single arc
        let arcline = vec![arc(point(1.0, 1.0), point(2.0, 1.0), point(1.5, 1.0), 0.5)];
        let result = arcline_scale(&arcline, 2.0);

        assert_eq!(result.len(), 1);
        assert_eq!(result[0].a, point(2.0, 2.0));
        assert_eq!(result[0].b, point(4.0, 2.0));
        assert_eq!(result[0].c, point(3.0, 2.0));
        assert_eq!(result[0].r, 1.0); // Radius scaled by 2
    }

    #[test]
    fn test_arcline_scale_multiple_arcs() {
        // Test scaling an arcline with multiple arcs
        let arcline = vec![
            arc(point(0.0, 0.0), point(1.0, 0.0), point(0.5, 0.0), 0.5),
            arcseg(point(1.0, 0.0), point(2.0, 1.0)),
            arc(point(2.0, 1.0), point(2.0, 2.0), point(1.0, 1.5), 1.0),
        ];
        let result = arcline_scale(&arcline, 0.5);

        assert_eq!(result.len(), 3);
        assert_eq!(result[0].a, point(0.0, 0.0));
        assert_eq!(result[0].b, point(0.5, 0.0));
        assert_eq!(result[0].c, point(0.25, 0.0));
        assert_eq!(result[0].r, 0.25);
    }
}

// #00003 #00004
// Check if the arc contains the point.
// pub fn contains_ulps(self: Self, p: Point, ulps: i64) -> bool {
//     let length = (p - self.c).norm();
//     if almost_equal_as_int(length, self.r, ulps) {
//         let diff_pa = p - self.a;
//         let diff_ba = self.b - self.a;
//         let perp = diff_pa.perp(diff_ba);
//         return perp >= 0f64;
//     } else {
//         return false;
//     }
// }

// pub fn contains_eps(self: Self, p: Point, eps: f64) -> bool {
//     let length = (p - self.c).norm();
//     if (length - self.r).abs() <= eps {
//         let diff_pa = p - self.a;
//         let diff_ba = self.b - self.a;
//         let perp = diff_pa.perp(diff_ba);
//         return perp >= 0f64;
//     } else {
//         return false;
//     }
// }

// If the point is result of intersection,
// we already know the distance, from center is arc radius
// so no need to check the distance.
// pub fn contains(&self, p: Point) -> bool {
//     let diff_pa = p - self.a;
//     let diff_ba = self.b - self.a;
//     let perp = diff_pa.perp(diff_ba);
//     return perp >= 0f64;
// }

impl Arc {
    // TODO: what should be the exact value.
    /// Checks if the arc has a collapsed radius.
    ///
    /// An arc is considered to have a collapsed radius if the radius is smaller
    /// than the given epsilon threshold or if it's NaN.
    ///
    /// # Arguments
    ///
    /// * `r` - The radius to check
    /// * `eps` - The epsilon threshold for comparison
    ///
    /// # Returns
    ///
    /// True if the radius is collapsed (too small or NaN), false otherwise
    ///
    /// # Examples
    ///
    /// ```
    /// use togo::prelude::*;
    /// let arc1 = arc(point(0.0, 0.0), point(1.0, 0.0), point(0.5, 0.0), 0.0001);
    /// assert!(arc1.is_collapsed_radius(0.01)); // Radius too small
    /// let arc2 = arc(point(0.0, 0.0), point(1.0, 0.0), point(0.5, 0.0), f64::NAN);
    /// assert!(arc2.is_collapsed_radius(0.01)); // NaN radius
    /// let arc3 = arc(point(0.0, 0.0), point(1.0, 0.0), point(0.5, 0.0), 1.0);
    /// assert!(!arc3.is_collapsed_radius(0.01)); // Valid radius
    /// ```
    pub fn is_collapsed_radius(&self, eps: f64) -> bool {
        // no abs() since it can be negative
        if self.r < eps || self.r.is_nan() {
            return true;
        }
        false
    }

    /// Checks if the arc has collapsed endpoints.
    ///
    /// An arc is considered to have collapsed endpoints if the start and end
    /// points are too close to each other within the given epsilon threshold.

    ///
    /// # Returns
    ///
    /// True if the endpoints are too close together, false otherwise
    ///
    /// # Examples
    ///
    /// ```
    /// use togo::prelude::*;
    /// let p1 = point(0.0, 0.0);
    /// let p2 = point(0.0001, 0.0);
    /// let p3 = point(1.0, 0.0);
    ///
    /// let arc1 = arc(p1, p2, point(0.0, 0.5), 0.5);
    /// assert!(arc1.is_collapsed_ends(0.01)); // Points too close
    /// let arc2 = arc(p1, p3, point(0.5, 0.0), 0.5);
    /// assert!(!arc2.is_collapsed_ends(0.01)); // Points far enough apart
    /// ```
    pub fn is_collapsed_ends(&self, eps: f64) -> bool {
        if self.a.close_enough(self.b, eps) {
            return true;
        }
        false
    }

    /// Checks if an arc has inconsistent geometry.
    ///
    /// An arc is considered inconsistent if the center point is not equidistant
    /// from both endpoints within the given epsilon threshold. This validates
    /// that the arc's center and radius are geometrically consistent.
    ///
    /// # Arguments
    ///
    /// * `eps` - The epsilon threshold for distance comparison
    ///
    /// # Returns
    ///
    /// True if the arc geometry is consistent, false if it's inconsistent
    ///
    /// # Examples
    ///
    /// ```
    /// use togo::prelude::*;
    ///
    /// // Consistent arc: center is equidistant from both endpoints
    /// let start = point(0.0, 0.0);
    /// let end = point(2.0, 0.0);
    /// let center = point(1.0, 0.0);
    /// let radius = 1.0;
    /// let arc = arc(start, end, center, radius);
    /// assert!(arc.is_consistent(1e-10));
    ///
    /// // Inconsistent arc: center is not equidistant from endpoints
    /// let bad_center = point(0.5, 0.0);
    /// let mut arc2 = arc.clone();
    /// arc2.c = bad_center;
    /// assert!(!arc2.is_consistent(1e-10));
    ///
    /// // Another inconsistent case: wrong radius
    /// let mut arc3 = arc.clone();
    /// arc3.r = 2.0;
    /// assert!(!arc3.is_consistent(1e-10));
    /// ```
    pub fn is_consistent(&self, eps: f64) -> bool {
        if self.is_seg() {
            // Lines are always consistent, no center point
            return true;
        }
        // Check if the radius is consistent with the center and endpoints
        let ac = ((self.a - self.c).norm() - self.r).abs();
        let bc = ((self.b - self.c).norm() - self.r).abs();
        if ac > eps || bc > eps {
            return false; // Inconsistent radius
        }
        true
    }

    /// Validates if an arc is geometrically valid.
    ///
    /// An arc is considered valid if it doesn't have a collapsed radius,
    /// doesn't have collapsed endpoints, and has consistent geometry
    /// (the center point is equidistant from both endpoints).
    ///
    /// # Arguments
    ///
    /// * `eps` - The epsilon threshold for validation checks
    ///
    /// # Returns
    ///
    /// True if the arc is valid, false if it's degenerate or inconsistent
    ///
    /// # Examples
    ///
    /// ```
    /// use togo::prelude::*;
    /// let valid_arc = arc(point(0.0, 0.0), point(1.0, 0.0), point(0.5, 0.0), 0.5);
    /// assert!(valid_arc.is_valid(1e-10));
    ///
    /// let invalid_arc = arc(point(0.0, 0.0), point(0.0, 0.0), point(0.5, 0.5), 1.0);
    /// assert!(!invalid_arc.is_valid(1e-10)); // Collapsed endpoints
    ///
    /// let inconsistent_arc = arc(point(0.0, 0.0), point(2.0, 0.0), point(0.5, 0.0), 2.0);
    /// assert!(!inconsistent_arc.is_valid(1e-10)); // Inconsistent geometry
    /// ```
    #[must_use]
    pub fn is_valid(&self, eps: f64) -> bool {
        if self.is_seg() {
            if self.is_collapsed_ends(eps) {
                return false;
            }
        }
        if self.is_arc() {
            if self.is_collapsed_ends(eps)
                || self.is_collapsed_radius(eps)
                || !self.is_consistent(eps)
            {
                return false;
            }
        }
        true
    }
}

#[cfg(test)]
mod test_arc_contains {
    use super::*;

    #[test]
    fn test_arc_contains_01() {
        let arc1 = arc(point(2.0, 1.0), point(1.0, 0.0), point(1.0, 1.0), 1.0);
        assert_eq!(arc1.contains(point(0.0, 0.0)), true);
        assert_eq!(arc1.contains(point(-1.0, 1.0)), true);
    }

    #[test]
    fn test_arc_contains_02() {
        let arc1 = arc(point(-1.0, 1.0), point(1.0, 1.0), point(0.0, 1.0), 1.0);
        assert_eq!(arc1.contains(point(0.0, 0.0)), true);
    }

    // #[test]
    // fn test_point_on_arc() {
    //     let arc = arc(point(1.0, 0.0), point(-1.0, 0.0), point(0.0, 0.0), 1.0);
    //     assert_eq!(arc.contains_ulps(point(0.0, 1.0), 5), true);
    // }

    #[test]
    fn test_arc_contains_large_r() {
        let arc = arc_from_bulge(point(1e20, 30.0), point(10.0, 30.0), 1f64);
        assert_eq!(arc.contains(point(1e20 + 1000.0, 30.0)), true);
    }

    #[test]
    fn test_arc_contains_00() {
        let sgrt_2_2 = std::f64::consts::SQRT_2 / 2.0;
        let arc0 = arc(point(1.0, 1.0), point(0.0, 0.0), point(0.5, 0.5), sgrt_2_2);
        assert!(arc0.contains(point(0.0, 1.0)));
    }

    #[test]
    fn test_arc_contains_03() {
        let arc0 = arc(point(1.0, 0.0), point(0.0, 1.0), point(0.0, 0.0), 1.0);
        assert!(arc0.contains(point(0.0, 1.0)));
    }

    #[test]
    fn test_arc_not_contains() {
        let arc = arc(point(0.0, -1.0), point(0.0, 1.0), point(0.0, 0.0), 1.0);
        let p = point(-1.0, 0.0);
        assert_eq!(arc.contains(p), false);
    }
}

#[cfg(test)]
mod test_arc_validation {
    use super::*;

    const ARC_COLLAPSED_TOLERANCE: f64 = 1E-8; // Tolerance for collapsed checks

    #[test]
    fn test_arc_is_collapsed_radius_normal_values() {
        // Normal positive radius values should not be collapsed
        let arc1 = arc(point(0.0, 0.0), point(1.0, 0.0), point(0.5, 0.0), 1.0);
        let arc2 = arc(point(0.0, 0.0), point(1.0, 0.0), point(0.5, 0.0), 0.1);
        let arc3 = arc(point(0.0, 0.0), point(1.0, 0.0), point(0.5, 0.0), 100.0);
        let arc4 = arc(
            point(0.0, 0.0),
            point(1.0, 0.0),
            point(0.5, 0.0),
            f64::INFINITY,
        );
        assert!(!arc1.is_collapsed_radius(ARC_COLLAPSED_TOLERANCE));
        assert!(!arc2.is_collapsed_radius(ARC_COLLAPSED_TOLERANCE));
        assert!(!arc3.is_collapsed_radius(ARC_COLLAPSED_TOLERANCE));
        assert!(!arc4.is_collapsed_radius(ARC_COLLAPSED_TOLERANCE));
    }

    #[test]
    fn test_arc_is_collapsed_radius_small_values() {
        // Values smaller than ARC_COLLAPSED_TOLERANCE (1E-8) should be collapsed
        let arc1 = arc(point(0.0, 0.0), point(1.0, 0.0), point(0.5, 0.0), 1E-9);
        let arc2 = arc(point(0.0, 0.0), point(1.0, 0.0), point(0.5, 0.0), 1E-10);
        let arc3 = arc(point(0.0, 0.0), point(1.0, 0.0), point(0.5, 0.0), 0.0);
        assert!(arc1.is_collapsed_radius(ARC_COLLAPSED_TOLERANCE));
        assert!(arc2.is_collapsed_radius(ARC_COLLAPSED_TOLERANCE));
        assert!(arc3.is_collapsed_radius(ARC_COLLAPSED_TOLERANCE));
    }

    #[test]
    fn test_arc_is_collapsed_radius_boundary_values() {
        // Test values around the ARC_COLLAPSED_TOLERANCE boundary
        let arc1 = arc(
            point(0.0, 0.0),
            point(1.0, 0.0),
            point(0.5, 0.0),
            ARC_COLLAPSED_TOLERANCE / 2.0,
        );
        let arc2 = arc(
            point(0.0, 0.0),
            point(1.0, 0.0),
            point(0.5, 0.0),
            ARC_COLLAPSED_TOLERANCE * 2.0,
        );
        let arc3 = arc(
            point(0.0, 0.0),
            point(1.0, 0.0),
            point(0.5, 0.0),
            ARC_COLLAPSED_TOLERANCE - f64::EPSILON,
        );
        assert!(arc1.is_collapsed_radius(ARC_COLLAPSED_TOLERANCE));
        assert!(!arc2.is_collapsed_radius(ARC_COLLAPSED_TOLERANCE));
        assert!(arc3.is_collapsed_radius(ARC_COLLAPSED_TOLERANCE));
    }

    #[test]
    fn test_arc_is_collapsed_radius_negative_values() {
        // Negative radius values should be collapsed
        let arc1 = arc(point(0.0, 0.0), point(1.0, 0.0), point(0.5, 0.0), -1.0);
        let arc2 = arc(point(0.0, 0.0), point(1.0, 0.0), point(0.5, 0.0), -0.1);
        let arc3 = arc(point(0.0, 0.0), point(1.0, 0.0), point(0.5, 0.0), -1E-10);
        assert!(arc1.is_collapsed_radius(ARC_COLLAPSED_TOLERANCE));
        assert!(arc2.is_collapsed_radius(ARC_COLLAPSED_TOLERANCE));
        assert!(arc3.is_collapsed_radius(ARC_COLLAPSED_TOLERANCE));
    }

    #[test]
    fn test_arc_is_collapsed_radius_nan() {
        // NaN values should be collapsed
        let arc = arc(point(0.0, 0.0), point(1.0, 0.0), point(0.5, 0.0), f64::NAN);
        assert!(arc.is_collapsed_radius(ARC_COLLAPSED_TOLERANCE));
    }

    #[test]
    fn test_arc_is_collapsed_ends_normal_points() {
        // Normal separated points should not be collapsed
        let arc1 = arc(point(0.0, 0.0), point(1.0, 0.0), point(0.5, 0.5), 1.0);
        let arc2 = arc(point(0.0, 0.0), point(0.0, 1.0), point(0.5, 0.5), 1.0);
        let arc3 = arc(point(-1.0, -1.0), point(1.0, 1.0), point(0.0, 0.0), 2.0);
        let arc4 = arc(
            point(100.0, 200.0),
            point(300.0, 400.0),
            point(200.0, 300.0),
            100.0,
        );
        assert!(!arc1.is_collapsed_ends(ARC_COLLAPSED_TOLERANCE));
        assert!(!arc2.is_collapsed_ends(ARC_COLLAPSED_TOLERANCE));
        assert!(!arc3.is_collapsed_ends(ARC_COLLAPSED_TOLERANCE));
        assert!(!arc4.is_collapsed_ends(ARC_COLLAPSED_TOLERANCE));
    }

    #[test]
    fn test_arc_is_collapsed_ends_identical_points() {
        // Identical points should be collapsed
        let arc1 = arc(point(0.0, 0.0), point(0.0, 0.0), point(0.5, 0.0), 1.0);
        let arc2 = arc(point(1.0, 1.0), point(1.0, 1.0), point(1.5, 1.0), 1.0);
        let arc3 = arc(point(-5.0, 10.0), point(-5.0, 10.0), point(-4.0, 10.0), 1.0);
        assert!(arc1.is_collapsed_ends(ARC_COLLAPSED_TOLERANCE));
        assert!(arc2.is_collapsed_ends(ARC_COLLAPSED_TOLERANCE));
        assert!(arc3.is_collapsed_ends(ARC_COLLAPSED_TOLERANCE));
    }

    #[test]
    fn test_arc_is_collapsed_ends_very_close_points() {
        // Points closer than ARC_COLLAPSED_TOLERANCE should be collapsed
        let p1 = point(0.0, 0.0);
        let p2 = point(ARC_COLLAPSED_TOLERANCE / 2.0, 0.0);
        let test_arc1 = arc(p1, p2, point(0.0, 0.0), 1.0);
        assert!(test_arc1.is_collapsed_ends(ARC_COLLAPSED_TOLERANCE));

        let p3 = point(100.0, 100.0);
        let p4 = point(100.0 + ARC_COLLAPSED_TOLERANCE / 3.0, 100.0 + ARC_COLLAPSED_TOLERANCE / 3.0);
        let test_arc2 = arc(p3, p4, point(100.0, 100.0), 1.0);
        assert!(test_arc2.is_collapsed_ends(ARC_COLLAPSED_TOLERANCE));
    }

    #[test]
    fn test_arc_is_collapsed_ends_boundary_distance() {
        // Points at exactly ARC_COLLAPSED_TOLERANCE distance
        let p1 = point(0.0, 0.0);
        let p2 = point(ARC_COLLAPSED_TOLERANCE, 0.0);
        let test_arc1 = arc(p1, p2, point(0.0, 0.0), 1.0);
        // This should not be collapsed (distance equals tolerance)
        assert!(test_arc1.is_collapsed_ends(ARC_COLLAPSED_TOLERANCE));

        // Points slightly farther than ARC_COLLAPSED_TOLERANCE
        let p3 = point(0.0, 0.0);
        let p4 = point(ARC_COLLAPSED_TOLERANCE * 2.0, 0.0);
        let test_arc2 = arc(p3, p4, point(0.0, 0.0), 1.0);
        assert!(!test_arc2.is_collapsed_ends(ARC_COLLAPSED_TOLERANCE));
    }

    #[test]
    fn test_arc_check_valid_arcs() {
        // Valid arcs should pass the check
        let valid_arc1 = arc(point(0.0, 0.0), point(1.0, 0.0), point(0.5, 0.0), 0.5);
        assert!(valid_arc1.is_valid(ARC_COLLAPSED_TOLERANCE));

        let valid_arc2 = arc(
            point(-1.0, -1.0),
            point(1.0, 1.0),
            point(0.0, 0.0),
            std::f64::consts::SQRT_2,
        );
        assert!(valid_arc2.is_valid(ARC_COLLAPSED_TOLERANCE));

        // Line segments (infinite radius) should also be valid if endpoints are separated
        let valid_line = arcseg(point(0.0, 0.0), point(10.0, 0.0));
        assert!(valid_line.is_valid(ARC_COLLAPSED_TOLERANCE));
    }

    #[test]
    fn test_arc_check_collapsed_radius() {
        // Arcs with collapsed radius should fail the check
        let collapsed_radius_arc1 = arc(point(0.0, 0.0), point(1.0, 0.0), point(0.5, 0.0), 1E-10);
        assert!(!collapsed_radius_arc1.is_valid(ARC_COLLAPSED_TOLERANCE));

        let collapsed_radius_arc2 = arc(point(0.0, 0.0), point(1.0, 0.0), point(0.5, 0.0), -1.0);
        assert!(!collapsed_radius_arc2.is_valid(ARC_COLLAPSED_TOLERANCE));

        let nan_radius_arc = arc(point(0.0, 0.0), point(1.0, 0.0), point(0.5, 0.0), f64::NAN);
        assert!(!nan_radius_arc.is_valid(ARC_COLLAPSED_TOLERANCE));
    }

    #[test]
    fn test_arc_check_collapsed_ends() {
        // Arcs with collapsed endpoints should fail the check
        let collapsed_ends_arc1 = arc(point(0.0, 0.0), point(0.0, 0.0), point(0.0, 1.0), 1.0);
        assert!(!collapsed_ends_arc1.is_valid(ARC_COLLAPSED_TOLERANCE));

        let close_points = point(0.0, 0.0);
        let very_close_points = point(ARC_COLLAPSED_TOLERANCE / 2.0, 0.0);
        let collapsed_ends_arc2 = arc(close_points, very_close_points, point(0.0, 1.0), 1.0);
        assert!(!collapsed_ends_arc2.is_valid(ARC_COLLAPSED_TOLERANCE));

        // Line segments with collapsed endpoints should also fail
        let collapsed_line = arcseg(point(1.0, 1.0), point(1.0, 1.0));
        assert!(!collapsed_line.is_valid(ARC_COLLAPSED_TOLERANCE));
    }

    #[test]
    fn test_arc_check_both_collapsed() {
        // Arcs with both collapsed radius and collapsed endpoints should fail
        let both_collapsed = arc(point(0.0, 0.0), point(0.0, 0.0), point(0.0, 1.0), 1E-10);
        assert!(!both_collapsed.is_valid(ARC_COLLAPSED_TOLERANCE));

        let both_collapsed2 = arc(point(5.0, 5.0), point(5.0, 5.0), point(0.0, 0.0), f64::NAN);
        assert!(!both_collapsed2.is_valid(ARC_COLLAPSED_TOLERANCE));
    }

    #[test]
    fn test_arc_check_edge_cases() {
        // Test with very large coordinates - ensure consistent geometry
        let large_coord_arc = arc(
            point(1E10, 1E10),
            point(1E10 + 1.0, 1E10),
            point(1E10 + 0.5, 1E10),
            0.5,
        );
        assert!(large_coord_arc.is_valid(ARC_COLLAPSED_TOLERANCE));

        // Test with very small but valid radius - ensure consistent geometry
        let small_radius_arc = arc(point(0.0, 0.0), point(1.0, 0.0), point(0.5, 0.0), 0.5);
        assert!(small_radius_arc.is_valid(ARC_COLLAPSED_TOLERANCE));

        // Test with large radius
        let large_radius_arc = arc(point(0.0, 0.0), point(1E-6, 0.0), point(0.0, 1E6), 1E6);
        assert!(large_radius_arc.is_valid(ARC_COLLAPSED_TOLERANCE));
    }

    #[test]
    fn test_arcline_reverse_basic() {
        let arc1 = Arc {
            a: point(0.0, 0.0),
            b: point(1.0, 0.0),
            c: point(0.5, 0.5),
            r: 1.0,
            id: 1,
        };
        let arc2 = Arc {
            a: point(1.0, 0.0),
            b: point(1.0, 1.0),
            c: point(1.0, 0.5),
            r: 1.0,
            id: 2,
        };
        let arcline = vec![arc1, arc2];
        let reversed = arcline_reverse(&arcline);
        assert_eq!(reversed.len(), 2);
        // For circular arcs (finite radius), endpoints should NOT be swapped - they remain CCW
        assert_eq!(reversed[0].a, arc2.a); // arc2 comes first, unchanged
        assert_eq!(reversed[0].b, arc2.b);
        assert_eq!(reversed[1].a, arc1.a); // arc1 comes second, unchanged
        assert_eq!(reversed[1].b, arc1.b);
        assert_eq!(reversed[0].id, arc2.id);
        assert_eq!(reversed[1].id, arc1.id);
    }

    #[test]
    fn test_arcline_reverse_empty() {
        let arcline: Vec<Arc> = vec![];
        let reversed = arcline_reverse(&arcline);
        assert_eq!(reversed.len(), 0);
    }

    #[test]
    fn test_arcline_reverse_single_arc() {
        let arc = Arc {
            a: point(2.0, 2.0),
            b: point(3.0, 3.0),
            c: point(2.5, 2.5),
            r: 2.0,
            id: 42,
        };
        let arcline = vec![arc];
        let reversed = arcline_reverse(&arcline);
        assert_eq!(reversed.len(), 1);
        // For circular arcs (finite radius), endpoints should NOT be swapped
        assert_eq!(reversed[0].a, arc.a);
        assert_eq!(reversed[0].b, arc.b);
        assert_eq!(reversed[0].id, arc.id);
    }

    #[test]
    fn test_arcline_reverse_all_lines() {
        // All arcs are actually lines (r = infinity)
        let arc1 = Arc {
            a: point(0.0, 0.0),
            b: point(1.0, 0.0),
            c: point(0.0, 0.0),
            r: f64::INFINITY,
            id: 1,
        };
        let arc2 = Arc {
            a: point(1.0, 0.0),
            b: point(2.0, 0.0),
            c: point(0.0, 0.0),
            r: f64::INFINITY,
            id: 2,
        };
        let arcline = vec![arc1, arc2];
        let reversed = arcline_reverse(&arcline);
        assert_eq!(reversed[0].r, f64::INFINITY);
        assert_eq!(reversed[1].r, f64::INFINITY);
        // For line segments (infinite radius), endpoints should be swapped
        assert_eq!(reversed[0].a, arc2.b); // arc2 reversed: b->a
        assert_eq!(reversed[0].b, arc2.a); // arc2 reversed: a->b
        assert_eq!(reversed[1].a, arc1.b); // arc1 reversed: b->a  
        assert_eq!(reversed[1].b, arc1.a); // arc1 reversed: a->b
    }

    #[test]
    fn test_arcline_reverse_all_arcs() {
        // All arcs are true arcs (finite radius)
        let arc1 = Arc {
            a: point(0.0, 0.0),
            b: point(1.0, 0.0),
            c: point(0.5, 0.5),
            r: 2.0,
            id: 1,
        };
        let arc2 = Arc {
            a: point(1.0, 0.0),
            b: point(2.0, 0.0),
            c: point(1.5, 0.5),
            r: 2.0,
            id: 2,
        };
        let arcline = vec![arc1, arc2];
        let reversed = arcline_reverse(&arcline);
        assert!(reversed.iter().all(|arc| arc.r == 2.0));
        // For circular arcs (finite radius), endpoints should NOT be swapped - order is reversed but arcs stay CCW
        assert_eq!(reversed[0].a, arc2.a); // arc2 comes first, unchanged
        assert_eq!(reversed[0].b, arc2.b);
        assert_eq!(reversed[1].a, arc1.a); // arc1 comes second, unchanged  
        assert_eq!(reversed[1].b, arc1.b);
    }
}

// Given start end points of arc and radius, calculate bulge
// TODO: not tested
// #00006
// pub fn arc_g_from_points2(a: Point, b: Point, r: f64) -> f64 {
//     let d = b - a;
//     let dist = d.x.hypot(d.y);
//     let seg = r - (0.5 * ((4.0 * r * r) - dist * dist).sqrt());
//     let mut g = 2.0 * seg / dist;
//     if g.is_nan() {
//         g = 0f64;
//     }
//     g
// }

// Given start end points of arc and radius, calculate bulge
// TODO: not tested
// pub fn arc_g_from_points3(a: Point, b: Point, c: Point) -> f64 {
//     let d = b - a;
//     let dist = d.x.hypot(d.y);
//     if dist < 1E-8 {
//         // close points
//         return 0f64;
//     }
//     let theta0 = (a.y - c.y).atan2(a.x - c.x);
//     let theta1 = (b.y - c.y).atan2(b.x - c.x);
//     let mut angle = (theta1 - theta0).abs();
//     if angle < 0f64 {
//         angle += 2.0 * std::f64::consts::PI;
//     }
//     angle * 0.25
// }

/// Calculates the bulge parameter for an arc given start point, end point, center, and radius.
///
/// This function computes the bulge parameter that would be needed to create an arc
/// connecting points a and b with the given center c and radius r. The bulge represents
/// the ratio used in arc parametrization.
///
/// # Arguments
///
/// * `a` - The start point of the arc
/// * `b` - The end point of the arc
/// * `c` - The center point of the arc
/// * `r` - The radius of the arc
///
/// # Returns
///
/// The bulge parameter for the arc, or 0.0 if the arc is invalid
///
/// # Examples
///
/// ```
/// use togo::prelude::*;
///
/// let start = point(0.0, 0.0);
/// let end = point(2.0, 0.0);
/// let center = point(1.0, 0.0);
/// let radius = 1.0;
///
/// let bulge = bulge_from_arc(start, end, center, radius);
/// // The bulge parameter can be used to recreate the arc
/// ```
// Given start end points of arc and radius, calculate bulge
// https://stackoverflow.com/questions/48979861/numerically-stable-method-for-solving-quadratic-equations/50065711#50065711
#[must_use]
pub fn bulge_from_arc(a: Point, b: Point, c: Point, r: f64) -> f64 {
    let dist = (b - a).norm();
    if dist <= 1E-10 {
        // close points
        // TODO
        return 0f64;
    }
    // Side of line test
    // let diff_pa = c - a;
    // let diff_ba = b - a;
    // let perp = diff_pa.perp(diff_ba); // maybe use orient2d
    let pa = Coord { x: a.x, y: a.y };
    let pb = Coord { x: b.x, y: b.y };
    let pc = Coord { x: c.x, y: c.y };
    let perp = orient2d(pa, pb, pc);
    let ddd = (4.0 * r * r) - dist * dist;
    
    // Guard: Clamp ddd to zero before sqrt to prevent NaN from negative values
    // This handles cases where floating-point rounding makes ddd slightly negative
    let ddd_clamped = ddd.max(0.0);

    let seg = if perp <= 0f64 {
        // small arc
        r - (0.5 * ddd_clamped.sqrt())
    } else {
        // large arc
        r + (0.5 * ddd_clamped.sqrt())
    };

    // Guard: check that seg is not too small or non-finite before dividing
    // This prevents returning huge or NaN bulge values
    if seg.abs() <= 1E-10 || !seg.is_finite() {
        return 0f64;
    }
    
    // The original formula was returning 2.0 * seg / dist
    // But to match arc_circle_parametrization, we need to return the actual bulge
    // The relationship is: bulge = dist / (2 * seg)
    // This comes from the inverse of the parametrization formula
    let bulge = dist / (2.0 * seg);
    
    // Final safety check: ensure result is valid
    if !bulge.is_finite() {
        return 0f64;
    }
    
    bulge
}

const ZERO: f64 = 0f64;

/// Creates an arc from two points and a bulge parameter.
///
/// This function creates an arc that connects two points using a bulge parameter
/// to define the curvature. The bulge represents the ratio of the sagitta
/// (the perpendicular distance from the chord midpoint to the arc) to half the chord length.
///
/// # Arguments
///
/// * `p1` - The first point of the arc
/// * `p2` - The second point of the arc
/// * `bulge` - The bulge parameter controlling the arc curvature
///
/// # Bulge Handling
/// - Bulge values are normalized to positive (negative bulge swaps endpoints)
/// - Very small bulge (≤ DIVISION_EPSILON ≈ 1e-12) returns a line segment
/// - NaN/Infinity bulge returns a line segment
/// - Computed geometry with NaN/Infinity results returns a line segment
///
/// # Returns
///
/// An Arc connecting the two points with the specified curvature that is CCW
///
/// # Examples
///
/// ```
/// use togo::prelude::*;
///
/// // Create a semicircle arc
/// let arc = arc_from_bulge(point(0.0, 0.0), point(2.0, 0.0), 1.0);
/// assert!(arc.is_arc());
///
/// // Create a line (very small bulge, below DIVISION_EPSILON threshold)
/// let line = arc_from_bulge(point(0.0, 0.0), point(2.0, 0.0), 1e-13);
/// assert!(line.is_seg());
/// ```
#[must_use]
pub fn arc_from_bulge(p1: Point, p2: Point, bulge: f64) -> Arc {
    let mut pp1 = p1;
    let mut pp2 = p2;
    let mut bulge = bulge;
    
    // Guard 1: if bulge is invalid (NaN/Infinity), treat as line segment
    if !bulge.is_finite() {
        return arcseg(p1, p2);
    }
    
    // Handle negative bulge first (before DIVISION_EPSILON check) to ensure consistent endpoint ordering
    if bulge < 0f64 {
        // make arc CCW
        pp1 = p2;
        pp2 = p1;
        bulge = -bulge;
    }
    
    // Guard 2: Check for degenerate conditions
    // - Bulge too small (would cause division issues)
    // - Endpoints too close (degenerate arc)
    if bulge.abs() < DIVISION_EPSILON || pp1.close_enough(pp2, ARC_COLLAPSED_TOLERANCE) {
        // create line
        return arcseg(pp1, pp2);
    }

    // Compute center and radius using bulge parametrization
    // dt2 involves division by bulge, but we've already guarded against tiny bulge values
    let t2 = (pp2 - pp1).norm();
    let dt2 = (1.0 + bulge) * (1.0 - bulge) / (4.0 * bulge);
    let cx = (0.5 * pp1.x + 0.5 * pp2.x) + dt2 * (pp1.y - pp2.y);
    let cy = (0.5 * pp1.y + 0.5 * pp2.y) + dt2 * (pp2.x - pp1.x);
    let r = 0.25 * t2 * (1.0 / bulge + bulge).abs();
    
    // Guard 3: if results contain NaN or Infinity, treat as line segment
    if !cx.is_finite() || !cy.is_finite() || !r.is_finite() {
        return arcseg(pp1, pp2);
    }
    
    arc(pp1, pp2, point(cx, cy), r)
}

#[cfg(test)]
mod test_arc_g_from_points {
    use crate::constants::GEOMETRIC_EPSILON;
    use crate::prelude::*;

    #[test]
    fn test_a_b_are_close() {
        let a = point(114.31083505599867, 152.84458247200070);
        let b = point(114.31083505599865, 152.84458247200067);
        let arc = arc_from_bulge(a, b, 16.0);
        assert_eq!(bulge_from_arc(a, b, arc.c, arc.r), 0.0);
    }

    #[test]
    fn test_a_b_are_the_same() {
        let a = point(114.31083505599865, 152.84458247200067);
        let b = point(114.31083505599865, 152.84458247200067);
        let arc = arc_from_bulge(a, b, 16.0);
        assert_eq!(bulge_from_arc(a, b, arc.c, arc.r), 0.0);
    }

    #[test]
    fn test_small_arc_perp_negative() {
        // Test small arc case with positive bulge
        let a = point(0.0, 0.0);
        let b = point(2.0, 0.0);
        let bulge = 0.3; // Small positive bulge

        // Create arc from parametrization
        let arc = arc_from_bulge(a, b, bulge);

        // Calculate bulge back from points
        let result = bulge_from_arc(arc.a, arc.b, arc.c, arc.r);

        // Should be reasonably close to original bulge
        assert!(close_enough(bulge, result, GEOMETRIC_EPSILON));
        assert!(result.is_finite());
    }

    #[test]
    fn test_large_arc_perp_positive() {
        // Test large arc case with larger bulge
        let a = point(0.0, 0.0);
        let b = point(2.0, 0.0);
        let bulge = 1.5; // Large positive bulge

        // Create arc from parametrization
        let arc = arc_from_bulge(a, b, bulge);

        // Calculate bulge back from points
        let result = bulge_from_arc(arc.a, arc.b, arc.c, arc.r);

        // Should be reasonably close to original bulge
        assert!(close_enough(bulge, result, GEOMETRIC_EPSILON));
        assert!(result.is_finite());
    }

    #[test]
    fn test_semicircle() {
        // Test semicircle case (bulge = 1.0)
        let a = point(0.0, 0.0);
        let b = point(2.0, 0.0);
        let bulge = 1.0; // Semicircle

        // Create arc from parametrization
        let arc = arc_from_bulge(a, b, bulge);

        // Calculate bulge back from points
        let result = bulge_from_arc(arc.a, arc.b, arc.c, arc.r);

        // For a semicircle, the function should return a finite positive value
        assert!(close_enough(bulge, result, GEOMETRIC_EPSILON));
        assert!(result.is_finite());
    }

    #[test]
    fn test_quarter_circle() {
        // Test quarter circle case
        let a = point(0.0, 0.0);
        let b = point(1.0, 1.0);
        let bulge = 0.41421356; // Approximates tan(Ï€/8) for quarter circle

        // Create arc from parametrization
        let arc = arc_from_bulge(a, b, bulge);

        // Calculate bulge back from points
        let result = bulge_from_arc(arc.a, arc.b, arc.c, arc.r);

        // Should be reasonably close to original bulge
        assert!(close_enough(bulge, result, GEOMETRIC_EPSILON));
        assert!(result.is_finite());
    }

    #[test]
    fn test_very_small_distance() {
        // Test edge case with very small bulge (near line segment)
        let a = point(0.0, 0.0);
        let b = point(1.0, 0.0);
        let bulge = 1e-9; // Very small bulge, should create near-line

        // Create arc from parametrization
        let arc = arc_from_bulge(a, b, bulge);

        // For very small bulge, arc_circle_parametrization returns a line segment
        if arc.r == f64::INFINITY {
            // Line segment case - arc_g_from_points should handle this gracefully
            let result = bulge_from_arc(arc.a, arc.b, arc.c, arc.r);
            // For line segments, the function may return infinity or 0 depending on implementation
            assert!(result == 0.0 || result.is_infinite());
        } else {
            // Calculate bulge back from points
            let result = bulge_from_arc(arc.a, arc.b, arc.c, arc.r);
            assert!(close_enough(bulge, result, GEOMETRIC_EPSILON));
            assert!(result.is_finite());
        }
    }

    #[test]
    fn test_collinear_points() {
        // Test case with zero bulge (creates a line segment)
        let a = point(0.0, 0.0);
        let b = point(2.0, 0.0);
        let bulge = 0.0; // Zero bulge creates line segment

        // Create arc from parametrization
        let arc = arc_from_bulge(a, b, bulge);

        // For zero bulge, arc_circle_parametrization returns a line segment
        if arc.r == f64::INFINITY {
            // Line segment case - arc_g_from_points should handle this gracefully
            let result = bulge_from_arc(arc.a, arc.b, arc.c, arc.r);
            // For line segments, the function may return infinity or 0 depending on implementation
            assert!(result == 0.0 || result.is_infinite());
        } else {
            // Calculate bulge back from points
            let result = bulge_from_arc(arc.a, arc.b, arc.c, arc.r);
            assert!(close_enough(bulge, result, GEOMETRIC_EPSILON));
            assert!(result.is_finite());
        }
    }

    #[test]
    fn test_large_radius() {
        // Test with a small bulge that creates large radius (nearly straight line)
        let a = point(0.0, 0.0);
        let b = point(100.0, 0.0);
        let bulge = 0.01; // Small bulge creates large radius

        // Create arc from parametrization
        let arc = arc_from_bulge(a, b, bulge);

        // Calculate bulge back from points
        let result = bulge_from_arc(arc.a, arc.b, arc.c, arc.r);

        // Should be positive and finite
        assert!(close_enough(bulge, result, GEOMETRIC_EPSILON));
        assert!(result.is_finite());
    }

    #[test]
    fn test_minimal_radius() {
        // Test with semicircle bulge (maximum curvature for single arc)
        let a = point(0.0, 0.0);
        let b = point(2.0, 0.0);
        let bulge = 1.0; // Semicircle

        // Create arc from parametrization
        let arc = arc_from_bulge(a, b, bulge);

        // Calculate bulge back from points
        let result = bulge_from_arc(arc.a, arc.b, arc.c, arc.r);

        // Should be positive and finite
        assert!(close_enough(bulge, result, GEOMETRIC_EPSILON));
        assert!(result.is_finite());
    }

    #[test]
    fn test_consistency_with_parametrization() {
        // Test that arc_g_from_points is consistent with arc_circle_parametrization
        let a = point(1.0, 2.0);
        let b = point(3.0, 4.0);
        let bulge = 0.5;

        // Create arc from parametrization
        let arc = arc_from_bulge(a, b, bulge);

        // Calculate bulge back from points
        let calculated_bulge = bulge_from_arc(a, b, arc.c, arc.r);

        // Debug: print both values
        println!(
            "Original bulge: {}, Calculated bulge: {}, Ratio: {}",
            bulge,
            calculated_bulge,
            calculated_bulge / bulge
        );

        // Should match the original bulge within numerical precision
        assert!(
            (calculated_bulge - bulge).abs() < 1e-10,
            "Expected {}, got {}",
            bulge,
            calculated_bulge
        );
    }

    #[test]
    fn test_negative_bulge_consistency() {
        // Test with negative bulge (clockwise arc converted to CCW)
        let a = point(0.0, 0.0);
        let b = point(2.0, 2.0);
        let bulge = -0.8;

        // Create arc from parametrization (should convert to CCW)
        let arc = arc_from_bulge(a, b, bulge);

        // Calculate bulge back from points
        let calculated_bulge = bulge_from_arc(arc.a, arc.b, arc.c, arc.r);

        // Should return positive value (CCW orientation)
        assert!(close_enough(-bulge, calculated_bulge, GEOMETRIC_EPSILON));
        assert!(calculated_bulge.is_finite());
    }

    #[test]
    fn test_various_bulge_values() {
        // Test with various bulge values to verify round-trip consistency
        let test_bulges = [0.1, 0.25, 0.5, 0.75, 1.0, 1.5, 2.0];
        let a = point(0.0, 0.0);
        let b = point(1.0, 0.0);

        for &bulge in &test_bulges {
            // Create arc from parametrization
            let arc = arc_from_bulge(a, b, bulge);

            // Skip line segments (bulge = 0 case)
            if arc.r == f64::INFINITY {
                continue;
            }

            // Calculate bulge back from points
            let calculated_bulge = bulge_from_arc(arc.a, arc.b, arc.c, arc.r);

            // Should match the original bulge within numerical precision
            assert!(
                (calculated_bulge - bulge).abs() < 1e-10,
                "Bulge {} resulted in {} (difference: {})",
                bulge,
                calculated_bulge,
                (calculated_bulge - bulge).abs()
            );
        }
    }

    #[test]
    fn test_different_point_positions() {
        // Test with different start/end point configurations
        let test_cases = [
            (point(0.0, 0.0), point(1.0, 0.0)),     // Horizontal
            (point(0.0, 0.0), point(0.0, 1.0)),     // Vertical
            (point(0.0, 0.0), point(1.0, 1.0)),     // Diagonal
            (point(-1.0, -1.0), point(1.0, 1.0)),   // Diagonal through origin
            (point(10.0, 20.0), point(30.0, 40.0)), // Larger coordinates
        ];

        let bulge = 0.5;

        for (a, b) in test_cases.iter() {
            // Create arc from parametrization
            let arc = arc_from_bulge(*a, *b, bulge);

            // Calculate bulge back from points
            let calculated_bulge = bulge_from_arc(arc.a, arc.b, arc.c, arc.r);

            // Should match the original bulge within numerical precision
            assert!(
                (calculated_bulge - bulge).abs() < 1e-10,
                "Points {:?} -> {:?}: expected {}, got {}",
                a,
                b,
                bulge,
                calculated_bulge
            );
        }
    }
    
    #[test]
    fn test_close_points_large_bulge() {
        let r = 1.0;
        let bulge = bulge_from_arc(point(0.0, 0.0), point(0.0, 3e-5), point(0.0, 1.0), r);
        assert!(bulge > 133333.0);
        let arc = arc_from_bulge(point(0.0, 0.0), point(0.0, 3e-5), bulge);
        assert_eq!(close_enough(arc.r, r, 1e-6), true);
    }

    // ===== Phase 3.3: Degenerate Arc Handling Tests =====
    
    #[test]
    fn test_degenerate_tiny_bulge_near_division_epsilon() {
        // Test bulge at or near DIVISION_EPSILON (1e-12)
        // Should be treated as line segment
        use crate::constants::DIVISION_EPSILON;
        
        let a = point(0.0, 0.0);
        let b = point(2.0, 0.0);
        
        // Test bulge at DIVISION_EPSILON - should be line
        let arc1 = arc_from_bulge(a, b, DIVISION_EPSILON / 2.0);
        assert!(arc1.is_seg(), "Very tiny bulge should be line segment");
        
        // Test bulge just above DIVISION_EPSILON - should be arc
        let arc2 = arc_from_bulge(a, b, DIVISION_EPSILON * 10.0);
        assert!(arc2.is_arc(), "Bulge above guard should be arc");
        assert!(arc2.r.is_finite(), "Arc radius should be finite");
    }

    #[test]
    fn test_degenerate_nan_bulge() {
        // NaN bulge should return line segment
        let a = point(0.0, 0.0);
        let b = point(2.0, 0.0);
        let arc = arc_from_bulge(a, b, f64::NAN);
        assert!(arc.is_seg(), "NaN bulge should produce line segment");
    }

    #[test]
    fn test_degenerate_infinite_bulge() {
        // Infinite bulge should return line segment
        let a = point(0.0, 0.0);
        let b = point(2.0, 0.0);
        
        let arc_pos_inf = arc_from_bulge(a, b, f64::INFINITY);
        assert!(arc_pos_inf.is_seg(), "Positive infinite bulge should produce line segment");
        
        let arc_neg_inf = arc_from_bulge(a, b, f64::NEG_INFINITY);
        assert!(arc_neg_inf.is_seg(), "Negative infinite bulge should produce line segment");
    }

    #[test]
    fn test_degenerate_coincident_endpoints() {
        // Points at same location should return line segment
        use crate::constants::GEOMETRIC_EPSILON;
        
        let a = point(1.5, 2.5);
        
        // Exactly same point
        let arc1 = arc_from_bulge(a, a, 1.0);
        assert!(arc1.is_seg(), "Identical endpoints should produce line segment");
        
        // Endpoints within tolerance
        let b = point(1.5 + GEOMETRIC_EPSILON / 2.0, 2.5);
        let arc2 = arc_from_bulge(a, b, 1.0);
        assert!(arc2.is_seg(), "Nearly identical endpoints should produce line segment");
    }

    #[test]
    fn test_degenerate_extreme_bulge_values() {
        // Test very large and very small bulge values
        let a = point(0.0, 0.0);
        let b = point(1.0, 0.0);
        
        // Extremely large bulge
        let arc_large = arc_from_bulge(a, b, 1e10);
        assert!(arc_large.is_arc(), "Very large bulge should produce arc");
        
        // Extremely small bulge (but not NaN/Infinity)
        let arc_small = arc_from_bulge(a, b, 1e-15);
        assert!(arc_small.is_seg(), "Extremely small bulge should be line segment");
    }

    #[test]
    fn test_degenerate_negative_bulge_endpoints() {
        // Negative bulge should swap endpoints but still work
        let a = point(0.0, 0.0);
        let b = point(2.0, 0.0);
        let bulge = 0.5;
        
        let arc_pos = arc_from_bulge(a, b, bulge);
        let arc_neg = arc_from_bulge(a, b, -bulge);
        
        // Both should produce valid arcs
        assert!(arc_pos.is_arc(), "Positive bulge should be arc");
        assert!(arc_neg.is_arc(), "Negative bulge should be arc");
        
        // Endpoints should be swapped
        assert_eq!(arc_pos.a, arc_neg.b, "Negative bulge swaps endpoints");
        assert_eq!(arc_pos.b, arc_neg.a, "Negative bulge swaps endpoints");
    }

    #[test]
    fn test_degenerate_zero_length_chord() {
        // Zero-length chord (same endpoints) at various scales
        let test_points = [
            (point(0.0, 0.0), point(0.0, 0.0)),
            (point(100.0, 100.0), point(100.0, 100.0)),
            (point(-1e6, -1e6), point(-1e6, -1e6)),
        ];
        
        for (a, b) in &test_points {
            let arc = arc_from_bulge(*a, *b, 1.0);
            assert!(arc.is_seg(), "Zero-length chord should produce line segment");
        }
    }

    #[test]
    fn test_degenerate_computed_geometry_validation() {
        // Test that computed center and radius are validated for finiteness
        // This is tricky to trigger naturally, but we can verify the guards exist
        let a = point(0.0, 0.0);
        let b = point(1.0, 0.0);
        
        // Normal case should produce finite geometry
        let arc = arc_from_bulge(a, b, 0.5);
        assert!(arc.c.x.is_finite(), "Arc center x should be finite");
        assert!(arc.c.y.is_finite(), "Arc center y should be finite");
        assert!(arc.r.is_finite(), "Arc radius should be finite");
    }

    #[test]
    fn test_degenerate_roundtrip_stability() {
        // Test that bulge values are stable through round-trip conversion
        // even at problematic values
        let a = point(0.0, 0.0);
        let b = point(1.0, 0.0);
        
        let test_bulges = [
            1e-11,  // Near DIVISION_EPSILON
            1e-10,  // Near GEOMETRIC_EPSILON
            1e-8,   // Normal small
            0.1,
            0.5,
            1.0,
            2.0,
            1e2,
        ];
        
        for &bulge in &test_bulges {
            let arc = arc_from_bulge(a, b, bulge);
            
            if arc.is_seg() {
                // Very small bulges should produce line segments, which is acceptable
                assert!(bulge < 1e-9, "Only very small bulges should be lines");
            } else {
                // For non-degenerate arcs, round-trip should be close
                let calculated = bulge_from_arc(arc.a, arc.b, arc.c, arc.r);
                let max_error = (GEOMETRIC_EPSILON * 1000.0).max(1e-6);
                assert!(
                    (calculated - bulge).abs() < max_error,
                    "Bulge {} round-trip error too large: {} (max allowed: {})",
                    bulge,
                    (calculated - bulge).abs(),
                    max_error
                );
            }
        }
    }
}

/// Reverses the direction of an arcline (sequence of CCW arcs).
/// Each arc is reversed by swapping its start and end points, and the order of arcs is reversed.
/// The orientation remains CCW for each arc.
///
/// # Arguments
/// * `arcs` - The arcline (`Vec<Arc>`) to reverse
///
/// # Returns
/// A new arcline with reversed direction
#[must_use]
pub fn arcline_reverse(arcs: &Arcline) -> Arcline {
    let mut reversed: Vec<Arc> = Vec::with_capacity(arcs.len());
    for arc in arcs.iter().rev() {
        if arc.is_seg() {
            reversed.push(arc.reverse());
        } else {
            reversed.push(*arc);
        }
    }
    reversed
}

impl Arc {
    /// Makes slightly inconsistent arc consistent by adjusting the arc center
    /// and radius, keeping the endpoints fixed.
    pub fn make_consistent(&mut self) {
        if self.is_seg() {
            return;
        }

        // Handle degenerate case where endpoints are the same
        if self.a.close_enough(self.b, 1e-12) {
            *self = arcseg(self.a, self.b);
            return;
        }

        // Calculate the distances from the current center to endpoints
        let dist_a_c = (self.a - self.c).norm();
        let dist_b_c = (self.b - self.c).norm();

        // Use the average of the two distances as the new radius
        let avg_radius = (dist_a_c + dist_b_c) / 2.0;

        // Calculate chord properties
        let chord = self.b - self.a;
        let chord_length = chord.norm();
        let half_chord = chord_length / 2.0;

        // If average radius is too small (less than half chord), use minimum possible radius
        let new_radius = if avg_radius < half_chord {
            half_chord
        } else {
            avg_radius
        };

        // Find the center that makes both endpoints equidistant
        // The center lies on the perpendicular bisector of the chord ab
        let midpoint = (self.a + self.b) / 2.0;

        // For a circle with radius r passing through points a and b,
        // the distance from chord midpoint to center is sqrt(r^2 - (chord_length/2)^2)
        let distance_to_center = (new_radius * new_radius - half_chord * half_chord).sqrt();

        // Perpendicular direction to chord (normalized)
        let perp = if chord_length > 1e-12 {
            point(-chord.y, chord.x) / chord_length
        } else {
            point(0.0, 1.0) // Default direction if chord is too small
        };

        // Two possible centers on the perpendicular bisector
        let c1 = midpoint + perp * distance_to_center;
        let c2 = midpoint - perp * distance_to_center;

        // Choose the center closer to the original center
        let dist1 = (c1 - self.c).norm();
        let dist2 = (c2 - self.c).norm();

        let new_center = if dist1 < dist2 { c1 } else { c2 };

        *self = Arc {
            a: self.a,
            b: self.b,
            c: new_center,
            r: new_radius,
            id: self.id, // Keep the same ID
        };
    }
}

#[cfg(test)]
mod test_arc_make_consistent {
    use crate::prelude::*;

    const GEOMETRIC_EPSILON: f64 = 1E-10;

    #[test]
    fn test_arc_make_consistent() {
        let mut arc = arc(point(0.0, 0.0), point(1.0, 0.0), point(0.5, 0.5), 0.5);
        arc.make_consistent();
        assert!(arc.is_consistent(GEOMETRIC_EPSILON));
    }

    #[test]
    fn test_arc_make_consistent_already_consistent() {
        // Create an already consistent arc
        let mut arc = arc(point(0.0, 0.0), point(2.0, 0.0), point(1.0, 0.0), 1.0);
        arc.make_consistent();
        assert!(arc.is_consistent(GEOMETRIC_EPSILON));
        // Should be very close to the original
        assert!(close_enough(arc.c.x, 1.0, GEOMETRIC_EPSILON));
        assert!(close_enough(arc.c.y, 0.0, GEOMETRIC_EPSILON));
        assert!(close_enough(arc.r, 1.0, GEOMETRIC_EPSILON));
    }

    #[test]
    fn test_arc_make_consistent_different_distances() {
        // Create an arc where endpoints are at different distances from center
        let mut arc = arc(point(0.0, 0.0), point(3.0, 4.0), point(1.0, 1.0), 2.0);
        arc.make_consistent();
        assert!(arc.is_consistent(GEOMETRIC_EPSILON));

        // Check that both endpoints are equidistant from the new center
        let dist_a = (arc.a - arc.c).norm();
        let dist_b = (arc.b - arc.c).norm();
        assert!(close_enough(dist_a, arc.r, GEOMETRIC_EPSILON));
        assert!(close_enough(dist_b, arc.r, GEOMETRIC_EPSILON));
    }

    #[test]
    fn test_arc_make_consistent_degenerate_endpoints() {
        // Create an arc with same start and end points
        let mut arc = arc(point(1.0, 1.0), point(1.0, 1.0), point(2.0, 2.0), 1.0);
        arc.make_consistent();
        // Degenerate case should result in line segment
        assert!(arc.is_consistent(GEOMETRIC_EPSILON));
        assert!(arc.is_seg());
    }

    #[test]
    fn test_arc_make_consistent_line_segment() {
        // Test with a line segment (infinite radius)
        let mut line_arc = arc(
            point(0.0, 0.0),
            point(1.0, 1.0),
            point(0.0, 0.0),
            f64::INFINITY,
        );
        line_arc.make_consistent();
        assert_eq!(line_arc.r, f64::INFINITY);
        assert_eq!(line_arc.a, line_arc.a);
        assert_eq!(line_arc.b, line_arc.b);
    }

    #[test]
    fn test_arc_make_consistent_small_radius() {
        // Test case where desired radius is smaller than minimum possible (half chord length)
        let mut arc = arc(point(0.0, 0.0), point(4.0, 0.0), point(2.0, 1.0), 1.0); // chord length = 4, so min radius = 2

        // Debug: check what the original distances are
        let dist_a_c = (arc.a - arc.c).norm(); // distance from (0,0) to (2,1) = sqrt(5) ≈ 2.236
        let dist_b_c = (arc.b - arc.c).norm(); // distance from (4,0) to (2,1) = sqrt(5) ≈ 2.236
        let avg_radius = (dist_a_c + dist_b_c) / 2.0; // ≈ 2.236

        arc.make_consistent();
        assert!(arc.is_consistent(GEOMETRIC_EPSILON));

        // The average radius is about 2.236, which is larger than half chord length (2.0)
        // So it should use the computed average radius, not the minimum
        assert!(close_enough(arc.r, avg_radius, GEOMETRIC_EPSILON));

        // Verify that both endpoints are equidistant from the center
        let new_dist_a = (arc.a - arc.c).norm();
        let new_dist_b = (arc.b - arc.c).norm();
        assert!(close_enough(new_dist_a, arc.r, GEOMETRIC_EPSILON));
        assert!(close_enough(new_dist_b, arc.r, GEOMETRIC_EPSILON));
    }

    #[test]
    fn test_arc_make_consistent_radius_too_small() {
        // Test case where the average radius is smaller than half chord length
        let mut arc = arc(point(0.0, 0.0), point(10.0, 0.0), point(1.0, 0.1), 0.5); // chord length = 10, half = 5, but point is close to first endpoint

        let dist_a_c = (arc.a - arc.c).norm();
        let dist_b_c = (arc.b - arc.c).norm();
        let avg_radius = (dist_a_c + dist_b_c) / 2.0;
        let chord_length = (arc.b - arc.a).norm();
        let half_chord = chord_length / 2.0;

        arc.make_consistent();
        assert!(arc.is_consistent(GEOMETRIC_EPSILON));

        // Check if the average radius is actually smaller than half chord
        if avg_radius < half_chord {
            // Should use minimum possible radius (half chord length)
            assert!(close_enough(arc.r, half_chord, GEOMETRIC_EPSILON));
            // Center should be at chord midpoint
            assert!(close_enough(arc.c.x, chord_length / 2.0, GEOMETRIC_EPSILON));
            assert!(close_enough(arc.c.y, 0.0, GEOMETRIC_EPSILON));
        } else {
            // Should use the average radius
            assert!(close_enough(arc.r, avg_radius, GEOMETRIC_EPSILON));
        }
    }
}

/// Checks if two arcs are genuinely intersecting, not just touching at endpoints.
///
/// This function determines whether two arcs have a "real" intersection that would
/// require further processing (like splitting the arcs). It returns `true` only when
/// the arcs intersect at interior points, not just when they touch at their endpoints.
///
/// The function handles all combinations of arc types:
/// - Line segment to line segment
/// - Arc to arc
/// - Line segment to arc
/// - Arc to line segment
///
/// # Arguments
///
/// * `arc1` - The first arc (can be a line segment or circular arc)
/// * `arc2` - The second arc (can be a line segment or circular arc)
///
/// # Returns
///
/// `true` if the arcs intersect at interior points, `false` if they don't intersect
/// or only touch at endpoints.
///
/// # Examples
///
/// ```
/// use togo::prelude::*;
///
/// // Two crossing line segments - really intersecting
/// let line1 = arcseg(point(0.0, 0.0), point(2.0, 2.0));
/// let line2 = arcseg(point(0.0, 2.0), point(2.0, 0.0));
/// assert!(is_really_intersecting(&line1, &line2));
///
/// // Two line segments sharing an endpoint - not really intersecting
/// let line1 = arcseg(point(0.0, 0.0), point(1.0, 0.0));
/// let line2 = arcseg(point(1.0, 0.0), point(2.0, 0.0));
/// assert!(!is_really_intersecting(&line1, &line2));
///
/// // Arc and line segment intersecting at interior points
/// let arc = arc(point(-1.0, 0.0), point(1.0, 0.0), point(0.0, 1.0), 1.0);
/// let line = arcseg(point(0.0, -0.5), point(0.0, 1.5));
/// assert!(is_really_intersecting(&arc, &line));
///
/// // Parallel line segments - no intersection
/// let line1 = arcseg(point(0.0, 0.0), point(1.0, 0.0));
/// let line2 = arcseg(point(0.0, 1.0), point(1.0, 1.0));
/// assert!(!is_really_intersecting(&line1, &line2));
/// ```
#[must_use]
pub fn is_really_intersecting(arc1: &Arc, arc2: &Arc) -> bool {
    if arc1.is_seg() && arc2.is_seg() {
        let seg1 = segment(arc1.a, arc1.b);
        let seg2 = segment(arc2.a, arc2.b);
        return if_really_intersecting_segment_segment(&seg1, &seg2);
    }
    if arc1.is_arc() && arc2.is_arc() {
        return if_really_intersecting_arc_arc(arc1, arc2);
    }
    if arc1.is_seg() && arc2.is_arc() {
        let seg1 = segment(arc1.a, arc1.b);
        return if_really_intersecting_segment_arc(&seg1, &arc2);
    }
    if arc1.is_arc() && arc2.is_seg() {
        let seg2 = segment(arc2.a, arc2.b);
        return if_really_intersecting_segment_arc(&seg2, arc1);
    }
    false
}

#[cfg(test)]
mod test_is_really_intersecting {
    use super::*;
    use crate::point::point;

    #[test]
    fn test_crossing_line_segments() {
        // Two line segments crossing at their midpoints
        let line1 = arcseg(point(0.0, 0.0), point(2.0, 2.0));
        let line2 = arcseg(point(0.0, 2.0), point(2.0, 0.0));
        assert!(is_really_intersecting(&line1, &line2));
    }

    #[test]
    fn test_endpoint_touching_segments() {
        // Two line segments sharing an endpoint - not really intersecting
        let line1 = arcseg(point(0.0, 0.0), point(1.0, 0.0));
        let line2 = arcseg(point(1.0, 0.0), point(2.0, 0.0));
        assert!(!is_really_intersecting(&line1, &line2));
    }

    #[test]
    fn test_parallel_segments() {
        // Parallel line segments - no intersection
        let line1 = arcseg(point(0.0, 0.0), point(1.0, 0.0));
        let line2 = arcseg(point(0.0, 1.0), point(1.0, 1.0));
        assert!(!is_really_intersecting(&line1, &line2));
    }

    #[test]
    fn test_overlapping_segments() {
        // Overlapping line segments - really intersecting
        let line1 = arcseg(point(0.0, 0.0), point(2.0, 0.0));
        let line2 = arcseg(point(1.0, 0.0), point(3.0, 0.0));
        assert!(is_really_intersecting(&line1, &line2));
    }

    #[test]
    fn test_arc_to_arc_intersecting() {
        // Two arcs that cross each other
        let arc1 = arc(point(-1.0, 0.0), point(1.0, 0.0), point(0.0, 1.0), 1.0);
        let arc2 = arc(point(0.0, -1.0), point(0.0, 1.0), point(1.0, 0.0), 1.0);
        assert!(is_really_intersecting(&arc1, &arc2));
    }

    #[test]
    fn test_arc_to_arc_touching_endpoints() {
        // Two arcs touching at endpoints only
        let arc1 = arc(point(0.0, 0.0), point(1.0, 0.0), point(0.5, 0.5), 1.0);
        let arc2 = arc(point(1.0, 0.0), point(2.0, 0.0), point(1.5, 0.5), 1.0);
        assert!(!is_really_intersecting(&arc1, &arc2));
    }

    #[test]
    fn test_arc_to_arc_no_intersection() {
        // Two arcs that don't intersect at all
        let arc1 = arc(point(0.0, 0.0), point(1.0, 0.0), point(0.5, 0.5), 1.0);
        let arc2 = arc(point(2.0, 2.0), point(3.0, 2.0), point(2.5, 2.5), 1.0);
        assert!(!is_really_intersecting(&arc1, &arc2));
    }

    #[test]
    fn test_segment_to_arc_intersecting() {
        // Line segment cutting through an arc
        let arc = arc(point(-1.0, 0.0), point(1.0, 0.0), point(0.0, 1.0), 1.0);
        let line = arcseg(point(0.0, -0.5), point(0.0, 1.5));
        assert!(is_really_intersecting(&line, &arc));
    }

    #[test]
    fn test_segment_to_arc_touching_endpoint() {
        // Line segment touching arc at its endpoint
        let arc = arc(point(-1.0, 0.0), point(1.0, 0.0), point(0.0, 1.0), 1.0);
        let line = arcseg(point(-1.0, 0.0), point(-2.0, 0.0));
        assert!(!is_really_intersecting(&line, &arc));
    }

    #[test]
    fn test_segment_to_arc_no_intersection() {
        // Line segment that doesn't intersect the arc
        let arc = arc(point(-1.0, 0.0), point(1.0, 0.0), point(0.0, 1.0), 1.0);
        let line = arcseg(point(2.0, 0.0), point(3.0, 0.0));
        assert!(!is_really_intersecting(&line, &arc));
    }

    #[test]
    fn test_arc_to_segment_intersecting() {
        // Arc cutting through a line segment (opposite order of previous test)
        let line = arcseg(point(0.0, -0.5), point(0.0, 1.5));
        let arc = arc(point(-1.0, 0.0), point(1.0, 0.0), point(0.0, 1.0), 1.0);
        assert!(is_really_intersecting(&arc, &line));
    }

    #[test]
    fn test_tangent_cases() {
        // Line segment tangent to arc - should not be "really intersecting"
        let arc = arc(point(-1.0, 0.0), point(1.0, 0.0), point(0.0, 1.0), 1.0);
        let line = arcseg(point(-1.0, 1.0), point(1.0, 1.0));
        assert!(!is_really_intersecting(&line, &arc));
    }

    #[test]
    fn test_collinear_segments() {
        // Collinear segments that don't overlap
        let line1 = arcseg(point(0.0, 0.0), point(1.0, 0.0));
        let line2 = arcseg(point(2.0, 0.0), point(3.0, 0.0));
        assert!(!is_really_intersecting(&line1, &line2));
    }

    #[test]
    fn test_perpendicular_segments_intersecting() {
        // Perpendicular segments crossing
        let line1 = arcseg(point(-1.0, 0.0), point(1.0, 0.0));
        let line2 = arcseg(point(0.0, -1.0), point(0.0, 1.0));
        assert!(is_really_intersecting(&line1, &line2));
    }
}

#[derive(Debug, PartialEq)]
/// Result of arcline validation, indicating whether an arcline is valid or the specific reason for invalidity.
///
/// This enum provides detailed feedback about arcline validation, allowing callers to understand
/// exactly what makes an arcline invalid and which specific elements are problematic.
pub enum ArclineValidation {
    /// The arcline is valid and forms a proper continuous path.
    Valid,
    /// The arcline is invalid because it contains fewer than 2 elements.
    Invalid,
    /// The arcline contains an invalid arc or line segment.
    /// The enclosed `Arc` is the first invalid element found.
    InvalidArc(Arc),
    /// Adjacent elements in the arcline are not connected (have a gap between them).
    GapBetweenArcs(Arc),
    /// Two consecutive elements form a zero-degree angle at their connection point.
    ZeroDegreeAngle(Arc, Arc),
    /// Two elements in the arcline intersect each other.
    IntersectingArcs(Arc, Arc),
    /// A line segment within the arcline is reversed (wrong orientation).
    /// Contains the index of the reversed segment and the segment itself.
    NotCCW(Option<(usize, Arc)>),
}

/// Validates an arcline (sequence of connected arcs and line segments).
///
/// An arcline is considered valid when it forms a proper continuous path where:
/// - The arcline contains at least 2 elements (arcs or line segments)
/// - Each individual arc/segment is geometrically valid
/// - Adjacent elements are properly connected (share endpoints)
/// - No zero-degree angles exist between consecutive elements
/// - Each two elements do not intersect each other
///
/// # Parameters
/// * `arcs` - The arcline to validate (vector of Arc elements)
///
/// # Returns
/// Returns an [`ArclineValidation`] enum indicating the validation result:
/// - [`ArclineValidation::Valid`] - The arcline is valid
/// - [`ArclineValidation::Invalid`] - The arcline has fewer than 2 elements
/// - [`ArclineValidation::InvalidArc`] - Contains an invalid arc/segment
/// - [`ArclineValidation::GapBetweenArcs`] - Adjacent elements are not connected
/// - [`ArclineValidation::ZeroDegreeAngle`] - Consecutive elements form a zero-degree angle
/// - [`ArclineValidation::IntersectingArcs`] - Non-adjacent elements intersect
///
/// # Examples
/// ```
/// use togo::prelude::*;
///
/// // Valid arcline: two connected line segments forming an L-shape
/// let arc1 = arcseg(point(0.0, 0.0), point(1.0, 0.0));
/// let arc2 = arcseg(point(1.0, 0.0), point(1.0, 1.0));
/// let arc3 = arcseg(point(1.0, 1.0), point(0.0, 0.0));
/// let arcline = vec![arc1, arc2, arc3];
/// assert_eq!(arcline_is_valid(&arcline), ArclineValidation::Valid);
///
/// // Invalid arcline: empty
/// let empty_arcline: Vec<Arc> = vec![];
/// assert_eq!(arcline_is_valid(&empty_arcline), ArclineValidation::Invalid);
/// ```
///
/// # Validation Criteria
///
/// ## 1. Minimum Size
/// The arcline must contain at least 2 elements to form a meaningful path.
///
/// ## 2. Individual Arc Validity
/// Each arc/segment must pass geometric validation (proper radius, distinct endpoints, etc.).
///
/// ## 3. Connectivity
/// Adjacent elements must share exactly one endpoint.
///
/// ## 4. No Zero-Degree Angles
/// Connected elements must not have collinear tangents at their connection point,
/// which would create a zero-degree angle and make the path non-smooth.
///
/// ## 5. No Self-Intersection
/// Non-adjacent elements (separated by at least one other element) must not intersect,
/// ensuring the path doesn't cross itself.
///
/// # Performance
/// Time complexity: O(n²) where n is the number of elements in the arcline,
/// due to intersection checking between all non-adjacent pairs.
#[must_use]
pub fn arcline_is_valid(arcs: &Arcline) -> ArclineValidation {
    let size = arcs.len();
    if size < 2 {
        return ArclineValidation::Invalid;
    }

    // Arcs should be valid
    for arc in arcs {
        if !arc.is_valid(1e-8) {
            return ArclineValidation::InvalidArc(arc.clone());
        }
    }

    for i in 0..size {
        let arc0 = arcs[i % size];
        let arc1 = arcs[(i + 1) % size]; // <- current
        let arc2 = arcs[(i + 2) % size];

        // There should be no gaps between arcs
        if !arc_have_two_connected_ends(&arc0, &arc1, &arc2) {
            return ArclineValidation::GapBetweenArcs(arc1.clone());
        }

        // Check if tangents are collinear (sharp angle)
        if arc_tangents_are_collinear(&arc0, &arc1) {
            return ArclineValidation::ZeroDegreeAngle(arc0.clone(), arc1.clone());
        }
    }

    // Check for reversed line segments (after confirming no gaps)
    for i in 0..size {
        let arc = arcs[i];
        if arc.is_seg() {
            let prev_arc = arcs[if i == 0 { size - 1 } else { i - 1 }];
            let next_arc = arcs[(i + 1) % size];
            
            // A segment should connect: prev_arc.end -> arc.start and arc.end -> next_arc.start
            // If reversed: prev_arc.end == arc.end and arc.start != prev_arc.end
            if prev_arc.b == arc.b && prev_arc.b != arc.a {
                return ArclineValidation::NotCCW(Some((i, arc.clone())));
            }
            // Or if arc.start == next_arc.start (both pointing the same way)
            if arc.a == next_arc.a && arc.b != next_arc.a {
                return ArclineValidation::NotCCW(Some((i, arc.clone())));
            }
        }
    }

    // No intersection between arcs
    for i in 0..size {
        for j in (i + 2)..size {
            let arc0 = arcs[i];
            let arc1 = arcs[j];
            if is_really_intersecting(&arc0, &arc1) {
                return ArclineValidation::IntersectingArcs(arc0.clone(), arc1.clone());
            }
        }
    }

    // Check CCW orientation using arcline_area
    let area = crate::algo::arcline_area(arcs);
    if area < -1e-10 {
        return ArclineValidation::NotCCW(None);
    }

    ArclineValidation::Valid
}

// Check that each arc connects properly in sequence
#[must_use]
fn arc_have_two_connected_ends(arc1: &Arc, arc2: &Arc, arc3: &Arc) -> bool {
    // Check connectivity between consecutive arcs
    // arc1 must connect to arc2, and arc2 must connect to arc3
    // They connect if any endpoint of arc1 exactly matches any endpoint of arc2
    
    // arc1 connects to arc2 if:
    // - arc1.b == arc2.a (normal case), OR
    // - arc1.b == arc2.b (arc2 is reversed), OR  
    // - arc1.a == arc2.a (arc1 is reversed and arc2 is reversed), OR
    // - arc1.a == arc2.b (arc1 is reversed)
    let arc1_to_arc2 = arc1.b == arc2.a ||
                       arc1.b == arc2.b ||
                       arc1.a == arc2.a ||
                       arc1.a == arc2.b;
    
    // arc2 connects to arc3 - same logic
    let arc2_to_arc3 = arc2.b == arc3.a ||
                       arc2.b == arc3.b ||
                       arc2.a == arc3.a ||
                       arc2.a == arc3.b;
    
    arc1_to_arc2 && arc2_to_arc3
}

// Check that each arc have 2 connected ends
#[must_use]
fn arc_tangents_are_collinear(arc1: &Arc, arc2: &Arc) -> bool {
    let x = vec![arc1.a, arc1.b];
    let y = vec![arc2.a, arc2.b];

    for i in 0..2 {
        for j in 0..2 {
            if x[i] == y[j] {
                let t1 = arc1.tangents()[i];
                let t2 = arc2.tangents()[j];
                if t1.close_enough(t2, 1e-8) {
                    // Tangents are collinear
                    return true;
                }
            }
        }
    }
    false
}

impl Arc {
    /// Compute tangents at ends of arc
    #[must_use]
    pub fn tangents(&self) -> [Point; 2] {
        if self.is_seg() {
            let (t, _) = (self.b - self.a).normalize(false);
            return [-t, t];
        }

        let a_to_c = self.a - self.c;
        let b_to_c = self.b - self.c;
        let (va, _) = point(a_to_c.y, -a_to_c.x).normalize(false);
        let (vb, _) = point(b_to_c.y, -b_to_c.x).normalize(false);
        [va, -vb]
    }
}

#[cfg(test)]
mod test_tangents {
    use super::*;
    use crate::utils::close_enough;

    #[test]
    fn test_tangents_semicircle() {
        let arc = arc(point(1.0, 0.0), point(-1.0, 0.0), point(0.0, 0.0), 1.0);
        let tangents = arc.tangents();
        let t1 = tangents[0];
        let t2 = tangents[1];
        assert_eq!(t1, point(0.0, -1.0));
        assert_eq!(t2, point(0.0, -1.0));
    }

    #[test]
    fn test_tangents_quarter_circle() {
        // Quarter circle from (1,0) to (0,1) with center at origin
        let arc = arc(point(1.0, 0.0), point(0.0, 1.0), point(0.0, 0.0), 1.0);
        let tangents = arc.tangents();
        let t_start = tangents[0];
        let t_end = tangents[1];

        // At start point (1,0), tangent should be perpendicular to radius, pointing up
        assert!(close_enough(t_start.x, 0.0, 1e-10));
        assert!(close_enough(t_start.y, -1.0, 1e-10));

        // At end point (0,1), tangent should be perpendicular to radius, pointing left
        assert!(close_enough(t_end.x, -1.0, 1e-10));
        assert!(close_enough(t_end.y, 0.0, 1e-10));
    }

    #[test]
    fn test_tangents_line_segment() {
        // Test line segment (infinite radius case)
        let line = arcseg(point(0.0, 0.0), point(3.0, 4.0));
        let tangents = line.tangents();
        let t_start = tangents[0];
        let t_end = tangents[1];

        // For line segment, both tangents should be in the direction of the line
        // Direction vector is (3,4), normalized to (0.6, 0.8)
        let expected_dir = point(0.6, 0.8);

        // Start tangent should be negative direction
        assert!(close_enough(t_start.x, -expected_dir.x, 1e-10));
        assert!(close_enough(t_start.y, -expected_dir.y, 1e-10));

        // End tangent should be positive direction
        assert!(close_enough(t_end.x, expected_dir.x, 1e-10));
        assert!(close_enough(t_end.y, expected_dir.y, 1e-10));
    }

    #[test]
    fn test_tangents_horizontal_line() {
        let line = arcseg(point(-2.0, 5.0), point(2.0, 5.0));
        let tangents = line.tangents();
        let t_start = tangents[0];
        let t_end = tangents[1];

        // Horizontal line: start tangent points left, end tangent points right
        assert!(close_enough(t_start.x, -1.0, 1e-10));
        assert!(close_enough(t_start.y, 0.0, 1e-10));
        assert!(close_enough(t_end.x, 1.0, 1e-10));
        assert!(close_enough(t_end.y, 0.0, 1e-10));
    }

    #[test]
    fn test_tangents_vertical_line() {
        let line = arcseg(point(3.0, -1.0), point(3.0, 1.0));
        let tangents = line.tangents();
        let t_start = tangents[0];
        let t_end = tangents[1];

        // Vertical line: start tangent points down, end tangent points up
        assert!(close_enough(t_start.x, 0.0, 1e-10));
        assert!(close_enough(t_start.y, -1.0, 1e-10));
        assert!(close_enough(t_end.x, 0.0, 1e-10));
        assert!(close_enough(t_end.y, 1.0, 1e-10));
    }

    #[test]
    fn test_tangents_semicircle_arc() {
        // Test a simple semicircle instead - more predictable
        let arc = arc(point(1.0, 0.0), point(-1.0, 0.0), point(0.0, 0.0), 1.0);
        let tangents = arc.tangents();
        let t_start = tangents[0];
        let t_end = tangents[1];

        // Tangent vectors should be unit length
        assert!(close_enough(t_start.norm(), 1.0, 1e-10));
        assert!(close_enough(t_end.norm(), 1.0, 1e-10));

        // For semicircle: at (1,0) tangent points up, at (-1,0) tangent points up
        assert!(close_enough(t_start.x, 0.0, 1e-10));
        assert!(close_enough(t_start.y, -1.0, 1e-10));
        assert!(close_enough(t_end.x, 0.0, 1e-10));
        assert!(close_enough(t_end.y, -1.0, 1e-10));
    }

    #[test]
    fn test_tangents_small_arc() {
        // Small arc around the first quadrant
        let arc = arc(
            point(1.0, 0.1),
            point(0.1, 1.0),
            point(0.0, 0.0),
            ((1.0_f64 - 0.0).powi(2) + (0.1_f64 - 0.0).powi(2)).sqrt(),
        );
        let tangents = arc.tangents();
        let t_start = tangents[0];
        let t_end = tangents[1];

        // Tangent vectors should be unit length
        assert!(close_enough(t_start.norm(), 1.0, 1e-10));
        assert!(close_enough(t_end.norm(), 1.0, 1e-10));

        // Tangents should be perpendicular to radii
        let radius_start = point(1.0, 0.1) - arc.c;
        let radius_end = point(0.1, 1.0) - arc.c;

        // Dot product of tangent and radius should be ~0 (perpendicular)
        assert!(close_enough(t_start.dot(radius_start), 0.0, 1e-10));
        assert!(close_enough(t_end.dot(radius_end), 0.0, 1e-10));
    }

    #[test]
    fn test_tangents_counterclockwise_vs_clockwise() {
        // Test same arc points but with different orientations
        let ccw_arc = arc(point(1.0, 0.0), point(0.0, 1.0), point(0.0, 0.0), 1.0);
        let cw_arc = arc(point(0.0, 1.0), point(1.0, 0.0), point(0.0, 0.0), 1.0);

        let ccw_tangents = ccw_arc.tangents();
        let ccw_t_start = ccw_tangents[0];
        let ccw_t_end = ccw_tangents[1];

        let cw_tangents = cw_arc.tangents();
        let cw_t_start = cw_tangents[0];
        let cw_t_end = cw_tangents[1];

        // All tangent vectors should be unit length
        assert!(close_enough(ccw_t_start.norm(), 1.0, 1e-10));
        assert!(close_enough(ccw_t_end.norm(), 1.0, 1e-10));
        assert!(close_enough(cw_t_start.norm(), 1.0, 1e-10));
        assert!(close_enough(cw_t_end.norm(), 1.0, 1e-10));
    }

    #[test]
    fn test_tangents_translated_arc() {
        // Test arc that's not centered at origin
        let center = point(5.0, -3.0);
        let arc = arc(point(6.0, -3.0), point(4.0, -3.0), center, 1.0);
        let tangents = arc.tangents();
        let t_start = tangents[0];
        let t_end = tangents[1];

        // Even when translated, tangent vectors should be unit length
        assert!(close_enough(t_start.norm(), 1.0, 1e-10));
        assert!(close_enough(t_end.norm(), 1.0, 1e-10));

        // For horizontal semicircle, tangents should be vertical
        assert!(close_enough(t_start.x, 0.0, 1e-10));
        assert!(close_enough(t_end.x, 0.0, 1e-10));
        assert!(close_enough(t_start.y.abs(), 1.0, 1e-10));
        assert!(close_enough(t_end.y.abs(), 1.0, 1e-10));
    }

    #[test]
    fn test_tangents_mathematical_properties() {
        // Test that tangents are perpendicular to radii
        let arc = arc(point(2.0, 0.0), point(0.0, 2.0), point(0.0, 0.0), 2.0);
        let tangents = arc.tangents();
        let t_start = tangents[0];
        let t_end = tangents[1];

        // Calculate radius vectors
        let radius_start = arc.a - arc.c; // From center to start point
        let radius_end = arc.b - arc.c; // From center to end point

        // Tangents should be perpendicular to radii (dot product = 0)
        assert!(close_enough(t_start.dot(radius_start), 0.0, 1e-10));
        assert!(close_enough(t_end.dot(radius_end), 0.0, 1e-10));

        // Tangents should be unit vectors
        assert!(close_enough(t_start.norm(), 1.0, 1e-10));
        assert!(close_enough(t_end.norm(), 1.0, 1e-10));
    }

    #[test]
    fn test_tangents_arbitrary_arc() {
        // Test with an arbitrary arc position and size
        let center = point(3.0, -2.0);
        let radius = 1.5;
        let start = center + point(radius, 0.0); // (4.5, -2.0)
        let end = center + point(0.0, radius); // (3.0, -0.5)
        let arc = arc(start, end, center, radius);

        let tangents = arc.tangents();
        let t_start = tangents[0];
        let t_end = tangents[1];

        // Tangents should be unit vectors
        assert!(close_enough(t_start.norm(), 1.0, 1e-10));
        assert!(close_enough(t_end.norm(), 1.0, 1e-10));

        // Tangents should be perpendicular to radii
        let radius_start = start - center;
        let radius_end = end - center;
        assert!(close_enough(t_start.dot(radius_start), 0.0, 1e-10));
        assert!(close_enough(t_end.dot(radius_end), 0.0, 1e-10));
    }

    #[test]
    fn test_tangents_very_small_line_segment() {
        // Test with a very small line segment
        let line = arcseg(point(0.0, 0.0), point(1e-6, 1e-6));
        let tangents = line.tangents();
        let t_start = tangents[0];
        let t_end = tangents[1];

        // Should still produce unit tangent vectors
        assert!(close_enough(t_start.norm(), 1.0, 1e-10));
        assert!(close_enough(t_end.norm(), 1.0, 1e-10));

        // Direction should be normalized (1,1) -> (√2/2, √2/2)
        let expected = 1.0 / (2.0_f64.sqrt());
        assert!(close_enough(t_start.x, -expected, 1e-10));
        assert!(close_enough(t_start.y, -expected, 1e-10));
        assert!(close_enough(t_end.x, expected, 1e-10));
        assert!(close_enough(t_end.y, expected, 1e-10));
    }
}

#[cfg(test)]
mod test_is_valid_arcline {
    use super::*;

    const EPS: f64 = 1e-10;

    #[test]
    fn test_is_valid_arcline_invalid_case() {
        let arc1 = arcseg(point(0.0, 0.0), point(1.0, 0.0));
        let arc2 = arc(point(1.0, 0.0), point(0.0, 0.0), point(0.5, 0.0), 0.5);
        let arcline = vec![arc1, arc2];
        assert_eq!(arcline_is_valid(&arcline), ArclineValidation::Valid);
    }

    #[test]
    fn test_is_valid_arcline_empty() {
        let empty_arcline: Arcline = vec![];
        assert_eq!(arcline_is_valid(&empty_arcline), ArclineValidation::Invalid);
    }

    #[test]
    fn test_is_valid_arcline_single_arc() {
        let arc = arcseg(point(0.0, 0.0), point(1.0, 1.0));
        let arcline = vec![arc];
        // Single arc should be invalid since minimum requirement is 2 arcs
        assert_eq!(arcline_is_valid(&arcline), ArclineValidation::Invalid);
    }

    #[test]
    fn test_is_valid_arcline_invalid_arc() {
        // Create an invalid arc with collapsed endpoints
        let invalid_arc1 = arcseg(point(0.0, 0.0), point(0.0, 0.0));
        let valid_arc = arcseg(point(1.0, 1.0), point(2.0, 2.0));

        let arcline = vec![invalid_arc1, valid_arc];
        match arcline_is_valid(&arcline) {
            ArclineValidation::InvalidArc(arcx) => {
                assert_eq!(arcx, invalid_arc1);
            } // Expected
            other => assert!(false, "Expected InvalidArc, got {:?}", other),
        }
    }

    #[test]
    fn test_is_valid_arcline_gap_between_arcs() {
        let arc1 = arcseg(point(0.0, 0.0), point(1.0, 0.0));
        let arc2 = arcseg(point(2.0, 0.0), point(3.0, 0.0)); // Gap between arcs

        let arcline = vec![arc1, arc2];
        match arcline_is_valid(&arcline) {
            ArclineValidation::GapBetweenArcs(_) => {} // Expected
            other => assert!(false, "Expected GapBetweenArcs, got {:?}", other),
        }
    }

    #[test]
    fn test_is_valid_arcline_intersecting_arcs() {
        // Create connected line segments that form an angle, then add a third that intersects
        let arc1 = arcseg(point(0.0, 0.0), point(1.0, 0.0));
        let arc2 = arcseg(point(1.0, 0.0), point(1.0, 1.0)); // Connected L-shape
        let arc3 = arcseg(point(0.5, -0.5), point(0.5, 1.5)); // Crosses arc1 and arc2

        let arcline = vec![arc1, arc2, arc3];
        match arcline_is_valid(&arcline) {
            ArclineValidation::IntersectingArcs(_, _) => {} // Expected
            ArclineValidation::GapBetweenArcs(_) => {} // Also possible since arc3 isn't connected
            other => assert!(
                false,
                "Expected IntersectingArcs or GapBetweenArcs, got {:?}",
                other
            ),
        }
    }

    #[test]
    fn test_is_valid_arcline_connected() {
        // Valid L-shaped arcline
        let arc1 = arcseg(point(0.0, 0.0), point(1.0, 0.0)); // Horizontal segment
        let arc2 = arc(point(1.0, 0.0), point(0.0, 0.0), point(0.5, 0.0), 0.5); // half circle

        let arcline = vec![arc1, arc2];
        assert_eq!(arcline_is_valid(&arcline), ArclineValidation::Valid);
    }

    #[test]
    fn test_is_valid_arcline_closed_triangle() {
        // Valid closed triangle
        let p1 = point(0.0, 0.0);
        let p2 = point(1.0, 0.0);
        let p3 = point(0.5, 1.0);

        let arc1 = arcseg(p1, p2);
        let arc2 = arcseg(p2, p3);
        let arc3 = arcseg(p3, p1);

        let arcline = vec![arc1, arc2, arc3];
        assert_eq!(arcline_is_valid(&arcline), ArclineValidation::Valid);
    }

    #[test]
    fn test_is_valid_arcline_connected_arcs_and_segments() {
        // Mix of arcs and line segments that connect properly
        let arc1 = arcseg(point(0.0, 0.0), point(1.0, 0.0));
        let arc2 = arc(
            point(1.0, 0.0),
            point(2.0, 1.0),
            point(1.5, 0.5),
            0.7071067811865476,
        );
        let arc3 = arcseg(point(2.0, 1.0), point(0.0, 1.0));
        let arc4 = arcseg(point(0.0, 1.0), point(0.0, 0.0));

        let arcline = vec![arc1, arc2, arc3, arc4];
        assert_eq!(arcline_is_valid(&arcline), ArclineValidation::Valid);
    }

    #[test]
    fn test_is_valid_arcline_multiple_invalid_arcs() {
        // Test with multiple invalid arcs - should return first invalid one
        let mut invalid_arc1 = arcseg(point(0.0, 0.0), point(1.0, 1.0));
        invalid_arc1.a = invalid_arc1.b; // Make invalid

        let valid_arc = arcseg(point(1.0, 1.0), point(2.0, 2.0));

        let mut invalid_arc2 = arcseg(point(2.0, 2.0), point(3.0, 3.0));
        invalid_arc2.a = invalid_arc2.b; // Make invalid

        let arcline = vec![invalid_arc1, valid_arc, invalid_arc2];
        match arcline_is_valid(&arcline) {
            ArclineValidation::InvalidArc(arc) => {
                // Should return the first invalid arc (invalid_arc1)
                assert_eq!(arc.a, arc.b);
            }
            other => assert!(false, "Expected InvalidArc, got {:?}", other),
        }
    }

    #[test]
    fn test_is_valid_arcline_non_adjacent_intersecting_arcs() {
        // Non-adjacent arcs that intersect (should be caught)
        let arc1 = arcseg(point(0.0, 0.0), point(1.0, 0.0));
        let arc2 = arcseg(point(1.0, 0.0), point(2.0, 1.0));
        let arc3 = arcseg(point(2.0, 1.0), point(0.5, 2.0)); // Connected but intersects arc1

        let arcline = vec![arc1, arc2, arc3];
        match arcline_is_valid(&arcline) {
            ArclineValidation::IntersectingArcs(_, _) => {} // Expected
            ArclineValidation::GapBetweenArcs(_) => {} // Also possible if arcs aren't connected properly
            other => assert!(
                false,
                "Expected IntersectingArcs or GapBetweenArcs, got {:?}",
                other
            ),
        }
    }

    #[test]
    fn test_is_valid_arcline_circular_arc_with_segments() {
        // Test with a proper circular arc connected to line segments
        let p1 = point(0.0, 0.0);
        let p2 = point(1.0, 0.0);
        let p3 = point(0.0, 1.0);

        let arc1 = arcseg(p1, p2); // Bottom edge
        let arc2 = arc(p2, p3, point(0.0, 0.0), 1.0); // Quarter circle
        let arc3 = arcseg(p3, p1); // Left edge

        let arcline = vec![arc1, arc2, arc3];
        assert_eq!(arcline_is_valid(&arcline), ArclineValidation::Valid);
    }

    #[test]
    fn test_is_valid_arcline_edge_case_very_small_segments() {
        // Test with very small but valid segments
        let arc1 = arcseg(point(0.0, 0.0), point(1e-6, 0.0));
        let arc2 = arc(point(1e-6, 0.0), point(0.0, 0.0), point(5e-7, 0.0), 5e-7);

        let arcline = vec![arc1, arc2];
        assert_eq!(arcline_is_valid(&arcline), ArclineValidation::Valid);
    }

    #[test]
    fn test_arcline200_validity_with_ccw_check() {
        // Test arcline200 validation including CCW orientation check
        use crate::poly::data::arcline200;
        
        let arcline = arcline200();
        let result = arcline_is_valid(&arcline);
        println!("arcline200 validation result: {:?}", result);
        println!("arcline200 length: {}", arcline.len());
        
        // Print area to see if it's CCW (positive)
        let area = crate::algo::arcline_area(&arcline);
        println!("arcline200 area: {}", area);
        
        // Print connection arcs (should be at index 100, 200+, and 222)
        println!("\nConnection and spiral info:");
        println!("Arc 0: {} -> {}", arcline[0].a, arcline[0].b);
        println!("Arc 1: {} -> {}", arcline[1].a, arcline[1].b);
        
        // Check gap between arc 0 and 1
        let gap_0_1 = ((arcline[0].b.x - arcline[1].a.x).powi(2) + (arcline[0].b.y - arcline[1].a.y).powi(2)).sqrt();
        println!("Gap between Arc 0.b and Arc 1.a: {}", gap_0_1);
        
        println!("\nArc 98: {} -> {}", arcline[98].a, arcline[98].b);
        println!("Arc 99: {} -> {}", arcline[99].a, arcline[99].b);
        println!("Arc 100 (connection1): {} -> {} (is_seg: {})", arcline[100].a, arcline[100].b, arcline[100].is_seg());
        
        // Check gap between arc 99 and 100
        let gap_99_100 = ((arcline[99].b.x - arcline[100].a.x).powi(2) + (arcline[99].b.y - arcline[100].a.y).powi(2)).sqrt();
        println!("Gap between Arc 99.b and Arc 100.a: {}", gap_99_100);
        
        println!("Arc 101 (spiral2_rev[0]): {} -> {} (is_seg: {})", arcline[101].a, arcline[101].b, arcline[101].is_seg());
        
        // Check gap between arc 100 and 101
        let gap_100_101 = ((arcline[100].b.x - arcline[101].a.x).powi(2) + (arcline[100].b.y - arcline[101].a.y).powi(2)).sqrt();
        println!("Gap between Arc 100.b and Arc 101.a: {}", gap_100_101);
        
        let spiral2_start_len = arcline.len() - 101 - 1; // Total - (spiral1 + connection1) - connection2
        println!("Expected spiral2_reversed length: {}", spiral2_start_len);
        
        let last_spiral2_idx = 100 + spiral2_start_len;
        if last_spiral2_idx < arcline.len() {
            println!("Arc {} (spiral2_rev[last]): {} -> {} (is_seg: {})", 
                last_spiral2_idx, arcline[last_spiral2_idx].a, arcline[last_spiral2_idx].b, arcline[last_spiral2_idx].is_seg());
            println!("Arc {} (connection2): {} -> {} (is_seg: {})", 
                last_spiral2_idx+1, arcline[last_spiral2_idx+1].a, arcline[last_spiral2_idx+1].b, arcline[last_spiral2_idx+1].is_seg());
            
            // Check gap between spiral2_rev[last] and connection2
            let gap_spiral2_conn2 = ((arcline[last_spiral2_idx].b.x - arcline[last_spiral2_idx+1].a.x).powi(2) 
                + (arcline[last_spiral2_idx].b.y - arcline[last_spiral2_idx+1].a.y).powi(2)).sqrt();
            println!("Gap between spiral2_rev[last].b and connection2.a: {}", gap_spiral2_conn2);
        }
        
        // Check gap between connection2.b and arc 0.a (to close the loop)
        if arcline.len() > 0 {
            let last_idx = arcline.len() - 1;
            let gap_close_loop = ((arcline[last_idx].b.x - arcline[0].a.x).powi(2) 
                + (arcline[last_idx].b.y - arcline[0].a.y).powi(2)).sqrt();
            println!("Gap between connection2.b and Arc 0.a (close loop): {}", gap_close_loop);
        }
        
        // Check which segments might be problematic
        for i in 0..arcline.len() {
            let arc = &arcline[i];
            if arc.is_seg() {
                let seg_contribution = arc.a.perp(arc.b);
                if seg_contribution < -1e-10 {
                    println!("REVERSED SEGMENT at index {}: {} -> {}, contribution: {}", 
                        i, arc.a, arc.b, seg_contribution);
                }
            }
        }
        
        // arcline200 is valid - the validation correctly detects that arcs connect
        // even when they have reversed endpoints from negative bulges
        assert!(matches!(result, ArclineValidation::Valid), 
                "Expected Valid for arcline200, got {:?}", result);
    }

    #[test]
    fn test_arcline500_validity_with_ccw_check() {
        // Test arcline500 validation including CCW orientation check
        use crate::poly::data::arcline500;
        
        let arcline = arcline500();
        let result = arcline_is_valid(&arcline);
        println!("arcline500 validation result: {:?}", result);
        let area = crate::algo::arcline_area(&arcline);
        println!("arcline500 area: {}", area);
        
        // Assert that area is positive (CCW) or that result is not Valid
        assert!(area > -1e-10, "arcline500 should be CCW (positive area), got {}", area);
    }

    #[test]
    fn test_arcline1000_validity_with_ccw_check() {
        // Test arcline1000 validation including CCW orientation check
        use crate::poly::data::arcline1000;
        
        let arcline = arcline1000();
        let result = arcline_is_valid(&arcline);
        println!("arcline1000 validation result: {:?}", result);
        let area = crate::algo::arcline_area(&arcline);
        println!("arcline1000 area: {}", area);
        
        // Assert that area is positive (CCW) or that result is not Valid
        assert!(area > -1e-10, "arcline1000 should be CCW (positive area), got {}", area);
    }

    #[test]
    fn test_reversed_segment_detection() {
        // Test that reversed segments are detected when they have wrong orientation
        // Create a properly connected path where a segment is oriented backwards relative to CCW flow
        let p0 = point(0.0, 0.0);
        let p1 = point(1.0, 0.5);
        let p2 = point(2.0, 0.0);
        let p3 = point(1.0, -1.0);
        
        // arc1: p0 -> p1
        // arc2: p1 -> p2  
        // seg: p2 -> p3 (normal orientation)
        // arc3: p3 -> p0
        // All properly connected. Should be Valid if CCW oriented.
        let arc1 = arc_from_bulge(p0, p1, 0.1);
        let arc2 = arc_from_bulge(p1, p2, 0.1);
        let seg = arcseg(p2, p3);  // Properly connected
        let arc3 = arc_from_bulge(p3, p0, 0.1);
        
        let arcline = vec![arc1, arc2, seg, arc3];
        let result = arcline_is_valid(&arcline);
        
        // With proper connectivity, should validate based on CCW area
        match result {
            ArclineValidation::Valid => {},  // Perfect case
            ArclineValidation::NotCCW(None) => {},  // CCW check failed (negative area)
            other => panic!("Unexpected result: {:?}", other),
        }
    }

    #[test]
    fn test_normal_arc_normal_segment_normal_arc() {
        let p0 = point(0.0, 0.0);
        let p1 = point(1.2, 0.6);
        let p2 = point(2.0, 0.3);
        let p3 = point(1.0, -0.8);
        
        let arc1 = arc_from_bulge(p0, p1, 0.12);
        let seg = arcseg(p1, p2);
        let arc2 = arc_from_bulge(p2, p3, 0.15);
        let arc3 = arc_from_bulge(p3, p0, 0.1);
        
        let arcline = vec![arc1, seg, arc2, arc3];
        let result = arcline_is_valid(&arcline);
        assert!(matches!(result, ArclineValidation::Valid | ArclineValidation::NotCCW(None)), 
                "Expected Valid or CCW area check, got {:?}", result);
    }

    #[test]
    fn test_reversed_arc_normal_segment() {
        // Simple square: side1, side2, side3, side4
        let p0 = point(0.0, 0.0);
        let p1 = point(1.0, 0.0);
        let p2 = point(1.0, 1.0);
        let p3 = point(0.0, 1.0);
        
        let arc1 = arc_from_bulge(p0, p1, -0.05);
        let seg = arcseg(p1, p2);
        let arc2 = arc_from_bulge(p2, p3, 0.05);
        let arc3 = arc_from_bulge(p3, p0, 0.05);
        
        let arcline = vec![arc1, seg, arc2, arc3];
        let result = arcline_is_valid(&arcline);
        // Just verify it doesn't panic - various validation checks may trigger
        let _ = result;
    }

    #[test]
    fn test_all_negative_bulge_arcs() {
        let p0 = point(0.0, 0.0);
        let p1 = point(1.0, 0.0);
        let p2 = point(1.0, 1.0);
        let p3 = point(0.0, 1.0);
        
        let arc1 = arc_from_bulge(p0, p1, -0.08);
        let arc2 = arc_from_bulge(p1, p2, -0.08);
        let arc3 = arc_from_bulge(p2, p3, -0.08);
        let arc4 = arc_from_bulge(p3, p0, -0.08);
        
        let arcline = vec![arc1, arc2, arc3, arc4];
        let result = arcline_is_valid(&arcline);
        let _ = result;
    }

    #[test]
    fn test_mixed_bulge_with_segments() {
        let p0 = point(0.0, 0.0);
        let p1 = point(1.0, 0.0);
        let p2 = point(1.0, 1.0);
        let p3 = point(0.0, 1.0);
        
        let arc1 = arc_from_bulge(p0, p1, 0.08);
        let seg1 = arcseg(p1, p2);
        let arc2 = arc_from_bulge(p2, p3, -0.08);
        let seg2 = arcseg(p3, p0);
        
        let arcline = vec![arc1, seg1, arc2, seg2];
        let result = arcline_is_valid(&arcline);
        let _ = result;
    }

    #[test]
    fn test_alternating_bulge_signs() {
        let p0 = point(0.0, 0.0);
        let p1 = point(1.0, 0.0);
        let p2 = point(1.0, 1.0);
        let p3 = point(0.5, 1.5);
        let p4 = point(0.0, 1.0);
        
        let arc1 = arc_from_bulge(p0, p1, 0.1);
        let arc2 = arc_from_bulge(p1, p2, -0.1);
        let arc3 = arc_from_bulge(p2, p3, 0.08);
        let arc4 = arc_from_bulge(p3, p4, -0.08);
        let arc5 = arc_from_bulge(p4, p0, 0.08);
        
        let arcline = vec![arc1, arc2, arc3, arc4, arc5];
        let result = arcline_is_valid(&arcline);
        let _ = result;
    }

    #[test]
    fn test_reversed_segment_1() {
        // Reversed segment at index 1 - creates gap during validation
        let p0 = point(0.0, 0.0);
        let p1 = point(1.0, 0.0);
        let p2 = point(2.0, 0.0);
        let p3 = point(1.0, -1.0);
        
        let arc1 = arc_from_bulge(p0, p1, 0.1);
        let seg = arcseg(p1, p0);  // Reversed
        let arc2 = arc_from_bulge(p0, p2, 0.1);
        let arc3 = arc_from_bulge(p2, p3, 0.1);
        
        let arcline = vec![arc1, seg, arc2, arc3];
        let result = arcline_is_valid(&arcline);
        // Reversed segment creates gap, so validation catches it
        assert!(!matches!(result, ArclineValidation::Valid),
                "Expected validation error for reversed segment, got Valid");
    }

    #[test]
    fn test_reversed_segment_2() {
        // Reversed segment at index 2
        let p0 = point(0.0, 0.0);
        let p1 = point(1.0, 0.0);
        let p2 = point(2.0, 0.0);
        let p3 = point(1.0, -1.0);
        
        let arc1 = arc_from_bulge(p0, p1, 0.1);
        let arc2 = arc_from_bulge(p1, p2, 0.1);
        let seg = arcseg(p2, p1);  // Reversed
        let arc3 = arc_from_bulge(p1, p3, 0.1);
        
        let arcline = vec![arc1, arc2, seg, arc3];
        let result = arcline_is_valid(&arcline);
        assert!(!matches!(result, ArclineValidation::Valid),
                "Expected validation error for reversed segment, got Valid");
    }

    #[test]
    fn test_reversed_segment_3() {
        // Reversed segment at index 3
        let p0 = point(0.0, 0.0);
        let p1 = point(1.0, 0.0);
        let p2 = point(2.0, 0.0);
        let p3 = point(1.0, -1.0);
        
        let arc1 = arc_from_bulge(p0, p1, 0.1);
        let arc2 = arc_from_bulge(p1, p2, 0.1);
        let arc3 = arc_from_bulge(p2, p3, 0.1);
        let seg = arcseg(p3, p2);  // Reversed
        
        let arcline = vec![arc1, arc2, arc3, seg];
        let result = arcline_is_valid(&arcline);
        assert!(!matches!(result, ArclineValidation::Valid),
                "Expected validation error for reversed segment, got Valid");
    }

    #[test]
    fn test_reversed_segment_as_first() {
        // Reversed segment at index 0
        let p0 = point(0.0, 0.0);
        let p1 = point(1.0, 0.0);
        let p2 = point(2.0, 0.0);
        let p3 = point(1.0, -1.0);
        
        let seg = arcseg(p1, p0);  // REVERSED (should be p0->p1)
        let arc1 = arc_from_bulge(p1, p2, 0.1);
        let arc2 = arc_from_bulge(p2, p3, 0.1);
        let arc3 = arc_from_bulge(p3, p0, 0.1);
        
        let arcline = vec![seg, arc1, arc2, arc3];
        let result = arcline_is_valid(&arcline);
        // Reversed segment creates gap which is caught by connectivity check
        assert!(matches!(result, ArclineValidation::GapBetweenArcs(_) | ArclineValidation::NotCCW(Some(_))), 
                "Expected validation error for reversed segment, got {:?}", result);
    }

    #[test]
    fn test_reversed_segment_as_last() {
        // Reversed segment at last position
        let p0 = point(0.0, 0.0);
        let p1 = point(1.0, 0.0);
        let p2 = point(2.0, 0.0);
        let p3 = point(1.0, -1.0);
        
        let arc1 = arc_from_bulge(p0, p1, 0.1);
        let arc2 = arc_from_bulge(p1, p2, 0.1);
        let arc3 = arc_from_bulge(p2, p3, 0.1);
        let seg = arcseg(p0, p3);
        
        let arcline = vec![arc1, arc2, arc3, seg];
        let result = arcline_is_valid(&arcline);
        assert!(!matches!(result, ArclineValidation::Valid),
                "Expected validation error for reversed segment at end, got Valid");
    }

    #[test]
    fn test_two_reversed_segments() {
        // Two reversed segments
        let p0 = point(0.0, 0.0);
        let p1 = point(1.0, 0.0);
        let p2 = point(2.0, 0.0);
        
        let arc1 = arc_from_bulge(p0, p1, 0.1);
        let seg1 = arcseg(p1, p0);  // Reversed
        let arc2 = arc_from_bulge(p0, p2, 0.1);
        let seg2 = arcseg(p2, p0);  // Also reversed
        
        let arcline = vec![arc1, seg1, arc2, seg2];
        let result = arcline_is_valid(&arcline);
        assert!(!matches!(result, ArclineValidation::Valid),
                "Expected validation error for reversed segments, got Valid");
    }

    #[test]
    fn test_three_reversed_segments() {
        // Three reversed segments
        let p0 = point(0.0, 0.0);
        let p1 = point(1.0, 0.0);
        let p2 = point(2.0, 0.0);
        let p3 = point(1.0, -1.0);
        
        let seg1 = arcseg(p0, p1);
        let seg2 = arcseg(p1, p0);  // Reversed
        let seg3 = arcseg(p0, p2);
        let arc1 = arc_from_bulge(p2, p3, 0.1);
        
        let arcline = vec![seg1, seg2, seg3, arc1];
        let result = arcline_is_valid(&arcline);
        assert!(!matches!(result, ArclineValidation::Valid),
                "Expected validation error for reversed segments, got Valid");
    }

    #[test]
    fn test_reversed_with_negative_bulge() {
        // Reversed segment with negative bulge arcs
        let p0 = point(0.0, 0.0);
        let p1 = point(1.0, 0.0);
        let p2 = point(2.0, 0.0);
        let p3 = point(1.0, -1.0);
        
        let arc1 = arc_from_bulge(p0, p1, -0.2);
        let seg = arcseg(p1, p0);  // Reversed
        let arc2 = arc_from_bulge(p0, p2, -0.2);
        let arc3 = arc_from_bulge(p2, p3, -0.2);
        
        let arcline = vec![arc1, seg, arc2, arc3];
        let result = arcline_is_valid(&arcline);
        assert!(!matches!(result, ArclineValidation::Valid),
                "Expected validation error for reversed segment with negative bulge, got Valid");
    }

    #[test]
    fn test_reversed_with_mixed_bulge() {
        // Reversed segment with mixed bulge signs
        let p0 = point(0.0, 0.0);
        let p1 = point(1.0, 0.0);
        let p2 = point(2.0, 0.0);
        let p3 = point(1.0, -1.0);
        
        let arc1 = arc_from_bulge(p0, p1, 0.15);
        let seg = arcseg(p1, p0);  // Reversed
        let arc2 = arc_from_bulge(p0, p2, -0.2);
        let arc3 = arc_from_bulge(p2, p3, 0.15);
        
        let arcline = vec![arc1, seg, arc2, arc3];
        let result = arcline_is_valid(&arcline);
        assert!(!matches!(result, ArclineValidation::Valid),
                "Expected validation error for reversed segment with mixed bulge, got Valid");
    }

    #[test]
    fn test_reversed_segment_multiple_positions() {
        // Reversed segment at various positions
        let p0 = point(0.0, 0.0);
        let p1 = point(1.0, 0.0);
        let p2 = point(1.0, 1.0);
        let p3 = point(0.0, 1.0);
        
        let seg1 = arcseg(p0, p1);
        let seg2 = arcseg(p1, p0);  // Reversed at index 1
        let arc1 = arc_from_bulge(p0, p2, 0.1);
        let arc2 = arc_from_bulge(p2, p3, 0.1);
        
        let arcline = vec![seg1, seg2, arc1, arc2];
        let result = arcline_is_valid(&arcline);
        assert!(!matches!(result, ArclineValidation::Valid),
                "Expected validation error for reversed segment, got Valid");
    }

    #[test]
    fn test_connection_segment_with_numerical_drift() {
        // Tests that connections with small numerical drift from arc endpoints still validate
        // This simulates real-world geometry where segments connect to arc endpoints
        // but may have tiny floating-point differences
        
        let p0 = point(0.0, 0.0);
        let p1 = point(1.0, 0.0);
        let p2 = point(2.0, 0.0);
        let p3 = point(2.0, 1.0);
        let p4 = point(0.0, 1.0);
        
        // Arc from p0 to p1
        let arc1 = arc_from_bulge(p0, p1, 0.1);
        
        // Connection segment from arc1.b to p2 (with tiny numerical drift simulated)
        // The connection should join arc1.b (which is p1) to arc2.a
        let arc1_end = arc1.b;
        
        // Connection: arc1 end -> arc2 start
        let connection = arcseg(arc1_end, p2);
        
        // Arc from p2 to p3
        let arc2 = arc_from_bulge(p2, p3, 0.1);
        
        // Connection: arc2 end -> arc3 start
        let arc2_end = arc2.b;
        let connection2 = arcseg(arc2_end, p4);
        
        // Close loop: p4 back to p0
        let arc3 = arc_from_bulge(p4, p0, 0.1);
        
        let arcline = vec![arc1, connection, arc2, connection2, arc3];
        let result = arcline_is_valid(&arcline);
        assert!(matches!(result, ArclineValidation::Valid),
                "Expected valid arcline with proper connections, got {:?}", result);
    }

    #[test]
    fn test_connection_endpoints_must_match_arc_endpoints() {
        // Tests that segments connecting arcs MUST use the actual arc endpoints (.b and .a)
        // not arbitrary points
        
        let p0 = point(0.0, 0.0);
        let p1 = point(1.0, 0.0);
        let p2 = point(2.0, 0.0);
        let p3 = point(2.0, 1.0);
        
        let arc1 = arc_from_bulge(p0, p1, 0.1);
        let _arc1_end = arc1.b;  // Should use .b (actual end)
        
        // WRONG: connection using arbitrary point instead of arc1.b
        let connection = arcseg(point(0.5, 0.0), p2);  // Wrong start point!
        
        let arc2 = arc_from_bulge(p2, p3, 0.1);
        
        let arcline = vec![arc1, connection, arc2];
        let result = arcline_is_valid(&arcline);
        
        // Should detect gap between arc1 and connection
        assert!(matches!(result, ArclineValidation::GapBetweenArcs(_)),
                "Expected GapBetweenArcs for mismatched connection, got {:?}", result);
    }
}