symplex 0.39.0

Exact symbolic mathematics for Rust: calculus, summation, solving, linear algebra, transforms, compile-time dimensional analysis, and Rust/C code generation
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
1205
1206
1207
1208
1209
1210
1211
1212
1213
1214
1215
1216
1217
1218
1219
1220
1221
1222
1223
1224
1225
1226
1227
1228
1229
1230
1231
1232
1233
1234
1235
1236
1237
1238
1239
1240
1241
1242
1243
1244
1245
1246
1247
1248
1249
1250
1251
1252
1253
1254
1255
1256
1257
1258
1259
1260
1261
1262
1263
1264
1265
1266
1267
1268
1269
1270
1271
1272
1273
1274
1275
1276
1277
1278
1279
1280
1281
1282
1283
1284
1285
1286
1287
1288
1289
1290
1291
1292
1293
1294
1295
1296
1297
1298
1299
1300
1301
1302
1303
1304
1305
1306
1307
1308
1309
1310
1311
1312
1313
1314
1315
1316
1317
1318
1319
1320
1321
1322
1323
1324
1325
1326
1327
1328
1329
1330
1331
1332
1333
1334
1335
1336
1337
1338
1339
1340
1341
1342
1343
1344
1345
1346
1347
1348
1349
1350
1351
1352
1353
1354
1355
1356
1357
1358
1359
1360
1361
1362
1363
1364
1365
1366
1367
1368
1369
1370
1371
1372
1373
1374
1375
1376
1377
1378
1379
1380
1381
1382
1383
1384
1385
1386
1387
1388
1389
1390
1391
1392
1393
1394
1395
1396
1397
1398
1399
1400
1401
1402
1403
1404
1405
1406
1407
1408
1409
1410
1411
1412
1413
1414
1415
1416
1417
1418
1419
1420
1421
1422
1423
1424
1425
1426
1427
1428
1429
1430
1431
1432
1433
1434
1435
1436
1437
1438
1439
1440
1441
1442
1443
1444
1445
1446
1447
1448
1449
1450
1451
1452
1453
1454
1455
1456
1457
1458
1459
1460
1461
1462
1463
1464
1465
1466
1467
1468
1469
1470
1471
1472
1473
1474
1475
1476
1477
1478
1479
1480
1481
1482
1483
1484
1485
1486
1487
1488
1489
1490
1491
1492
1493
1494
1495
1496
1497
1498
1499
1500
1501
1502
1503
1504
1505
1506
1507
1508
1509
1510
1511
1512
1513
1514
1515
1516
1517
1518
1519
1520
1521
1522
1523
1524
1525
1526
1527
1528
1529
1530
1531
1532
1533
1534
1535
1536
1537
1538
1539
1540
1541
1542
1543
1544
1545
1546
1547
1548
1549
1550
1551
1552
1553
1554
1555
1556
1557
1558
1559
1560
1561
1562
1563
1564
1565
1566
1567
1568
1569
1570
1571
1572
1573
1574
1575
1576
1577
1578
1579
1580
1581
1582
1583
1584
1585
1586
1587
1588
1589
1590
1591
1592
1593
1594
1595
1596
1597
1598
1599
1600
1601
1602
1603
1604
1605
1606
1607
1608
1609
1610
1611
1612
1613
1614
1615
1616
1617
1618
1619
1620
1621
1622
1623
1624
1625
1626
1627
1628
1629
1630
1631
1632
1633
1634
1635
1636
1637
1638
1639
1640
1641
1642
1643
1644
1645
1646
1647
1648
1649
1650
1651
1652
1653
1654
1655
1656
1657
1658
1659
1660
1661
1662
1663
1664
1665
1666
1667
1668
1669
1670
1671
1672
1673
1674
1675
1676
1677
1678
1679
1680
1681
1682
1683
1684
1685
1686
1687
1688
1689
1690
1691
1692
1693
1694
1695
1696
1697
1698
1699
1700
1701
1702
1703
1704
1705
1706
1707
1708
1709
1710
1711
1712
1713
1714
1715
1716
1717
1718
1719
1720
1721
1722
1723
1724
1725
1726
1727
1728
1729
1730
1731
1732
1733
1734
1735
1736
1737
1738
1739
1740
1741
1742
1743
1744
1745
1746
1747
1748
1749
1750
1751
1752
1753
1754
1755
1756
1757
1758
1759
1760
1761
1762
1763
1764
1765
1766
1767
1768
1769
1770
1771
1772
1773
1774
1775
1776
1777
1778
1779
1780
1781
1782
1783
1784
1785
1786
1787
1788
1789
1790
1791
1792
1793
1794
1795
1796
1797
1798
1799
1800
1801
1802
1803
1804
1805
1806
1807
1808
1809
1810
1811
1812
1813
1814
1815
1816
1817
1818
1819
1820
1821
1822
1823
1824
1825
1826
1827
1828
1829
1830
1831
1832
1833
1834
1835
1836
1837
1838
1839
1840
1841
1842
1843
1844
1845
1846
1847
1848
1849
1850
1851
1852
1853
1854
1855
1856
1857
1858
1859
1860
1861
1862
1863
1864
1865
1866
1867
1868
1869
1870
1871
1872
1873
1874
1875
1876
1877
1878
1879
1880
1881
1882
1883
1884
1885
1886
1887
1888
1889
1890
1891
1892
1893
1894
1895
1896
1897
1898
1899
1900
1901
1902
1903
1904
1905
1906
1907
1908
1909
1910
1911
1912
1913
1914
1915
1916
1917
1918
1919
1920
1921
1922
1923
1924
1925
1926
1927
1928
1929
1930
1931
1932
1933
1934
1935
1936
1937
1938
1939
1940
1941
1942
1943
1944
1945
1946
1947
1948
1949
1950
1951
1952
1953
1954
1955
1956
1957
1958
1959
1960
1961
1962
1963
1964
1965
1966
1967
1968
1969
1970
1971
1972
1973
1974
1975
1976
1977
1978
1979
1980
1981
1982
1983
1984
1985
1986
1987
1988
1989
1990
1991
1992
1993
1994
1995
1996
1997
1998
1999
2000
2001
2002
2003
2004
2005
2006
2007
2008
2009
2010
2011
2012
2013
2014
2015
2016
2017
2018
2019
2020
2021
2022
2023
2024
2025
2026
2027
2028
2029
2030
2031
2032
2033
2034
2035
2036
2037
2038
2039
2040
2041
2042
2043
2044
2045
2046
2047
2048
2049
2050
2051
2052
2053
2054
2055
2056
2057
2058
2059
2060
2061
2062
2063
2064
2065
2066
2067
2068
2069
2070
2071
2072
2073
2074
2075
2076
2077
2078
2079
2080
2081
2082
2083
2084
2085
2086
2087
2088
2089
2090
2091
2092
2093
2094
2095
2096
2097
2098
2099
2100
2101
2102
2103
2104
2105
2106
2107
2108
2109
2110
2111
2112
2113
2114
2115
2116
2117
2118
2119
2120
2121
2122
2123
2124
2125
2126
2127
2128
2129
2130
2131
2132
2133
2134
2135
2136
2137
2138
2139
2140
2141
2142
2143
2144
2145
2146
2147
2148
2149
2150
2151
2152
2153
2154
2155
2156
2157
2158
2159
2160
2161
2162
2163
2164
2165
2166
2167
2168
2169
2170
2171
2172
2173
2174
2175
2176
2177
2178
2179
2180
2181
2182
2183
2184
2185
2186
2187
2188
2189
2190
2191
2192
2193
2194
2195
2196
2197
2198
2199
2200
2201
2202
2203
2204
2205
2206
2207
2208
2209
2210
2211
2212
2213
2214
2215
2216
2217
2218
2219
2220
2221
2222
2223
2224
2225
2226
2227
2228
2229
2230
2231
2232
2233
2234
2235
2236
2237
2238
2239
2240
2241
2242
2243
2244
2245
2246
2247
2248
2249
2250
2251
2252
2253
2254
2255
2256
2257
2258
2259
2260
2261
2262
2263
2264
2265
2266
2267
2268
2269
2270
2271
2272
2273
2274
2275
2276
2277
2278
2279
2280
2281
2282
2283
2284
2285
2286
2287
2288
2289
2290
2291
2292
2293
2294
2295
2296
2297
2298
2299
2300
2301
2302
2303
2304
2305
2306
2307
2308
2309
2310
2311
2312
2313
2314
2315
2316
2317
2318
2319
2320
2321
2322
2323
2324
2325
2326
2327
2328
2329
2330
2331
2332
2333
2334
2335
2336
2337
2338
2339
2340
2341
2342
2343
2344
2345
2346
2347
2348
2349
2350
2351
2352
2353
2354
2355
2356
2357
2358
2359
2360
2361
2362
2363
2364
2365
2366
2367
2368
2369
2370
2371
2372
2373
2374
2375
2376
2377
2378
2379
2380
2381
2382
2383
2384
2385
2386
2387
2388
2389
2390
2391
2392
2393
2394
2395
2396
2397
2398
2399
2400
2401
2402
2403
2404
2405
2406
2407
2408
2409
2410
2411
2412
2413
2414
2415
2416
2417
2418
2419
2420
2421
2422
2423
2424
2425
2426
2427
2428
2429
2430
2431
2432
2433
2434
2435
2436
2437
2438
2439
2440
2441
2442
2443
2444
2445
2446
2447
2448
2449
2450
2451
2452
2453
2454
2455
2456
2457
2458
2459
2460
2461
2462
2463
2464
2465
2466
2467
2468
2469
2470
2471
2472
2473
2474
2475
2476
2477
2478
2479
2480
2481
2482
2483
2484
2485
2486
2487
2488
2489
2490
2491
2492
2493
2494
2495
2496
2497
2498
2499
2500
2501
2502
2503
2504
2505
2506
2507
2508
2509
2510
2511
2512
2513
2514
2515
2516
2517
2518
2519
2520
2521
2522
2523
2524
2525
2526
2527
2528
2529
2530
2531
2532
2533
2534
2535
2536
2537
2538
2539
2540
2541
2542
2543
2544
2545
2546
2547
2548
2549
2550
2551
2552
2553
2554
2555
2556
2557
2558
2559
2560
2561
2562
2563
2564
2565
2566
2567
2568
2569
2570
2571
2572
2573
2574
2575
2576
2577
2578
2579
2580
2581
2582
2583
2584
2585
2586
2587
2588
2589
2590
2591
2592
2593
2594
2595
2596
2597
2598
2599
2600
2601
2602
2603
2604
2605
2606
2607
2608
2609
2610
2611
2612
2613
2614
2615
2616
2617
2618
2619
2620
2621
2622
2623
2624
2625
2626
2627
2628
2629
2630
2631
2632
2633
2634
2635
2636
2637
2638
2639
2640
2641
2642
2643
2644
2645
2646
2647
2648
2649
2650
2651
2652
2653
2654
2655
2656
2657
2658
2659
2660
2661
2662
2663
2664
2665
2666
2667
2668
2669
2670
2671
2672
2673
2674
2675
2676
2677
2678
2679
2680
2681
2682
2683
2684
2685
2686
2687
2688
2689
2690
2691
2692
2693
2694
2695
2696
2697
2698
2699
2700
2701
2702
2703
2704
2705
2706
2707
2708
2709
2710
2711
2712
2713
2714
2715
2716
2717
2718
2719
2720
2721
2722
2723
2724
2725
2726
2727
2728
2729
2730
2731
2732
2733
2734
2735
2736
2737
2738
2739
2740
2741
2742
2743
2744
2745
2746
2747
2748
2749
2750
2751
2752
2753
2754
2755
2756
2757
2758
2759
2760
2761
2762
2763
2764
2765
2766
2767
2768
2769
2770
2771
2772
2773
2774
2775
2776
2777
2778
2779
2780
2781
2782
2783
2784
2785
2786
2787
2788
2789
2790
2791
2792
2793
2794
2795
2796
2797
2798
2799
2800
2801
2802
2803
2804
2805
2806
2807
2808
2809
2810
2811
2812
2813
2814
2815
2816
2817
2818
2819
2820
2821
2822
2823
2824
2825
2826
2827
2828
2829
2830
2831
2832
2833
2834
2835
2836
2837
2838
2839
2840
2841
2842
2843
2844
2845
2846
2847
2848
2849
2850
2851
2852
2853
2854
2855
2856
2857
2858
2859
2860
2861
2862
2863
2864
2865
2866
2867
2868
2869
2870
2871
2872
2873
2874
2875
2876
2877
2878
2879
2880
2881
2882
2883
2884
2885
2886
2887
2888
2889
2890
2891
2892
2893
2894
2895
2896
2897
2898
2899
2900
2901
2902
2903
2904
2905
2906
2907
2908
2909
2910
2911
2912
2913
2914
2915
2916
2917
2918
2919
2920
2921
2922
2923
2924
2925
2926
2927
2928
2929
2930
2931
2932
2933
2934
2935
2936
2937
2938
2939
2940
2941
2942
2943
2944
2945
2946
2947
2948
2949
2950
2951
2952
2953
2954
2955
2956
2957
2958
2959
2960
2961
2962
2963
2964
2965
2966
2967
2968
2969
2970
2971
2972
2973
2974
2975
2976
2977
2978
2979
2980
2981
2982
2983
2984
2985
2986
2987
2988
2989
2990
2991
2992
2993
2994
2995
2996
2997
2998
2999
3000
3001
3002
3003
3004
3005
3006
3007
3008
3009
3010
3011
3012
3013
3014
3015
3016
3017
3018
3019
3020
3021
3022
3023
3024
3025
3026
3027
3028
3029
3030
3031
3032
3033
3034
3035
3036
3037
3038
3039
3040
3041
3042
3043
3044
3045
3046
3047
3048
3049
3050
3051
3052
3053
3054
3055
3056
3057
3058
3059
3060
3061
3062
3063
3064
3065
3066
3067
3068
3069
3070
3071
3072
3073
3074
3075
3076
3077
3078
3079
3080
3081
3082
3083
3084
3085
3086
3087
3088
3089
3090
3091
3092
3093
3094
3095
3096
3097
3098
3099
3100
3101
3102
3103
3104
3105
3106
3107
3108
3109
3110
3111
3112
3113
3114
3115
3116
3117
3118
3119
3120
3121
3122
3123
3124
3125
3126
3127
3128
3129
3130
3131
3132
3133
3134
3135
3136
3137
3138
3139
3140
3141
3142
3143
3144
3145
3146
3147
3148
3149
3150
3151
3152
3153
3154
3155
3156
3157
3158
3159
3160
3161
3162
3163
3164
3165
3166
3167
3168
3169
3170
3171
3172
3173
3174
3175
3176
3177
3178
3179
3180
3181
3182
3183
3184
3185
3186
3187
3188
3189
3190
3191
3192
3193
3194
3195
3196
3197
3198
3199
3200
3201
3202
3203
3204
3205
3206
3207
3208
3209
3210
3211
3212
3213
3214
3215
3216
3217
3218
3219
3220
3221
3222
3223
3224
3225
3226
3227
3228
3229
3230
3231
3232
3233
3234
3235
3236
3237
3238
3239
3240
3241
3242
3243
3244
3245
3246
3247
3248
3249
3250
3251
3252
3253
3254
3255
3256
3257
3258
3259
3260
3261
3262
3263
3264
3265
3266
3267
3268
3269
3270
3271
3272
3273
3274
3275
3276
3277
3278
3279
3280
3281
3282
3283
3284
3285
3286
3287
3288
3289
3290
3291
3292
3293
3294
3295
3296
3297
3298
3299
3300
3301
3302
3303
3304
3305
3306
3307
3308
3309
3310
3311
3312
3313
3314
3315
3316
3317
3318
3319
3320
3321
3322
3323
3324
3325
3326
3327
3328
3329
3330
3331
3332
3333
3334
3335
3336
3337
3338
3339
3340
3341
3342
3343
3344
3345
3346
3347
3348
3349
3350
3351
3352
3353
3354
3355
3356
3357
3358
3359
3360
3361
3362
3363
3364
3365
3366
3367
3368
3369
3370
3371
3372
3373
3374
3375
3376
3377
3378
3379
3380
3381
3382
3383
3384
3385
3386
3387
3388
3389
3390
3391
3392
3393
3394
3395
3396
3397
3398
3399
3400
3401
3402
3403
3404
3405
3406
3407
3408
3409
3410
3411
3412
3413
3414
3415
3416
3417
3418
3419
3420
3421
3422
3423
3424
3425
3426
3427
3428
3429
3430
3431
3432
3433
3434
3435
3436
3437
3438
3439
3440
3441
3442
3443
3444
3445
3446
3447
3448
3449
3450
3451
3452
3453
3454
3455
3456
3457
3458
3459
3460
3461
3462
3463
3464
3465
3466
3467
3468
3469
3470
3471
3472
3473
3474
3475
3476
3477
3478
3479
3480
3481
3482
3483
3484
3485
3486
3487
3488
3489
3490
3491
3492
3493
3494
3495
3496
3497
3498
3499
3500
3501
3502
3503
3504
3505
3506
3507
3508
3509
3510
3511
3512
3513
3514
3515
3516
3517
3518
3519
3520
3521
3522
3523
3524
3525
3526
3527
3528
3529
3530
3531
3532
3533
3534
3535
3536
3537
3538
3539
3540
3541
3542
3543
3544
3545
3546
3547
3548
3549
3550
3551
3552
3553
3554
3555
3556
3557
3558
3559
3560
3561
3562
3563
3564
3565
3566
3567
3568
3569
3570
3571
3572
3573
3574
3575
3576
3577
3578
3579
3580
3581
3582
3583
3584
3585
3586
3587
3588
3589
3590
3591
3592
3593
3594
3595
3596
3597
3598
3599
3600
3601
3602
3603
3604
3605
3606
3607
3608
3609
3610
3611
3612
3613
3614
3615
3616
3617
3618
3619
3620
3621
3622
3623
3624
3625
3626
3627
3628
3629
3630
3631
3632
3633
3634
3635
3636
3637
3638
3639
3640
3641
3642
3643
3644
3645
3646
3647
3648
3649
3650
3651
3652
3653
3654
3655
3656
3657
3658
3659
3660
3661
3662
3663
3664
3665
3666
3667
3668
3669
3670
3671
3672
3673
3674
3675
3676
3677
3678
3679
3680
3681
3682
3683
3684
3685
3686
3687
3688
3689
3690
3691
3692
3693
3694
3695
3696
3697
3698
3699
3700
3701
3702
3703
3704
3705
3706
3707
3708
3709
3710
3711
3712
3713
3714
3715
3716
3717
3718
3719
3720
3721
3722
3723
3724
3725
3726
3727
3728
3729
3730
3731
3732
3733
3734
3735
3736
3737
3738
3739
3740
3741
3742
3743
3744
3745
3746
3747
3748
3749
3750
3751
3752
3753
3754
3755
3756
3757
3758
3759
3760
3761
3762
3763
3764
3765
3766
3767
3768
3769
3770
3771
3772
3773
3774
3775
3776
3777
3778
3779
3780
3781
3782
3783
3784
3785
3786
3787
3788
3789
3790
3791
3792
3793
3794
3795
3796
3797
3798
3799
3800
3801
3802
3803
3804
3805
3806
3807
3808
3809
3810
3811
3812
3813
3814
3815
3816
3817
3818
3819
3820
3821
3822
3823
3824
3825
3826
3827
3828
3829
3830
3831
3832
3833
3834
3835
3836
3837
3838
3839
3840
3841
3842
3843
3844
3845
3846
3847
3848
3849
3850
3851
3852
3853
3854
3855
3856
3857
3858
3859
3860
3861
3862
3863
3864
3865
3866
3867
3868
3869
3870
3871
3872
3873
3874
3875
3876
3877
3878
3879
3880
3881
3882
3883
3884
3885
3886
3887
3888
3889
3890
3891
3892
3893
3894
3895
3896
3897
3898
3899
3900
3901
3902
3903
3904
3905
3906
3907
3908
3909
3910
3911
3912
3913
3914
3915
3916
3917
3918
3919
3920
3921
3922
3923
3924
3925
3926
3927
3928
3929
3930
3931
3932
3933
3934
3935
3936
3937
3938
3939
3940
3941
3942
3943
3944
3945
3946
3947
3948
3949
3950
3951
3952
3953
3954
3955
3956
3957
3958
3959
3960
3961
3962
3963
3964
3965
3966
3967
3968
3969
3970
3971
3972
3973
3974
3975
3976
3977
3978
3979
3980
3981
3982
3983
3984
3985
3986
3987
3988
3989
3990
3991
3992
3993
3994
3995
3996
3997
3998
3999
4000
4001
4002
4003
4004
4005
4006
4007
4008
4009
4010
4011
4012
4013
4014
4015
4016
4017
4018
4019
4020
4021
4022
4023
4024
4025
4026
4027
4028
4029
4030
4031
4032
4033
4034
4035
4036
4037
4038
4039
4040
4041
4042
4043
4044
4045
4046
4047
4048
4049
4050
4051
4052
4053
4054
4055
4056
4057
4058
4059
4060
4061
4062
4063
4064
4065
4066
4067
4068
4069
4070
4071
4072
4073
4074
4075
4076
4077
4078
4079
4080
4081
4082
4083
4084
4085
4086
4087
4088
4089
4090
4091
4092
4093
4094
4095
4096
4097
4098
4099
4100
4101
4102
4103
4104
4105
4106
4107
4108
4109
4110
4111
4112
4113
4114
4115
4116
4117
4118
4119
4120
4121
4122
4123
4124
4125
4126
4127
4128
4129
4130
4131
4132
4133
4134
4135
4136
4137
4138
4139
4140
4141
4142
4143
4144
4145
4146
4147
4148
4149
4150
4151
4152
4153
4154
4155
4156
4157
4158
4159
4160
4161
4162
4163
4164
4165
4166
4167
4168
4169
4170
4171
4172
4173
4174
4175
4176
4177
4178
4179
4180
4181
4182
4183
4184
4185
4186
4187
4188
4189
4190
4191
4192
4193
4194
4195
4196
4197
4198
4199
4200
4201
4202
4203
4204
4205
4206
4207
4208
4209
4210
4211
4212
4213
4214
4215
4216
4217
4218
4219
4220
4221
4222
4223
4224
4225
4226
4227
4228
4229
4230
4231
4232
4233
4234
4235
4236
4237
4238
4239
4240
4241
4242
4243
4244
4245
4246
4247
4248
4249
4250
4251
4252
4253
4254
4255
4256
4257
4258
4259
4260
4261
4262
4263
4264
4265
4266
4267
4268
4269
4270
4271
4272
4273
4274
4275
4276
4277
4278
4279
4280
4281
4282
4283
4284
4285
4286
4287
4288
4289
4290
4291
4292
4293
4294
4295
4296
4297
4298
4299
4300
4301
4302
4303
4304
4305
4306
4307
4308
4309
4310
4311
4312
4313
4314
4315
4316
4317
4318
4319
4320
4321
4322
4323
4324
4325
4326
4327
4328
4329
4330
4331
4332
4333
4334
4335
4336
4337
4338
4339
4340
4341
4342
4343
4344
4345
4346
4347
4348
4349
4350
4351
4352
4353
4354
4355
4356
4357
4358
4359
4360
4361
4362
4363
4364
4365
4366
4367
4368
4369
4370
4371
4372
4373
4374
4375
4376
4377
4378
4379
4380
4381
4382
4383
4384
4385
4386
4387
4388
4389
4390
4391
4392
4393
4394
4395
4396
4397
4398
4399
4400
4401
4402
4403
4404
4405
4406
4407
4408
4409
4410
4411
4412
4413
4414
4415
4416
4417
4418
4419
4420
4421
4422
4423
4424
4425
4426
4427
4428
4429
4430
4431
4432
4433
4434
4435
4436
4437
4438
4439
4440
4441
4442
4443
4444
4445
4446
4447
4448
4449
4450
4451
4452
4453
4454
4455
4456
4457
4458
4459
4460
4461
4462
4463
4464
4465
4466
4467
4468
4469
4470
4471
4472
4473
4474
4475
4476
4477
4478
4479
4480
4481
4482
4483
4484
4485
4486
4487
4488
4489
4490
4491
4492
4493
4494
4495
4496
4497
4498
4499
4500
4501
4502
4503
4504
4505
4506
4507
4508
4509
4510
4511
4512
4513
4514
4515
4516
4517
4518
4519
4520
4521
4522
4523
4524
4525
4526
4527
4528
4529
4530
4531
4532
4533
4534
4535
4536
4537
4538
4539
4540
4541
4542
4543
4544
4545
4546
4547
4548
4549
4550
4551
4552
4553
4554
4555
4556
4557
4558
4559
4560
4561
4562
4563
4564
4565
4566
4567
4568
4569
4570
4571
4572
4573
4574
4575
4576
4577
4578
4579
4580
4581
4582
4583
4584
4585
4586
4587
4588
4589
4590
4591
4592
4593
4594
4595
4596
4597
4598
4599
4600
4601
4602
4603
4604
4605
4606
4607
4608
4609
4610
4611
4612
4613
4614
4615
4616
4617
4618
4619
4620
4621
4622
4623
4624
4625
4626
4627
4628
4629
4630
4631
4632
4633
4634
4635
4636
4637
4638
4639
4640
4641
4642
4643
4644
4645
4646
4647
4648
4649
4650
4651
4652
4653
4654
4655
4656
4657
4658
4659
4660
4661
4662
4663
4664
4665
4666
4667
4668
4669
4670
4671
4672
4673
4674
4675
4676
4677
4678
4679
4680
4681
4682
4683
4684
4685
4686
4687
4688
4689
4690
4691
4692
4693
4694
4695
4696
4697
4698
4699
4700
4701
4702
4703
4704
4705
4706
4707
4708
4709
4710
4711
4712
4713
4714
4715
4716
4717
4718
4719
4720
4721
4722
4723
4724
4725
4726
4727
4728
4729
4730
4731
4732
4733
4734
4735
4736
4737
4738
4739
4740
4741
4742
4743
4744
4745
4746
4747
4748
4749
4750
4751
4752
4753
4754
4755
4756
4757
4758
4759
4760
4761
4762
4763
4764
4765
4766
4767
4768
4769
4770
4771
4772
4773
4774
4775
4776
4777
4778
4779
4780
4781
4782
4783
4784
4785
4786
4787
4788
4789
4790
4791
4792
4793
4794
4795
4796
4797
4798
4799
4800
4801
4802
4803
4804
4805
4806
4807
4808
4809
4810
4811
4812
4813
4814
4815
4816
4817
4818
4819
4820
4821
4822
4823
4824
4825
4826
4827
4828
4829
4830
4831
4832
4833
4834
4835
4836
4837
4838
4839
4840
4841
4842
4843
4844
4845
4846
4847
4848
4849
4850
4851
4852
4853
4854
4855
4856
4857
4858
4859
4860
4861
4862
4863
4864
4865
4866
4867
4868
4869
4870
4871
4872
4873
4874
4875
4876
4877
4878
4879
4880
4881
4882
4883
4884
4885
4886
4887
4888
4889
4890
4891
4892
4893
4894
4895
4896
4897
4898
4899
4900
4901
4902
4903
4904
4905
4906
4907
4908
4909
4910
4911
4912
4913
4914
4915
4916
4917
4918
4919
4920
4921
4922
4923
4924
4925
4926
4927
4928
4929
4930
4931
4932
4933
4934
4935
4936
4937
4938
4939
4940
4941
4942
4943
4944
4945
4946
4947
4948
4949
4950
4951
4952
4953
4954
4955
4956
4957
4958
4959
4960
4961
4962
4963
4964
4965
4966
4967
4968
4969
4970
4971
4972
4973
4974
4975
4976
4977
4978
4979
4980
4981
4982
4983
4984
4985
4986
4987
4988
4989
4990
4991
4992
4993
4994
4995
4996
4997
4998
4999
5000
5001
5002
5003
5004
5005
5006
5007
5008
5009
5010
5011
5012
5013
5014
5015
5016
5017
5018
5019
5020
5021
5022
5023
5024
5025
5026
5027
5028
5029
5030
5031
5032
5033
5034
5035
5036
5037
5038
5039
5040
5041
5042
5043
5044
5045
5046
5047
5048
5049
5050
5051
5052
5053
5054
5055
5056
5057
5058
5059
5060
5061
5062
5063
5064
5065
5066
5067
5068
5069
5070
5071
5072
5073
5074
5075
5076
5077
5078
5079
5080
5081
5082
5083
5084
5085
5086
5087
5088
5089
5090
5091
5092
5093
5094
5095
5096
5097
5098
5099
5100
5101
5102
5103
5104
5105
5106
5107
5108
5109
5110
5111
5112
5113
5114
5115
5116
5117
5118
5119
5120
5121
5122
5123
5124
5125
5126
5127
5128
5129
5130
5131
5132
5133
5134
5135
5136
5137
5138
5139
5140
5141
5142
5143
5144
5145
5146
5147
5148
5149
5150
5151
5152
5153
5154
5155
5156
5157
5158
5159
5160
5161
5162
5163
5164
5165
5166
5167
5168
5169
5170
5171
5172
5173
5174
5175
5176
5177
5178
5179
5180
5181
5182
5183
5184
5185
5186
5187
5188
5189
5190
5191
5192
5193
5194
5195
5196
5197
5198
5199
5200
5201
5202
5203
5204
5205
5206
5207
5208
5209
5210
5211
5212
5213
5214
5215
5216
5217
5218
5219
5220
5221
5222
5223
5224
5225
5226
5227
5228
5229
5230
5231
5232
5233
5234
5235
5236
5237
5238
5239
5240
5241
5242
5243
5244
5245
5246
5247
5248
5249
5250
5251
5252
5253
5254
5255
5256
5257
5258
5259
5260
5261
5262
5263
5264
5265
5266
5267
5268
5269
5270
5271
5272
5273
5274
5275
5276
5277
5278
5279
5280
5281
5282
5283
5284
5285
5286
5287
5288
5289
5290
5291
5292
5293
5294
5295
5296
5297
5298
5299
5300
5301
5302
5303
5304
5305
5306
5307
5308
5309
5310
5311
5312
5313
5314
5315
5316
5317
5318
5319
5320
5321
5322
5323
5324
5325
5326
5327
5328
5329
5330
5331
5332
5333
5334
5335
5336
5337
5338
5339
5340
5341
5342
5343
5344
5345
5346
5347
5348
5349
5350
5351
5352
5353
5354
5355
5356
5357
5358
5359
5360
5361
5362
5363
5364
5365
5366
5367
5368
5369
5370
5371
5372
5373
5374
5375
5376
5377
5378
5379
5380
5381
5382
5383
5384
5385
5386
5387
5388
5389
5390
5391
5392
5393
5394
5395
5396
5397
5398
5399
5400
5401
5402
5403
5404
5405
5406
5407
5408
5409
5410
5411
5412
5413
5414
5415
5416
5417
5418
5419
5420
5421
5422
5423
5424
5425
5426
5427
5428
5429
5430
5431
5432
5433
5434
5435
5436
5437
5438
5439
5440
5441
5442
5443
5444
5445
5446
5447
5448
5449
5450
5451
5452
5453
5454
5455
5456
5457
5458
5459
5460
5461
5462
5463
5464
5465
5466
5467
5468
5469
5470
5471
5472
5473
5474
5475
5476
5477
5478
5479
5480
5481
5482
5483
5484
5485
5486
5487
5488
5489
5490
5491
5492
5493
5494
5495
5496
5497
5498
5499
5500
5501
5502
5503
5504
5505
5506
5507
5508
5509
5510
5511
5512
5513
5514
5515
5516
5517
5518
5519
5520
5521
5522
5523
5524
5525
5526
5527
5528
5529
5530
5531
5532
5533
5534
5535
5536
5537
5538
5539
5540
5541
5542
5543
5544
5545
5546
5547
5548
5549
5550
5551
5552
5553
5554
5555
5556
5557
5558
5559
5560
5561
5562
5563
5564
5565
5566
5567
5568
5569
5570
5571
5572
5573
5574
5575
5576
5577
5578
5579
5580
5581
5582
5583
5584
5585
5586
5587
5588
5589
5590
5591
5592
5593
5594
5595
5596
5597
5598
5599
5600
5601
5602
5603
5604
5605
5606
5607
5608
5609
5610
5611
5612
5613
5614
5615
5616
5617
5618
5619
5620
5621
5622
5623
5624
5625
5626
5627
5628
5629
5630
5631
5632
5633
5634
5635
5636
5637
5638
5639
5640
5641
5642
5643
5644
5645
5646
5647
5648
5649
5650
5651
5652
5653
5654
5655
5656
5657
5658
5659
5660
5661
5662
5663
5664
5665
5666
5667
5668
5669
5670
5671
5672
5673
5674
5675
5676
5677
5678
5679
5680
5681
5682
5683
5684
5685
5686
5687
5688
5689
5690
5691
5692
5693
5694
5695
5696
5697
5698
5699
5700
5701
5702
5703
5704
5705
5706
5707
5708
5709
5710
5711
5712
5713
5714
5715
5716
5717
5718
5719
5720
5721
5722
5723
5724
5725
5726
5727
5728
5729
5730
5731
5732
5733
5734
5735
5736
5737
5738
5739
5740
5741
5742
5743
5744
5745
5746
5747
5748
5749
5750
5751
5752
5753
5754
5755
5756
5757
5758
5759
5760
5761
5762
5763
5764
5765
5766
5767
5768
5769
5770
5771
5772
5773
5774
5775
5776
5777
5778
5779
5780
5781
5782
5783
5784
5785
5786
5787
5788
5789
5790
5791
5792
5793
5794
5795
5796
5797
5798
5799
5800
5801
5802
5803
5804
5805
5806
5807
5808
5809
5810
5811
5812
5813
5814
5815
5816
5817
5818
5819
5820
5821
5822
5823
5824
5825
5826
5827
5828
5829
5830
5831
5832
5833
5834
5835
5836
5837
5838
5839
5840
5841
5842
5843
5844
5845
5846
5847
5848
5849
5850
5851
5852
5853
5854
5855
5856
5857
5858
5859
5860
5861
5862
5863
5864
5865
5866
5867
5868
5869
5870
5871
5872
5873
5874
5875
5876
5877
5878
5879
5880
5881
5882
5883
5884
5885
5886
5887
5888
5889
5890
5891
5892
5893
5894
5895
5896
5897
5898
5899
5900
5901
5902
5903
5904
5905
5906
5907
5908
5909
5910
5911
5912
5913
5914
5915
5916
5917
5918
5919
5920
5921
5922
5923
5924
5925
5926
5927
5928
5929
5930
5931
5932
5933
5934
5935
5936
5937
5938
5939
5940
5941
5942
5943
5944
5945
5946
5947
5948
5949
5950
5951
5952
5953
5954
5955
5956
5957
5958
5959
5960
5961
5962
5963
5964
5965
5966
5967
5968
5969
5970
5971
5972
5973
5974
5975
5976
5977
5978
5979
5980
5981
5982
5983
5984
5985
5986
5987
5988
5989
5990
5991
5992
5993
5994
5995
5996
5997
5998
5999
6000
6001
6002
6003
6004
6005
6006
6007
6008
6009
6010
6011
6012
6013
6014
6015
6016
6017
6018
6019
6020
6021
6022
6023
6024
6025
6026
6027
6028
6029
6030
6031
6032
6033
6034
6035
6036
6037
6038
6039
6040
6041
6042
6043
6044
6045
6046
6047
6048
6049
6050
6051
6052
6053
6054
6055
6056
6057
6058
6059
6060
6061
6062
6063
6064
6065
6066
6067
6068
6069
6070
6071
6072
6073
6074
6075
6076
6077
6078
6079
6080
6081
6082
6083
6084
6085
6086
6087
6088
6089
6090
6091
6092
6093
6094
6095
6096
6097
6098
6099
6100
6101
6102
6103
6104
6105
6106
6107
6108
6109
6110
6111
6112
6113
6114
6115
6116
6117
6118
6119
6120
6121
6122
6123
6124
6125
6126
6127
6128
6129
6130
6131
6132
6133
6134
6135
6136
6137
6138
6139
6140
6141
6142
6143
6144
6145
6146
6147
6148
6149
6150
6151
6152
6153
6154
6155
6156
6157
6158
6159
6160
6161
6162
6163
6164
6165
6166
6167
6168
6169
6170
6171
6172
6173
6174
6175
6176
6177
6178
6179
6180
6181
6182
6183
6184
6185
6186
6187
6188
6189
6190
6191
6192
6193
6194
6195
6196
6197
6198
6199
6200
6201
6202
6203
6204
6205
6206
6207
6208
6209
6210
6211
6212
6213
6214
6215
6216
6217
6218
6219
6220
6221
6222
6223
6224
6225
6226
6227
6228
6229
6230
6231
6232
6233
6234
6235
6236
6237
6238
6239
6240
6241
6242
6243
6244
6245
6246
6247
6248
6249
6250
6251
6252
6253
6254
6255
6256
6257
6258
6259
6260
6261
6262
6263
6264
6265
6266
6267
6268
6269
6270
6271
6272
6273
6274
6275
6276
6277
6278
6279
6280
6281
6282
6283
6284
6285
6286
6287
6288
6289
6290
6291
6292
6293
6294
6295
6296
6297
6298
6299
6300
6301
6302
6303
6304
6305
6306
6307
6308
6309
6310
6311
6312
6313
6314
6315
6316
6317
6318
6319
6320
6321
6322
6323
6324
6325
6326
6327
6328
6329
6330
6331
6332
6333
6334
6335
6336
6337
6338
6339
6340
6341
6342
6343
6344
6345
6346
6347
6348
6349
6350
6351
6352
6353
6354
6355
6356
6357
6358
6359
6360
6361
6362
6363
6364
6365
6366
6367
6368
6369
6370
6371
6372
6373
6374
6375
6376
6377
6378
6379
6380
6381
6382
6383
6384
6385
6386
6387
6388
6389
6390
6391
6392
6393
6394
6395
6396
6397
6398
6399
6400
6401
6402
6403
6404
6405
6406
6407
6408
6409
6410
6411
6412
6413
6414
6415
6416
6417
6418
6419
6420
6421
6422
6423
6424
6425
6426
6427
6428
6429
6430
6431
6432
6433
6434
6435
6436
6437
6438
6439
6440
6441
6442
6443
6444
6445
6446
6447
6448
6449
6450
6451
6452
6453
6454
6455
6456
6457
6458
6459
6460
6461
6462
6463
6464
6465
6466
6467
6468
6469
6470
6471
6472
6473
6474
6475
6476
6477
6478
6479
6480
6481
6482
6483
6484
6485
6486
6487
6488
6489
6490
6491
6492
6493
6494
6495
6496
6497
6498
6499
6500
6501
6502
6503
6504
6505
6506
6507
6508
6509
6510
6511
6512
6513
6514
6515
6516
6517
6518
6519
6520
6521
6522
6523
6524
6525
6526
6527
6528
6529
6530
6531
6532
6533
6534
6535
6536
6537
6538
6539
6540
6541
6542
6543
6544
6545
6546
6547
6548
6549
6550
6551
6552
6553
6554
6555
6556
6557
6558
6559
6560
6561
6562
6563
6564
6565
6566
6567
6568
6569
6570
6571
6572
6573
6574
6575
6576
6577
6578
6579
6580
6581
6582
6583
6584
6585
6586
6587
6588
6589
6590
6591
6592
6593
6594
6595
6596
6597
6598
6599
6600
6601
6602
6603
6604
6605
6606
6607
6608
6609
6610
6611
6612
6613
6614
6615
6616
6617
6618
6619
6620
6621
6622
6623
6624
6625
6626
6627
6628
6629
6630
6631
6632
6633
6634
6635
6636
6637
6638
6639
6640
6641
6642
6643
6644
6645
6646
6647
6648
6649
6650
6651
6652
6653
6654
6655
6656
6657
6658
6659
6660
6661
6662
6663
6664
6665
6666
6667
6668
6669
6670
6671
6672
6673
6674
6675
6676
6677
6678
6679
6680
6681
6682
6683
6684
6685
6686
6687
6688
6689
6690
6691
6692
6693
6694
6695
6696
6697
6698
6699
6700
6701
6702
6703
6704
6705
6706
6707
6708
6709
6710
6711
6712
6713
6714
6715
6716
6717
6718
6719
6720
6721
6722
6723
6724
6725
6726
6727
6728
6729
6730
6731
6732
6733
6734
6735
6736
6737
6738
6739
6740
6741
6742
6743
6744
6745
6746
6747
6748
6749
6750
6751
6752
6753
6754
6755
6756
6757
6758
6759
6760
6761
6762
6763
6764
6765
6766
6767
6768
6769
6770
6771
6772
6773
6774
6775
6776
6777
6778
6779
6780
6781
6782
6783
6784
6785
6786
6787
6788
6789
6790
6791
6792
6793
6794
6795
6796
6797
6798
6799
6800
6801
6802
6803
6804
6805
6806
6807
6808
6809
6810
6811
6812
6813
6814
6815
6816
6817
6818
6819
6820
6821
6822
6823
6824
6825
6826
6827
6828
6829
6830
6831
6832
6833
6834
6835
6836
6837
6838
6839
6840
6841
6842
6843
6844
6845
6846
6847
6848
6849
6850
6851
6852
6853
6854
6855
6856
6857
6858
6859
6860
6861
6862
6863
6864
6865
6866
6867
6868
6869
6870
6871
6872
6873
6874
6875
6876
6877
6878
6879
6880
6881
6882
6883
6884
6885
6886
6887
6888
6889
6890
6891
6892
6893
6894
6895
6896
6897
6898
6899
6900
6901
6902
6903
6904
6905
6906
6907
6908
6909
6910
6911
6912
6913
6914
6915
6916
6917
6918
6919
6920
6921
6922
6923
6924
6925
6926
6927
6928
6929
6930
6931
6932
6933
6934
6935
6936
6937
6938
6939
6940
6941
6942
6943
6944
6945
6946
6947
6948
6949
6950
6951
6952
6953
6954
6955
6956
6957
6958
6959
6960
6961
6962
6963
6964
6965
6966
6967
6968
6969
6970
6971
6972
6973
6974
6975
6976
6977
6978
6979
6980
6981
6982
6983
6984
6985
6986
6987
6988
6989
6990
6991
6992
6993
6994
6995
6996
6997
6998
6999
7000
7001
7002
7003
7004
7005
7006
7007
7008
7009
7010
7011
7012
7013
7014
7015
7016
7017
7018
7019
7020
7021
7022
7023
7024
7025
7026
7027
7028
7029
7030
7031
7032
7033
7034
7035
7036
7037
7038
7039
7040
7041
7042
7043
7044
7045
7046
7047
7048
7049
7050
7051
7052
7053
7054
7055
7056
7057
7058
7059
7060
7061
7062
7063
7064
7065
7066
7067
7068
7069
7070
7071
7072
7073
7074
7075
7076
7077
7078
7079
7080
7081
7082
7083
7084
7085
7086
7087
7088
7089
7090
7091
7092
7093
7094
7095
7096
7097
7098
7099
7100
7101
7102
7103
7104
7105
7106
7107
7108
7109
7110
7111
7112
7113
7114
7115
7116
7117
7118
7119
7120
7121
7122
7123
7124
7125
7126
7127
7128
7129
7130
7131
7132
7133
7134
7135
7136
7137
7138
7139
7140
7141
7142
7143
7144
7145
7146
7147
7148
7149
7150
7151
7152
7153
7154
7155
7156
7157
7158
7159
7160
7161
7162
7163
7164
7165
7166
7167
7168
7169
7170
7171
7172
7173
7174
7175
7176
7177
7178
7179
7180
7181
7182
7183
7184
7185
7186
7187
7188
7189
7190
7191
7192
7193
7194
7195
7196
7197
7198
7199
7200
7201
7202
7203
7204
7205
7206
7207
7208
7209
7210
7211
7212
7213
7214
7215
7216
7217
7218
7219
7220
7221
7222
7223
7224
7225
7226
7227
7228
7229
7230
7231
7232
7233
7234
7235
7236
7237
7238
7239
7240
7241
7242
7243
7244
7245
7246
7247
7248
7249
7250
7251
7252
7253
7254
7255
7256
7257
7258
7259
7260
7261
7262
7263
7264
7265
7266
7267
7268
7269
7270
7271
7272
7273
7274
7275
7276
7277
7278
7279
7280
7281
7282
7283
7284
7285
7286
7287
7288
7289
7290
7291
7292
7293
7294
7295
7296
7297
7298
7299
7300
7301
7302
7303
7304
7305
7306
7307
7308
7309
7310
7311
7312
7313
7314
7315
7316
7317
7318
7319
7320
7321
7322
7323
7324
7325
7326
7327
7328
7329
7330
7331
7332
7333
7334
7335
7336
7337
7338
7339
7340
7341
7342
7343
7344
7345
7346
7347
7348
7349
7350
7351
7352
7353
7354
7355
7356
7357
7358
7359
7360
7361
7362
7363
7364
7365
7366
7367
7368
7369
7370
7371
7372
7373
7374
7375
7376
7377
7378
7379
7380
7381
7382
7383
7384
7385
7386
7387
7388
7389
7390
7391
7392
7393
7394
7395
7396
7397
7398
7399
7400
7401
7402
7403
7404
7405
7406
7407
7408
7409
7410
7411
7412
7413
7414
7415
7416
7417
7418
7419
7420
7421
7422
7423
7424
7425
7426
7427
7428
7429
7430
7431
7432
7433
7434
7435
7436
7437
7438
7439
7440
7441
7442
7443
7444
7445
7446
7447
7448
7449
7450
7451
7452
7453
7454
7455
7456
7457
7458
7459
7460
7461
7462
7463
7464
7465
7466
7467
7468
7469
7470
7471
7472
7473
7474
7475
7476
7477
7478
7479
7480
7481
7482
7483
7484
7485
7486
7487
7488
7489
7490
7491
7492
7493
7494
7495
7496
7497
7498
7499
7500
7501
7502
7503
7504
7505
7506
7507
7508
7509
7510
7511
7512
7513
7514
7515
7516
7517
7518
7519
7520
7521
7522
7523
7524
7525
7526
7527
7528
7529
7530
7531
7532
7533
7534
7535
7536
7537
7538
7539
7540
7541
7542
7543
7544
7545
7546
7547
7548
7549
7550
7551
7552
7553
7554
7555
7556
7557
7558
7559
7560
7561
7562
7563
7564
7565
7566
7567
7568
7569
7570
7571
7572
7573
7574
7575
7576
7577
7578
7579
7580
7581
7582
7583
7584
7585
7586
7587
7588
7589
7590
7591
7592
7593
7594
7595
7596
7597
7598
7599
7600
7601
7602
7603
7604
7605
7606
7607
7608
7609
7610
7611
7612
7613
7614
7615
7616
7617
7618
7619
7620
7621
7622
7623
7624
7625
7626
7627
7628
7629
7630
7631
7632
7633
7634
7635
7636
7637
7638
7639
7640
7641
7642
7643
7644
7645
7646
7647
7648
7649
7650
7651
7652
7653
7654
7655
7656
7657
7658
7659
7660
7661
7662
7663
7664
7665
7666
7667
7668
7669
7670
7671
7672
7673
7674
7675
7676
7677
7678
7679
7680
7681
7682
7683
7684
7685
7686
7687
7688
7689
7690
7691
7692
7693
7694
7695
7696
7697
7698
7699
7700
7701
7702
7703
7704
7705
7706
7707
7708
7709
7710
7711
7712
7713
7714
7715
7716
7717
7718
7719
7720
7721
7722
7723
7724
7725
7726
7727
7728
7729
7730
7731
7732
7733
7734
7735
7736
7737
7738
7739
7740
7741
7742
7743
7744
7745
7746
7747
7748
7749
7750
7751
7752
7753
7754
7755
7756
7757
7758
7759
7760
7761
7762
7763
7764
7765
7766
7767
7768
7769
7770
7771
7772
7773
7774
7775
7776
7777
7778
7779
7780
7781
7782
7783
7784
7785
7786
7787
7788
7789
7790
7791
7792
7793
7794
7795
7796
7797
7798
7799
7800
7801
7802
7803
7804
7805
7806
7807
7808
7809
7810
7811
7812
7813
7814
7815
7816
7817
7818
7819
7820
7821
7822
7823
7824
7825
7826
7827
7828
7829
7830
7831
7832
7833
7834
7835
7836
7837
7838
7839
7840
7841
7842
7843
7844
7845
7846
7847
7848
7849
7850
7851
7852
7853
7854
7855
7856
7857
7858
7859
7860
7861
7862
7863
7864
7865
7866
7867
7868
7869
7870
7871
7872
7873
7874
7875
7876
7877
7878
7879
7880
7881
7882
7883
7884
7885
7886
7887
7888
7889
7890
7891
7892
7893
7894
7895
7896
7897
7898
7899
7900
7901
7902
7903
7904
7905
7906
7907
7908
7909
7910
7911
7912
7913
7914
7915
7916
7917
7918
7919
7920
7921
7922
7923
7924
7925
7926
7927
7928
7929
7930
7931
7932
7933
7934
7935
7936
7937
7938
7939
7940
7941
7942
7943
7944
7945
7946
7947
7948
7949
7950
7951
7952
7953
7954
7955
7956
7957
7958
7959
7960
7961
7962
7963
7964
7965
7966
7967
7968
7969
7970
7971
7972
7973
7974
7975
7976
7977
7978
7979
7980
7981
7982
7983
7984
7985
7986
7987
7988
7989
7990
7991
7992
7993
7994
7995
7996
7997
7998
7999
8000
8001
8002
8003
8004
8005
8006
8007
8008
8009
8010
8011
8012
8013
8014
8015
8016
8017
8018
8019
8020
8021
8022
8023
8024
8025
8026
8027
8028
8029
8030
8031
8032
8033
8034
8035
8036
8037
8038
8039
8040
8041
8042
8043
8044
8045
8046
8047
8048
8049
8050
8051
8052
8053
8054
8055
8056
8057
8058
8059
8060
8061
8062
8063
8064
8065
8066
8067
8068
8069
8070
8071
8072
8073
8074
8075
8076
8077
8078
8079
8080
8081
8082
8083
8084
8085
8086
8087
8088
8089
8090
8091
8092
8093
8094
8095
8096
8097
8098
8099
8100
8101
8102
8103
8104
8105
8106
8107
8108
8109
8110
8111
8112
8113
8114
8115
8116
8117
8118
8119
8120
8121
8122
8123
8124
8125
8126
8127
8128
8129
8130
8131
8132
8133
8134
8135
8136
8137
8138
8139
8140
8141
8142
8143
8144
8145
8146
8147
8148
8149
8150
8151
8152
8153
8154
8155
8156
8157
8158
8159
8160
8161
8162
8163
8164
8165
8166
8167
8168
8169
8170
8171
8172
8173
8174
8175
8176
8177
8178
8179
8180
8181
8182
8183
8184
8185
8186
8187
8188
8189
8190
8191
8192
8193
8194
8195
8196
8197
8198
8199
8200
8201
8202
8203
8204
8205
8206
8207
8208
8209
8210
8211
8212
8213
8214
8215
8216
8217
8218
8219
8220
8221
8222
8223
8224
8225
8226
8227
8228
8229
8230
8231
8232
8233
8234
8235
8236
8237
8238
8239
8240
8241
8242
8243
8244
8245
8246
8247
8248
8249
8250
8251
8252
8253
8254
8255
8256
8257
8258
8259
8260
8261
8262
8263
8264
8265
8266
8267
8268
8269
8270
8271
8272
8273
8274
8275
8276
8277
8278
8279
8280
8281
8282
8283
8284
8285
8286
8287
8288
8289
8290
8291
8292
8293
8294
8295
8296
8297
8298
8299
8300
8301
8302
8303
8304
8305
8306
8307
8308
8309
8310
8311
8312
8313
8314
8315
8316
8317
8318
8319
8320
8321
8322
8323
8324
8325
8326
8327
8328
8329
8330
8331
8332
8333
8334
8335
8336
8337
8338
8339
8340
8341
8342
8343
8344
8345
8346
8347
8348
8349
8350
8351
8352
8353
8354
8355
8356
8357
8358
8359
8360
8361
8362
8363
8364
8365
8366
8367
8368
8369
8370
8371
8372
8373
8374
8375
8376
8377
8378
8379
8380
8381
8382
8383
8384
8385
8386
8387
8388
8389
8390
8391
8392
8393
8394
8395
8396
8397
8398
8399
8400
8401
8402
8403
8404
8405
8406
8407
8408
8409
8410
8411
8412
8413
8414
8415
8416
8417
8418
8419
8420
8421
8422
8423
8424
8425
8426
8427
8428
8429
8430
8431
8432
8433
8434
8435
8436
8437
8438
8439
8440
8441
8442
8443
8444
8445
8446
8447
8448
8449
8450
8451
8452
8453
8454
8455
8456
8457
8458
8459
8460
8461
8462
8463
8464
8465
8466
8467
8468
8469
8470
8471
8472
8473
8474
8475
8476
8477
8478
8479
8480
8481
8482
8483
8484
8485
8486
8487
8488
8489
8490
8491
8492
8493
8494
8495
8496
8497
8498
8499
8500
8501
8502
8503
8504
8505
8506
8507
8508
8509
8510
8511
8512
8513
8514
8515
8516
8517
8518
8519
8520
8521
8522
8523
8524
8525
8526
8527
8528
8529
8530
8531
8532
8533
8534
8535
8536
8537
8538
8539
8540
8541
8542
8543
8544
8545
8546
8547
8548
8549
8550
8551
8552
8553
8554
8555
8556
8557
8558
8559
8560
8561
8562
8563
8564
8565
8566
8567
8568
8569
8570
8571
8572
8573
8574
8575
8576
8577
8578
8579
8580
8581
8582
8583
8584
8585
8586
8587
8588
8589
8590
8591
8592
8593
8594
8595
8596
8597
8598
8599
8600
8601
8602
8603
8604
8605
8606
8607
8608
8609
8610
8611
8612
8613
8614
8615
8616
8617
8618
8619
8620
8621
8622
8623
8624
8625
8626
8627
8628
8629
8630
8631
8632
8633
8634
8635
8636
8637
8638
8639
8640
8641
8642
8643
8644
8645
8646
8647
8648
8649
8650
8651
8652
8653
8654
8655
8656
8657
8658
8659
8660
8661
8662
8663
8664
8665
8666
8667
8668
8669
8670
8671
8672
8673
8674
8675
8676
8677
8678
8679
8680
8681
8682
8683
8684
8685
8686
8687
8688
8689
8690
8691
8692
8693
8694
8695
8696
8697
8698
8699
8700
8701
8702
8703
8704
8705
8706
8707
8708
8709
8710
8711
8712
8713
8714
8715
8716
8717
8718
8719
8720
8721
8722
8723
8724
8725
8726
8727
8728
8729
8730
8731
8732
8733
8734
8735
8736
8737
8738
8739
8740
8741
8742
8743
8744
8745
8746
8747
8748
8749
8750
8751
8752
8753
8754
8755
8756
8757
8758
8759
8760
8761
8762
8763
8764
8765
8766
8767
8768
8769
8770
8771
8772
8773
8774
8775
8776
8777
8778
8779
8780
8781
8782
8783
8784
8785
8786
8787
8788
8789
8790
8791
8792
8793
8794
8795
8796
8797
8798
8799
8800
8801
8802
8803
8804
8805
8806
8807
8808
8809
8810
8811
8812
8813
8814
8815
8816
8817
8818
8819
8820
8821
8822
8823
8824
8825
8826
8827
8828
8829
8830
8831
8832
8833
8834
8835
8836
8837
8838
8839
8840
8841
8842
8843
8844
8845
8846
8847
8848
8849
8850
8851
8852
8853
8854
8855
8856
8857
8858
8859
8860
8861
8862
8863
8864
8865
8866
8867
8868
8869
8870
8871
8872
8873
8874
8875
8876
8877
8878
8879
8880
8881
8882
8883
8884
8885
8886
8887
8888
8889
8890
8891
8892
8893
8894
8895
8896
8897
8898
8899
8900
8901
8902
8903
8904
8905
8906
8907
8908
8909
8910
8911
8912
8913
8914
8915
8916
8917
8918
8919
8920
8921
8922
8923
8924
8925
8926
8927
8928
8929
8930
8931
8932
8933
8934
8935
8936
8937
8938
8939
8940
8941
8942
8943
8944
8945
8946
8947
8948
8949
8950
8951
8952
8953
8954
8955
8956
8957
8958
8959
8960
8961
8962
8963
8964
8965
8966
8967
8968
8969
8970
8971
8972
8973
8974
8975
8976
8977
8978
8979
8980
8981
8982
8983
8984
8985
8986
8987
8988
8989
8990
8991
8992
8993
8994
8995
8996
8997
8998
8999
9000
9001
9002
9003
9004
9005
9006
9007
9008
9009
9010
9011
9012
9013
9014
9015
9016
9017
9018
9019
9020
9021
9022
9023
9024
9025
9026
9027
9028
9029
9030
9031
9032
9033
9034
9035
9036
9037
9038
9039
9040
9041
9042
9043
9044
9045
9046
9047
9048
9049
9050
9051
9052
9053
9054
9055
9056
9057
9058
9059
9060
9061
9062
9063
9064
9065
9066
9067
9068
9069
9070
9071
9072
9073
9074
9075
9076
9077
9078
9079
9080
9081
9082
9083
9084
9085
9086
9087
9088
9089
9090
9091
9092
9093
9094
9095
9096
9097
9098
9099
9100
9101
9102
9103
9104
9105
9106
9107
9108
9109
9110
9111
9112
9113
9114
9115
9116
9117
9118
9119
9120
9121
9122
9123
9124
9125
9126
9127
9128
9129
9130
9131
9132
9133
9134
9135
9136
9137
9138
9139
9140
9141
9142
9143
9144
9145
9146
9147
9148
9149
9150
9151
9152
9153
9154
9155
9156
9157
9158
9159
9160
9161
9162
9163
9164
9165
9166
9167
9168
9169
9170
9171
9172
9173
9174
9175
9176
9177
9178
9179
9180
9181
9182
9183
9184
9185
9186
9187
9188
9189
9190
9191
9192
9193
9194
9195
9196
9197
9198
9199
9200
9201
9202
9203
9204
9205
9206
9207
9208
9209
9210
9211
9212
9213
9214
9215
9216
9217
9218
9219
9220
9221
9222
9223
9224
9225
9226
9227
9228
9229
9230
9231
9232
9233
9234
9235
9236
9237
9238
9239
9240
9241
9242
9243
9244
9245
9246
9247
9248
9249
9250
9251
9252
9253
9254
9255
9256
9257
9258
9259
9260
9261
9262
9263
9264
9265
9266
9267
9268
9269
9270
9271
9272
9273
9274
9275
9276
9277
9278
9279
9280
9281
9282
9283
9284
9285
9286
9287
9288
9289
9290
9291
9292
9293
9294
9295
9296
9297
9298
9299
9300
9301
9302
9303
9304
9305
9306
9307
9308
9309
9310
9311
9312
9313
9314
9315
9316
9317
9318
9319
9320
9321
9322
9323
9324
9325
9326
9327
9328
9329
9330
9331
9332
9333
9334
9335
9336
9337
9338
9339
9340
9341
9342
9343
9344
9345
9346
9347
9348
9349
9350
9351
9352
9353
9354
9355
9356
9357
9358
9359
9360
9361
9362
9363
9364
9365
9366
9367
9368
9369
9370
9371
9372
9373
9374
9375
9376
9377
9378
9379
9380
9381
9382
9383
9384
9385
9386
9387
9388
9389
9390
9391
9392
9393
9394
9395
9396
9397
9398
9399
9400
9401
9402
9403
9404
9405
9406
9407
9408
9409
9410
9411
9412
9413
9414
9415
9416
9417
9418
9419
9420
9421
9422
9423
9424
9425
9426
9427
9428
9429
9430
9431
9432
9433
9434
9435
9436
9437
9438
9439
9440
9441
9442
9443
9444
9445
9446
9447
9448
9449
9450
9451
9452
9453
9454
9455
9456
9457
9458
9459
9460
9461
9462
9463
9464
9465
9466
9467
9468
9469
9470
9471
9472
9473
9474
9475
9476
9477
9478
9479
9480
9481
9482
9483
9484
9485
9486
9487
9488
9489
9490
9491
9492
9493
9494
9495
9496
9497
9498
9499
9500
9501
9502
9503
9504
9505
9506
9507
9508
9509
9510
9511
9512
9513
9514
9515
9516
9517
9518
9519
9520
9521
9522
9523
9524
9525
9526
9527
9528
9529
9530
9531
9532
9533
9534
9535
9536
9537
9538
9539
9540
9541
9542
9543
9544
9545
9546
9547
9548
9549
9550
9551
9552
9553
9554
9555
9556
9557
9558
9559
9560
9561
9562
9563
9564
9565
9566
9567
9568
9569
9570
9571
9572
9573
9574
9575
9576
9577
9578
9579
9580
9581
9582
9583
9584
9585
9586
9587
9588
9589
9590
9591
9592
9593
9594
9595
9596
9597
9598
9599
9600
9601
9602
9603
9604
9605
9606
9607
9608
9609
9610
9611
9612
9613
9614
9615
9616
9617
9618
9619
9620
9621
9622
9623
9624
9625
9626
9627
9628
9629
9630
9631
9632
9633
9634
9635
9636
9637
9638
9639
9640
9641
9642
9643
9644
9645
9646
9647
9648
9649
9650
9651
9652
9653
9654
9655
9656
9657
9658
9659
9660
9661
9662
9663
9664
9665
9666
9667
9668
9669
9670
9671
9672
9673
9674
9675
9676
9677
9678
9679
9680
9681
9682
9683
9684
9685
9686
9687
9688
9689
9690
9691
9692
9693
9694
9695
9696
9697
9698
9699
9700
9701
9702
9703
9704
9705
9706
9707
9708
9709
9710
9711
9712
9713
9714
9715
9716
9717
9718
9719
9720
9721
9722
9723
9724
9725
9726
9727
9728
9729
9730
9731
9732
9733
9734
9735
9736
9737
9738
9739
9740
9741
9742
9743
9744
9745
9746
9747
9748
9749
9750
9751
9752
9753
9754
9755
9756
9757
9758
9759
9760
9761
9762
9763
9764
9765
9766
9767
9768
9769
9770
9771
9772
9773
9774
9775
9776
9777
9778
9779
9780
9781
9782
9783
9784
9785
9786
9787
9788
9789
9790
9791
9792
9793
9794
9795
9796
9797
9798
9799
9800
9801
9802
9803
9804
9805
9806
9807
9808
9809
9810
9811
9812
9813
9814
9815
9816
9817
9818
9819
9820
9821
9822
9823
9824
9825
9826
9827
9828
9829
9830
9831
9832
9833
9834
9835
9836
9837
9838
9839
9840
9841
9842
9843
9844
9845
9846
9847
9848
9849
9850
9851
9852
9853
9854
9855
9856
9857
9858
9859
9860
9861
9862
9863
9864
9865
9866
9867
9868
9869
9870
9871
9872
9873
9874
9875
9876
9877
9878
9879
9880
9881
9882
9883
9884
9885
9886
9887
9888
9889
9890
9891
9892
9893
9894
9895
9896
9897
9898
9899
9900
9901
9902
9903
9904
9905
9906
9907
9908
9909
9910
9911
9912
9913
9914
9915
9916
9917
9918
9919
9920
9921
9922
9923
9924
9925
9926
9927
9928
9929
9930
9931
9932
9933
9934
9935
9936
9937
9938
9939
9940
9941
9942
9943
9944
9945
9946
9947
9948
9949
9950
9951
9952
9953
9954
9955
9956
9957
9958
9959
9960
9961
9962
9963
9964
9965
9966
9967
9968
9969
9970
9971
9972
9973
9974
9975
9976
9977
9978
9979
9980
9981
9982
9983
9984
9985
9986
9987
9988
9989
9990
9991
9992
9993
9994
9995
9996
9997
9998
9999
10000
10001
10002
10003
10004
10005
10006
10007
10008
10009
10010
10011
10012
10013
10014
10015
10016
10017
10018
10019
10020
10021
10022
10023
10024
10025
10026
10027
10028
10029
10030
10031
10032
10033
10034
10035
10036
10037
10038
10039
10040
10041
10042
10043
10044
10045
10046
10047
10048
10049
10050
10051
10052
10053
10054
10055
10056
10057
10058
10059
10060
10061
10062
10063
10064
10065
10066
10067
10068
10069
10070
10071
10072
10073
10074
10075
10076
10077
10078
10079
10080
10081
10082
10083
10084
10085
10086
10087
10088
10089
10090
10091
10092
10093
10094
10095
10096
10097
10098
10099
10100
10101
10102
10103
10104
10105
10106
10107
10108
10109
10110
10111
10112
10113
10114
10115
10116
10117
10118
10119
10120
10121
10122
10123
10124
10125
10126
10127
10128
10129
10130
10131
10132
10133
10134
10135
10136
10137
10138
10139
10140
10141
10142
10143
10144
10145
10146
10147
10148
10149
10150
10151
10152
10153
10154
10155
10156
10157
10158
10159
10160
10161
10162
10163
10164
10165
10166
10167
10168
10169
10170
10171
10172
10173
10174
10175
10176
10177
10178
10179
10180
10181
10182
10183
10184
10185
10186
10187
10188
10189
10190
10191
10192
10193
10194
10195
10196
10197
10198
10199
10200
10201
10202
10203
10204
10205
10206
10207
10208
10209
10210
10211
10212
10213
10214
10215
10216
10217
10218
10219
10220
10221
10222
10223
10224
10225
10226
10227
10228
10229
10230
10231
10232
10233
10234
10235
10236
10237
10238
10239
10240
10241
10242
10243
10244
10245
10246
10247
10248
10249
10250
10251
10252
10253
10254
10255
10256
10257
10258
10259
10260
10261
10262
10263
10264
10265
10266
10267
10268
10269
10270
10271
10272
10273
10274
10275
10276
10277
10278
10279
10280
10281
10282
10283
10284
10285
10286
10287
10288
10289
10290
10291
10292
10293
10294
10295
10296
10297
10298
10299
10300
10301
10302
10303
10304
10305
10306
10307
10308
10309
10310
10311
10312
10313
10314
10315
10316
10317
10318
10319
10320
10321
10322
10323
10324
10325
10326
10327
10328
10329
10330
10331
10332
10333
10334
10335
10336
10337
10338
10339
10340
10341
10342
10343
10344
10345
10346
10347
10348
10349
10350
10351
10352
10353
10354
10355
10356
10357
10358
10359
10360
10361
10362
10363
10364
10365
10366
10367
10368
10369
10370
10371
10372
10373
10374
10375
10376
10377
10378
10379
10380
10381
10382
10383
10384
10385
10386
10387
10388
10389
10390
10391
10392
10393
10394
10395
10396
10397
10398
10399
10400
10401
10402
10403
10404
10405
10406
10407
10408
10409
10410
10411
10412
10413
10414
10415
10416
10417
10418
10419
10420
10421
10422
10423
10424
10425
10426
10427
10428
10429
10430
10431
10432
10433
10434
10435
10436
10437
10438
10439
10440
10441
10442
10443
10444
10445
10446
10447
10448
10449
10450
10451
10452
10453
10454
10455
10456
10457
10458
10459
10460
10461
10462
10463
10464
10465
10466
10467
10468
10469
10470
10471
10472
10473
10474
10475
10476
10477
//! Symbolic integration (antiderivatives).
//!
//! This module implements [`integrate`], which computes the indefinite
//! integral of an expression with respect to a symbol.
//!
//! # Supported integrands
//!
//! - **Power rule:** `∫ x^n dx = x^(n+1)/(n+1)` for n ≠ -1
//! - **Logarithmic:** `∫ x^(-1) dx = ln(|x|)`
//! - **Trigonometric:** `∫ sin(x) dx = -cos(x)`, `∫ cos(x) dx = sin(x)`
//! - **Tangent:** `∫ tan(x) dx = -ln|cos(x)|`
//! - **Natural log:** `∫ ln(x) dx = x·ln(x) - x`
//! - **Exponential:** `∫ exp(x) dx = exp(x)`
//! - **Linearity:** `∫ (f + g) dx = ∫f dx + ∫g dx`
//! - **Constant factor:** `∫ c·f dx = c · ∫f dx` (when c is independent of x)
//! - **Constants:** `∫ c dx = c·x`
//! - **Standard forms:** `∫ 1/(x²+a²) dx = (1/a)·atan(x/a)`, etc.
//! - **Partial fractions:** apart→integrate pipeline for rational integrands
//!
//! For integrands that don't match any rule, an unevaluated
//! `Integral(body, var)` node is returned.
//!
//! # Design
//!
//! Integration is computed bottom-up using an iterative post-order
//! traversal, mirroring the design of `diff.rs`. Results are
//! constructed through canonical arena constructors to preserve
//! invariants.

use rustc_hash::{FxHashMap, FxHashSet};
use smallvec::SmallVec;

use num_traits::One;
use num_traits::Signed;
use num_traits::Zero;

use crate::base::arena::{Arena, FN_CHI, FN_ERFI, FN_SHI};
use crate::base::node::{ExprId, ExprNode, SymbolId};
use crate::base::numeric::Q;
use crate::base::stage::stage;
use crate::poly::Poly;

/// Integrate `expr` with respect to `var`.
///
/// Returns the antiderivative. If integration cannot be performed,
/// returns an unevaluated `Integral(expr, var)` node.
pub(crate) fn integrate(arena: &mut Arena, expr: ExprId, var: ExprId) -> ExprId {
    let call = IntegrateCall::enter(arena);
    if call.depth > MAX_INTEGRATE_NESTING {
        tracing::debug!("integrate: nesting limit reached");
        return arena.intern(ExprNode::Integral(expr, var));
    }
    // The outermost call remembers the jumps at the poles of `tan w` for
    // all the substitutions and degenerate cases below it.
    let _jumps = crate::transforms::trig_integ::JumpMemo::enter();
    stage!(arena, "integrate", expr, integrate_impl(arena, expr, var))
}

/// Largest nesting of `integrate` calls (a substitution or a Risch tower
/// level re-enters it); a deeper call stays unevaluated.  A safety net
/// against a strategy that keeps nesting larger integrands: before 0.31's
/// guard in [`crate::calculus::risch::try_risch_tower`], the tower's
/// coefficient integrals of `∫ ln(c + d·x)/(a + b·x³) dx` nested 1,100
/// deep and overflowed the stack.
const MAX_INTEGRATE_NESTING: usize = 48;

/// One `integrate` call on this thread.  The outermost call owns the step
/// and arena budgets and the memo; nested calls (substitutions re-entering
/// the pipeline, `integrate_definite`) draw from them.  Dropping the guard
/// — also when a panic unwinds through the call, as under the Rubi
/// harness's `catch_unwind` — restores the nesting depth and, for the
/// outermost call, clears the memo, so no later call on another arena can
/// see its entries.
struct IntegrateCall {
    outermost: bool,
    /// Enclosing `integrate` calls on this thread.
    depth: usize,
}

impl IntegrateCall {
    fn enter(arena: &Arena) -> Self {
        let depth = NODE_BUDGET_DEPTH.with(|d| {
            let depth = d.get();
            d.set(depth + 1);
            depth
        });
        let outermost = depth == 0;
        if outermost {
            NODE_BUDGET_USED.with(|u| u.set(0));
            NODE_BUDGET_CAP.with(|c| c.set(usize::MAX));
            ARENA_BUDGET_START.with(|s| s.set(arena.node_count()));
            INTEGRATE_MEMO.with(|m| m.borrow_mut().clear());
            VERDICT_MEMO.with(|m| m.borrow_mut().clear());
            CLEARED_MEMO.with(|m| m.borrow_mut().clear());
            VARIES_MEMO.with(|m| m.borrow_mut().clear());
        }
        IntegrateCall { outermost, depth }
    }
}

impl Drop for IntegrateCall {
    fn drop(&mut self) {
        let _ = NODE_BUDGET_DEPTH.try_with(|d| d.set(d.get().saturating_sub(1)));
        if self.outermost {
            let _ = INTEGRATE_MEMO.try_with(|m| {
                if let Ok(mut m) = m.try_borrow_mut() {
                    m.clear();
                }
            });
            let _ = VERDICT_MEMO.try_with(|m| {
                if let Ok(mut m) = m.try_borrow_mut() {
                    m.clear();
                }
            });
            let _ = CLEARED_MEMO.try_with(|m| {
                if let Ok(mut m) = m.try_borrow_mut() {
                    m.clear();
                }
            });
            let _ = VARIES_MEMO.try_with(|m| {
                if let Ok(mut m) = m.try_borrow_mut() {
                    m.clear();
                }
            });
        }
    }
}

/// Upper bound on `integrate_node` calls for one top-level `integrate`.
/// Every successful integration in the test suite (≈ 4 000 of them) takes
/// at most ~600; a failing search can branch much further before it gives
/// up — `∫ x·ln(x + sin 2) dx` made 524 540 calls (12 s) to return the
/// unevaluated form.  At the cap the remaining sub-integrals stay
/// unevaluated, which the callers already treat as "no closed form".
const INTEGRATE_NODE_BUDGET: usize = 20_000;

/// Upper bound on the arena nodes one top-level `integrate` may create.
/// Successful integrations of the Rubi suite and the test suite stay far
/// below it; a search that keeps building larger candidates (as the
/// complex partial fractions of `∫ x³/(x⁸ + 1) dx` did in 0.24, past 8 GB)
/// stops here and leaves the remaining sub-integrals unevaluated, so no
/// integrand can exhaust memory through the arena.
const INTEGRATE_ARENA_BUDGET: usize = 2_000_000;

thread_local! {
    static NODE_BUDGET_DEPTH: std::cell::Cell<usize> = const { std::cell::Cell::new(0) };
    static NODE_BUDGET_USED: std::cell::Cell<usize> = const { std::cell::Cell::new(0) };
    static ARENA_BUDGET_START: std::cell::Cell<usize> = const { std::cell::Cell::new(0) };
    /// The step count at which the current [`StepCap`] ends (`usize::MAX`:
    /// none).
    static NODE_BUDGET_CAP: std::cell::Cell<usize> = const { std::cell::Cell::new(usize::MAX) };
}

/// A bound of `steps` further `integrate_node` steps on a nested
/// computation, within the top-level budget; the previous bound is
/// restored on drop (also when a panic unwinds).  While one is active, a
/// failure is not remembered in `INTEGRATE_MEMO`: it may be the bound's.
struct StepCap(usize);

impl StepCap {
    fn enter(steps: usize) -> Self {
        let used = NODE_BUDGET_USED.with(std::cell::Cell::get);
        let old = NODE_BUDGET_CAP.with(|c| {
            let old = c.get();
            c.set(old.min(used.saturating_add(steps)));
            old
        });
        StepCap(old)
    }

    fn active() -> bool {
        NODE_BUDGET_CAP.with(std::cell::Cell::get) != usize::MAX
    }
}

impl Drop for StepCap {
    fn drop(&mut self) {
        let _ = NODE_BUDGET_CAP.try_with(|c| c.set(self.0));
    }
}

/// Has the outermost `integrate` created more than
/// [`INTEGRATE_ARENA_BUDGET`] arena nodes?
fn arena_budget_exhausted(arena: &Arena) -> bool {
    let start = ARENA_BUDGET_START.with(std::cell::Cell::get);
    let exhausted = arena.node_count().saturating_sub(start) > INTEGRATE_ARENA_BUDGET;
    if exhausted {
        tracing::debug!("integrate: arena budget exhausted");
    }
    exhausted
}

/// Charge one `integrate_node` step; `true` once the budget is spent.
fn node_budget_exhausted() -> bool {
    NODE_BUDGET_USED.with(|u| {
        let used = u.get() + 1;
        u.set(used);
        used > INTEGRATE_NODE_BUDGET || used > NODE_BUDGET_CAP.with(std::cell::Cell::get)
    })
}

fn integrate_impl(arena: &mut Arena, expr: ExprId, var: ExprId) -> ExprId {
    let var_sym = match arena.node(var) {
        ExprNode::Symbol(sid) => *sid,
        _ => {
            // var is not a symbol — can't integrate w.r.t. a non-symbol.
            return arena.intern(ExprNode::Integral(expr, var));
        }
    };
    // Exact constants first: `ln 1`, `atan 0`, `tan 0` are zero but not
    // structurally so, and a route that divides by a constant it cannot
    // see is zero is wrong — `∫ ln(x)/(x² + ln 1) dx` came out as
    // `atan(x/√(ln 1))`-terms (fuzz_integrate, 0.25).
    let expr = crate::transforms::eval::eval(arena, expr);

    // A `RootSum` that depends on the variable (an earlier answer, met by
    // by parts or a Risch coefficient) has no route here: every strategy
    // would take its body's `ln(x − t)` for a function of `x` alone.
    if crate::base::walk::post_order_ids(arena, expr)
        .iter()
        .any(|&id| {
            matches!(arena.node(id), ExprNode::RootSum(..)) && contains_var(arena, id, var_sym)
        })
    {
        return arena.intern(ExprNode::Integral(expr, var));
    }

    // Linearity first (see `integrate_node_uncached`): every stage below —
    // the substitutions, the Risch tower, heurisch — then sees the
    // integrand without its constant factors.  Before 0.30 they saw `c·f`:
    // `∫ a/cosh x`, `∫ π·e^x/(e^{2x} + 1)`, `∫ √2/(e^x + 1)` stayed
    // unevaluated although `∫ f` had a closed form.
    if let Some((constants, f)) = split_constant_factors(arena, expr, var_sym) {
        let big_f = integrate_stages(arena, f, var, var_sym);
        if matches!(arena.node(big_f), ExprNode::Integral(..)) {
            return arena.intern(ExprNode::Integral(expr, var));
        }
        return wrap_with_constants(arena, big_f, &constants);
    }
    integrate_stages(arena, expr, var, var_sym)
}

/// The stages of [`integrate_impl`] on an evaluated integrand, then — when
/// they leave it unevaluated — once more on its normal form as a fraction:
/// a polynomial in its transcendental subexpressions with reduced
/// rational coefficients ([`crate::calculus::risch::reduced_fraction_terms`];
/// `(x²·cos x + cos x)/(x² + 1)` is `cos x`, `(eˣ·x·(x + 1) + 1)/(x + 1)`
/// is `x·eˣ + 1/(x + 1)`), and the degenerate parameter values in
/// `Piecewise`.  The normal form is its own normal form, so this retries
/// at most once.
fn integrate_stages(arena: &mut Arena, expr: ExprId, var: ExprId, var_sym: SymbolId) -> ExprId {
    let result = integrate_stages_once(arena, expr, var, var_sym);
    let result = if let ExprNode::Integral(_, _) = arena.node(result)
        && let Some(reduced) = crate::calculus::risch::reduced_fraction_terms(arena, expr, var)
    {
        let r = stage!(
            arena,
            "reduced_fraction_retry",
            reduced,
            integrate_stages_once(arena, reduced, var, var_sym)
        );
        if crate::base::walk::has_unevaluated(arena, r) {
            result
        } else {
            accept_or_unevaluated(arena, expr, r, var, var_sym)
        }
    } else {
        result
    };
    let result = if crate::base::walk::has_unevaluated(arena, result) {
        integrate_terms_separately(arena, expr, var, var_sym).unwrap_or(result)
    } else {
        result
    };

    // Piecewise wrapping for parametric degenerate cases
    stage!(
        arena,
        "piecewise_wrap",
        result,
        try_piecewise_wrap(arena, result, expr, var, var_sym)
    )
}

/// `∫ (f₁ + … + fₖ) = Σ ∫ fᵢ` with every term through the whole pipeline,
/// for a sum the stages left (partly) unevaluated.  Inside the stages the
/// terms of a sum are integrated one by one too, but only by the rules of
/// `integrate_node`: the substitutions, the Risch tower and heurisch run on
/// the whole integrand, and fit one term but not the sum.  `∫ (x^(5/2) +
/// x²·|x|)/(x³ + x² + 1) dx` kept `∫ x^(5/2)/(x³ + x² + 1)` unevaluated,
/// which `x = s²` solves on its own (and the `|x|` makes that substitution
/// refuse the sum).  A product with a sum factor is distributed first
/// (`(√x + |x|)/(x + x⁻² + 1)`).  `None` unless every term has a closed
/// form.
fn integrate_terms_separately(
    arena: &mut Arena,
    expr: ExprId,
    var: ExprId,
    var_sym: SymbolId,
) -> Option<ExprId> {
    let sum = match arena.node(expr) {
        ExprNode::Add(_) => expr,
        ExprNode::Mul(children)
            if children
                .iter()
                .any(|&c| matches!(arena.node(c), ExprNode::Add(_))) =>
        {
            crate::transforms::expand::expand(arena, expr)
        }
        _ => return None,
    };
    let ExprNode::Add(terms) = arena.node(sum).clone() else {
        return None;
    };
    if terms.len() < 2 || terms.len() > MAX_SEPARATE_TERMS {
        return None;
    }
    let mut parts = Vec::with_capacity(terms.len());
    for &t in &terms {
        if !contains_var(arena, t, var_sym) {
            parts.push(arena.mul(&[t, var]));
            continue;
        }
        let (constants, f) = match split_constant_factors(arena, t, var_sym) {
            Some((c, f)) => (c, f),
            None => (SmallVec::new(), t),
        };
        let big_f = integrate_stages(arena, f, var, var_sym);
        if crate::base::walk::has_unevaluated(arena, big_f) {
            return None;
        }
        parts.push(wrap_with_constants(arena, big_f, &constants));
    }
    tracing::debug!("integrate: the terms of a sum, each through every stage");
    let sum = arena.add(&parts);
    let r = accept_or_unevaluated(arena, expr, sum, var, var_sym);
    (!crate::base::walk::has_unevaluated(arena, r)).then_some(r)
}

/// Sums with more terms are not retried term by term
/// ([`integrate_terms_separately`]): every term re-runs every stage.
const MAX_SEPARATE_TERMS: usize = 8;

/// One pass of the stages of [`integrate_stages`].
fn integrate_stages_once(
    arena: &mut Arena,
    expr: ExprId,
    var: ExprId,
    var_sym: SymbolId,
) -> ExprId {
    // Every stage's closed form faces the same evidence rule before it is
    // returned ([`accept_or_unevaluated`]); a rejected one counts as no answer,
    // so the next stage still gets its chance.  Up to 0.28.0 only some
    // routes inside the stages checked their candidates: by parts returned
    // `x·e^{kx}/k − e^{kx}/k²` for `∫ x·e^{kx} dx` with a `k` that is 0
    // without being so structurally — undefined everywhere.
    let result = integrate_node(arena, expr, var, var_sym, 20);
    let result = accept_or_unevaluated(arena, expr, result, var, var_sym);

    // Substitution-based strategies (u = e^{ax}, x = s^q, hyperbolic → exp,
    // piecewise-defined integrands).  Each one re-enters the full pipeline
    // on the transformed integrand, bounded by `SUBST_DEPTH`.
    let result = if let ExprNode::Integral(_, _) = arena.node(result)
        && let Some(r) = stage!(
            arena,
            "substitutions",
            expr,
            try_substitution_strategies(arena, expr, var, var_sym)
        ) {
        accept_or_unevaluated(arena, expr, r, var, var_sym)
    } else {
        result
    };

    // If the rule-based integrator returned an unevaluated Integral node,
    // try the Risch tower (exact method for exp/ln integrands) before
    // falling back to the heuristic integrator.
    if let ExprNode::Integral(_, _) = arena.node(result) {
        match stage!(
            arena,
            "risch_tower",
            expr,
            crate::calculus::risch::try_risch_tower(arena, expr, var)
        ) {
            // A dropped coefficient in the tower's θ-polynomial extraction
            // once returned a wrong closed form (0.22.3).
            crate::calculus::risch::TowerResult::Elementary(id) => {
                accept_or_unevaluated(arena, expr, id, var, var_sym)
            }
            crate::calculus::risch::TowerResult::NonElementary => {
                // Proved non-elementary — keep the unevaluated Integral node.
                // Skip heurisch: it can't succeed and would waste cycles.
                result
            }
            crate::calculus::risch::TowerResult::NotApplicable => {
                // Tower couldn't handle this — fall through to heurisch.
                if let Some(heurisch_result) = stage!(
                    arena,
                    "heurisch",
                    expr,
                    crate::transforms::heurisch::heurisch_integrate(arena, expr, var, var_sym)
                ) {
                    accept_or_unevaluated(arena, expr, heurisch_result, var, var_sym)
                } else {
                    result
                }
            }
        }
    } else {
        result
    }
}

/// A stage's answer `candidate` for `∫ f d(var)` in the form in which
/// `integrate` returns it, or the unevaluated `Integral(f, var)` when that
/// form is [`candidate_rejected`].  [`analytic_log_of_complex_arguments`]
/// comes first, so the evidence rule judges the answer that would be
/// returned.
fn accept_or_unevaluated(
    arena: &mut Arena,
    f: ExprId,
    candidate: ExprId,
    var: ExprId,
    var_sym: SymbolId,
) -> ExprId {
    let unevaluated = arena.intern(ExprNode::Integral(f, var));
    if candidate == unevaluated {
        return candidate;
    }
    let candidate = analytic_log_of_complex_arguments(arena, candidate, var_sym);
    if candidate_rejected(arena, f, candidate, var, var_sym) {
        tracing::debug!("integrate: rejecting an unverified closed form");
        return unevaluated;
    }
    candidate
}

/// `true` when the candidate `big_f` for `∫ f d(var)` must not be used:
/// [`antiderivative_rejected`], or it introduces a `RootOf` (one its
/// integrand does not contain).  The routes that check their own
/// candidates call it on the candidate as they built it; every stage of
/// `integrate_impl` calls it through [`accept_or_unevaluated`].
///
/// Such a `RootOf` comes from `solve` in the root-based fallback of
/// `apart`, and a sum of logarithms over those roots is the rational
/// integrator's `RootSum` written out term by term.  It also names its
/// polynomial in the integration (or substitution) variable, which the
/// structural `subs` of a sample point or of a back-substitution rewrites
/// along with the free occurrences (`RootOf(u⁸ − u⁶ + …, 0)` became
/// `RootOf(e^{8x} − …, 0)`, which is no polynomial).  Such pieces had never
/// been integrated before [`contains_var`] learned that the polynomial's
/// variable is bound.
///
/// The evidence rule judges `big_f` after
/// [`analytic_log_of_complex_arguments`], the form in which the stage will
/// return it: a route may build `ln|b·x + a|` for an unassumed `a`, `b`,
/// which the stage exit turns into `ln(b·x + a)`; the complex round of
/// [`check_antiderivative`] would reject the first (decision D4, 0.31).
fn candidate_rejected(
    arena: &mut Arena,
    f: ExprId,
    big_f: ExprId,
    var: ExprId,
    var_sym: SymbolId,
) -> bool {
    if introduces_root_of(arena, f, big_f) {
        tracing::debug!("integrate: rejecting a closed form over implicit roots");
        return true;
    }
    let big_f = analytic_log_of_complex_arguments(arena, big_f, var_sym);
    antiderivative_rejected(arena, f, big_f, var, var_sym)
}

/// Does `big_f` contain a `RootOf` node that `f` does not?
fn introduces_root_of(arena: &Arena, f: ExprId, big_f: ExprId) -> bool {
    let root_ofs = |e: ExprId| -> Vec<ExprId> {
        crate::base::walk::post_order_ids(arena, e)
            .into_iter()
            .filter(|&id| matches!(arena.node(id), ExprNode::RootOf(..)))
            .collect()
    };
    let new = root_ofs(big_f);
    !new.is_empty() && {
        let old: FxHashSet<ExprId> = root_ofs(f).into_iter().collect();
        new.iter().any(|id| !old.contains(id))
    }
}

/// Every `ln|u|` in `e` whose `u` depends on the variable and is not known
/// to be real ([`log_argument_is_real`]) becomes `ln u`.  `|u|` of a
/// non-real `u` is not the real-variable device the integrator means by it
/// (`d/dx ln|u| = Re(u′/u) ≠ u′/u`), while `ln u` is an antiderivative of
/// `u′/u` for real and complex `u` alike (analytic along the real line as
/// long as `u` avoids the negative real axis, which a `u` with a non-zero
/// imaginary part does; a real `u` only adds the constant `iπ` where it is
/// negative).  So `ln|u|` is kept only where realness is established.
/// Up to 0.28.0 only an explicit `i` counted: `∫ dx/(x − √(1/2 − √5/2))`
/// came out as `ln|x − √(1/2 − √5/2)|`, whose derivative is the conjugate
/// of the integrand.
fn analytic_log_of_complex_arguments(arena: &mut Arena, e: ExprId, var_sym: SymbolId) -> ExprId {
    let mut out = e;
    let mut reals = crate::base::assumptions::AssumptionCache::new();
    for id in crate::base::walk::post_order_ids(arena, e) {
        if let ExprNode::Ln(inner) = arena.node(id).clone()
            && let ExprNode::Abs(u) = arena.node(inner).clone()
            && contains_var(arena, u, var_sym)
            && !log_argument_is_real(arena, u, var_sym, &mut reals)
        {
            let plain = arena.ln(u);
            out = arena.subs_structural(out, id, plain);
        }
    }
    out
}

/// Is the argument `u` of an `ln|u|` real, as far as its constants go?
///
/// The variable-dependent structure of `u` is read with the real-variable
/// convention (`√(x − 5)` is real where the integrand is); what is decided
/// here is each maximal variable-free subexpression, by
/// [`constant_is_real`].  A constant that is not known to be real makes
/// `u` not known to be real — in particular every constant with a symbol
/// that has no declared assumptions (decision D4, 0.31: the variable is
/// real, a parameter is what its assumptions say, and an unassumed one
/// may be complex).  So `ln|a·x + 1|` stays only for a declared-real `a`;
/// up to 0.30 an unassumed `a` counted as real and `∫ dx/(a·x + 1)` was
/// `ln|a·x + 1|/a`, whose derivative `re(conj(u)·a)/|u|²` is not
/// `1/(a·x + 1)` for a non-real `a` (SymPy, Mathematica and Maple all
/// return `log(a·x + 1)/a`).
fn log_argument_is_real(
    arena: &mut Arena,
    u: ExprId,
    var_sym: SymbolId,
    reals: &mut crate::base::assumptions::AssumptionCache,
) -> bool {
    let mut stack = vec![u];
    let mut seen: FxHashSet<ExprId> = FxHashSet::default();
    while let Some(id) = stack.pop() {
        if !seen.insert(id) {
            continue;
        }
        if contains_var(arena, id, var_sym) {
            arena.node(id).for_each_child(|c| stack.push(c));
        } else if !constant_is_real(arena, id, reals) {
            return false;
        }
    }
    true
}

/// Is the variable-free `c` known to be real under the declared
/// assumptions of its parameters?
/// [`crate::transforms::realness::constant_realness_as_declared`] to
/// [`FTC_CHECK_DIGITS`] digits (`√(1/2 − √5/2)` is not, `√(3 − √5)` is,
/// `a + 1` is for a declared-real `a` and undecided for an unassumed one,
/// `√a` is undecided either way).  An undecided `c` is not known to be
/// real: the answer then keeps `ln u`, which is still an antiderivative.
fn constant_is_real(
    arena: &mut Arena,
    c: ExprId,
    reals: &mut crate::base::assumptions::AssumptionCache,
) -> bool {
    crate::transforms::realness::constant_realness_as_declared(arena, c, FTC_CHECK_DIGITS, reals)
        == Some(true)
}

/// Check whether `expr` is a suitable candidate for the `u` factor in
/// integration by parts.  Returns `true` when `expr` is a polynomial
/// in `var` **or** when it is `ln(inner)` with `inner` depending on `var`.
fn is_by_parts_candidate(arena: &Arena, expr: ExprId, var: ExprId, var_sym: SymbolId) -> bool {
    if is_polynomial_in(arena, expr, var, var_sym) {
        return true;
    }
    match arena.node(expr) {
        ExprNode::Ln(inner)
        | ExprNode::Asin(inner)
        | ExprNode::Acos(inner)
        | ExprNode::Atan(inner) => contains_var(arena, *inner, var_sym),
        _ => false,
    }
}

/// LIATE priority for integration by parts: lower = better choice for u.
/// L(og) = 1, I(nverse trig) = 2, A(lgebraic/polynomial) = 3,
/// T(rig) = 4, E(xponential) = 5, other = 6.
fn liate_rank(arena: &Arena, expr: ExprId, var: ExprId, var_sym: SymbolId) -> u8 {
    match arena.node(expr) {
        ExprNode::Ln(_) => 1,
        ExprNode::Asin(_) | ExprNode::Acos(_) | ExprNode::Atan(_) => 2,
        _ if is_polynomial_in(arena, expr, var, var_sym) => 3,
        ExprNode::Sin(_) | ExprNode::Cos(_) | ExprNode::Tan(_) => 4,
        ExprNode::Exp(_) | ExprNode::Sinh(_) | ExprNode::Cosh(_) | ExprNode::Tanh(_) => 5,
        _ => 6,
    }
}

/// Check whether `expr` is `Pow(var, 2)`, i.e. `x²`.
fn is_var_squared(arena: &Arena, expr: ExprId, var: ExprId) -> bool {
    if let ExprNode::Pow(b, e) = arena.node(expr)
        && *b == var
        && let Some(n) = arena.as_num(*e)
    {
        return *n == num_rational::Ratio::from_integer(2.into());
    }
    false
}

/// Check whether `expr` represents `-x²` in canonical form.
///
/// Handles both `Neg(Pow(var, 2))` and `Mul([-1, Pow(var, 2)])`.
fn is_neg_var_squared(arena: &Arena, expr: ExprId, var: ExprId) -> bool {
    match arena.node(expr).clone() {
        ExprNode::Neg(inner) => is_var_squared(arena, inner, var),
        ExprNode::Mul(ref children) if children.len() == 2 => {
            let neg_one_val = num_rational::Ratio::<num_bigint::BigInt>::from_integer((-1).into());
            let has_neg_one = children
                .iter()
                .any(|&c| arena.as_num(c).is_some_and(|n| *n == neg_one_val));
            let has_var_sq = children.iter().any(|&c| is_var_squared(arena, c, var));
            has_neg_one && has_var_sq
        }
        _ => false,
    }
}

/// Try to recognise standard‑form integrals of the shape
/// `(x² ± a²)^n` where `n` is −1 or −1/2.
///
/// Returns `Some(antiderivative)` on success.
fn try_standard_form_integral(
    arena: &mut Arena,
    _expr: ExprId,
    base: ExprId,
    exp: ExprId,
    var: ExprId,
    _var_sym: SymbolId,
) -> Option<ExprId> {
    // ── Check exponent ─────────────────────────────────────────────
    let exp_val = arena.as_num(exp)?.clone();
    let neg_one = num_rational::Ratio::<num_bigint::BigInt>::from_integer((-1).into());
    let neg_half = num_rational::Ratio::<num_bigint::BigInt>::new((-1).into(), 2.into());

    let is_neg_one = exp_val == neg_one;
    let is_neg_half = exp_val == neg_half;
    if !is_neg_one && !is_neg_half {
        return None;
    }

    // ── Check base is Add with exactly 2 children ──────────────────
    let children = match arena.node(base).clone() {
        ExprNode::Add(c) if c.len() == 2 => c,
        _ => return None,
    };

    // ── Classify each child ────────────────────────────────────────
    let mut const_val: Option<Q> = None;
    let mut has_pos_x2 = false;
    let mut has_neg_x2 = false;

    for &child in children.iter() {
        if let Some(n) = arena.as_num(child) {
            const_val = Some(n.clone());
        } else if is_var_squared(arena, child, var) {
            has_pos_x2 = true;
        } else if is_neg_var_squared(arena, child, var) {
            has_neg_x2 = true;
        } else {
            return None;
        }
    }

    let c_val = const_val?;
    if !has_pos_x2 && !has_neg_x2 {
        return None;
    }

    let a_squared = c_val.abs();
    if a_squared.is_zero() {
        return None;
    }

    // ── Build x/a and 1/a (simplify when a²=1) ────────────────────
    let a_sq_is_one = a_squared == num_rational::Ratio::<num_bigint::BigInt>::one();

    let x_over_a = if a_sq_is_one {
        var
    } else {
        let a_sq_id = arena.num_ratio(a_squared.clone());
        let nh = arena.rational(-1, 2);
        let a_inv = arena.pow(a_sq_id, nh); // (a²)^{-1/2} = 1/a
        arena.mul(&[var, a_inv])
    };

    // 1/a   (only needed for exp == -1 forms)
    let one_over_a = if a_sq_is_one {
        None
    } else {
        let a_sq_id = arena.num_ratio(a_squared.clone());
        let nh = arena.rational(-1, 2);
        Some(arena.pow(a_sq_id, nh))
    };

    // ── Match patterns ─────────────────────────────────────────────

    // Pattern: x² + a²  (c_val > 0, positive x²)
    if has_pos_x2 && c_val.is_positive() {
        if is_neg_one {
            // A3: ∫ (x²+a²)^{-1} dx = (1/a)·atan(x/a)
            let atan_val = arena.atan(x_over_a);
            return Some(match one_over_a {
                Some(inv_a) => arena.mul(&[inv_a, atan_val]),
                None => atan_val,
            });
        }
        if is_neg_half {
            // A5: ∫ (x²+a²)^{-1/2} dx = asinh(x/a)
            let asinh_val = arena.asinh(x_over_a);
            return Some(asinh_val);
        }
    }

    // Pattern: a² − x²  (c_val > 0, negative x²)
    if has_neg_x2 && c_val.is_positive() {
        if is_neg_half {
            // A4: ∫ (a²−x²)^{-1/2} dx = asin(x/a)
            let asin_val = arena.asin(x_over_a);
            return Some(asin_val);
        }
        if is_neg_one {
            // A7: ∫ (a²−x²)^{-1} dx = (1/a)·atanh(x/a)
            let atanh_val = arena.atanh(x_over_a);
            return Some(match one_over_a {
                Some(inv_a) => arena.mul(&[inv_a, atanh_val]),
                None => atanh_val,
            });
        }
    }

    // Pattern: x² − a²  (c_val < 0, positive x², a² = |c_val|)
    if has_pos_x2 && c_val.is_negative() && is_neg_half {
        // A6: ∫ (x²−a²)^{-1/2} dx = ln|x + √(x²−a²)|, the real-variable
        // antiderivative on both x > a and x < −a.  `acosh(x/a)` (SymPy's
        // answer, and ours before 0.24) differs from it by a constant for
        // x > a but has the wrong derivative for x < −a.
        return Some(ln_abs_x_plus_sqrt(arena, var, base));
    }

    None
}

/// `ln|v + √q|`, the real-variable antiderivative of `v′/√q` when
/// `q = v² − c` for a constant `c > 0` (`q` is `x² − a²`, or `a·u² + d`
/// with `v = √a·u`): `d/dx ln|v + √(v² − c)| = v′/√(v² − c)` on both
/// `v > √c` and `v < −√c`.
fn ln_abs_x_plus_sqrt(arena: &mut Arena, v: ExprId, q: ExprId) -> ExprId {
    let half = arena.rational(1, 2);
    let sqrt_q = arena.pow(q, half);
    let sum = arena.add(&[v, sqrt_q]);
    let abs_sum = arena.abs(sum);
    arena.ln(abs_sum)
}

/// Try integrating `(ax²+bx+c)^exp` via completing the square.
///
/// Handles two exponent values:
/// - `exp = -1`:   `∫ 1/(ax²+bx+c) dx` → atan form
/// - `exp = -1/2`: `∫ 1/√(ax²+bx+c) dx` → asinh / acosh / asin form
fn try_complete_square_integral(
    arena: &mut Arena,
    base: ExprId,
    exp: ExprId,
    var: ExprId,
    _var_sym: SymbolId,
) -> Option<ExprId> {
    let exp_r = arena.as_num(exp)?.clone();
    let neg_one = num_rational::Ratio::<num_bigint::BigInt>::from_integer((-1).into());
    let neg_half = num_rational::Ratio::<num_bigint::BigInt>::new((-1).into(), 2.into());

    let is_neg_one = exp_r == neg_one;
    let is_neg_half = exp_r == neg_half;
    if !is_neg_one && !is_neg_half {
        return None;
    }

    // base must be a quadratic in var: ax² + bx + c
    let poly_opt = crate::poly::polybridge::expr_to_poly(arena, base, var);

    // ── Symbolic fallback for irrational coefficients ──────────────
    // When expr_to_poly fails (e.g., coefficients contain √5 or ∛2),
    // try symbolic_quadratic_coeffs and arena-level completing the square.
    // This enables integration of terms produced by apart for cyclotomic
    // denominators like x⁵−1 and x⁸−1.
    if poly_opt.is_none() && is_neg_one {
        tracing::debug!(
            "try_complete_square: expr_to_poly failed, trying symbolic quadratic coefficients"
        );
        if let Some((c_id, d_id, e_id)) = symbolic_quadratic_coeffs(arena, base, var, _var_sym) {
            tracing::debug!(
                "try_complete_square: symbolic quadratic coefficients extracted, completing the square"
            );

            // Normalize to monic: b_sym = d/c, c_norm = e/c
            let b_sym = arena.div(d_id, c_id);
            let c_norm = arena.div(e_id, c_id);

            // Complete the square: x² + bx + c_norm = (x + b/2)² + (c_norm − b²/4)
            let two = arena.int(2);
            let half_b = arena.div(b_sym, two);
            let half_b_sq = arena.mul(&[half_b, half_b]);
            let disc = arena.sub(c_norm, half_b_sq);
            let disc = crate::transforms::eval::eval(arena, disc);

            // Sign test: discriminant must be positive for the atan form.
            let disc_sign = crate::poly::algebraic::sign_checked(arena, disc);
            tracing::debug!(?disc_sign, "try_complete_square: discriminant sign");
            if disc_sign != Some(1) {
                tracing::debug!(
                    "try_complete_square: discriminant non-positive, atan form not applicable"
                );
                return None;
            }

            // Result: (1/(a·√d)) · atan((x + b/2) / √d)
            let half = arena.rational(1, 2);
            let sqrt_disc = arena.pow(disc, half);
            let shifted = arena.add(&[var, half_b]);
            let ratio = arena.div(shifted, sqrt_disc);
            let atan_val = arena.atan(ratio);

            let sqrt_disc2 = arena.pow(disc, half);
            let a_sqrt_d = arena.mul(&[c_id, sqrt_disc2]);
            tracing::debug!(
                "try_complete_square: symbolic completing-the-square succeeded → atan form"
            );
            return Some(arena.div(atan_val, a_sqrt_d));
        }
    }

    // ── Rational-coefficient path ──────────────────────────────────
    let poly = poly_opt?;
    if poly.degree()? != 2 {
        return None;
    }

    let a_coeff = poly.coeff(2);
    let b_coeff = poly.coeff(1);
    let c_coeff = poly.coeff(0);

    if a_coeff.is_zero() {
        return None;
    }

    // ── exp = -1: ∫ 1/(ax²+bx+c) dx ───────────────────────────────
    if is_neg_one {
        // Normalize to monic: divide by a
        let b = &b_coeff / &a_coeff;
        let c = &c_coeff / &a_coeff;

        // If there's no linear term, this is a standard form — let the other helper handle it.
        if b.is_zero() {
            return None;
        }

        // Complete the square: x² + bx + c = (x + b/2)² + (c - b²/4)
        let half_b = &b / &num_rational::Ratio::from_integer(2.into());
        let d = &c - &(&half_b * &half_b); // d = c - b²/4

        if d.is_zero() || d.is_negative() {
            return None; // Can't use atan form if d ≤ 0
        }

        // Build (x + b/2)
        let half_b_id = {
            let nid = arena.intern_num(half_b.clone());
            arena.intern(crate::base::node::ExprNode::Num(nid))
        };
        let shifted = arena.add(&[var, half_b_id]);

        // Build √d
        let d_id = {
            let nid = arena.intern_num(d.clone());
            arena.intern(crate::base::node::ExprNode::Num(nid))
        };
        let half = arena.rational(1, 2);
        let sqrt_d = arena.pow(d_id, half);

        // Result: (1/(a·√d)) · atan((x+b/2)/√d)
        let ratio = arena.div(shifted, sqrt_d);
        let atan_result = arena.atan(ratio);

        // Divide by a·√d
        let a_id = {
            let nid = arena.intern_num(a_coeff);
            arena.intern(crate::base::node::ExprNode::Num(nid))
        };
        // Rebuild √d for the denominator (arena IDs are Copy, but let's be explicit)
        let sqrt_d2 = arena.pow(d_id, half);
        let a_sqrt_d = arena.mul(&[a_id, sqrt_d2]);

        return Some(arena.div(atan_result, a_sqrt_d));
    }

    // ── exp = -1/2: ∫ 1/√(ax²+bx+c) dx ───────────────────────────
    // Complete the square: ax²+bx+c = a·(x + b/(2a))² + (c − b²/(4a))
    // Let u = x + b/(2a),  d = c − b²/(4a).
    // Then ∫ 1/√(a·u² + d) du.
    let two_r = num_rational::Ratio::<num_bigint::BigInt>::from_integer(2.into());
    let four_r = num_rational::Ratio::<num_bigint::BigInt>::from_integer(4.into());

    let shift = &b_coeff / &(&a_coeff * &two_r); // b/(2a)
    let d = &c_coeff - &(&b_coeff * &b_coeff / &(&a_coeff * &four_r)); // c − b²/(4a)

    // Build u = x + b/(2a)
    let u_expr = if shift.is_zero() {
        var
    } else {
        let shift_id = arena.num_ratio(shift.clone());
        arena.add(&[var, shift_id])
    };

    let half = arena.rational(1, 2);

    if a_coeff.is_positive() {
        // a > 0
        let a_id = arena.num_ratio(a_coeff.clone());
        let sqrt_a = arena.pow(a_id, half); // √a
        let inv_sqrt_a = {
            let neg_half_e = arena.rational(-1, 2);
            arena.pow(a_id, neg_half_e)
        }; // 1/√a

        if d.is_positive() {
            // a > 0, d > 0: (1/√a) · asinh(u·√a / √d)
            let d_id = arena.num_ratio(d.clone());
            let sqrt_d = arena.pow(d_id, half);
            let u_sqrt_a = arena.mul(&[u_expr, sqrt_a]);
            let arg = arena.div(u_sqrt_a, sqrt_d);
            let asinh_val = arena.asinh(arg);
            return Some(arena.mul(&[inv_sqrt_a, asinh_val]));
        } else if d.is_negative() {
            // a > 0, d < 0: (1/√a) · ln|u·√a + √(a u² + d)|, valid on both
            // sides of the gap (acosh(u·√a/√|d|) is wrong for u < 0).
            let u_sqrt_a = arena.mul(&[u_expr, sqrt_a]);
            let ln_val = ln_abs_x_plus_sqrt(arena, u_sqrt_a, base);
            return Some(arena.mul(&[inv_sqrt_a, ln_val]));
        } else {
            // a > 0, d = 0: √(a·u²) = √a·|u| for the real variable, so the
            // antiderivative is sign(u)·ln|u|/√a (0.23 dropped the sign:
            // ∫ 1/√((3x − 2)²) dx was ln|x − 2/3|/3, wrong for x < 2/3;
            // found by the Rubi suite).
            let abs_u = arena.abs(u_expr);
            let ln_u = arena.ln(abs_u);
            let sign_u = arena.sign(u_expr);
            return Some(arena.mul(&[inv_sqrt_a, sign_u, ln_u]));
        }
    } else if a_coeff.is_negative() && d.is_positive() {
        // a < 0, d > 0: (1/√|a|) · asin(u·√|a| / √d)
        let abs_a = a_coeff.abs();
        let abs_a_id = arena.num_ratio(abs_a.clone());
        let sqrt_abs_a = arena.pow(abs_a_id, half);
        let inv_sqrt_abs_a = {
            let neg_half_e = arena.rational(-1, 2);
            arena.pow(abs_a_id, neg_half_e)
        };
        let d_id = arena.num_ratio(d.clone());
        let sqrt_d = arena.pow(d_id, half);
        let u_sqrt_abs_a = arena.mul(&[u_expr, sqrt_abs_a]);
        let arg = arena.div(u_sqrt_abs_a, sqrt_d);
        let asin_val = arena.asin(arg);
        return Some(arena.mul(&[inv_sqrt_abs_a, asin_val]));
    }

    None
}

/// Detect `sec(x)·tan(x)` and `csc(x)·cot(x)` patterns in a product.
///
/// - `sin(x) · cos(x)^{-2}` → `cos(x)^{-1}`   (∫ sec·tan dx = sec)
/// - `cos(x) · sin(x)^{-2}` → `-sin(x)^{-1}`   (∫ csc·cot dx = −csc)
fn try_trig_recip_product(
    arena: &mut Arena,
    dependent: &[ExprId],
    var: ExprId,
    var_sym: SymbolId,
) -> Option<ExprId> {
    if dependent.len() != 2 {
        return None;
    }

    let neg_two = num_rational::Ratio::<num_bigint::BigInt>::from_integer((-2).into());

    for (i, j) in [(0usize, 1usize), (1, 0)] {
        let node_i = arena.node(dependent[i]).clone();
        let node_j = arena.node(dependent[j]).clone();

        // Pattern: sin(g) · cos(g)^{-2} → cos(g)^{-1} [/ chain coeff]
        if let ExprNode::Sin(inner_sin) = node_i
            && let ExprNode::Pow(base_j, exp_j) = node_j
            && let ExprNode::Cos(inner_cos) = arena.node(base_j).clone()
            && inner_sin == inner_cos
            && let Some(e) = arena.as_num(exp_j)
            && *e == neg_two
        {
            let neg_one_e = arena.int(-1);
            if inner_sin == var {
                return Some(arena.pow(base_j, neg_one_e));
            } else if let Some((a_expr, _)) =
                symbolic_linear_coeff_of(arena, inner_sin, var, var_sym)
            {
                let recip = arena.pow(base_j, neg_one_e);
                return Some(arena.div(recip, a_expr));
            }
        }

        // Pattern: cos(g) · sin(g)^{-2} → −sin(g)^{-1} [/ chain coeff]
        if let ExprNode::Cos(inner_cos) = node_i
            && let ExprNode::Pow(base_j, exp_j) = node_j
            && let ExprNode::Sin(inner_sin) = arena.node(base_j).clone()
            && inner_cos == inner_sin
            && let Some(e) = arena.as_num(exp_j)
            && *e == neg_two
        {
            let neg_one_e = arena.int(-1);
            if inner_cos == var {
                let recip = arena.pow(base_j, neg_one_e);
                return Some(arena.neg(recip));
            } else if let Some((a_expr, _)) =
                symbolic_linear_coeff_of(arena, inner_cos, var, var_sym)
            {
                let recip = arena.pow(base_j, neg_one_e);
                let neg_recip = arena.neg(recip);
                return Some(arena.div(neg_recip, a_expr));
            }
        }
    }

    None
}

/// Detect `x / √(ax²+bx+c)` and integrate using the decomposition:
///
///   `∫ x/√R dx = √R/a − (b/(2a))·∫ 1/√R dx`
///
/// where `R = ax²+bx+c`.
fn try_x_over_sqrt_quadratic(
    arena: &mut Arena,
    dependent: &[ExprId],
    var: ExprId,
    var_sym: SymbolId,
    depth: usize,
) -> Option<ExprId> {
    if dependent.len() != 2 {
        return None;
    }

    // Find which factor is var and which is Pow(quadratic, -1/2)
    let pow_idx = if dependent[0] == var {
        1
    } else if dependent[1] == var {
        0
    } else {
        return None;
    };

    // Check the other factor is Pow(base, -1/2)
    let (base, exp_id) = match arena.node(dependent[pow_idx]).clone() {
        ExprNode::Pow(b, e) => (b, e),
        _ => return None,
    };

    let exp_r = arena.as_num(exp_id)?.clone();
    let neg_half = num_rational::Ratio::<num_bigint::BigInt>::new((-1).into(), 2.into());
    if exp_r != neg_half {
        return None;
    }

    // base must be quadratic in var
    let poly = crate::poly::polybridge::expr_to_poly(arena, base, var)?;
    if poly.degree()? != 2 {
        return None;
    }

    let a_coeff = poly.coeff(2);
    let b_coeff = poly.coeff(1);

    if a_coeff.is_zero() {
        return None;
    }

    // √R = base^{1/2}
    let half = arena.rational(1, 2);
    let sqrt_r = arena.pow(base, half);

    // First term: √R / a
    let a_id = arena.num_ratio(a_coeff.clone());
    let first_term = arena.div(sqrt_r, a_id);

    if b_coeff.is_zero() {
        // No linear term: ∫ x/√(ax²+c) dx = √(ax²+c)/a
        return Some(first_term);
    }

    // Need I_0 = ∫ 1/√R dx
    let i_0 = integrate_node(
        arena,
        dependent[pow_idx],
        var,
        var_sym,
        depth.saturating_sub(1),
    );
    if matches!(arena.node(i_0), ExprNode::Integral(_, _)) {
        return None;
    }

    // b/(2a)
    let two_r = num_rational::Ratio::<num_bigint::BigInt>::from_integer(2.into());
    let b_over_2a = &b_coeff / &(&a_coeff * &two_r);
    let b_over_2a_id = arena.num_ratio(b_over_2a.clone());

    // Result: √R/a − (b/(2a))·I_0
    let second_term = arena.mul(&[b_over_2a_id, i_0]);
    Some(arena.sub(first_term, second_term))
}

/// Try to integrate `(a² ± x²)^{1/2}` forms using trig substitution results.
///
/// Handles the three standard trig substitution patterns with positive
/// half-exponent:
/// - `∫ √(a²−x²) dx = ½(x·√(a²−x²) + a²·asin(x/a))`
/// - `∫ √(x²+a²) dx = ½(x·√(x²+a²) + a²·asinh(x/a))`
/// - `∫ √(x²−a²) dx = ½(x·√(x²−a²) − a²·acosh(x/a))`
fn try_trig_sub_sqrt_integral(
    arena: &mut Arena,
    base: ExprId,
    exp: ExprId,
    var: ExprId,
    _var_sym: SymbolId,
) -> Option<ExprId> {
    // ── Check exponent is 1/2 ──────────────────────────────────────
    let exp_val = arena.as_num(exp)?.clone();
    let pos_half = num_rational::Ratio::<num_bigint::BigInt>::new(1.into(), 2.into());
    if exp_val != pos_half {
        return None;
    }

    // ── Check base is Add with exactly 2 children ──────────────────
    let children = match arena.node(base).clone() {
        ExprNode::Add(c) if c.len() == 2 => c,
        _ => return None,
    };

    // ── Classify each child ────────────────────────────────────────
    let mut const_val: Option<Q> = None;
    let mut has_pos_x2 = false;
    let mut has_neg_x2 = false;

    for &child in children.iter() {
        if let Some(n) = arena.as_num(child) {
            const_val = Some(n.clone());
        } else if is_var_squared(arena, child, var) {
            has_pos_x2 = true;
        } else if is_neg_var_squared(arena, child, var) {
            has_neg_x2 = true;
        } else {
            return None;
        }
    }

    let c_val = const_val?;
    if !has_pos_x2 && !has_neg_x2 {
        return None;
    }

    let a_squared = c_val.abs();
    if a_squared.is_zero() {
        return None;
    }

    let half = arena.rational(1, 2);
    let a_sq_is_one = a_squared == num_rational::Ratio::<num_bigint::BigInt>::one();

    // √(base) for reuse in the result
    let sqrt_base = arena.pow(base, half);

    // a² as an expression
    let a_sq_expr = if a_sq_is_one {
        arena.one
    } else {
        arena.num_ratio(a_squared.clone())
    };

    // x/a = x · (a²)^{-1/2}
    let x_over_a = if a_sq_is_one {
        var
    } else {
        let neg_half = arena.rational(-1, 2);
        let a_inv = arena.pow(a_sq_expr, neg_half);
        arena.mul(&[var, a_inv])
    };

    // ── Pattern: a² − x²  (c_val > 0, negative x²) ───────────────
    // ∫ √(a²−x²) dx = ½(x·√(a²−x²) + a²·asin(x/a))
    if has_neg_x2 && c_val.is_positive() {
        let x_sqrt = arena.mul(&[var, sqrt_base]);
        let asin_term = arena.asin(x_over_a);
        let a_sq_asin = if a_sq_is_one {
            asin_term
        } else {
            arena.mul(&[a_sq_expr, asin_term])
        };
        let sum = arena.add(&[x_sqrt, a_sq_asin]);
        return Some(arena.mul(&[half, sum]));
    }

    // ── Pattern: x² + a²  (c_val > 0, positive x²) ───────────────
    // ∫ √(x²+a²) dx = ½(x·√(x²+a²) + a²·asinh(x/a))
    if has_pos_x2 && c_val.is_positive() {
        let x_sqrt = arena.mul(&[var, sqrt_base]);
        let asinh_term = arena.asinh(x_over_a);
        let a_sq_asinh = if a_sq_is_one {
            asinh_term
        } else {
            arena.mul(&[a_sq_expr, asinh_term])
        };
        let sum = arena.add(&[x_sqrt, a_sq_asinh]);
        return Some(arena.mul(&[half, sum]));
    }

    // ── Pattern: x² − a²  (c_val < 0, positive x²) ───────────────
    // ∫ √(x²−a²) dx = ½(x·√(x²−a²) − a²·ln|x + √(x²−a²)|), valid for
    // x > a and x < −a (the acosh(x/a) form is wrong for x < −a).
    if has_pos_x2 && c_val.is_negative() {
        let x_sqrt = arena.mul(&[var, sqrt_base]);
        let ln_term = ln_abs_x_plus_sqrt(arena, var, base);
        let a_sq_ln = if a_sq_is_one {
            ln_term
        } else {
            arena.mul(&[a_sq_expr, ln_term])
        };
        let diff = arena.sub(x_sqrt, a_sq_ln);
        return Some(arena.mul(&[half, diff]));
    }

    None
}

/// Integrate a product of a linear polynomial times `(quadratic)^{-1}`:
///
///   `∫ (ax+b) / (cx²+dx+e) dx`
///
/// Decomposes the linear numerator as a multiple of the derivative of the
/// quadratic denominator plus a constant remainder:
///
///   `ax+b = (a/(2c))·(2cx+d) + (b − ad/(2c))`
///
/// Then:
///   - First part:  `(a/(2c)) · ln|cx²+dx+e|`
///   - Second part: `(b − ad/(2c)) · ∫ 1/(cx²+dx+e) dx`  (completing the square)
fn try_linear_over_quadratic(
    arena: &mut Arena,
    dependent: &[ExprId],
    var: ExprId,
    var_sym: SymbolId,
    depth: usize,
) -> Option<ExprId> {
    if dependent.len() != 2 {
        return None;
    }

    // Identify linear factor and Pow(quadratic, -1) factor.
    let (linear_idx, pow_idx) = {
        let mut li = None;
        let mut pi = None;
        for (i, &d) in dependent.iter().enumerate() {
            if let ExprNode::Pow(_, _) = arena.node(d) {
                if pi.is_none() {
                    pi = Some(i);
                }
            } else if li.is_none() {
                li = Some(i);
            }
        }
        (li?, pi?)
    };

    let linear = dependent[linear_idx];
    let (pow_base, pow_exp) = match arena.node(dependent[pow_idx]).clone() {
        ExprNode::Pow(b, e) => (b, e),
        _ => return None,
    };

    // Exponent must be exactly −1.
    let exp_val = arena.as_num(pow_exp)?.clone();
    let neg_one = num_rational::Ratio::<num_bigint::BigInt>::from_integer((-1).into());
    if exp_val != neg_one {
        return None;
    }

    // ── Try rational-coefficient path first ────────────────────────
    let lin_poly = crate::poly::polybridge::expr_to_poly(arena, linear, var);
    let quad_poly = crate::poly::polybridge::expr_to_poly(arena, pow_base, var);

    if let (Some(lp), Some(qp)) = (&lin_poly, &quad_poly) {
        tracing::trace!("try_linear_over_quadratic: rational coefficient path");
        if lp.degree() == Some(1) && qp.degree() == Some(2) {
            let a_coeff = lp.coeff(1);
            let b_coeff = lp.coeff(0);
            let c_coeff = qp.coeff(2);
            let d_coeff = qp.coeff(1);

            use num_traits::Zero;
            if !c_coeff.is_zero() && !a_coeff.is_zero() {
                // Decompose: ax+b = (a/(2c))·(2cx+d) + (b − ad/(2c))
                let two_r = num_rational::Ratio::<num_bigint::BigInt>::from_integer(2.into());
                let a_over_2c = &a_coeff / &(&c_coeff * &two_r);
                let remainder = &b_coeff - &(&a_coeff * &d_coeff / &(&c_coeff * &two_r));

                let mut terms: Vec<ExprId> = Vec::new();

                // First term: (a/(2c)) · ln|cx²+dx+e|
                if !a_over_2c.is_zero() {
                    let coeff_id = arena.num_ratio(a_over_2c.clone());
                    let abs_quad = arena.abs(pow_base);
                    let ln_quad = arena.ln(abs_quad);
                    terms.push(arena.mul(&[coeff_id, ln_quad]));
                }

                // Second term: remainder · ∫ 1/(cx²+dx+e) dx
                if !remainder.is_zero() {
                    let inv_quad = arena.pow(pow_base, pow_exp); // (quad)^{-1}
                    let inv_integral =
                        integrate_node(arena, inv_quad, var, var_sym, depth.saturating_sub(1));
                    if matches!(arena.node(inv_integral), ExprNode::Integral(_, _)) {
                        return None;
                    }
                    let rem_id = arena.num_ratio(remainder.clone());
                    terms.push(arena.mul(&[rem_id, inv_integral]));
                }

                return match terms.len() {
                    0 => Some(arena.zero),
                    1 => Some(terms[0]),
                    _ => Some(arena.add(&terms)),
                };
            }
        }

        // Rational polys exist but don't match expected shape.
        return None;
    }

    // ── Symbolic fallback for irrational coefficients ──────────────
    // When expr_to_poly fails (e.g., coefficients contain √5 or √2),
    // extract symbolic coefficients and decompose using arena arithmetic.
    tracing::debug!(
        "try_linear_over_quadratic: expr_to_poly failed, trying symbolic coefficient path"
    );
    let (a_id, b_id) = symbolic_linear_coeff_of(arena, linear, var, var_sym)?;
    let (c_id, d_id, _e_id) = symbolic_quadratic_coeffs(arena, pow_base, var, var_sym)?;
    tracing::debug!(
        "try_linear_over_quadratic: symbolic coefficients extracted for linear/quadratic decomposition"
    );

    // log_coeff = a / (2c)
    let two = arena.int(2);
    let two_c = arena.mul(&[two, c_id]);
    let log_coeff = arena.div(a_id, two_c);
    let log_coeff = crate::transforms::eval::eval(arena, log_coeff);

    // remainder = b − a·d/(2c)
    let a_d = arena.mul(&[a_id, d_id]);
    let a_d_over_2c = arena.div(a_d, two_c);
    let remainder_expr = arena.sub(b_id, a_d_over_2c);
    let remainder_expr = crate::transforms::eval::eval(arena, remainder_expr);

    let mut terms: Vec<ExprId> = Vec::new();

    // A term is dropped only when its coefficient is *known* to vanish:
    // structurally zero, or a constant whose value is zero to the working
    // precision (`√5·√5/5 − 1`).  A coefficient with a free parameter has no
    // numeric value, and treating that as "zero" returned
    // `∫ (a·x + b)/(x² + 1) dx = 0` — 56 wrong answers on the Rubi suite (0.24).
    let known_zero = |arena: &mut Arena, c: ExprId| {
        arena.is_zero_structural(c)
            || crate::transforms::evalf::eval_const_f64(arena, c).is_some_and(|v| v.abs() <= 1e-14)
    };

    // First term: log_coeff · ln|quadratic|
    if !known_zero(arena, log_coeff) {
        let abs_quad = arena.abs(pow_base);
        let ln_quad = arena.ln(abs_quad);
        terms.push(arena.mul(&[log_coeff, ln_quad]));
    }

    // Second term: remainder · ∫ 1/(cx²+dx+e) dx
    if !known_zero(arena, remainder_expr) {
        let inv_quad = arena.pow(pow_base, pow_exp); // (quad)^{-1}
        let inv_integral = integrate_node(arena, inv_quad, var, var_sym, depth.saturating_sub(1));
        if crate::base::walk::has_unevaluated(arena, inv_integral) {
            return None;
        }
        terms.push(arena.mul(&[remainder_expr, inv_integral]));
    }

    match terms.len() {
        0 => Some(arena.zero),
        1 => Some(terms[0]),
        _ => Some(arena.add(&terms)),
    }
}

/// Check whether `expr` is a rational function of `sin(var)` and `cos(var)`.
///
/// A rational trig function may contain sin(var), cos(var), numeric
/// constants, and arithmetic operations (+, ×, integer powers, negation).
/// The integration variable must appear **only** inside sin/cos.
fn is_rational_trig(arena: &Arena, expr: ExprId, var: ExprId, var_sym: SymbolId) -> bool {
    if !contains_var(arena, expr, var_sym) {
        return true; // constant → trivially rational
    }
    match arena.node(expr).clone() {
        ExprNode::Sin(inner) if inner == var => true,
        ExprNode::Cos(inner) if inner == var => true,
        ExprNode::Add(children) => children
            .iter()
            .all(|&c| is_rational_trig(arena, c, var, var_sym)),
        ExprNode::Mul(children) => children
            .iter()
            .all(|&c| is_rational_trig(arena, c, var, var_sym)),
        ExprNode::Neg(inner) => is_rational_trig(arena, inner, var, var_sym),
        ExprNode::Pow(base, exp) => {
            if !contains_var(arena, exp, var_sym)
                && let Some(e) = arena.as_num(exp)
                && e.is_integer()
            {
                return is_rational_trig(arena, base, var, var_sym);
            }
            false
        }
        _ => false,
    }
}

/// Apply the Weierstrass (half-angle tangent) substitution to integrate a
/// rational function of `sin(var)` and `cos(var)`.
///
/// Substitution: `t = tan(var/2)`, giving
///   - `sin(var) = 2t/(1+t²)`
///   - `cos(var) = (1−t²)/(1+t²)`
///   - `dx        = 2/(1+t²) dt`
///
/// After substitution the integrand becomes a rational function of `t`.
/// With parameters, all declared real, an integrand with `f(x + π) = f(x)`
/// first goes through `t = tan x` ([`try_bioche_tan_substitution`]).
fn try_weierstrass_substitution(
    arena: &mut Arena,
    expr: ExprId,
    var: ExprId,
    var_sym: SymbolId,
    depth: usize,
) -> Option<ExprId> {
    if depth < 3 {
        return None;
    }
    if !is_rational_trig(arena, expr, var, var_sym) {
        return None;
    }
    // The jump at the poles of `tan(x/2)` with parameters not declared
    // real, as for real ones (up to 0.37 the answer was kept uncorrected:
    // `∫ dx/(a + b·cos x)` dropped by `2π/√(a² − b²)` at every odd multiple
    // of `π` for `a > |b|`; the continuity hunter's 118 jumps).
    let _jumps = crate::transforms::trig_integ::RealParameterJumps::enable(false);
    if has_only_real_parameters(arena, expr, var_sym)
        && let Some(result) = try_bioche_tan_substitution(arena, expr, var, var_sym, depth, false)
    {
        return Some(result);
    }

    tracing::debug!("trying Weierstrass substitution");

    let t = arena.symbol("__wt");
    let ExprNode::Symbol(t_sym) = *arena.node(t) else {
        return None;
    };

    let two = arena.int(2);
    let one = arena.one;
    let t_sq = arena.pow(t, two);
    let one_plus_t_sq = arena.add(&[one, t_sq]);

    let sin_var = arena.sin(var);
    let cos_var = arena.cos(var);

    // sin(var) → 2t/(1+t²)
    let two_t = arena.mul(&[two, t]);
    let sin_sub = arena.div(two_t, one_plus_t_sq);

    // cos(var) → (1−t²)/(1+t²)
    let one_minus_t_sq = arena.sub(one, t_sq);
    let cos_sub = arena.div(one_minus_t_sq, one_plus_t_sq);

    // dx factor: 2/(1+t²)
    let dx_factor = arena.div(two, one_plus_t_sq);

    // Apply substitution
    let mut sub_expr = arena.subs_structural(expr, sin_var, sin_sub);
    sub_expr = arena.subs_structural(sub_expr, cos_var, cos_sub);

    // Multiply by dx factor
    let integrand_t = arena.mul(&[sub_expr, dx_factor]);

    // Aggressively simplify / cancel
    let integrand_t = crate::transforms::eval::eval(arena, integrand_t);
    let integrand_t = crate::transforms::expand::expand(arena, integrand_t);
    let integrand_t = crate::transforms::eval::eval(arena, integrand_t);
    let integrand_t = arena.cancel_expr(integrand_t, t);
    let integrand_t = crate::transforms::eval::eval(arena, integrand_t);
    // Clear nested fractions such as 2/((1+t²)(2 + (1−t²)/(1+t²))) by
    // normalising to a single numerator/denominator pair.
    let integrand_t = clear_nested_fractions(arena, integrand_t, t);
    tracing::debug!(integrand_t = %arena.display(integrand_t), "weierstrass: integrand in t");

    // Integrate w.r.t. t
    let integral_t = integrate_node(arena, integrand_t, t, t_sym, depth.saturating_sub(2));

    if crate::base::walk::has_unevaluated(arena, integral_t) {
        return None;
    }
    // The integrand in `t` is a rational function; check the closed form
    // before it is dressed up in tan(x/2) (the rational integrator's
    // nested-radical failures show up here as e.g. `atan(3·tan(x/2))` for
    // `∫ cos x/(sin²x + 1)`).
    if candidate_rejected(arena, integrand_t, integral_t, t, t_sym) {
        tracing::debug!("weierstrass: closed form in t failed verification");
        return None;
    }

    // Substitute back, t → tan(var/2), continuously across var = π + 2kπ
    // (up to 0.37 `∫ dx/(2 + cos x)` was `2/√3·atan(tan(x/2)/√3)`, which
    // drops by 2π/√3 there; definite integrals taken from it were wrong).
    let half = arena.rational(1, 2);
    let half_var = arena.mul(&[half, var]);
    match crate::transforms::trig_integ::continuous_through_tan(
        arena, integral_t, t, t_sym, half_var,
    ) {
        Some(result) => Some(result),
        None if undecided_jump_kept(arena, integrand_t, integral_t, t, t_sym) => {
            tracing::debug!("weierstrass: the jump at x = π is not decided; uncorrected form");
            let tan_half = arena.tan(half_var);
            let back = arena.subs_structural(integral_t, t, tan_half);
            Some(crate::transforms::trig_integ::atan_tan_terms_to_argument(
                arena, back, half_var,
            ))
        }
        None => {
            tracing::debug!("weierstrass: the jump of G(tan(x/2)) at x = π is not decided");
            None
        }
    }
}

/// Does `expr` have parameters (free symbols other than the variable), all
/// of them declared real?
fn has_only_real_parameters(arena: &Arena, expr: ExprId, var_sym: SymbolId) -> bool {
    let params: Vec<SymbolId> = crate::base::walk::free_symbols(arena, expr)
        .into_iter()
        .filter_map(|s| match *arena.node(s) {
            ExprNode::Symbol(sid) if sid != var_sym => Some(sid),
            _ => None,
        })
        .collect();
    !params.is_empty()
        && params
            .iter()
            .all(|&sid| crate::transforms::realness::symbol_declared_real(arena, sid))
}

/// Bioche's rule for a rational function `f` of `sin x`, `cos x` with
/// `f(x + π) = f(x)`: the substitution `t = tan x` (`sin x = t·c`, `cos x =
/// c`, `c² = 1/(1 + t²)`, `dx = dt/(1 + t²)`) gives a rational function of
/// `t` of half the degree the half-angle substitution gives.  For real
/// parameters that decides the jump of `G(tan x)` at the poles of `tan x`
/// where the half-angle route's cannot be: `∫ dx/(a + b·sin²x)` (`a`, `b > 0`)
/// is `∫ dt/(a + (a + b)·t²)`, an `atan` with a positive coefficient, where
/// `tan(x/2)` gives a quartic whose roots' half-planes depend on the
/// parameters (up to 0.37 the answer was a sum of four logarithms that
/// jumped at every odd multiple of `π`).  Rubi integrates these integrands
/// so (`atan(√(a + b)·tan x/√a)/√(a(a + b))`); the floor term is the
/// continuity correction of [`crate::transforms::trig_integ::continuous_through_tan`].
///
/// `f(tc, c)` is even in `c` exactly when `f(x + π) = f(x)`; its numerator
/// and denominator (cancelled) are then both even or both odd in `c`.
/// `None` when `f` is not so invariant, the integral in `t` is not found or
/// fails the check, or its jump at `t = ±∞` is not decided (the caller
/// then takes the half-angle route) — unless `keep_undecided`, when such a
/// jump is one [`jump_kept_undecided`] lets the half-angle route keep: the
/// answer is then `G(tan x)` uncorrected, as that route would give it (of
/// half the degree in `t`).
fn try_bioche_tan_substitution(
    arena: &mut Arena,
    expr: ExprId,
    var: ExprId,
    var_sym: SymbolId,
    depth: usize,
    keep_undecided: bool,
) -> Option<ExprId> {
    let t = arena.symbol("__bt");
    let c = arena.symbol("__bc");
    let ExprNode::Symbol(t_sym) = *arena.node(t) else {
        return None;
    };
    let sin_var = arena.sin(var);
    let cos_var = arena.cos(var);
    let t_c = arena.mul(&[t, c]);
    let substituted = arena.subs_structural(expr, sin_var, t_c);
    let substituted = arena.subs_structural(substituted, cos_var, c);
    if contains_var(arena, substituted, var_sym) {
        return None;
    }
    let in_c = clear_nested_fractions(arena, substituted, c);
    let (num, den) = crate::poly::polybridge::as_numer_denom(arena, in_c);
    let num_c = crate::transforms::solve::symbolic_poly_coeffs(arena, num, c)?;
    let den_c = crate::transforms::solve::symbolic_poly_coeffs(arena, den, c)?;
    let vanishes = |arena: &mut Arena, cs: &[ExprId], parity: usize| {
        cs.iter()
            .skip(parity)
            .step_by(2)
            .all(|&k| crate::poly::algebraic::is_zero_checked(arena, k) == Some(true))
    };
    // `shift` 0: both even; 1: both odd (divided by `c`).
    let shift = if vanishes(arena, &num_c, 1) && vanishes(arena, &den_c, 1) {
        0
    } else if vanishes(arena, &num_c, 0) && vanishes(arena, &den_c, 0) {
        1
    } else {
        return None;
    };
    let one = arena.one;
    let two = arena.int(2);
    let t_sq = arena.pow(t, two);
    let one_plus_t_sq = arena.add(&[one, t_sq]);
    let in_t = |arena: &mut Arena, cs: &[ExprId]| -> ExprId {
        let mut terms: Vec<ExprId> = Vec::new();
        for (j, &k) in cs.iter().enumerate().skip(shift).step_by(2) {
            let half_degree = i64::try_from((j - shift) / 2).unwrap_or(0);
            let e = arena.int(-half_degree);
            let c_pow = arena.pow(one_plus_t_sq, e);
            terms.push(arena.mul(&[k, c_pow]));
        }
        arena.add(&terms)
    };
    let num_t = in_t(arena, &num_c);
    let den_t = in_t(arena, &den_c);
    let dt = arena.mul(&[den_t, one_plus_t_sq]);
    let integrand_t = arena.div(num_t, dt);
    let integrand_t = crate::transforms::eval::eval(arena, integrand_t);
    let integrand_t = clear_nested_fractions(arena, integrand_t, t);
    if contains_var(arena, integrand_t, var_sym)
        || crate::base::walk::contains(arena, integrand_t, c)
    {
        return None;
    }
    tracing::debug!(integrand_t = %arena.display(integrand_t), "bioche: integrand in tan x");
    let integral_t = integrate_node(arena, integrand_t, t, t_sym, depth.saturating_sub(2));
    if crate::base::walk::has_unevaluated(arena, integral_t)
        || candidate_rejected(arena, integrand_t, integral_t, t, t_sym)
    {
        return None;
    }
    let result = match crate::transforms::trig_integ::continuous_through_tan(
        arena, integral_t, t, t_sym, var,
    ) {
        Some(result) => result,
        None if keep_undecided && undecided_jump_kept(arena, integrand_t, integral_t, t, t_sym) => {
            let tan_var = arena.tan(var);
            let back = arena.subs_structural(integral_t, t, tan_var);
            crate::transforms::trig_integ::atan_tan_terms_to_argument(arena, back, var)
        }
        None => return None,
    };
    if candidate_rejected(arena, expr, result, var, var_sym) {
        tracing::debug!("bioche: the antiderivative in x failed verification");
        return None;
    }
    Some(result)
}

/// Largest multiple `k` of the common angle in
/// [`try_trig_rational_substitution`]: `sin k·u` becomes a polynomial of
/// degree `k` in `sin u`, `cos u`.
const MAX_ANGLE_MULTIPLE: i64 = 12;

/// `(sin k·u, cos k·u)` as polynomials in `s = sin u`, `c = cos u` (`k ≥ 1`):
/// `cos k·u = Tₖ(c)`, `sin k·u = s·Uₖ₋₁(c)` (Chebyshev polynomials, DLMF
/// 18.5.1–18.5.2), by the recurrences `Tₙ₊₁ = 2c·Tₙ − Tₙ₋₁`, `Uₙ₊₁ = 2c·Uₙ −
/// Uₙ₋₁`.
fn multiple_angle(arena: &mut Arena, k: i64, s: ExprId, c: ExprId) -> (ExprId, ExprId) {
    let two = arena.int(2);
    let two_c = arena.mul(&[two, c]);
    let minus_one = arena.int(-1);
    let (mut t_prev, mut t_cur) = (arena.one, c);
    let (mut u_prev, mut u_cur) = (arena.zero, arena.one);
    for _ in 1..k {
        let t_lead = arena.mul(&[two_c, t_cur]);
        let t_back = arena.mul(&[minus_one, t_prev]);
        let t_next = arena.add(&[t_lead, t_back]);
        let t_next = crate::transforms::expand::expand(arena, t_next);
        let u_lead = arena.mul(&[two_c, u_cur]);
        let u_back = arena.mul(&[minus_one, u_prev]);
        let u_next = arena.add(&[u_lead, u_back]);
        let u_next = crate::transforms::expand::expand(arena, u_next);
        (t_prev, t_cur) = (t_cur, t_next);
        (u_prev, u_cur) = (u_cur, u_next);
    }
    let sin_k = arena.mul(&[s, u_cur]);
    let sin_k = crate::transforms::expand::expand(arena, sin_k);
    (sin_k, t_cur)
}

/// Is the polynomial `p` (in the symbol `v`, other symbols as coefficients)
/// even (`Some(0)`) or odd (`Some(1)`) in `v`?  `None` when it has both
/// kinds of powers, is zero, or is not a polynomial in `v`.  A coefficient
/// counts as zero when it is so structurally or proved so.
fn parity_in(arena: &mut Arena, p: ExprId, v: ExprId) -> Option<usize> {
    let coeffs = crate::transforms::solve::symbolic_poly_coeffs(arena, p, v)?;
    let mut nonzero = [false, false];
    for (j, &k) in coeffs.iter().enumerate() {
        let zero = arena.is_zero_structural(k)
            || (crate::base::walk::free_symbols(arena, k).is_empty()
                && crate::poly::algebraic::is_zero_checked(arena, k) == Some(true));
        if !zero {
            nonzero[j % 2] = true;
        }
    }
    match nonzero {
        [true, false] => Some(0),
        [false, true] => Some(1),
        _ => None,
    }
}

/// `p = κ·p̃` for a polynomial `p` in the symbols `vars` whose coefficients are
/// all constant multiples of one of them, `κ`, which has free parameters:
/// `(κ, p̃)` with `p̃` free of parameters (`a + a·s` = `a·(1 + s)`).  `None`
/// otherwise.  The jump of an antiderivative through `tan w` is decided
/// for `p̃` where it is not for `p` (a parameter not declared real may be
/// complex), and it scales with `κ`.
fn parameter_content(arena: &mut Arena, p: ExprId, vars: &[ExprId]) -> Option<(ExprId, ExprId)> {
    let mut monomials: Vec<(ExprId, ExprId)> = vec![(p, arena.one)];
    for &v in vars {
        let mut next: Vec<(ExprId, ExprId)> = Vec::new();
        for (q, mono) in monomials {
            let coeffs = crate::transforms::solve::symbolic_poly_coeffs(arena, q, v)?;
            for (j, k) in coeffs.into_iter().enumerate() {
                if arena.is_zero_structural(k) {
                    continue;
                }
                let e = arena.int(i64::try_from(j).ok()?);
                let v_j = arena.pow(v, e);
                next.push((k, arena.mul(&[mono, v_j])));
            }
        }
        monomials = next;
    }
    let &(lead, _) = monomials.first()?;
    if crate::base::walk::free_symbols(arena, lead).is_empty() {
        return None;
    }
    let mut terms: Vec<ExprId> = Vec::with_capacity(monomials.len());
    for (k, mono) in monomials {
        let ratio = arena.div(k, lead);
        let ratio = crate::transforms::eval::eval(arena, ratio);
        if !crate::base::walk::free_symbols(arena, ratio).is_empty() {
            return None;
        }
        terms.push(arena.mul(&[ratio, mono]));
    }
    Some((lead, arena.add(&terms)))
}

/// `R/w` for a rational function `R = num/den` of `w` and `o` odd in `w`
/// (`num` and `den` of the parities `pn ≠ pd` in `w`), written in `t` with
/// `w² = 1 − t²`, `o = t`: the integrand in `t` of Bioche's substitutions
/// `t = cos u` (`w = sin u`, `dt = −w·du`) and `t = sin u` (`w = cos u`,
/// `dt = w·du`).  `R/w = w^(pn − pd − 1)·Ñ(w²)/D̃(w²)`, the power `w⁰` or
/// `w⁻²`.
fn odd_part_in_t(
    arena: &mut Arena,
    fraction: (ExprId, ExprId),
    parities: (usize, usize),
    w: ExprId,
    o: ExprId,
    t: ExprId,
) -> Option<ExprId> {
    let one = arena.one;
    let two = arena.int(2);
    let t_sq = arena.pow(t, two);
    let minus_t_sq = arena.neg(t_sq);
    let w_sq = arena.add(&[one, minus_t_sq]);
    let reduce = |arena: &mut Arena, p: ExprId, parity: usize| -> Option<ExprId> {
        let coeffs = crate::transforms::solve::symbolic_poly_coeffs(arena, p, w)?;
        let mut terms: Vec<ExprId> = Vec::new();
        for (j, &k) in coeffs.iter().enumerate().skip(parity).step_by(2) {
            let half = arena.int(i64::try_from((j - parity) / 2).ok()?);
            let k_t = arena.subs_structural(k, o, t);
            let power = arena.pow(w_sq, half);
            terms.push(arena.mul(&[k_t, power]));
        }
        Some(arena.add(&terms))
    };
    let n = reduce(arena, fraction.0, parities.0)?;
    let d = reduce(arena, fraction.1, parities.1)?;
    let d = if parities.0 == 1 {
        d
    } else {
        arena.mul(&[w_sq, d])
    };
    Some(arena.div(n, d))
}

/// Is `e` a rational function of the symbols `vars` (sums, products and
/// integer powers of them and of constants)?
fn is_rational_in_all(arena: &Arena, e: ExprId, vars: &[ExprId]) -> bool {
    vars.iter().all(|&v| match *arena.node(v) {
        ExprNode::Symbol(sid) => is_rational_in(arena, e, sid),
        _ => false,
    })
}

/// `∫ R(sin L₁, cos L₁, tan L₁, …, tan Lₖ) dx` for a rational function `R`
/// (with parameters) of trigonometric functions of linear arguments `Lᵢ =
/// αᵢ·x + βᵢ` whose rates are rational multiples of one another (`sec`,
/// `csc`, `cot` are written with `sin`, `cos`).  `u = g·(α₁·x + β₁)` (`g`
/// the gcd of the ratios `αᵢ/α₁`) makes every `Lᵢ = kᵢ·u + γᵢ` with an
/// integer `kᵢ`, and the multiple-angle and addition formulas give a
/// rational function `R̃(sin u, cos u)`; `du = g·α₁·dx`.  Bioche's rules
/// then pick the substitution that keeps the rational function in `t`
/// small:
///
/// - `R̃` odd in `sin u` (`R̃(u)·du` invariant under `u → −u`): `t = cos u`;
/// - odd in `cos u` (invariant under `u → π − u`): `t = sin u`;
/// - invariant under `u → π + u`: `t = tan u`
///   ([`try_bioche_tan_substitution`]);
/// - otherwise `t = tan(u/2)` ([`try_weierstrass_substitution`]).
///
/// The first two have no poles, so `G(sin u)` and `G(cos u)` are continuous
/// wherever the integrand is, whatever the parameters (`∫ cos u/(a +
/// b·sin u)² du = − 1/(b·(a + b·sin u))`); the last two add the floor
/// correction of [`crate::transforms::trig_integ::continuous_through_tan`].
/// Its jump `J` is decided with every parameter taken for real
/// ([`crate::transforms::trig_integ::RealParameterJumps`]: exact for real
/// values, `J·⌊w/π + 1/2⌋` locally constant for others), and an answer whose
/// jump is still not decided is returned only where the integrand is not
/// continuous across the poles ([`undecided_jump_kept`]).  A parameter
/// that multiplies the whole numerator or denominator (`(a + a·sin u)²`) is
/// split off first ([`parameter_content`]), and parameters only in the
/// numerator are taken term by term ([`trig_rational_in_u`]), which decides
/// `J` without signs.  Radicals: algebraic functions of `tan u`
/// ([`tan_algebraic_in_u`]) and radicals of `sin u` (`cos u`) times an odd
/// power of `cos u` (`sin u`) ([`odd_algebraic_in_u`]); a polynomial factor
/// in `x` goes through [`trig_polynomial_substitution`].  Before 0.38 a
/// trigonometric argument other than `x` itself went to the half-angle
/// substitution only for `sin`, `cos` powers, and `tan` never: `∫ dx/(5 +
/// 3·sin(2x + 1))`, `∫ dx/(2 + 3·tan x)` and 3,395 rational trigonometric
/// integrands of the Rubi suite (4.1–4.7, nearly all over `c + d·x`)
/// stayed unevaluated.  The substitutions follow the mathematics of Rubi's
/// rules for these integrands (4.1–4.7), not their form.  `None` when an
/// argument is not linear, the rates are not commensurable, a multiple
/// exceeds [`MAX_ANGLE_MULTIPLE`], the integrand is of none of these
/// forms, or no substitution gives a verified answer.
fn try_trig_rational_substitution(
    arena: &mut Arena,
    expr: ExprId,
    var: ExprId,
    var_sym: SymbolId,
) -> Option<ExprId> {
    use num_integer::Integer;
    let mut trig: Vec<(ExprId, ExprId, ExprId)> = Vec::new();
    for id in crate::base::walk::post_order_ids(arena, expr) {
        let arg = match *arena.node(id) {
            ExprNode::Sin(a) | ExprNode::Cos(a) | ExprNode::Tan(a) => a,
            _ => continue,
        };
        if !contains_var(arena, arg, var_sym) {
            continue;
        }
        let (alpha, beta) = symbolic_linear_coeff_of(arena, arg, var, var_sym)?;
        trig.push((id, alpha, beta));
    }
    let &(_, alpha0, beta0) = trig.first()?;
    let mut ratios: Vec<Q> = Vec::with_capacity(trig.len());
    for &(_, alpha, _) in &trig {
        let r = arena.div(alpha, alpha0);
        let r = crate::transforms::eval::eval(arena, r);
        ratios.push(arena.as_num(r)?.clone());
    }
    let mut num_gcd = num_bigint::BigInt::zero();
    let mut den_lcm = num_bigint::BigInt::one();
    for r in &ratios {
        num_gcd = num_gcd.gcd(r.numer());
        den_lcm = den_lcm.lcm(r.denom());
    }
    if num_gcd.is_zero() {
        return None;
    }
    let g = Q::new(num_gcd, den_lcm);
    let u = arena.symbol("__tru");
    let s = arena.symbol("__trs");
    let c = arena.symbol("__trc");
    let ExprNode::Symbol(u_sym) = *arena.node(u) else {
        return None;
    };
    let mut sub = expr;
    for (&(node, _, beta), r) in trig.iter().zip(&ratios) {
        let k = r / &g;
        if !k.is_integer() {
            return None;
        }
        let k = i64::try_from(k.to_integer()).ok()?;
        if k == 0 || k.abs() > MAX_ANGLE_MULTIPLE {
            return None;
        }
        let r_id = arena.num_ratio(r.clone());
        let r_beta0 = arena.mul(&[r_id, beta0]);
        let gamma = arena.sub(beta, r_beta0);
        let gamma = crate::transforms::eval::eval(arena, gamma);
        let (sin_k, cos_k) = multiple_angle(arena, k.abs(), s, c);
        let sin_k = if k < 0 { arena.neg(sin_k) } else { sin_k };
        let (sin_l, cos_l) = if arena.is_zero_structural(gamma) {
            (sin_k, cos_k)
        } else {
            let sin_g = arena.sin(gamma);
            let cos_g = arena.cos(gamma);
            let a = arena.mul(&[sin_k, cos_g]);
            let b = arena.mul(&[cos_k, sin_g]);
            let sin_l = arena.add(&[a, b]);
            let a = arena.mul(&[cos_k, cos_g]);
            let b = arena.mul(&[sin_k, sin_g]);
            let cos_l = arena.sub(a, b);
            (sin_l, cos_l)
        };
        let repl = match arena.node(node) {
            ExprNode::Sin(_) => sin_l,
            ExprNode::Cos(_) => cos_l,
            _ => arena.div(sin_l, cos_l),
        };
        sub = arena.subs_structural(sub, node, repl);
    }
    let rate = arena.num_ratio(g.clone());
    let rate = arena.mul(&[rate, alpha0]);
    let shift = arena.num_ratio(g);
    let shift = arena.mul(&[shift, beta0]);
    let shift = crate::transforms::eval::eval(arena, shift);
    if contains_var(arena, sub, var_sym) {
        return trig_polynomial_substitution(arena, expr, sub, (s, c), (rate, shift), var, var_sym);
    }
    // The jumps of answers through `tan w` with parameters, as for real
    // ones (exact for real values, locally constant otherwise), of the
    // answer with the logarithms the stage exit writes `ln u`.
    let undeclared = |arena: &Arena, e: ExprId| {
        crate::base::walk::free_symbols(arena, e)
            .into_iter()
            .any(|v| match *arena.node(v) {
                ExprNode::Symbol(sid) => {
                    !crate::transforms::realness::symbol_declared_real(arena, sid)
                }
                _ => true,
            })
    };
    let plain_logs = undeclared(arena, rate) || undeclared(arena, shift);
    let _jumps = crate::transforms::trig_integ::RealParameterJumps::enable(plain_logs);
    let _strict = crate::transforms::trig_integ::StrictJumps::enable();
    let (kappa, result_u) = if is_rational_in_all(arena, sub, &[s, c]) {
        tracing::debug!(
            "integrate: a rational function of the trigonometric functions of a linear argument"
        );
        let r = clear_nested_fractions(arena, sub, s);
        let (num, den) = crate::poly::polybridge::as_numer_denom(arena, r);
        let num = crate::transforms::expand::expand(arena, num);
        let den = crate::transforms::expand::expand(arena, den);
        // A parameter that multiplies the whole numerator or denominator.
        let (num_k, num) = parameter_content(arena, num, &[s, c]).unwrap_or((arena.one, num));
        let (den_k, den) = parameter_content(arena, den, &[s, c]).unwrap_or((arena.one, den));
        let kappa = arena.div(num_k, den_k);
        (
            kappa,
            trig_rational_in_u(arena, (num, den), (s, c), u, u_sym)?,
        )
    } else {
        let result = match odd_algebraic_in_u(arena, sub, (s, c), u) {
            Some(r) => r,
            None => match tan_algebraic_in_u(arena, sub, (s, c), u) {
                Some(r) => r,
                None => half_angle_radical_in_u(arena, sub, (s, c), u)?,
            },
        };
        (arena.one, result)
    };
    let l = arena.mul(&[rate, var]);
    let l = arena.add(&[l, shift]);
    let back = arena.subs_structural(result_u, u, l);
    let minus_one = arena.int(-1);
    let inv_rate = arena.pow(rate, minus_one);
    let back = arena.mul(&[kappa, inv_rate, back]);
    let back = crate::transforms::eval::eval(arena, back);
    if candidate_rejected(arena, expr, back, var, var_sym) {
        tracing::debug!(
            "integrate: rejecting an unverified trigonometric-substitution closed form"
        );
        return None;
    }
    Some(back)
}

/// The terms of the polynomial `p` in the symbols `vars` grouped by their
/// constant factors with free parameters: `p = Σ πₖ·pₖ` with every `pₖ` free
/// of parameters (`A + B·s + C·s²` = `A·1 + B·s + C·s²`).
fn parameter_terms(arena: &mut Arena, p: ExprId, vars: &[ExprId]) -> Vec<(ExprId, ExprId)> {
    let p = crate::transforms::expand::expand(arena, p);
    let terms: Vec<ExprId> = match arena.node(p) {
        ExprNode::Add(children) => children.to_vec(),
        _ => vec![p],
    };
    let mut groups: Vec<(ExprId, Vec<ExprId>)> = Vec::new();
    for term in terms {
        let factors: Vec<ExprId> = match arena.node(term) {
            ExprNode::Mul(children) => children.to_vec(),
            _ => vec![term],
        };
        let mut key: Vec<ExprId> = Vec::new();
        let mut part: Vec<ExprId> = Vec::new();
        for f in factors {
            let dependent = vars.iter().any(|&v| contains_var_id(arena, f, v));
            if !dependent && !crate::base::walk::free_symbols(arena, f).is_empty() {
                key.push(f);
            } else {
                part.push(f);
            }
        }
        let key = arena.mul(&key);
        let part = arena.mul(&part);
        match groups.iter_mut().find(|(k, _)| *k == key) {
            Some((_, parts)) => parts.push(part),
            None => groups.push((key, vec![part])),
        }
    }
    groups
        .into_iter()
        .map(|(k, parts)| (k, arena.add(&parts)))
        .collect()
}

/// [`try_trig_rational_substitution`] for an integrand with the variable
/// also outside the trigonometric functions, polynomially (`(c + d·x)²·
/// cos²(a + b·x)·sin³(a + b·x)`, Rubi 4.x.10, 4.7.3): `sub` is the
/// integrand with the trigonometric functions written in `s = sin u`, `c =
/// cos u` (`sc`), `u = rate·x + shift` (`linear`).  With `x = (u −
/// shift)/rate` the integrand in `u` has `u` as every argument (multiple
/// angles expanded: `csc(a + b·x)·sin(3a + 3b·x)` is `3 − 4·sin²u`), and
/// goes through the whole pipeline (by parts takes linear arguments only
/// as `x` itself).  `None` when the substitution is `u = x`, the variable
/// is not polynomial in `sub`, or no answer is found.
fn trig_polynomial_substitution(
    arena: &mut Arena,
    expr: ExprId,
    sub: ExprId,
    sc: (ExprId, ExprId),
    linear: (ExprId, ExprId),
    var: ExprId,
    var_sym: SymbolId,
) -> Option<ExprId> {
    let (s, c) = sc;
    let (rate, shift) = linear;
    if !is_rational_in_all(arena, sub, &[s, c])
        || crate::transforms::solve::symbolic_poly_coeffs(arena, sub, var).is_none()
    {
        return None;
    }
    let u = arena.symbol("__trp");
    let minus_shift = arena.neg(shift);
    let u_minus = arena.add(&[u, minus_shift]);
    let x_of_u = arena.div(u_minus, rate);
    let in_u = arena.subs_structural(sub, var, x_of_u);
    let sin_u = arena.sin(u);
    let cos_u = arena.cos(u);
    let in_u = arena.subs_structural(in_u, s, sin_u);
    let in_u = arena.subs_structural(in_u, c, cos_u);
    let in_u = arena.div(in_u, rate);
    let in_u = crate::transforms::eval::eval(arena, in_u);
    // `u = x` with nothing rewritten: the pipeline has seen this integrand.
    let same = arena.subs_structural(in_u, u, var);
    if same == expr {
        return None;
    }
    tracing::debug!(integrand_u = %arena.display(in_u), "integrate: polynomial times trigonometric functions of a linear argument");
    let res = integrate_nested_generic(arena, in_u, u)?;
    let l = arena.mul(&[rate, var]);
    let l = arena.add(&[l, shift]);
    let back = arena.subs_structural(res, u, l);
    let back = crate::transforms::eval::eval(arena, back);
    if candidate_rejected(arena, expr, back, var, var_sym) {
        return None;
    }
    Some(back)
}

/// `∫ R(sin u, cos u) du` for `R = num/den`, polynomials in the symbols
/// `s = sin u`, `c = cos u` (`sc`), by Bioche's rules (see
/// [`try_trig_rational_substitution`]).  With a denominator free of
/// parameters, a numerator `Σ πₖ·pₖ` ([`parameter_terms`]) is integrated term
/// by term: each `∫ pₖ/den` is free of parameters, so the jump of an
/// answer through `tan w` is decided for it (`∫ (A + B·cos u)/(1 + cos u)²
/// du`; the jump of the whole depends on whether `A`, `B` are real).
fn trig_rational_in_u(
    arena: &mut Arena,
    fraction: (ExprId, ExprId),
    sc: (ExprId, ExprId),
    u: ExprId,
    u_sym: SymbolId,
) -> Option<ExprId> {
    let (num, den) = fraction;
    let (s, c) = sc;
    let parametric = |arena: &Arena, e: ExprId| {
        crate::base::walk::free_symbols(arena, e)
            .into_iter()
            .any(|v| v != s && v != c)
    };
    let groups = if !parametric(arena, den) && parametric(arena, num) {
        parameter_terms(arena, num, &[s, c])
    } else {
        Vec::new()
    };
    if groups.len() < 2 {
        return trig_rational_single(arena, fraction, sc, u, u_sym);
    }
    let mut sum: Vec<ExprId> = Vec::with_capacity(groups.len());
    for (key, part) in groups {
        let r = trig_rational_single(arena, (part, den), sc, u, u_sym)?;
        sum.push(arena.mul(&[key, r]));
    }
    Some(arena.add(&sum))
}

/// [`trig_rational_in_u`] for one fraction.
fn trig_rational_single(
    arena: &mut Arena,
    fraction: (ExprId, ExprId),
    sc: (ExprId, ExprId),
    u: ExprId,
    u_sym: SymbolId,
) -> Option<ExprId> {
    let (num, den) = fraction;
    let (s, c) = sc;
    let ratio = arena.div(num, den);
    if !contains_var_id(arena, ratio, s) && !contains_var_id(arena, ratio, c) {
        return Some(arena.mul(&[ratio, u]));
    }
    let t = arena.symbol("__trt");
    let ExprNode::Symbol(t_sym) = *arena.node(t) else {
        return None;
    };
    let sin_u = arena.sin(u);
    let cos_u = arena.cos(u);
    // `t = cos u` when `R` is odd in `sin u`, `t = sin u` when odd in `cos u`.
    for (w, o, back, sign) in [(s, c, cos_u, -1), (c, s, sin_u, 1)] {
        let (Some(pn), Some(pd)) = (parity_in(arena, num, w), parity_in(arena, den, w)) else {
            continue;
        };
        if pn == pd {
            continue;
        }
        let Some(in_t) = odd_part_in_t(arena, (num, den), (pn, pd), w, o, t) else {
            continue;
        };
        let sign = arena.int(sign);
        let in_t = arena.mul(&[sign, in_t]);
        let in_t = clear_nested_fractions(arena, in_t, t);
        tracing::debug!(integrand_t = %arena.display(in_t), "bioche: integrand in sin u or cos u");
        let g = integrate_node(arena, in_t, t, t_sym, 18);
        if crate::base::walk::has_unevaluated(arena, g)
            || candidate_rejected(arena, in_t, g, t, t_sym)
        {
            continue;
        }
        return Some(arena.subs_structural(g, t, back));
    }
    let r_s = arena.subs_structural(ratio, s, sin_u);
    let r_u = arena.subs_structural(r_s, c, cos_u);
    let r_u = crate::transforms::eval::eval(arena, r_u);
    let lam = arena.symbol("__trl");
    let joint = |arena: &mut Arena, p: ExprId| -> Option<usize> {
        let ls = arena.mul(&[lam, s]);
        let lc = arena.mul(&[lam, c]);
        let p = arena.subs_structural(p, s, ls);
        let p = arena.subs_structural(p, c, lc);
        parity_in(arena, p, lam)
    };
    if let (Some(pn), Some(pd)) = (joint(arena, num), joint(arena, den))
        && pn == pd
        && let Some(result) = try_bioche_tan_substitution(arena, r_u, u, u_sym, 20, true)
    {
        return Some(result);
    }
    try_weierstrass_substitution(arena, r_u, u, u_sym, 20)
}

/// `∫ R(x) dx` for a rational function `R` with `i` in its coefficients
/// (Gaussian rationals, parameters allowed).  With `i` taken for a symbol
/// `ι` (`ι² = −1`), `R = (N₀ + ι·N₁)/(D₀ + ι·D₁)` with `N₀`, `N₁`, `D₀`, `D₁`
/// free of `i`, and `R = ((N₀D₀ + N₁D₁) + i·(N₁D₀ − N₀D₁))/(D₀² + D₁²)`:
/// two rational functions free of `i`, integrated separately.  This is an
/// identity of rational functions, so no parameter has to be real.  The
/// rational integrators work over ℚ and ℚ(parameters): up to 0.37 `∫ (1 +
/// i·t)⁵/(1 + t²)⁶ dt` stayed unevaluated, and with it the Rubi suite's
/// `(a + i·a·tan(c + d·x))ⁿ` families through `t = tan x`.  For a real
/// variable both parts come out as real antiderivatives (`ln|·|`, `atan`),
/// continuous wherever `R` is.
fn try_gaussian_rational(
    arena: &mut Arena,
    expr: ExprId,
    var: ExprId,
    var_sym: SymbolId,
    depth: usize,
) -> Option<ExprId> {
    let i = arena.i_unit();
    if depth < 2
        || !crate::base::walk::contains(arena, expr, i)
        || !is_rational_in(arena, expr, var_sym)
    {
        return None;
    }
    let iota = arena.symbol("__gi");
    let e = arena.subs_structural(expr, i, iota);
    if crate::base::walk::contains(arena, e, i) {
        return None;
    }
    let e = clear_nested_fractions(arena, e, var);
    let (n, d) = crate::poly::polybridge::as_numer_denom(arena, e);
    let split = |arena: &mut Arena, p: ExprId| -> Option<(ExprId, ExprId)> {
        let coeffs = crate::transforms::solve::symbolic_poly_coeffs(arena, p, iota)?;
        let mut re: Vec<ExprId> = Vec::new();
        let mut im: Vec<ExprId> = Vec::new();
        for (k, &c) in coeffs.iter().enumerate() {
            let c = if (k / 2) % 2 == 0 { c } else { arena.neg(c) };
            if k % 2 == 0 {
                re.push(c);
            } else {
                im.push(c);
            }
        }
        let re = arena.add(&re);
        let im = arena.add(&im);
        Some((
            crate::transforms::eval::eval(arena, re),
            crate::transforms::eval::eval(arena, im),
        ))
    };
    let (n0, n1) = split(arena, n)?;
    let (d0, d1) = split(arena, d)?;
    let (p, q, den) = if arena.is_zero_structural(d1) {
        (n0, n1, d0)
    } else {
        let a = arena.mul(&[n0, d0]);
        let b = arena.mul(&[n1, d1]);
        let p = arena.add(&[a, b]);
        let a = arena.mul(&[n1, d0]);
        let b = arena.mul(&[n0, d1]);
        let q = arena.sub(a, b);
        let two = arena.int(2);
        let a = arena.pow(d0, two);
        let b = arena.pow(d1, two);
        (p, q, arena.add(&[a, b]))
    };
    let mut parts: Vec<ExprId> = Vec::with_capacity(2);
    for (num, factor) in [(p, arena.one), (q, i)] {
        let num = crate::transforms::expand::expand(arena, num);
        if arena.is_zero_structural(num) {
            continue;
        }
        let f = arena.div(num, den);
        let f = clear_nested_fractions(arena, f, var);
        if crate::base::walk::contains(arena, f, iota) {
            return None;
        }
        let big_f = integrate_node(arena, f, var, var_sym, depth - 1);
        if crate::base::walk::has_unevaluated(arena, big_f) {
            return None;
        }
        // Term by term, so that the terms `c·atan(tan w)` of a substitution
        // through `tan w` stay terms (`add_tan_floor` writes them `c·w`).
        let terms: Vec<ExprId> = match arena.node(big_f) {
            ExprNode::Add(children) => children.to_vec(),
            _ => vec![big_f],
        };
        for term in terms {
            parts.push(arena.mul(&[factor, term]));
        }
    }
    tracing::debug!(
        "integrate: a rational function with Gaussian coefficients, by real and imaginary parts"
    );
    let result = arena.add(&parts);
    if candidate_rejected(arena, expr, result, var, var_sym) {
        return None;
    }
    Some(result)
}

/// `∫ A(sin u, cos u) du` for `A = R(sin u, cos u)·√(1 + ε·w)^p` (`w` = `sin u`
/// or `cos u`, `ε = ±1`, every radical `(κ·(1 + ε·w))^(k/2)` of the
/// integrand of that one base: Rubi 4.1.1.1, 4.1.1.2, 4.2.1.1 `(a + a·sin(c +
/// d·x))^(7/2)`, `cos²(c + d·x)·√(a + a·sin(c + d·x))`), `R` rational with
/// poles only where `1 + ε·w = 0`.  `(κ·p)^r = κ^r·p^r` for real `p ≥ 0`, and
/// with `v = u/2 + φ` (`φ = ε·π/4` for `sin u`, `π/2` or `0` for `1 ± cos u`)
/// `1 + ε·w = 2·sin²v`, so `√(1 + ε·w) = √2·σ·sin v` with `σ = sign(sin v)`:
/// the integrand is `σ·g(v)·dv` with `g` rational in `sin v`, `cos v` and
/// `g(v + π) = −g(v)`.
///
/// Where `g` is a polynomial (the integrand is continuous), its parts odd
/// in `sin v` and in `cos v` integrate (`t = cos v`, `t = sin v`) to an
/// antiderivative `G` with `G(v + π) = −G(v)`, and `F = σ·G − 2·G(0)·⌊v/π⌋`
/// is continuous at the zeros `v = kπ` of `sin v`, where `σ` flips (`σ·G`
/// steps by `2·G(0)` at each).  `σ·G` is written without `σ`, with
/// `σ·sin v = √(1 + ε·w)/√2` and `σ·cos v = √(1 + ε·w)·sin 2v/(√2·(1 + ε·w))`:
/// `∫ √(1 + sin x) dx = −2·cos x/√(1 + sin x) + 4√2·⌊(x/2 + π/4)/π⌋`.
/// Rubi's answers are the first term alone and jump by `4√2` at every
/// zero of `1 + sin x`; SymPy 1.14 leaves these integrands unevaluated.
/// Where `g` has poles (at `sin v = 0` only) `F = σ·G`.  `None` for other
/// radicals, a part of `A` with an even power of the radical, poles of `R`
/// elsewhere, or no answer for `G`.
fn half_angle_radical_in_u(
    arena: &mut Arena,
    e: ExprId,
    sc: (ExprId, ExprId),
    u: ExprId,
) -> Option<ExprId> {
    let (s, c) = sc;
    // The radicals `B^(k/2)` and their common base `κ·(1 + ε·w)`.
    let mut base_kind: Option<(ExprId, ExprId)> = None;
    let mut radicals: Vec<(ExprId, ExprId, i64, ExprId)> = Vec::new();
    for id in crate::base::walk::post_order_ids(arena, e) {
        let ExprNode::Pow(base, ex) = *arena.node(id) else {
            continue;
        };
        let Some(r) = arena.as_num(ex).cloned() else {
            continue;
        };
        if r.is_integer() || !(contains_var_id(arena, base, s) || contains_var_id(arena, base, c)) {
            continue;
        }
        if *r.denom() != num_bigint::BigInt::from(2) {
            return None;
        }
        let k = i64::try_from(r.numer()).ok()?;
        let (w, other) = if contains_var_id(arena, base, c) {
            (c, s)
        } else {
            (s, c)
        };
        if contains_var_id(arena, base, other) {
            return None;
        }
        let coeffs = crate::transforms::solve::symbolic_poly_coeffs(arena, base, w)?;
        let [kappa, b1] = coeffs.as_slice() else {
            return None;
        };
        let eps = arena.div(*b1, *kappa);
        let eps = crate::transforms::eval::eval(arena, eps);
        let eps_one = arena.as_num(eps).filter(|q| q.abs().is_one())?.clone();
        let eps = arena.num_ratio(eps_one);
        match base_kind {
            None => base_kind = Some((w, eps)),
            Some(kind) if kind == (w, eps) => {}
            Some(_) => return None,
        }
        radicals.push((id, *kappa, k, w));
    }
    let (w, eps) = base_kind?;
    let eps_positive = arena.as_num(eps).is_some_and(|q| q.is_positive());
    // `√(1 + ε·w)` as the symbol `rad`: `B^(k/2) = κ^(k/2)·rad^k`.
    let rad = arena.symbol("__hrad");
    let mut sub = e;
    for &(id, kappa, k, _) in &radicals {
        let half_k = arena.rational(k, 2);
        let kappa_pow = arena.pow(kappa, half_k);
        let k_id = arena.int(k);
        let rad_pow = arena.pow(rad, k_id);
        let repl = arena.mul(&[kappa_pow, rad_pow]);
        sub = arena.subs_structural(sub, id, repl);
    }
    let ExprNode::Symbol(rad_sym) = *arena.node(rad) else {
        return None;
    };
    if !is_rational_in_all(arena, sub, &[s, c, rad]) || !is_rational_in(arena, sub, rad_sym) {
        return None;
    }
    // `sub = rad·E₁` with `E₁` free of `rad` after `rad² = 1 + ε·w`.
    let (num, den) = crate::poly::polybridge::as_numer_denom(arena, sub);
    let one = arena.one;
    let eps_w = arena.mul(&[eps, w]);
    let rad_sq = arena.add(&[one, eps_w]);
    let reduce_rad = |arena: &mut Arena, p: ExprId| -> Option<(ExprId, ExprId)> {
        let cs = crate::transforms::solve::symbolic_poly_coeffs(arena, p, rad)?;
        let mut even: Vec<ExprId> = Vec::new();
        let mut odd: Vec<ExprId> = Vec::new();
        for (j, &k) in cs.iter().enumerate() {
            let e = arena.int(i64::try_from(j / 2).ok()?);
            let power = arena.pow(rad_sq, e);
            let term = arena.mul(&[k, power]);
            if j % 2 == 0 {
                even.push(term);
            } else {
                odd.push(term);
            }
        }
        let even = arena.add(&even);
        let odd = arena.add(&odd);
        Some((
            crate::transforms::expand::expand(arena, even),
            crate::transforms::expand::expand(arena, odd),
        ))
    };
    let (n_even, n_odd) = reduce_rad(arena, num)?;
    let (d_even, d_odd) = reduce_rad(arena, den)?;
    // `(n₀ + rad·n₁)/(d₀ + rad·d₁)`: only `rad·n₁/d₀` and `n₀/(rad·d₁)` are
    // odd in `rad`.
    let e1 = if arena.is_zero_structural(n_even) && arena.is_zero_structural(d_odd) {
        arena.div(n_odd, d_even)
    } else if arena.is_zero_structural(n_odd) && arena.is_zero_structural(d_even) {
        // `n₀/(rad·d₁) = rad·n₀/((1 + ε·w)·d₁)`.
        let d = arena.mul(&[rad_sq, d_odd]);
        arena.div(n_even, d)
    } else {
        return None;
    };
    // `v = u/2 + φ`; `sin u`, `cos u` in `S = sin v`, `C = cos v`.
    let big_s = arena.symbol("__hs");
    let big_c = arena.symbol("__hc");
    let two = arena.int(2);
    let two_sc = arena.mul(&[two, big_s, big_c]);
    let s_sq = arena.pow(big_s, two);
    let c_sq = arena.pow(big_c, two);
    let c2_minus_s2 = arena.sub(c_sq, s_sq);
    let neg = |arena: &mut Arena, z: ExprId| arena.neg(z);
    let w_is_sin = w == s;
    let (sin_u, cos_u, phi) = match (w_is_sin, eps_positive) {
        (true, true) => (neg(arena, c2_minus_s2), two_sc, arena.rational(1, 4)),
        (true, false) => (c2_minus_s2, neg(arena, two_sc), arena.rational(-1, 4)),
        (false, true) => (
            neg(arena, two_sc),
            neg(arena, c2_minus_s2),
            arena.rational(1, 2),
        ),
        (false, false) => (two_sc, c2_minus_s2, arena.zero),
    };
    let pi = arena.pi();
    let phi = arena.mul(&[phi, pi]);
    // `g(v) = 2·√2·S·E₁(sin u, cos u)` (`du = 2·dv`, `rad = √2·σ·S`).
    let g = arena.subs_structural(e1, s, sin_u);
    let g = arena.subs_structural(g, c, cos_u);
    let sqrt2 = arena.sqrt(two);
    let g = arena.mul(&[two, sqrt2, big_s, g]);
    let g = clear_nested_fractions(arena, g, big_s);
    let (g_num, g_den) = crate::poly::polybridge::as_numer_denom(arena, g);
    // Reduce `C² = 1 − S²` in both: `A(S) + C·B(S)`.
    let reduce_c = |arena: &mut Arena, p: ExprId| -> Option<(ExprId, ExprId)> {
        let cs = crate::transforms::solve::symbolic_poly_coeffs(arena, p, big_c)?;
        let one = arena.one;
        let s_sq = arena.pow(big_s, two);
        let minus = arena.neg(s_sq);
        let one_minus = arena.add(&[one, minus]);
        let mut even: Vec<ExprId> = Vec::new();
        let mut odd: Vec<ExprId> = Vec::new();
        for (j, &k) in cs.iter().enumerate() {
            let e = arena.int(i64::try_from(j / 2).ok()?);
            let power = arena.pow(one_minus, e);
            let term = arena.mul(&[k, power]);
            if j % 2 == 0 {
                even.push(term);
            } else {
                odd.push(term);
            }
        }
        let even = arena.add(&even);
        let odd = arena.add(&odd);
        Some((
            crate::transforms::expand::expand(arena, even),
            crate::transforms::expand::expand(arena, odd),
        ))
    };
    let (a_part, b_part) = reduce_c(arena, g_num)?;
    let (den_s, den_c) = reduce_c(arena, g_den)?;
    if !arena.is_zero_structural(den_c) {
        return None;
    }
    // The denominator: a constant times `Sᵐ`.
    let den_coeffs = crate::transforms::solve::symbolic_poly_coeffs(arena, den_s, big_s)?;
    let nonzero: Vec<usize> = (0..den_coeffs.len())
        .filter(|&j| !arena.is_zero_structural(den_coeffs[j]))
        .collect();
    let [m] = nonzero.as_slice() else {
        return None;
    };
    let mut m = *m;
    // `A + C·B` vanishes to order `k` at `S = 0` (`C = ±1` there) exactly when
    // `Sᵏ` divides `A` and `B`: those powers cancel against `Sᵐ` (`cos⁶u/√(1 +
    // sin u)` has no pole where `σ` flips).
    let lowest = |arena: &mut Arena, p: ExprId| -> Option<usize> {
        if arena.is_zero_structural(p) {
            return Some(usize::MAX);
        }
        let cs = crate::transforms::solve::symbolic_poly_coeffs(arena, p, big_s)?;
        cs.iter().position(|&k| !arena.is_zero_structural(k))
    };
    let k = lowest(arena, a_part)?.min(lowest(arena, b_part)?).min(m);
    let (a_part, b_part, den_s) = if k > 0 {
        let shift = |arena: &mut Arena, p: ExprId| -> Option<ExprId> {
            if arena.is_zero_structural(p) {
                return Some(p);
            }
            let cs = crate::transforms::solve::symbolic_poly_coeffs(arena, p, big_s)?;
            let mut terms: Vec<ExprId> = Vec::new();
            for (j, &c) in cs.iter().enumerate().skip(k) {
                let e = arena.int(i64::try_from(j - k).ok()?);
                let power = arena.pow(big_s, e);
                terms.push(arena.mul(&[c, power]));
            }
            Some(arena.add(&terms))
        };
        let a = shift(arena, a_part)?;
        let b = shift(arena, b_part)?;
        let d = shift(arena, den_s)?;
        m -= k;
        (a, b, d)
    } else {
        (a_part, b_part, den_s)
    };
    let v = arena.symbol("__hv");
    let ExprNode::Symbol(v_sym) = *arena.node(v) else {
        return None;
    };
    let b_times_c = arena.mul(&[big_c, b_part]);
    let half = arena.rational(1, 2);
    let half_u = arena.mul(&[half, u]);
    let v_of_u = arena.add(&[half_u, phi]);
    if m > 0 {
        // Poles where `σ` flips: `F = σ·G`, with `σ = √2·sin v/√(1 + ε·w)`
        // (analytic in the parameters of `u`, as `sign(sin v)` is not).
        let n = arena.add(&[a_part, b_times_c]);
        let big_g = trig_rational_in_u(arena, (n, den_s), (big_s, big_c), v, v_sym)?;
        let back = arena.subs_structural(big_g, v, v_of_u);
        let sin_v = arena.sin(v_of_u);
        let sqrt2 = arena.sqrt(two);
        let w_u = if w_is_sin { arena.sin(u) } else { arena.cos(u) };
        let eps_w_u = arena.mul(&[eps, w_u]);
        let one_eps_w = arena.add(&[one, eps_w_u]);
        let rad_u = arena.sqrt(one_eps_w);
        let minus_one = arena.int(-1);
        let inv_rad = arena.pow(rad_u, minus_one);
        tracing::debug!("integrate: a radical of 1 ± sin u (cos u) through the half angle");
        let big_f = arena.mul(&[sqrt2, sin_v, inv_rad, back]);
        return Some(crate::transforms::eval::eval(arena, big_f));
    }
    // `g(v + π) = −g(v)`: `A` odd and `B` even in `S`.  Each part goes
    // through Bioche's parity routes (`t = cos v`, `t = sin v`) to a
    // polynomial odd in `cos v` (`sin v`), with no constant: `G(v + π) =
    // −G(v)`.
    let odd_or_zero = |arena: &mut Arena, p: ExprId, parity: usize| {
        arena.is_zero_structural(p) || parity_in(arena, p, big_s) == Some(parity)
    };
    if !odd_or_zero(arena, a_part, 1) || !odd_or_zero(arena, b_part, 0) {
        return None;
    }
    // `σ·G` without `σ`: `σ·sin v = rad/√2` and `σ·cos v = rad·sin 2v/(√2·(1 +
    // ε·w))` (`sin²v = (1 + ε·w)/2`), with `rad = √(1 + ε·w)` of `u`: a form
    // analytic in the parameters of `u`, as Rubi writes these answers.
    let sin_u_node = arena.sin(u);
    let cos_u_node = arena.cos(u);
    let w_u = if w_is_sin { sin_u_node } else { cos_u_node };
    let eps_w_u = arena.mul(&[eps, w_u]);
    let one_eps_w = arena.add(&[one, eps_w_u]);
    let s2_u = arena.mul(&[half, one_eps_w]);
    let minus_s2 = arena.neg(s2_u);
    let c2_u = arena.add(&[one, minus_s2]);
    let sin_2v = match (w_is_sin, eps_positive) {
        (true, true) => cos_u_node,
        (true, false) => arena.neg(cos_u_node),
        (false, true) => arena.neg(sin_u_node),
        (false, false) => sin_u_node,
    };
    let mut over_s: Vec<ExprId> = Vec::new();
    let mut over_c: Vec<ExprId> = Vec::new();
    let mut at_zero: Vec<ExprId> = Vec::new();
    let sin_v = arena.sin(v);
    let cos_v = arena.cos(v);
    for (part, fv, sym, sq, out) in [
        (b_times_c, sin_v, big_s, s2_u, &mut over_s),
        (a_part, cos_v, big_c, c2_u, &mut over_c),
    ] {
        if arena.is_zero_structural(part) {
            continue;
        }
        let big_g = trig_rational_in_u(arena, (part, den_s), (big_s, big_c), v, v_sym)?;
        let p = arena.subs_structural(big_g, fv, sym);
        let p = crate::transforms::eval::eval(arena, p);
        if contains_var_id(arena, p, v) || parity_in(arena, p, sym) != Some(1) {
            return None;
        }
        let coeffs = crate::transforms::solve::symbolic_poly_coeffs(arena, p, sym)?;
        for (j, &k) in coeffs.iter().enumerate().skip(1).step_by(2) {
            let e = arena.int(i64::try_from(j / 2).ok()?);
            let power = arena.pow(sq, e);
            out.push(arena.mul(&[k, power]));
            if sym == big_c {
                at_zero.push(k);
            }
        }
    }
    let rad_u = arena.sqrt(one_eps_w);
    let inv_sqrt2 = {
        let r = arena.sqrt(two);
        let minus_one = arena.int(-1);
        arena.pow(r, minus_one)
    };
    let p_s = arena.add(&over_s);
    let p_c = arena.add(&over_c);
    let ratio = arena.div(sin_2v, one_eps_w);
    let c_term = arena.mul(&[ratio, p_c]);
    let bracket = arena.add(&[p_s, c_term]);
    let main = arena.mul(&[rad_u, inv_sqrt2, bracket]);
    // `σ·G` steps by `2·G(0)` at every `v = kπ`; `G(0)` is the sum of the
    // coefficients of the odd polynomial in `cos v` (`sin 0 = 0`).
    let g0 = arena.add(&at_zero);
    let g0 = crate::transforms::eval::eval(arena, g0);
    let minus_two = arena.int(-2);
    let minus_one = arena.int(-1);
    let inv_pi = arena.pow(pi, minus_one);
    let v_over_pi = arena.mul(&[v_of_u, inv_pi]);
    let fl = arena.floor(v_over_pi);
    let correction = arena.mul(&[minus_two, g0, fl]);
    tracing::debug!("integrate: a radical of 1 ± sin u (cos u) through the half angle");
    let big_f = arena.add(&[main, correction]);
    Some(crate::transforms::eval::eval(arena, big_f))
}

/// `∫ A(sin u, cos u) du` for an algebraic `A` odd in `cos u` with every
/// radical a function of `sin u` alone (`t = sin u`), or odd in `sin u`
/// with radicals of `cos u` (`t = cos u`): Bioche's first two rules of
/// [`try_trig_rational_substitution`] for radicals (`cos⁵u·√(a + b·sin u)`,
/// Rubi 4.1.1.2, is `∫ (1 − t²)²·√(a + b·t) dt`).  The integrand in `t`
/// goes through the whole pipeline; `G(sin u)`, `G(cos u)` need no
/// correction (the substitutions have no poles).
fn odd_algebraic_in_u(
    arena: &mut Arena,
    e: ExprId,
    sc: (ExprId, ExprId),
    u: ExprId,
) -> Option<ExprId> {
    let (s, c) = sc;
    let t = arena.symbol("__toa");
    // The bases of the radicals: every one must be free of `w`.
    let radical_bases: Vec<ExprId> = crate::base::walk::post_order_ids(arena, e)
        .into_iter()
        .filter_map(|id| match *arena.node(id) {
            ExprNode::Pow(base, ex) if !arena.as_num(ex).is_some_and(|r| r.is_integer()) => {
                Some(base)
            }
            _ => None,
        })
        .collect();
    let sin_u = arena.sin(u);
    let cos_u = arena.cos(u);
    for (w, o, back, sign) in [(c, s, sin_u, 1), (s, c, cos_u, -1)] {
        let ExprNode::Symbol(w_sym) = *arena.node(w) else {
            continue;
        };
        if radical_bases.iter().any(|&b| contains_var_id(arena, b, w))
            || !is_rational_in(arena, e, w_sym)
        {
            continue;
        }
        let (num, den) = crate::poly::polybridge::as_numer_denom(arena, e);
        let (Some(pn), Some(pd)) = (parity_in(arena, num, w), parity_in(arena, den, w)) else {
            continue;
        };
        if pn == pd {
            continue;
        }
        let Some(in_t) = odd_part_in_t(arena, (num, den), (pn, pd), w, o, t) else {
            continue;
        };
        let sign = arena.int(sign);
        let in_t = arena.mul(&[sign, in_t]);
        let in_t = crate::transforms::eval::eval(arena, in_t);
        if contains_var_id(arena, in_t, s) || contains_var_id(arena, in_t, c) {
            continue;
        }
        tracing::debug!(integrand_t = %arena.display(in_t), "integrate: an algebraic function through t = sin u or cos u");
        let Some(g) = integrate_nested_generic(arena, in_t, t) else {
            continue;
        };
        return Some(arena.subs_structural(g, t, back));
    }
    None
}

/// `∫ A(sin u, cos u) du` for an algebraic function `A` of `tan u` alone
/// (`s = sin u`, `c = cos u` in `sc`): radicals of `k·tan u`, `a + b·tan u`,
/// `a + b·tan²u` (Rubi 4.3, 4.4: `√(d·tan u)`, `(a + i·a·tan u)^(7/2)`) times a
/// rational function of `sin u`, `cos u` invariant under `u → u + π`.
/// With `s = t·c`, `A` is a function of `t` and of `c` in even (or odd)
/// integer powers outside the radicals, `c² = 1/(1 + t²)`, `du = dt/(1 + t²)`;
/// the integrand in `t` goes through the whole pipeline (its radical
/// substitutions).  The answer `G(tan u)` gets the floor correction of
/// [`crate::transforms::trig_integ::continuous_through_tan`] where its
/// jump is decided; otherwise it is kept only when the integrand is not
/// continuous across the poles of `tan u` ([`tan_pole_continuous`]: `√(tan
/// u)` is real on one side only), so that no answer jumps where the
/// integrand is continuous.
fn tan_algebraic_in_u(
    arena: &mut Arena,
    e: ExprId,
    sc: (ExprId, ExprId),
    u: ExprId,
) -> Option<ExprId> {
    let (s, c) = sc;
    let ExprNode::Symbol(c_sym) = *arena.node(c) else {
        return None;
    };
    let t = arena.symbol("__tat");
    let ExprNode::Symbol(t_sym) = *arena.node(t) else {
        return None;
    };
    let tc = arena.mul(&[t, c]);
    let e = arena.subs_structural(e, s, tc);
    let e = crate::transforms::eval::eval(arena, e);
    if contains_var_id(arena, e, s) || !is_rational_in(arena, e, c_sym) {
        return None;
    }
    let (num, den) = crate::poly::polybridge::as_numer_denom(arena, e);
    let num_c = crate::transforms::solve::symbolic_poly_coeffs(arena, num, c)?;
    let den_c = crate::transforms::solve::symbolic_poly_coeffs(arena, den, c)?;
    let parity = |arena: &mut Arena, cs: &[ExprId]| -> Option<usize> {
        let mut nonzero = [false, false];
        for (j, &k) in cs.iter().enumerate() {
            if !arena.is_zero_structural(k) {
                nonzero[j % 2] = true;
            }
        }
        match nonzero {
            [true, false] => Some(0),
            [false, true] => Some(1),
            _ => None,
        }
    };
    let shift = parity(arena, &num_c)?;
    if parity(arena, &den_c)? != shift {
        return None;
    }
    tracing::debug!("integrate: an algebraic function of tan u, through t = tan u");
    let one = arena.one;
    let two = arena.int(2);
    let t_sq = arena.pow(t, two);
    let one_plus_t_sq = arena.add(&[one, t_sq]);
    let in_t = |arena: &mut Arena, cs: &[ExprId]| -> Option<ExprId> {
        let mut terms: Vec<ExprId> = Vec::new();
        for (j, &k) in cs.iter().enumerate().skip(shift).step_by(2) {
            let e = arena.int(-i64::try_from((j - shift) / 2).ok()?);
            let c_pow = arena.pow(one_plus_t_sq, e);
            terms.push(arena.mul(&[k, c_pow]));
        }
        Some(arena.add(&terms))
    };
    let num_t = in_t(arena, &num_c)?;
    let den_t = in_t(arena, &den_c)?;
    let dt = arena.mul(&[den_t, one_plus_t_sq]);
    let integrand_t = arena.div(num_t, dt);
    let integrand_t = crate::transforms::eval::eval(arena, integrand_t);
    if contains_var_id(arena, integrand_t, c) {
        return None;
    }
    tracing::debug!(integrand_t = %arena.display(integrand_t), "tan u: algebraic integrand in t");
    let g = integrate_nested_generic(arena, integrand_t, t)?;
    if let Some(r) = crate::transforms::trig_integ::continuous_through_tan(arena, g, t, t_sym, u) {
        return Some(r);
    }
    if tan_pole_continuous(arena, integrand_t, t) != Some(false) {
        tracing::debug!("tan u: the jump at the poles of tan u is not decided");
        return None;
    }
    let tan_u = arena.tan(u);
    let back = arena.subs_structural(g, t, tan_u);
    Some(crate::transforms::trig_integ::atan_tan_terms_to_argument(
        arena, back, u,
    ))
}

/// Is the integrand `f(u) = h(t)·(1 + t²)` (`t = tan u`) continuous across
/// the poles of `tan u`, for its parameters at the generic values of
/// [`FTC_PARAMETER_VALUES`]?  By the limits of `(1 + t²)·h(t)` at `t = ±∞`:
/// `Some(false)` when one is infinite or they differ (`√(tan u)` is real on
/// one side only), `Some(true)` when they agree, `None` when a limit is not
/// found.
fn tan_pole_continuous(arena: &mut Arena, h: ExprId, t: ExprId) -> Option<bool> {
    let one = arena.one;
    let two = arena.int(2);
    let t_sq = arena.pow(t, two);
    let one_plus_t_sq = arena.add(&[one, t_sq]);
    let mut k = arena.mul(&[h, one_plus_t_sq]);
    let mut params: Vec<(String, ExprId)> = Vec::new();
    for s in crate::base::walk::free_symbols(arena, k) {
        if s == t {
            continue;
        }
        let ExprNode::Symbol(sid) = *arena.node(s) else {
            return None;
        };
        params.push((arena.symbol_name(sid).to_owned(), s));
    }
    if params.len() > FTC_PARAMETER_VALUES.len() {
        return None;
    }
    params.sort();
    for (j, &(_, s)) in params.iter().enumerate() {
        let (p, d) = FTC_PARAMETER_VALUES[j];
        let value = arena.rational(p, d);
        k = crate::transforms::subs::subs(arena, k, s, value);
    }
    let k = crate::transforms::eval::eval(arena, k);
    let mut values = Vec::with_capacity(2);
    for point in [arena.infinity(), arena.neg_infinity()] {
        let v = arena.limit_expr(k, t, point).ok()?;
        let v = crate::transforms::eval::eval(arena, v);
        if crate::base::walk::has_unevaluated(arena, v) || contains_var_id(arena, v, t) {
            return None;
        }
        if contains_non_finite(arena, v) {
            return Some(false);
        }
        let Ok(z) = crate::transforms::evalf::evalf_complex64(arena, v) else {
            return None;
        };
        if !z.re.is_finite() || !z.im.is_finite() {
            return Some(false);
        }
        values.push(z);
    }
    let gap = (values[0] - values[1]).norm();
    Some(gap <= 1e-9 * values[0].norm().max(1.0))
}

/// Does `e` contain the symbol `v` (free)?
fn contains_var_id(arena: &Arena, e: ExprId, v: ExprId) -> bool {
    match *arena.node(v) {
        ExprNode::Symbol(sid) => contains_var(arena, e, sid),
        _ => true,
    }
}

/// [`jump_kept_undecided`] for the answer `g` of the integrand `h` in `t =
/// tan w`, and inside the trigonometric substitutions of 0.38
/// ([`crate::transforms::trig_integ::strict_jumps_active`]) only
/// where the integrand is not continuous across the poles of `tan w`
/// ([`tan_pole_continuous`] at generic values of the parameters): those
/// routes return no answer that jumps where the integrand is continuous
/// (`∫ cos²u/(a − b·sin⁴u) du`, a `RootSum` over a polynomial with parameters,
/// is refused).
fn undecided_jump_kept(
    arena: &mut Arena,
    h: ExprId,
    g: ExprId,
    t: ExprId,
    t_sym: SymbolId,
) -> bool {
    jump_kept_undecided(arena, g, t_sym)
        && (!crate::transforms::trig_integ::strict_jumps_active()
            || tan_pole_continuous(arena, h, t) == Some(false))
}

/// May an antiderivative `G(tan w)` (`g` = `G(t)`, `t` the substitution's
/// symbol) whose jump `G(+∞) − G(−∞)` at the poles of `tan w` is not
/// decided be returned uncorrected, continuous only between those poles?
/// Yes when `G` has parameters — the jump depends on their values and, for
/// parameters not declared real, on the sides of the cuts their logarithms
/// approach (`∫ dx/(a + b·cos x)`; SymPy and Rubi answer such integrands so
/// too, and refusing them lost 435 answers of the Rubi suite) — or a
/// `RootSum` whose end values are not found (a logarithm of degree ≥ 2 in
/// `t`).  Any other undecided jump makes the substitution refuse.
fn jump_kept_undecided(arena: &Arena, g: ExprId, t_sym: SymbolId) -> bool {
    crate::base::walk::free_symbols(arena, g)
        .iter()
        .any(|&s| !matches!(arena.node(s), ExprNode::Symbol(sid) if *sid == t_sym))
        || crate::base::walk::post_order_ids(arena, g)
            .iter()
            .any(|&id| matches!(arena.node(id), ExprNode::RootSum(..)))
}

/// Normalise a rational expression in `var` with nested fractions into a
/// single cancelled `numer/denom`.
///
/// `together` only combines the top-level sum, so sums buried inside
/// powers (e.g. `2/((1+t²)(2 + (1−t²)/(1+t²)))`) are combined bottom-up
/// first, then the whole expression is split into numerator/denominator
/// and cancelled.
///
/// Inside an `integrate` call the result is remembered until the outermost
/// call ends ([`CLEARED_MEMO`]).
pub(crate) fn clear_nested_fractions(arena: &mut Arena, expr: ExprId, var: ExprId) -> ExprId {
    let inside = NODE_BUDGET_DEPTH.with(std::cell::Cell::get) > 0;
    let key = (std::ptr::from_ref::<Arena>(arena) as usize, expr, var);
    if inside && let Some(found) = CLEARED_MEMO.with(|m| m.borrow().get(&key).copied()) {
        return found;
    }
    let cleared = clear_nested_fractions_uncached(arena, expr, var);
    if inside {
        CLEARED_MEMO.with(|m| m.borrow_mut().insert(key, cleared));
    }
    cleared
}

thread_local! {
    /// [`clear_nested_fractions`] during the current top-level `integrate`
    /// (cleared with [`INTEGRATE_MEMO`]), by (arena, expression, variable).
    /// The trigonometric substitutions normalise the same pieces again for
    /// every degenerate case of the parameters and every group of a
    /// numerator: `∫ (A + B·sec u + C·sec²u)/(a + b·sec u)⁴ du` made 116
    /// such calls (1.4 s, multiplying out numerators such as `(t² + 1)⁷·…`)
    /// on inputs whose distinct ones took 0.16 s (0.38).
    static CLEARED_MEMO: std::cell::RefCell<FxHashMap<(usize, ExprId, ExprId), ExprId>> =
        std::cell::RefCell::new(FxHashMap::default());
}

/// [`clear_nested_fractions`] without the memo.
fn clear_nested_fractions_uncached(arena: &mut Arena, expr: ExprId, var: ExprId) -> ExprId {
    let mut current = expr;
    // Bottom-up: combine every inner sum over a common denominator.
    for _ in 0..16 {
        let order = crate::base::walk::post_order_ids(arena, current);
        let mut changed = false;
        for id in order {
            if id == current {
                continue;
            }
            if let ExprNode::Add(_) = arena.node(id) {
                let t = crate::poly::polybridge::together(arena, id);
                if t != id {
                    current = arena.subs_structural(current, id, t);
                    changed = true;
                    break;
                }
            }
        }
        if !changed {
            break;
        }
    }
    let together = crate::poly::polybridge::together(arena, current);
    let (n, d) = crate::poly::polybridge::as_numer_denom(arena, together);
    let n = crate::transforms::expand::expand(arena, n);
    let d = crate::transforms::expand::expand(arena, d);
    let n = crate::transforms::eval::eval(arena, n);
    let d = crate::transforms::eval::eval(arena, d);
    let ratio = arena.div(n, d);
    let cancelled = arena.cancel_expr(ratio, var);
    crate::transforms::eval::eval(arena, cancelled)
}

/// Attempt cyclic integration by parts for integrals like `∫ exp(x)·sin(x) dx`.
///
/// After two IBP rounds (with u₂ = du₁, dv₂ = v₁), if the remaining
/// integral is a constant multiple `c` of the original integrand we
/// solve algebraically:
///
/// ```text
///   I = boundary₁ − (boundary₂ − c·I)
///   I(1 − c) = boundary₁ − boundary₂
///   I = (boundary₁ − boundary₂) / (1 − c)
/// ```
fn try_cyclic_ibp(
    arena: &mut Arena,
    factors: &[ExprId],
    var: ExprId,
    var_sym: SymbolId,
    depth: usize,
) -> Option<ExprId> {
    if factors.len() != 2 || depth < 2 {
        return None;
    }

    // Use LIATE ordering: lower rank = u (trig before exp)
    let (u_idx, dv_idx) = {
        let r0 = liate_rank(arena, factors[0], var, var_sym);
        let r1 = liate_rank(arena, factors[1], var, var_sym);
        if r0 <= r1 { (0, 1) } else { (1, 0) }
    };
    let u1 = factors[u_idx];
    let dv1 = factors[dv_idx];

    // Both must depend on var
    if !contains_var(arena, u1, var_sym) || !contains_var(arena, dv1, var_sym) {
        return None;
    }

    // ── Round 1: ∫ u1·dv1 dx = u1·v1 − ∫ v1·du1 dx ──────────────
    let v1 = integrate_node(arena, dv1, var, var_sym, depth - 1);
    if crate::base::walk::has_unevaluated(arena, v1) {
        tracing::trace!("try_cyclic_ibp: v1 has unevaluated nodes, bailing");
        return None;
    }
    let du1 = crate::transforms::diff::diff(arena, u1, var);
    let boundary1 = arena.mul(&[u1, v1]); // u1·v1

    // ── Round 2: ∫ v1·du1 dx  with u₂ = du1, dv₂ = v1 ───────────
    let v2 = integrate_node(arena, v1, var, var_sym, depth - 1);
    if crate::base::walk::has_unevaluated(arena, v2) {
        tracing::trace!("try_cyclic_ibp: v2 has unevaluated nodes, bailing");
        return None;
    }
    let du2 = crate::transforms::diff::diff(arena, du1, var); // u1''
    let boundary2 = arena.mul(&[du1, v2]); // du1·v2

    // remaining₂ body = v2 · du2
    let remaining2 = arena.mul(&[v2, du2]);
    let original = arena.mul(&[factors[0], factors[1]]);

    // ── Check remaining₂ = c · original for some constant c ──────

    // Fast path: c = −1 (covers exp·sin, exp·cos and similar)
    let sum = arena.add(&[remaining2, original]);
    if sum == arena.zero {
        tracing::debug!("cyclic IBP detected (c = -1)");
        let numerator = arena.sub(boundary1, boundary2);
        let two = arena.int(2);
        return Some(arena.div(numerator, two));
    }

    // Fast path: c = +1 would be degenerate (1−c = 0), skip.
    let diff_check = arena.sub(remaining2, original);
    if diff_check == arena.zero {
        return None;
    }

    // General path: try polynomial cancellation on the ratio.
    let ratio = arena.div(remaining2, original);
    let cancelled = arena.cancel_expr(ratio, var);
    if !contains_var(arena, cancelled, var_sym) && cancelled != arena.one {
        tracing::debug!("cyclic IBP detected (general c)");
        let numerator = arena.sub(boundary1, boundary2);
        let one = arena.one;
        let one_minus_c = arena.sub(one, cancelled);
        return Some(arena.div(numerator, one_minus_c));
    }

    None
}

/// What one top-level `integrate` has learnt about a sub-integrand in a
/// given search context (see [`MemoKey`]).
#[derive(Clone, Copy)]
enum MemoOutcome {
    /// No closed form with this much remaining depth (or less).
    Failed { depth: usize },
    /// A fully evaluated antiderivative.
    Solved(ExprId),
}

/// A sub-integrand in its search context.  The strategies that apply
/// depend on whether `try_risch_rational` may run (its recursion guard) and
/// on the nesting of substitution strategies, so both are part of the key;
/// the arena's address keeps two arenas on one thread apart.
#[derive(Clone, Copy, PartialEq, Eq, Hash)]
struct MemoKey {
    arena: usize,
    expr: ExprId,
    var: ExprId,
    in_risch: bool,
    subst_depth: u8,
}

thread_local! {
    /// Outcomes of `integrate_node` during the current top-level
    /// `integrate` (cleared when it starts).  A failing search reaches the
    /// same sub-integrand again and again — by parts, substitution and
    /// partial fractions lead to the same pieces: `∫ x^(3/2)/(sin(−1) −
    /// 2x) dx` made 918 u-substitution attempts on 53 distinct integrands
    /// (0.24).
    static INTEGRATE_MEMO: std::cell::RefCell<FxHashMap<MemoKey, MemoOutcome>> =
        std::cell::RefCell::new(FxHashMap::default());
}

/// Integrate a single node with respect to `var`, remembering the outcome
/// for the rest of the top-level call: a sub-integrand that already failed
/// with at least this much depth fails at once (less depth only prunes
/// more), and a solved one returns its antiderivative.
fn integrate_node(
    arena: &mut Arena,
    expr: ExprId,
    var: ExprId,
    var_sym: SymbolId,
    depth: usize,
) -> ExprId {
    let key = MemoKey {
        arena: std::ptr::from_ref::<Arena>(arena) as usize,
        expr,
        var,
        in_risch: crate::calculus::risch::rational_guard_active(),
        subst_depth: SUBST_DEPTH.with(std::cell::Cell::get),
    };
    match INTEGRATE_MEMO.with(|m| m.borrow().get(&key).copied()) {
        Some(MemoOutcome::Solved(result)) => return result,
        Some(MemoOutcome::Failed { depth: failed }) if depth <= failed => {
            return arena.intern(ExprNode::Integral(expr, var));
        }
        _ => {}
    }
    // `∫ f(ln x)`-type integrands (`sin(ln x)`, `x²·cos(a + b·ln(c·xⁿ))`)
    // wherever they occur — also as a term of a sum, which the stage-level
    // substitutions never see on its own — and before by parts, which
    // would otherwise take `u = x²` and nest itself ten deep on the
    // substitution's `dv` (`∫ x·cos(ln(x)/3) dx` came out correct but with
    // coefficients such as `1463942969757/3700000000000`).
    let result = if depth > 0
        && !matches!(arena.node(expr), ExprNode::Add(_))
        && let Some(r) = try_log_substitution(arena, expr, var, var_sym)
    {
        r
    } else {
        integrate_node_uncached(arena, expr, var, var_sym, depth)
    };
    // Every intermediate result in the form the stage exit gives it: a
    // route that continues from one (by parts differentiates `u`, which
    // may be an earlier `∫`) must not meet `ln|a²x² + 1|` for an
    // unassumed `a`.  That leaves the stage as `ln(a²x² + 1)`, whose
    // derivative is `2a²x/(a²x² + 1)`, while `diff` gives `ln|·|` its
    // complex-safe derivative since 0.31 (`∫ x²(c + a²c·x²)·atan(a·x)`
    // then stayed unevaluated).
    let result = analytic_log_of_complex_arguments(arena, result, var_sym);
    let outcome = if matches!(arena.node(result), ExprNode::Integral(e, v) if *e == expr && *v == var)
    {
        (!StepCap::active()).then_some(MemoOutcome::Failed { depth })
    } else if !crate::base::walk::has_unevaluated(arena, result) {
        Some(MemoOutcome::Solved(result))
    } else {
        None
    };
    if let Some(outcome) = outcome {
        INTEGRATE_MEMO.with(|m| {
            let mut m = m.borrow_mut();
            let keep_old = matches!(
                (m.get(&key), outcome),
                (Some(MemoOutcome::Failed { depth: old }), MemoOutcome::Failed { depth: new }) if *old >= new
            );
            if !keep_old {
                m.insert(key, outcome);
            }
        });
    }
    result
}

/// [`integrate_node`] without the memo.
fn integrate_node_uncached(
    arena: &mut Arena,
    expr: ExprId,
    var: ExprId,
    var_sym: SymbolId,
    depth: usize,
) -> ExprId {
    tracing::trace!(depth = depth, "integrate_node entered");

    if depth == 0 || node_budget_exhausted() || arena_budget_exhausted(arena) {
        return arena.intern(ExprNode::Integral(expr, var));
    }

    // ── Linearity first: ∫ c·f = c·∫ f for factors c free of the variable ──
    // Every rule below then sees the integrand without its constant
    // factors.  Before 0.30 only the `Mul` arm split them off, after the
    // whole-expression rules had run on `c·f`: the trig-power rule handed
    // back `2·∫ sin/cos` (its unevaluated result with the constant
    // re-attached, which the check for an `Integral` node did not see), so
    // `∫ 2·sin x/cos x`, `∫ −sin x/cos x` and `∫ 2·cos x/sin x` stayed
    // unevaluated while `∫ sin x/cos x` worked (and variation of parameters
    // failed on `y″ + y = tan x`).
    if let Some((constants, f)) = split_constant_factors(arena, expr, var_sym) {
        // `f` has fewer factors than `expr`, so the same depth cannot loop,
        // unless rebuilding the product exposed a constant factor again.
        let d = if split_constant_factors(arena, f, var_sym).is_some() {
            depth - 1
        } else {
            depth
        };
        let big_f = integrate_node(arena, f, var, var_sym, d);
        if matches!(arena.node(big_f), ExprNode::Integral(..)) {
            return arena.intern(ExprNode::Integral(expr, var));
        }
        return wrap_with_constants(arena, big_f, &constants);
    }

    // Try trig power/product integration first (sin^n, cos^n, sin^m*cos^n)
    if let Some(result) =
        crate::transforms::trig_integ::try_trig_power_integral(arena, expr, var, var_sym)
    {
        // Only use the trig-power result when it is fully evaluated;
        // negative-exponent cases (e.g. sin·cos^{-2}) come back as
        // unevaluated Integral nodes — fall through so the Mul handler
        // can try sec·tan / csc·cot patterns and u-substitution.
        if !matches!(arena.node(result), ExprNode::Integral(_, _)) {
            return result;
        }
    }

    // ── Trig identity rewrites ────────────────────────────────────
    // Rewrite squared trig identities to forms with known antiderivatives.
    if let ExprNode::Pow(trig_base, trig_exp) = arena.node(expr).clone()
        && let Some(n_val) = arena.as_num(trig_exp)
    {
        let two_r = num_rational::Ratio::<num_bigint::BigInt>::from_integer(2.into());
        if *n_val == two_r {
            // tan²(g) → sec²(g) − 1 = cos(g)^{-2} − 1
            if let ExprNode::Tan(inner) = arena.node(trig_base).clone() {
                let cos_inner = arena.cos(inner);
                let neg_two = arena.int(-2);
                let sec_sq = arena.pow(cos_inner, neg_two);
                let rewritten = arena.sub(sec_sq, arena.one);
                return integrate_node(arena, rewritten, var, var_sym, depth - 1);
            }
            // tanh²(g) → 1 − sech²(g) = 1 − cosh(g)^{-2}
            if let ExprNode::Tanh(inner) = arena.node(trig_base).clone() {
                let cosh_inner = arena.cosh(inner);
                let neg_two = arena.int(-2);
                let sech_sq = arena.pow(cosh_inner, neg_two);
                let rewritten = arena.sub(arena.one, sech_sq);
                return integrate_node(arena, rewritten, var, var_sym, depth - 1);
            }
        }
    }

    // ── Type dispatch: rational function detection ────────────────
    // Before dispatching on node type, check if the expression is a
    // rational function P(x)/Q(x).  If so, route to the complete
    // Hermite + Rothstein-Trager algorithm.  This handles ALL structural
    // variants (Mul with negative powers, Pow with negative exponent,
    // etc.) because as_numer_denom normalizes them all to (numer, denom).
    //
    // This is the standard CAS architecture: rational function integration
    // is a solved problem with efficient algorithms, and it should run
    // before any heuristic pattern matching.
    //
    // The result is verified numerically before it is trusted: when the
    // Rothstein–Trager resultant has nested-radical roots the `log_to_real`
    // conversion can emit a closed form with opaque `re(…)`/`im(…)`
    // constants that is simply wrong (0.21 audit: `∫ 1/((x²−4)²+1)`).  A
    // rejected candidate goes to the biquadratic route below; if that does
    // not apply either, the integral is left unevaluated: every remaining
    // strategy for a rational function is the `apart` root-based fallback,
    // which recovers its coefficients from the same nested-radical roots
    // (and recurses deeply on them).  A wrong closed form is never returned
    // silently.
    let risch_rejected = match stage!(
        arena,
        "risch_rational",
        expr,
        crate::calculus::risch::try_risch_rational(arena, expr, var)
    ) {
        Some(result) if !matches!(arena.node(result), ExprNode::Integral(_, _)) => {
            if !candidate_rejected(arena, expr, result, var, var_sym) {
                return result;
            }
            tracing::debug!("integrate: rejecting unverified rational-function closed form");
            true
        }
        _ => false,
    };

    // ── N(x)/(x⁴ + p·x² + q): explicit real factorisation ──────────────
    // Reached only when the general rational integrator could not produce
    // a verified answer, so the output of the cases it handles is unchanged.
    if let Some(result) = stage!(
        arena,
        "biquadratic",
        expr,
        try_biquadratic_rational(arena, expr, var, var_sym)
    ) {
        return result;
    }
    if risch_rejected {
        return arena.intern(ExprNode::Integral(expr, var));
    }
    if let Some(result) = try_poly_over_symbolic_linear(arena, expr, var, var_sym) {
        return result;
    }
    // ── Rational functions over ℚ(p₁, …, p_k): parameters as coefficients ──
    // The rational integrator over the field of the parameters (0.31):
    // `∫ dx/((x + a)(x + b))`, `∫ dx/(x² + a·x + b)`, `∫ dx/(a² − x²)` were
    // unevaluated, `∫ dx/(x² − a²)` was `atan(x/√(−a²))/√(−a²)`.  A
    // rejected candidate falls through to the routes below.
    if let Some(result) = stage!(
        arena,
        "risch_rational_params",
        expr,
        crate::calculus::risch::try_risch_rational_params(arena, expr, var)
    ) && !candidate_rejected(arena, expr, result, var, var_sym)
    {
        return result;
    }
    if let Some(result) = stage!(
        arena,
        "gaussian_rational",
        expr,
        try_gaussian_rational(arena, expr, var, var_sym, depth)
    ) {
        return result;
    }
    if let Some(result) = try_poly_over_symbolic_quadratic(arena, expr, var, var_sym, depth) {
        return result;
    }

    let node = arena.node(expr).clone();

    match node {
        // ── Anything free of var → c * var ─────────────────────────
        // A `RootOf(x⁵ − x + 1, 0)` (its `x` is bound), `sin a`, `Γ(a)`:
        // up to 0.28.0 such a term of a sum fell through to the unevaluated
        // form (`∫ (x + RootOf(a⁵ − a + 1, 0)) dx`).  A sum keeps its
        // term-by-term split below.
        _ if !matches!(node, ExprNode::Add(_)) && !contains_var(arena, expr, var_sym) => {
            arena.mul(&[expr, var])
        }

        // ── Constants (independent of var) → c * var ───────────────
        ExprNode::Num(_)
        | ExprNode::Pi
        | ExprNode::E
        | ExprNode::ImaginaryUnit
        | ExprNode::Infinity
        | ExprNode::NegInfinity
        | ExprNode::ComplexInfinity
        | ExprNode::NaN => {
            // ∫ c dx = c * x
            arena.mul(&[expr, var])
        }

        ExprNode::Symbol(sid) => {
            if sid == var_sym {
                // ∫ x dx = x^2 / 2
                let two = arena.int(2);
                let x_sq = arena.pow(var, two);
                let half = arena.rational(1, 2);
                arena.mul(&[half, x_sq])
            } else {
                // ∫ c dx = c * x (c is independent of var)
                arena.mul(&[expr, var])
            }
        }

        // ── Add: linearity ─────────────────────────────────────────
        ExprNode::Add(ref children) => {
            let integrals: SmallVec<[ExprId; 6]> = children
                .iter()
                .map(|&child| integrate_node(arena, child, var, var_sym, depth - 1))
                .collect();
            arena.add(&integrals)
        }

        // ── Mul: factor out constants ──────────────────────────────
        ExprNode::Mul(ref children) => {
            // Separate constant factors (independent of var) from the rest,
            // with the dependent factors' nested powers flattened.
            let (mut constants, dependent) = partition_factors(arena, children, var_sym);

            if dependent.is_empty() {
                // All constant: ∫ c dx = c * x
                return arena.mul(&[expr, var]);
            }

            // ── A product of polynomials: multiplied out ──
            if let Some(expanded) = expand_polynomial_product(arena, &dependent, var_sym) {
                let expanded = wrap_with_constants(arena, expanded, &constants);
                let result = integrate_node(arena, expanded, var, var_sym, depth - 1);
                if !crate::base::walk::has_unevaluated(arena, result) {
                    return result;
                }
            }

            // ── Collect exponents: exp(u)·exp(v) → exp(u + v) ──
            if let Some(merged) = merge_exponential_factors(arena, &dependent, var, var_sym) {
                let merged = wrap_with_constants(arena, merged, &constants);
                let result = integrate_node(arena, merged, var, var_sym, depth - 1);
                if !crate::base::walk::has_unevaluated(arena, result) {
                    return result;
                }
            }

            if !constants.is_empty() && dependent.len() == 1 {
                // c * f(x) → c * ∫ f(x) dx
                let inner_integral = integrate_node(arena, dependent[0], var, var_sym, depth - 1);
                // Check if the inner integral is unevaluated
                if let ExprNode::Integral(_, _) = arena.node(inner_integral) {
                    // Can't integrate the inner part — return unevaluated for whole
                    return arena.intern(ExprNode::Integral(expr, var));
                }
                constants.push(inner_integral);
                return arena.mul(&constants);
            }

            // ── tanᵐ·sec² and secⁿ·tan forms ───────────────────────────
            if dependent.len() == 2
                && let Some(result) = try_tan_sec_patterns(arena, &dependent, var, var_sym)
            {
                return wrap_with_constants(arena, result, &constants);
            }

            // ── sec(x)·tan(x) and csc(x)·cot(x) forms ──────────────
            if dependent.len() == 2
                && let Some(result) = try_trig_recip_product(arena, &dependent, var, var_sym)
            {
                if constants.is_empty() {
                    return result;
                } else {
                    let mut all = constants.clone();
                    all.push(result);
                    return arena.mul(&all);
                }
            }

            // ── x/√(ax²+bx+c) form ──────────────────────────────────
            if dependent.len() == 2
                && let Some(result) =
                    try_x_over_sqrt_quadratic(arena, &dependent, var, var_sym, depth)
            {
                if constants.is_empty() {
                    return result;
                } else {
                    let mut all = constants.clone();
                    all.push(result);
                    return arena.mul(&all);
                }
            }

            // ── (linear) / (irreducible quadratic) ───────────────────
            if dependent.len() == 2
                && let Some(result) =
                    try_linear_over_quadratic(arena, &dependent, var, var_sym, depth)
            {
                if constants.is_empty() {
                    return result;
                } else {
                    let mut all = constants.clone();
                    all.push(result);
                    return arena.mul(&all);
                }
            }

            // ── DiracDelta sifting property: ∫ f(x)·δ(g(x)) dx = f(root)·H(g(x)) ──
            // Check if any factor in the product is a DiracDelta.
            {
                let all_children: SmallVec<[ExprId; 6]> = children.clone();
                for (i, &child) in all_children.iter().enumerate() {
                    if let ExprNode::DiracDelta(delta_arg) = arena.node(child).clone() {
                        tracing::debug!(
                            "integrate: detected DiracDelta factor in Mul, attempting sifting property"
                        );

                        // Collect the remaining factors as f(x)
                        let other_factors: SmallVec<[ExprId; 4]> = all_children
                            .iter()
                            .enumerate()
                            .filter(|&(j, _)| j != i)
                            .map(|(_, &c)| c)
                            .collect();
                        let f_expr = if other_factors.len() == 1 {
                            other_factors[0]
                        } else if other_factors.is_empty() {
                            arena.one
                        } else {
                            arena.mul(&other_factors)
                        };

                        // Simple case: δ(x) → root = 0
                        if delta_arg == var {
                            let f_at_0 =
                                crate::transforms::subs::subs(arena, f_expr, var, arena.zero);
                            let f_at_0_eval = crate::transforms::eval::eval(arena, f_at_0);
                            let heaviside = arena.intern(ExprNode::Heaviside(var));
                            return arena.mul(&[f_at_0_eval, heaviside]);
                        }

                        // General case: solve δ(g(x)) = 0, i.e. g(x) = 0 for x
                        let solutions = crate::transforms::solve::solve(arena, delta_arg, var);
                        if solutions.len() == 1 {
                            let root = solutions[0].value;
                            let f_at_root = crate::transforms::subs::subs(arena, f_expr, var, root);
                            let f_at_root_eval = crate::transforms::eval::eval(arena, f_at_root);
                            let heaviside = arena.intern(ExprNode::Heaviside(delta_arg));
                            return arena.mul(&[f_at_root_eval, heaviside]);
                        }

                        // If we can't solve, fall through to other strategies
                        break;
                    }
                }
            }

            // ── P(x)·|g(x)|, P(x)·sign(g(x)), P(x)·H(g(x)) ─────────────────
            // Before by parts: the factor's sign is constant on each side of
            // the root, so the rest is a smooth integrand.  By parts first took
            // `u = x²`, `dv = |x|/(x³ + x² + 1)` in `∫ x²·|x|/(x³ + x² + 1)`,
            // and `∫ v·du` of the Cardano-root antiderivative (17,000-character
            // integrands) ran into a 74 s refusal of `∫ (√x + |x|)/(x + x⁻² +
            // 1) dx` (`fuzz_integrate`, 2026-10-01).
            if let Some(result) = try_abs_sign_product(arena, &dependent, var, var_sym, depth) {
                return wrap_with_constants(arena, result, &constants);
            }

            // ── Integration by parts: ∫ u·dv = u·v - ∫ v·du ───────────
            // Try when there are exactly 2 dependent factors:
            // one that's a by-parts candidate (u), and one that's directly
            // integrable (dv).
            if dependent.len() == 2
                && let Some(result) = stage!(
                    arena,
                    "by_parts",
                    expr,
                    try_by_parts_pair(arena, &dependent, var, var_sym, depth)
                )
            {
                return wrap_with_constants(arena, result, &constants);
            }

            // ── Cyclic IBP: ∫ exp·sin, ∫ exp·cos, etc. ────────────
            if dependent.len() == 2
                && let Some(result) = stage!(
                    arena,
                    "cyclic_ibp",
                    expr,
                    try_cyclic_ibp(arena, &dependent, var, var_sym, depth)
                )
            {
                if constants.is_empty() {
                    return result;
                } else {
                    let mut all = constants.clone();
                    all.push(result);
                    return arena.mul(&all);
                }
            }

            // ── P(x)·Q(x)^{k/2}: reduction to R√Q + c∫1/√Q ────────────
            if let Some(result) = try_poly_times_half_power(arena, &dependent, var, var_sym, depth)
            {
                return wrap_with_constants(arena, result, &constants);
            }

            // ── x^{-n}·Q(x)^{-1/2}: substitution x = 1/t ───────────────
            if let Some(result) =
                try_reciprocal_sqrt_substitution(arena, &dependent, var, var_sym, depth)
            {
                return wrap_with_constants(arena, result, &constants);
            }

            // ── Three-factor by parts: u = polynomial, dv = product of the rest ──
            if dependent.len() == 3
                && let Some(result) =
                    try_by_parts_poly_times_pair(arena, &dependent, var, var_sym, depth)
            {
                return wrap_with_constants(arena, result, &constants);
            }

            // ── Several polynomial factors: multiply them out, then retry ──
            if dependent.len() >= 3
                && let Some(result) =
                    try_merge_polynomial_factors(arena, &dependent, var, var_sym, depth)
            {
                return wrap_with_constants(arena, result, &constants);
            }

            // ── Products of trig factors: product-to-sum, then retry ─────
            if dependent.len() >= 2
                && let Some(result) = stage!(
                    arena,
                    "trig_product_to_sum",
                    expr,
                    try_trig_product_to_sum(arena, expr, &dependent, var, var_sym, depth)
                )
            {
                return result;
            }

            // ── Try partial fraction decomposition for rational integrands ──
            // (verified: the root-based fallback of `apart` may recover its
            // coefficients from `f64` roots, which is not an antiderivative.)
            {
                let (_numer, denom) = crate::poly::polybridge::as_numer_denom(arena, expr);
                if denom != arena.one {
                    let decomposed = stage!(
                        arena,
                        "apart",
                        expr,
                        crate::transforms::apart::apart(arena, expr, var)
                    );
                    // Partial fractions over implicit roots could only give
                    // a candidate `candidate_rejected` refuses.
                    if decomposed != expr && !introduces_root_of(arena, expr, decomposed) {
                        let result = integrate_node(arena, decomposed, var, var_sym, depth - 1);
                        if !matches!(arena.node(result), ExprNode::Integral(_, _))
                            && !candidate_rejected(arena, expr, result, var, var_sym)
                        {
                            return result;
                        }
                    }
                }
            }

            // ── Try general u-substitution ──────────────────────────────
            if let Some(result) = stage!(
                arena,
                "u_substitution",
                expr,
                try_u_substitution(arena, &dependent, var, var_sym, depth - 1)
            ) {
                if constants.is_empty() {
                    return result;
                } else {
                    let mut all = constants.clone();
                    all.push(result);
                    return arena.mul(&all);
                }
            }

            // ── sin(u)ᵐ·cos(u)ⁿ times other factors: power reduction ──
            // `e^{x/2}·cos²(3x/2) = e^{x/2}/2 + e^{x/2}·cos(3x)/2`; up to 0.31
            // a trigonometric power times an exponential stayed unevaluated
            // (by parts and the cyclic rule need single factors).
            if dependent.len() >= 2
                && let Some(linear) = crate::transforms::trig_integ::linearize_trig_powers(
                    arena, &dependent, var, var_sym,
                )
            {
                let result = integrate_node(arena, linear, var, var_sym, depth - 1);
                if !crate::base::walk::has_unevaluated(arena, result) {
                    return wrap_with_constants(arena, result, &constants);
                }
            }

            // ── Distribute a sum factor: ∫ (s₁ + … + s_k)·g = Σ ∫ sᵢ·g ──
            if let Some(result) = stage!(
                arena,
                "distribute_sum_factor",
                expr,
                try_distribute_sum_factor(arena, &dependent, var, var_sym, depth)
            ) {
                return wrap_with_constants(arena, result, &constants);
            }

            // ── Weierstrass substitution for rational trig functions ──
            // The constant factors were split off above and are re-applied
            // here, so the substitution must see only the dependent part
            // (passing `expr` applied them twice: `∫ 3·g` came back as `9·∫g`).
            let dependent_product = if dependent.len() == 1 {
                dependent[0]
            } else {
                arena.mul(&dependent)
            };
            if let Some(result) = stage!(
                arena,
                "weierstrass",
                dependent_product,
                try_weierstrass_substitution(arena, dependent_product, var, var_sym, depth)
            ) {
                return wrap_with_constants(arena, result, &constants);
            }

            // ── Special function integration table ──────────────────
            if let Some(result) =
                try_special_function_integral(arena, &dependent, &constants, var, var_sym)
            {
                return result;
            }

            // General product of var-dependent terms — can't integrate without
            // further techniques.
            tracing::debug!("integration: no strategy succeeded, returning unevaluated");
            arena.intern(ExprNode::Integral(expr, var))
        }

        // ── Neg ────────────────────────────────────────────────────
        ExprNode::Neg(inner) => {
            let inner_int = integrate_node(arena, inner, var, var_sym, depth - 1);
            arena.neg(inner_int)
        }

        // ── Pow: power rule ────────────────────────────────────────
        ExprNode::Pow(base, exp) => {
            // Flatten Pow(Pow(a, m), n) → Pow(a, m·n) where that keeps the
            // value (see `flatten_nested_pow`): e.g. 1/√(x²+1) =
            // Pow(Pow(x²+1, 1/2), -1) becomes Pow(x²+1, -1/2) and hits the
            // standard-form / completing-the-square handlers, and √(x²) is
            // |x| for the real integration variable.
            if let Some(flattened) = flatten_nested_pow(arena, expr, var_sym)
                .or_else(|| exp_power_as_exp(arena, expr, var_sym))
                && flattened != expr
            {
                return integrate_node(arena, flattened, var, var_sym, depth - 1);
            }

            // ── |g|ⁿ, integer n ≥ 2: gⁿ for even n, |g|·gⁿ⁻¹ for odd n ──
            // (gⁿ⁻¹ ≥ 0 for odd n, so the product form is exact); the
            // product is then the `P(x)·|g(x)|` shape of `try_abs_sign_product`.
            // Only for g real on the real line: |√x|² = |x|, not x (0.23 gave
            // ∫ |√x|² dx = x²/2; found by fuzz_integrate).
            if let ExprNode::Abs(g) = arena.node(base).clone()
                && contains_var(arena, g, var_sym)
                && real_on_reals(arena, g, var_sym)
                && let Some(n_val) = arena.as_num(exp).cloned()
                && n_val.is_integer()
                && n_val >= num_rational::Ratio::from_integer(2.into())
            {
                let n_int = n_val.to_integer();
                let n_is_even = (&n_int % num_bigint::BigInt::from(2)).is_zero();
                let rewritten = if n_is_even {
                    arena.pow(g, exp)
                } else {
                    let n_minus_1 = arena.num_ratio(&n_val - &Q::one());
                    let g_pow = arena.pow(g, n_minus_1);
                    arena.mul(&[base, g_pow])
                };
                let result = integrate_node(arena, rewritten, var, var_sym, depth - 1);
                if !crate::base::walk::has_unevaluated(arena, result) {
                    return result;
                }
            }

            let base_is_var = base == var;
            let exp_has_var = contains_var(arena, exp, var_sym);
            let base_has_var = contains_var(arena, base, var_sym);

            if base_is_var && !exp_has_var {
                // ∫ x^n dx
                if let Some(n) = arena.as_num(exp) {
                    let n = n.clone();
                    if n == num_rational::Ratio::from_integer((-1).into()) {
                        // ∫ x^(-1) dx = ln(|x|)
                        let abs_x = arena.abs(var);
                        return arena.ln(abs_x);
                    }
                    // ∫ x^n dx = x^(n+1) / (n+1) for n ≠ -1
                    let one = num_rational::Ratio::<num_bigint::BigInt>::one();
                    let n_plus_1 = &n + &one;
                    let n_plus_1_id = {
                        let nid = arena.intern_num(n_plus_1.clone());
                        arena.intern(ExprNode::Num(nid))
                    };
                    let x_pow = arena.pow(var, n_plus_1_id);
                    let recip = {
                        let inv = one / n_plus_1;
                        let nid = arena.intern_num(inv);
                        arena.intern(ExprNode::Num(nid))
                    };
                    return arena.mul(&[recip, x_pow]);
                } else {
                    // Symbolic exponent: ∫ x^n dx = x^(n+1)/(n+1)
                    let one_id = arena.one;
                    let n_plus_1 = arena.add(&[exp, one_id]);
                    let x_pow = arena.pow(var, n_plus_1);
                    return arena.div(x_pow, n_plus_1);
                }
            }

            if !base_has_var && !exp_has_var {
                // Constant: ∫ c dx = c * x
                return arena.mul(&[expr, var]);
            }

            // ── c^{g(x)} with constant c > 0: rewrite as exp(g·ln c) ─────
            if !base_has_var && exp_has_var && base != arena.e_const() {
                let ln_c = arena.ln(base);
                let ln_c = crate::transforms::eval::eval(arena, ln_c);
                let new_exp = arena.mul(&[exp, ln_c]);
                let rewritten = arena.exp(new_exp);
                let result = integrate_node(arena, rewritten, var, var_sym, depth - 1);
                if !crate::base::walk::has_unevaluated(arena, result) {
                    return result;
                }
                return arena.intern(ExprNode::Integral(expr, var));
            }

            // ── tanⁿ(g), n ≥ 3 integer: tanⁿ = tanⁿ⁻²·(sec² − 1) ─────────
            if let ExprNode::Tan(inner) = arena.node(base).clone()
                && let Some(n_val) = arena.as_num(exp).cloned()
                && n_val.is_integer()
                && n_val >= num_rational::Ratio::from_integer(3.into())
                && n_val <= num_rational::Ratio::from_integer(12.into())
            {
                let n_minus_2 =
                    arena.num_ratio(&n_val - &num_rational::Ratio::from_integer(2.into()));
                let tan_pow = arena.pow(base, n_minus_2);
                let cos_inner = arena.cos(inner);
                let neg_two = arena.int(-2);
                let sec_sq = arena.pow(cos_inner, neg_two);
                let term1 = arena.mul(&[tan_pow, sec_sq]);
                let rewritten = arena.sub(term1, tan_pow);
                let result = integrate_node(arena, rewritten, var, var_sym, depth - 1);
                if !crate::base::walk::has_unevaluated(arena, result) {
                    return result;
                }
            }

            // ── sech²(g) = cosh(g)^{-2} → tanh(g) / chain_coeff ──
            if let ExprNode::Cosh(inner) = arena.node(base).clone()
                && let Some(e_val) = arena.as_num(exp)
            {
                let neg_two_r =
                    num_rational::Ratio::<num_bigint::BigInt>::from_integer((-2).into());
                if *e_val == neg_two_r {
                    if inner == var {
                        return arena.tanh(var);
                    }
                    if let Some((a_expr, _)) = symbolic_linear_coeff_of(arena, inner, var, var_sym)
                    {
                        let tanh_inner = arena.tanh(inner);
                        return arena.div(tanh_inner, a_expr);
                    }
                }
            }

            // ── csch²(g) = sinh(g)^{-2} → −coth(g) / chain_coeff ──
            if let ExprNode::Sinh(inner) = arena.node(base).clone()
                && let Some(e_val) = arena.as_num(exp)
            {
                let neg_two_r =
                    num_rational::Ratio::<num_bigint::BigInt>::from_integer((-2).into());
                if *e_val == neg_two_r {
                    if inner == var {
                        let cosh_v = arena.cosh(var);
                        let sinh_v = arena.sinh(var);
                        let neg1 = arena.int(-1);
                        let sinh_inv = arena.pow(sinh_v, neg1);
                        let coth_v = arena.mul(&[cosh_v, sinh_inv]);
                        return arena.neg(coth_v);
                    }
                    if let Some((a_expr, _)) = symbolic_linear_coeff_of(arena, inner, var, var_sym)
                    {
                        let cosh_i = arena.cosh(inner);
                        let sinh_i = arena.sinh(inner);
                        let neg1 = arena.int(-1);
                        let sinh_inv = arena.pow(sinh_i, neg1);
                        let coth_i = arena.mul(&[cosh_i, sinh_inv]);
                        let neg_coth = arena.neg(coth_i);
                        return arena.div(neg_coth, a_expr);
                    }
                }
            }

            // ── ln(x)^n by parts: ∫ ln(x)^n dx = x·ln(x)^n − n·∫ ln(x)^(n−1) dx ──
            if let ExprNode::Ln(inner) = arena.node(base).clone()
                && inner == var
                && !exp_has_var
                && let Some(n_val) = arena.as_num(exp)
            {
                let n_val = n_val.clone();
                if n_val.is_integer() && n_val.is_positive() {
                    let n_i64: i64 = n_val.to_integer().try_into().unwrap_or(0);
                    if n_i64 >= 2 {
                        let x_ln_n = arena.mul(&[var, expr]);
                        let n_id = arena.num_ratio(n_val.clone());
                        let n_minus_1 = {
                            let v = &n_val - &num_rational::Ratio::<num_bigint::BigInt>::one();
                            arena.num_ratio(v.clone())
                        };
                        let ln_x = arena.ln(var);
                        let ln_nm1 = if n_i64 == 2 {
                            ln_x
                        } else {
                            arena.pow(ln_x, n_minus_1)
                        };
                        let sub_int = integrate_node(arena, ln_nm1, var, var_sym, depth - 1);
                        let n_times_sub = arena.mul(&[n_id, sub_int]);
                        return arena.sub(x_ln_n, n_times_sub);
                    }
                }
            }

            // General linear substitution: ∫ (ax+b)^n dx = (ax+b)^(n+1) / (a*(n+1))
            if !exp_has_var
                && base_has_var
                && let Some((a_expr, _b_expr)) = symbolic_linear_coeff_of(arena, base, var, var_sym)
                && let Some(n) = arena.as_num(exp)
            {
                let n = n.clone();
                let neg_one = num_rational::Ratio::from_integer((-1).into());
                if n != neg_one {
                    // ∫ (ax+b)^n dx = (ax+b)^(n+1) / (a*(n+1))
                    let one = num_rational::Ratio::<num_bigint::BigInt>::one();
                    let n_plus_1 = &n + &one;
                    let n_plus_1_id = arena.num_ratio(n_plus_1.clone());
                    let base_pow = arena.pow(base, n_plus_1_id);
                    let denom = arena.mul(&[a_expr, n_plus_1_id]);
                    return arena.div(base_pow, denom);
                } else {
                    // ∫ (ax+b)^(-1) dx = ln|ax+b| / a
                    let abs_base = arena.abs(base);
                    let ln_base = arena.ln(abs_base);
                    return arena.div(ln_base, a_expr);
                }
            }

            // ── Standard form integrals (A3–A7) ───────────────────────
            if base_has_var
                && !exp_has_var
                && let Some(result) =
                    try_standard_form_integral(arena, expr, base, exp, var, var_sym)
            {
                return result;
            }

            // ── Symbolic standard form: ∫ (x² + k)^{-1} dx ──────────
            // where k is free of var (handles e.g. ∫ 1/(x²+a²) dx)
            if base_has_var
                && !exp_has_var
                && let Some(exp_val) = arena.as_num(exp)
            {
                let neg_one_r =
                    num_rational::Ratio::<num_bigint::BigInt>::from_integer((-1).into());
                if *exp_val == neg_one_r
                    && let ExprNode::Add(ref ac) = arena.node(base).clone()
                    && ac.len() == 2
                {
                    let (mut x2_found, mut k_id) = (false, None);
                    for &ch in ac.iter() {
                        if is_var_squared(arena, ch, var) {
                            x2_found = true;
                        } else if !contains_var(arena, ch, var_sym) {
                            k_id = Some(ch);
                        }
                    }
                    if x2_found
                        && let Some(k) = k_id
                        && arena.as_num(k).is_none()
                    {
                        // Only use symbolic path when k is NOT pure numeric
                        // (numeric case is handled by try_standard_form_integral)
                        // ∫ 1/(x²+k) dx = (1/√k)·atan(x/√k)
                        let half = arena.rational(1, 2);
                        let sqrt_k = arena.pow(k, half);
                        let x_over_sk = arena.div(var, sqrt_k);
                        let atan_val = arena.atan(x_over_sk);
                        let neg_half = arena.rational(-1, 2);
                        let inv_sk = arena.pow(k, neg_half);
                        return arena.mul(&[inv_sk, atan_val]);
                    }
                }
            }

            // ── Completing the square for 1/(ax²+bx+c) ───────────────
            if base_has_var
                && !exp_has_var
                && let Some(result) = try_complete_square_integral(arena, base, exp, var, var_sym)
            {
                return result;
            }

            // ── Trig substitution: √(a²±x²), √(x²±a²) ──────────────
            if base_has_var
                && !exp_has_var
                && let Some(result) = try_trig_sub_sqrt_integral(arena, base, exp, var, var_sym)
            {
                return result;
            }

            // ── Try partial fraction decomposition (verified, see the Mul arm) ──
            {
                let (_numer, denom) = crate::poly::polybridge::as_numer_denom(arena, expr);
                if denom != arena.one {
                    let decomposed = stage!(
                        arena,
                        "apart",
                        expr,
                        crate::transforms::apart::apart(arena, expr, var)
                    );
                    if decomposed != expr && !introduces_root_of(arena, expr, decomposed) {
                        let result = integrate_node(arena, decomposed, var, var_sym, depth - 1);
                        if !matches!(arena.node(result), ExprNode::Integral(_, _))
                            && !candidate_rejected(arena, expr, result, var, var_sym)
                        {
                            return result;
                        }
                    }
                }
            }

            // Fallback: if base is an Add and exp is a small positive integer, expand and retry
            if let ExprNode::Add(_) = arena.node(base)
                && let Some(n) = arena.as_num(exp)
                && n.is_integer()
                && n.is_positive()
            {
                let n_i64: i64 = n.to_integer().try_into().unwrap_or(0);
                if (2..=10).contains(&n_i64) {
                    let expanded = crate::transforms::expand::expand(arena, expr);
                    if expanded != expr {
                        let result = integrate_node(arena, expanded, var, var_sym, depth - 1);
                        if !matches!(arena.node(result), ExprNode::Integral(_, _)) {
                            return result;
                        }
                    }
                }
            }

            // ── Weierstrass substitution (Pow arm) ────────────────────
            if let Some(result) = stage!(
                arena,
                "weierstrass",
                expr,
                try_weierstrass_substitution(arena, expr, var, var_sym, depth)
            ) {
                return result;
            }

            // ── 1/ln(x) → li(x) (logarithmic integral) ──────────────
            if let ExprNode::Ln(inner) = arena.node(base).clone()
                && inner == var
                && let Some(n_val) = arena.as_num(exp)
            {
                let neg_one_r =
                    num_rational::Ratio::<num_bigint::BigInt>::from_integer((-1).into());
                if *n_val == neg_one_r {
                    return arena.li(var);
                }
            }

            // ── 1/(ax+b) with symbolic coefficients → ln|ax+b|/a ────
            if let Some(n_val) = arena.as_num(exp) {
                let neg_one_r =
                    num_rational::Ratio::<num_bigint::BigInt>::from_integer((-1).into());
                if *n_val == neg_one_r
                    && base_has_var
                    && let Some((a_expr, _b_expr)) =
                        symbolic_linear_coeff_of(arena, base, var, var_sym)
                {
                    let abs_base = arena.abs(base);
                    let ln_abs = arena.ln(abs_base);
                    return arena.div(ln_abs, a_expr);
                }
            }

            // ── Distribute inverse over Mul: 1/(a·b) → a^(-1)·b^(-1) ──
            // When the base is a Mul and the exponent is a negative integer,
            // distribute the power over each factor.  This transforms
            // Pow(Mul(x, ln(x)), -1) into Mul(x^(-1), ln(x)^(-1)), which
            // lets the Mul arm's u-substitution logic find candidates.
            if let ExprNode::Mul(ref children) = arena.node(base).clone()
                && let Some(e_val) = arena.as_num(exp)
                && e_val.is_negative()
                && e_val.is_integer()
            {
                let factors: SmallVec<[ExprId; 6]> = children
                    .iter()
                    .map(|&child| arena.pow(child, exp))
                    .collect();
                let distributed = arena.mul(&factors);
                if distributed != expr {
                    let result = integrate_node(arena, distributed, var, var_sym, depth - 1);
                    if !matches!(arena.node(result), ExprNode::Integral(_, _)) {
                        return result;
                    }
                }
            }

            // General case: unevaluated.
            tracing::debug!("integration: no strategy succeeded, returning unevaluated");
            arena.intern(ExprNode::Integral(expr, var))
        }

        // ── Elementary functions ────────────────────────────────────
        ExprNode::Sin(inner) => {
            if inner == var {
                // ∫ sin(x) dx = -cos(x)
                let cos_x = arena.cos(var);
                return arena.neg(cos_x);
            }
            // Try u-substitution: if inner = a*x + b, ∫ sin(a*x+b) dx = -cos(a*x+b)/a
            if let Some((a_expr, _)) = symbolic_linear_coeff_of(arena, inner, var, var_sym) {
                let cos_inner = arena.cos(inner);
                let neg_cos = arena.neg(cos_inner);
                return arena.div(neg_cos, a_expr);
            }
            arena.intern(ExprNode::Integral(expr, var))
        }

        ExprNode::Cos(inner) => {
            if inner == var {
                // ∫ cos(x) dx = sin(x)
                return arena.sin(var);
            }
            // Try u-substitution: if inner = a*x + b, ∫ cos(a*x+b) dx = sin(a*x+b)/a
            if let Some((a_expr, _)) = symbolic_linear_coeff_of(arena, inner, var, var_sym) {
                let sin_inner = arena.sin(inner);
                return arena.div(sin_inner, a_expr);
            }
            arena.intern(ExprNode::Integral(expr, var))
        }

        // ── Tan: ∫ tan(x) dx = -ln|cos(x)| ───────────────────────
        ExprNode::Tan(inner) => {
            if inner == var {
                // ∫ tan(x) dx = -ln(|cos(x)|)
                let cos_x = arena.cos(var);
                let abs_cos = arena.abs(cos_x);
                let ln_abs_cos = arena.ln(abs_cos);
                return arena.neg(ln_abs_cos);
            }
            // Try u-substitution: if inner = a*x + b,
            // ∫ tan(a*x+b) dx = -ln|cos(a*x+b)| / a
            if let Some((a_expr, _)) = symbolic_linear_coeff_of(arena, inner, var, var_sym) {
                let cos_inner = arena.cos(inner);
                let abs_cos = arena.abs(cos_inner);
                let ln_abs_cos = arena.ln(abs_cos);
                let neg_ln = arena.neg(ln_abs_cos);
                return arena.div(neg_ln, a_expr);
            }
            arena.intern(ExprNode::Integral(expr, var))
        }

        ExprNode::Exp(inner) => {
            if inner == var {
                // ∫ exp(x) dx = exp(x)
                return arena.exp(var);
            }

            // ── Gaussian form: ∫ exp(a·x²+b·x+c) dx where a < 0 ──
            // Result: √π/(2√(−a)) · exp(c − b²/(4a)) · erf((−2a·x−b)/(2√(−a)))
            if let Some(poly) = crate::poly::polybridge::expr_to_poly(arena, inner, var)
                && poly.degree() == Some(2)
            {
                let coeffs = poly.coeffs(); // [c, b, a]
                let a_coeff = &coeffs[2];
                let b_coeff = &coeffs[1];
                let c_coeff = &coeffs[0];

                if a_coeff.is_negative() {
                    // neg_a = -a (positive)
                    let neg_a = -a_coeff.clone();
                    let neg_a_expr = arena.num_ratio(neg_a.clone());

                    // sqrt(-a)
                    let sqrt_neg_a = arena.sqrt(neg_a_expr);

                    let two = arena.int(2);

                    // front = √π / (2·√(-a))
                    let pi_id = arena.pi;
                    let sqrt_pi = arena.sqrt(pi_id);
                    let two_sqrt_neg_a = arena.mul(&[two, sqrt_neg_a]);
                    let front = arena.div(sqrt_pi, two_sqrt_neg_a);

                    // exp_factor = exp(c - b²/(4a))
                    let b_expr = arena.num_ratio(b_coeff.clone());
                    let a_expr = arena.num_ratio(a_coeff.clone());
                    let c_expr = arena.num_ratio(c_coeff.clone());

                    let b_sq = arena.mul(&[b_expr, b_expr]);
                    let four = arena.int(4);
                    let four_a = arena.mul(&[four, a_expr]);
                    let b_sq_over_4a = arena.div(b_sq, four_a);
                    let exp_arg = arena.sub(c_expr, b_sq_over_4a);
                    let exp_arg = arena.eval_expr(exp_arg);
                    let exp_factor = if arena.is_zero_structural(exp_arg) {
                        arena.int(1)
                    } else {
                        arena.exp(exp_arg)
                    };

                    // erf_arg = (-2a·x - b) / (2·√(-a))
                    // Note: -2a is positive since a < 0
                    let neg_two_a = {
                        let two_r =
                            num_rational::Ratio::<num_bigint::BigInt>::from_integer(2.into());
                        let val = -two_r * a_coeff;
                        arena.num_ratio(val.clone())
                    };
                    let neg_2ax = arena.mul(&[neg_two_a, var]);
                    let erf_numer = arena.sub(neg_2ax, b_expr);
                    // recompute sqrt_neg_a fresh (the prior one may have been consumed)
                    let sqrt_neg_a2 = arena.sqrt(neg_a_expr);
                    let erf_denom = arena.mul(&[two, sqrt_neg_a2]);
                    let erf_arg = arena.div(erf_numer, erf_denom);
                    let erf_term = arena.erf(erf_arg);

                    return arena.mul(&[front, exp_factor, erf_term]);
                }
                if a_coeff.is_positive() {
                    // ∫ exp(a·x²+b·x+c) dx, a > 0:
                    //   √π/(2√a) · exp(c − b²/(4a)) · erfi((2a·x+b)/(2√a))   (0.9)
                    let a_expr = arena.num_ratio(a_coeff.clone());
                    let sqrt_a = arena.sqrt(a_expr);
                    let two = arena.int(2);
                    let pi_id = arena.pi;
                    let sqrt_pi = arena.sqrt(pi_id);
                    let two_sqrt_a = arena.mul(&[two, sqrt_a]);
                    let front = arena.div(sqrt_pi, two_sqrt_a);

                    let b_expr = arena.num_ratio(b_coeff.clone());
                    let c_expr = arena.num_ratio(c_coeff.clone());
                    let b_sq = arena.mul(&[b_expr, b_expr]);
                    let four = arena.int(4);
                    let four_a = arena.mul(&[four, a_expr]);
                    let b_sq_over_4a = arena.div(b_sq, four_a);
                    let exp_arg = arena.sub(c_expr, b_sq_over_4a);
                    let exp_arg = arena.eval_expr(exp_arg);
                    let exp_factor = if arena.is_zero_structural(exp_arg) {
                        arena.int(1)
                    } else {
                        arena.exp(exp_arg)
                    };

                    let two_a = {
                        let two_r =
                            num_rational::Ratio::<num_bigint::BigInt>::from_integer(2.into());
                        let val = two_r * a_coeff;
                        arena.num_ratio(val.clone())
                    };
                    let two_ax = arena.mul(&[two_a, var]);
                    let numer = arena.add(&[two_ax, b_expr]);
                    let sqrt_a2 = arena.sqrt(a_expr);
                    let denom = arena.mul(&[two, sqrt_a2]);
                    let erfi_arg = arena.div(numer, denom);
                    let erfi_term = special_apply(arena, FN_ERFI, erfi_arg);

                    return arena.mul(&[front, exp_factor, erfi_term]);
                }
            }

            // Try u-substitution: if inner = a*x + b, ∫ exp(a*x+b) dx = exp(a*x+b)/a
            if let Some((a_expr, _)) = symbolic_linear_coeff_of(arena, inner, var, var_sym) {
                let exp_inner = arena.exp(inner);
                return arena.div(exp_inner, a_expr);
            }
            arena.intern(ExprNode::Integral(expr, var))
        }

        // ── Ln: ∫ ln(x) dx = x·ln(x) - x ─────────────────────────
        ExprNode::Ln(inner) => {
            if inner == var {
                // ∫ ln(x) dx = x·ln(x) - x
                let ln_var = arena.ln(var);
                let x_ln_x = arena.mul(&[var, ln_var]);
                return arena.sub(x_ln_x, var);
            }
            // ∫ ln(ln(x)) dx = x·ln(ln(x)) − li(x)  (by parts:
            // u = ln(ln(x)), dv = dx  →  du = 1/(x·ln(x)) dx, v = x)
            if let ExprNode::Ln(ln_inner) = arena.node(inner).clone()
                && ln_inner == var
            {
                let ln_x = arena.ln(var);
                let ln_ln_x = arena.ln(ln_x);
                let x_ln_ln_x = arena.mul(&[var, ln_ln_x]);
                let li_x = arena.li(var);
                return arena.sub(x_ln_ln_x, li_x);
            }
            // Try u-substitution: if inner = a*x + b (linear),
            // ∫ ln(a*x+b) dx = ((a*x+b)·ln(a*x+b) - (a*x+b)) / a
            if let Some((a_expr, _)) = symbolic_linear_coeff_of(arena, inner, var, var_sym) {
                let ln_inner = arena.ln(inner);
                let inner_times_ln = arena.mul(&[inner, ln_inner]);
                let diff = arena.sub(inner_times_ln, inner);
                return arena.div(diff, a_expr);
            }
            arena.intern(ExprNode::Integral(expr, var))
        }

        ExprNode::Sinh(inner) => {
            if inner == var {
                // ∫ sinh(x) dx = cosh(x)
                return arena.intern(ExprNode::Cosh(var));
            }
            // u-sub: ∫ sinh(ax+b) dx = cosh(ax+b)/a
            if let Some((a_expr, _)) = symbolic_linear_coeff_of(arena, inner, var, var_sym) {
                let cosh_inner = arena.cosh(inner);
                return arena.div(cosh_inner, a_expr);
            }
            arena.intern(ExprNode::Integral(expr, var))
        }

        ExprNode::Cosh(inner) => {
            if inner == var {
                // ∫ cosh(x) dx = sinh(x)
                return arena.intern(ExprNode::Sinh(var));
            }
            // u-sub: ∫ cosh(ax+b) dx = sinh(ax+b)/a
            if let Some((a_expr, _)) = symbolic_linear_coeff_of(arena, inner, var, var_sym) {
                let sinh_inner = arena.sinh(inner);
                return arena.div(sinh_inner, a_expr);
            }
            arena.intern(ExprNode::Integral(expr, var))
        }

        ExprNode::Tanh(inner) => {
            if inner == var {
                // ∫ tanh(x) dx = ln(cosh(x))
                let cosh_x = arena.cosh(var);
                return arena.ln(cosh_x);
            }
            // u-sub: if inner = a*x + b, ∫ tanh(a*x+b) dx = ln(cosh(a*x+b))/a
            if let Some((a_expr, _)) = symbolic_linear_coeff_of(arena, inner, var, var_sym) {
                let cosh_inner = arena.cosh(inner);
                let ln_cosh = arena.ln(cosh_inner);
                return arena.div(ln_cosh, a_expr);
            }
            arena.intern(ExprNode::Integral(expr, var))
        }

        // ── asin/acos/atan of a linear argument g = ax+b ──────────────
        //   ∫ asin(g) = (g·asin(g) + √(1−g²))/a
        //   ∫ acos(g) = (g·acos(g) − √(1−g²))/a
        //   ∫ atan(g) = (g·atan(g) − ½ ln(1+g²))/a
        ExprNode::Asin(inner) | ExprNode::Acos(inner) | ExprNode::Atan(inner) => {
            let Some((a_expr, _)) = symbolic_linear_coeff_of(arena, inner, var, var_sym) else {
                return arena.intern(ExprNode::Integral(expr, var));
            };
            let g = inner;
            let g_f = arena.mul(&[g, expr]);
            let one = arena.one;
            let two = arena.int(2);
            let g2 = arena.pow(g, two);
            let half = arena.rational(1, 2);
            let numer = match node {
                ExprNode::Asin(_) => {
                    let one_minus_g2 = arena.sub(one, g2);
                    let sqrt_term = arena.pow(one_minus_g2, half);
                    arena.add(&[g_f, sqrt_term])
                }
                ExprNode::Acos(_) => {
                    let one_minus_g2 = arena.sub(one, g2);
                    let sqrt_term = arena.pow(one_minus_g2, half);
                    arena.sub(g_f, sqrt_term)
                }
                _ => {
                    let one_plus_g2 = arena.add(&[one, g2]);
                    let ln_term = arena.ln(one_plus_g2);
                    let half_ln = arena.mul(&[half, ln_term]);
                    arena.sub(g_f, half_ln)
                }
            };
            if a_expr == one {
                return numer;
            }
            arena.div(numer, a_expr)
        }

        // ── erf / erfc of a linear argument g = ax+b ───────────────────
        //   ∫ erf(g)  = (g·erf(g)  + e^{−g²}/√π)/a
        //   ∫ erfc(g) = (g·erfc(g) − e^{−g²}/√π)/a
        ExprNode::Erf(inner) | ExprNode::Erfc(inner) => {
            let Some((a_expr, _)) = symbolic_linear_coeff_of(arena, inner, var, var_sym) else {
                return arena.intern(ExprNode::Integral(expr, var));
            };
            let g = inner;
            let g_f = arena.mul(&[g, expr]);
            let two = arena.int(2);
            let g2 = arena.pow(g, two);
            let neg_g2 = arena.neg(g2);
            let e = arena.exp(neg_g2);
            let pi = arena.pi();
            let sqrt_pi = arena.sqrt(pi);
            let gauss = arena.div(e, sqrt_pi);
            let numer = if matches!(node, ExprNode::Erf(_)) {
                arena.add(&[g_f, gauss])
            } else {
                arena.sub(g_f, gauss)
            };
            if a_expr == arena.one {
                return numer;
            }
            arena.div(numer, a_expr)
        }

        // ── |g|, sign(g), Piecewise ───────────────────────────────────
        ExprNode::Abs(_) | ExprNode::Sign(_) => {
            if let Some(r) = try_abs_sign_product(arena, &[expr], var, var_sym, depth) {
                return r;
            }
            arena.intern(ExprNode::Integral(expr, var))
        }
        ExprNode::Piecewise(ref pairs) => {
            if let Some(r) = integrate_piecewise(arena, pairs, var, var_sym, depth) {
                return r;
            }
            arena.intern(ExprNode::Integral(expr, var))
        }

        // ── DiracDelta: ∫δ(f(x))dx ────────────────────────────────
        ExprNode::DiracDelta(inner) => {
            // ∫δ(x)dx = H(x)
            if inner == var {
                return arena.intern(ExprNode::Heaviside(var));
            }
            // Linear case: ∫δ(ax+b)dx = H(ax+b) / |a|
            if let Some((a_expr, _)) = symbolic_linear_coeff_of(arena, inner, var, var_sym) {
                let h = arena.intern(ExprNode::Heaviside(inner));
                let abs_a = arena.abs(a_expr);
                return arena.div(h, abs_a);
            }
            // Leave unevaluated
            arena.intern(ExprNode::Integral(expr, var))
        }

        // ── Heaviside: ∫ H(g(x)) dx ───────────────────────────────
        ExprNode::Heaviside(inner) => {
            // ∫ H(x) dx = x·H(x)
            if inner == var {
                return arena.mul(&[var, expr]);
            }
            // Linear case: ∫ H(ax+b) dx = (ax+b)·H(ax+b) / a
            if let Some((a_expr, _b_expr)) = symbolic_linear_coeff_of(arena, inner, var, var_sym) {
                let h = arena.intern(ExprNode::Heaviside(inner));
                let product = arena.mul(&[inner, h]);
                return arena.div(product, a_expr);
            }
            // Leave unevaluated
            arena.intern(ExprNode::Integral(expr, var))
        }

        // ── Asinh: ∫ asinh(x) dx = x·asinh(x) - √(x²+1) ─────────
        ExprNode::Asinh(inner) => {
            if inner == var {
                tracing::debug!("integrate: matched asinh(x) direct");
                let asinh_var = arena.asinh(var);
                let x_asinh = arena.mul(&[var, asinh_var]);
                let two = arena.int(2);
                let x2 = arena.pow(var, two);
                let one = arena.one;
                let x2_plus_1 = arena.add(&[x2, one]);
                let half = arena.rational(1, 2);
                let sqrt_term = arena.pow(x2_plus_1, half);
                return arena.sub(x_asinh, sqrt_term);
            }
            // Linear chain rule: ∫ asinh(ax+b) dx = (ax+b)·asinh(ax+b)/a - √((ax+b)²+1)/a
            if let Some((a_expr, _b_expr)) = symbolic_linear_coeff_of(arena, inner, var, var_sym) {
                tracing::debug!("integrate: matched asinh(ax+b) linear");
                let asinh_g = arena.asinh(inner);
                let g_asinh = arena.mul(&[inner, asinh_g]);
                let two = arena.int(2);
                let g2 = arena.pow(inner, two);
                let one = arena.one;
                let g2_plus_1 = arena.add(&[g2, one]);
                let half = arena.rational(1, 2);
                let sqrt_term = arena.pow(g2_plus_1, half);
                let numer = arena.sub(g_asinh, sqrt_term);
                return arena.div(numer, a_expr);
            }
            arena.intern(ExprNode::Integral(expr, var))
        }

        // ── Acosh: ∫ acosh(g) dx = (g·acosh(g) − √(g−1)·√(g+1))/a ──
        // for g = a·x + b.  The product of roots is the principal-branch
        // companion of acosh (its derivative is g/(√(g−1)√(g+1))); the
        // single root √(g²−1) of 0.23 had the wrong sign for g < −1.
        ExprNode::Acosh(inner) => {
            let a_expr = if inner == var {
                Some(arena.one)
            } else {
                symbolic_linear_coeff_of(arena, inner, var, var_sym).map(|(a, _)| a)
            };
            if let Some(a_expr) = a_expr {
                tracing::debug!("integrate: matched acosh(ax+b)");
                let acosh_g = arena.acosh(inner);
                let g_acosh = arena.mul(&[inner, acosh_g]);
                let one = arena.one;
                let g_minus_1 = arena.sub(inner, one);
                let g_plus_1 = arena.add(&[inner, one]);
                let half = arena.rational(1, 2);
                let root_minus = arena.pow(g_minus_1, half);
                let root_plus = arena.pow(g_plus_1, half);
                let roots = arena.mul(&[root_minus, root_plus]);
                let numer = arena.sub(g_acosh, roots);
                return if a_expr == arena.one {
                    numer
                } else {
                    arena.div(numer, a_expr)
                };
            }
            arena.intern(ExprNode::Integral(expr, var))
        }

        // ── Atanh: ∫ atanh(x) dx = x·atanh(x) + ½·ln(1-x²) ──────
        ExprNode::Atanh(inner) => {
            if inner == var {
                tracing::debug!("integrate: matched atanh(x) direct");
                let atanh_var = arena.atanh(var);
                let x_atanh = arena.mul(&[var, atanh_var]);
                let two = arena.int(2);
                let x2 = arena.pow(var, two);
                let one = arena.one;
                let one_minus_x2 = arena.sub(one, x2);
                let half = arena.rational(1, 2);
                let ln_term = arena.ln(one_minus_x2);
                let half_ln = arena.mul(&[half, ln_term]);
                return arena.add(&[x_atanh, half_ln]);
            }
            // Linear chain rule: ∫ atanh(ax+b) dx
            if let Some((a_expr, _b_expr)) = symbolic_linear_coeff_of(arena, inner, var, var_sym) {
                tracing::debug!("integrate: matched atanh(ax+b) linear");
                let atanh_g = arena.atanh(inner);
                let g_atanh = arena.mul(&[inner, atanh_g]);
                let two = arena.int(2);
                let g2 = arena.pow(inner, two);
                let one = arena.one;
                let one_minus_g2 = arena.sub(one, g2);
                let half = arena.rational(1, 2);
                let ln_term = arena.ln(one_minus_g2);
                let half_ln = arena.mul(&[half, ln_term]);
                let numer = arena.add(&[g_atanh, half_ln]);
                return arena.div(numer, a_expr);
            }
            arena.intern(ExprNode::Integral(expr, var))
        }

        // Everything else: unevaluated integral.
        _ => {
            tracing::debug!("integration: no strategy succeeded, returning unevaluated");
            arena.intern(ExprNode::Integral(expr, var))
        }
    }
}

/// Does `expr` depend on the symbol `var` — does `var` occur *free* in it?
///
/// [`crate::base::walk::has_free_symbol`], which reads the binder table
/// shared with `free_symbols` and `subs`: the variable of a `Sum` is bound
/// in its body (not in its limits), a `RootOf` binds its polynomial's
/// variable, and so on.  So `RootOf(x⁵ − x + 1, 0)` — the
/// form in which `solve` returns a root of a polynomial in `x` — is a
/// constant.  Up to 0.28.0 the test was structural, and
/// `1/(x − RootOf(x⁵ − x + 1, 0))` did not look like `1/(x − c)`.
/// An indefinite `Integral` or a `Derivative` does not bind: `∫ f dx` is a
/// function of `x`.
fn contains_var(arena: &Arena, expr: ExprId, var: SymbolId) -> bool {
    crate::base::walk::has_free_symbol(arena, expr, var)
}

/// Check if an expression is a polynomial in the given variable.
/// A polynomial is: the variable itself, a power of the variable with a
/// non-negative integer exponent, a numeric constant, or sums/products of these.
fn is_polynomial_in(arena: &Arena, expr: ExprId, var: ExprId, var_sym: SymbolId) -> bool {
    let mut stack = vec![expr];
    while let Some(e) = stack.pop() {
        if e == var || !contains_var(arena, e, var_sym) {
            continue;
        }
        match arena.node(e) {
            // `xⁿ`, and a polynomial to a small power: `(2x + 1)²` was not a
            // polynomial, so by parts never took it for `u` and `∫ (2x +
            // 1)²·sin x dx` stayed unevaluated (Rubi 4.x.10 after `u = a + b·x`).
            ExprNode::Pow(base, exp) => match arena.as_num(*exp) {
                Some(r)
                    if r.is_integer()
                        && !r.is_negative()
                        && (*base == var || *r <= Q::from_integer(MAX_POLYNOMIAL_POWER.into())) =>
                {
                    stack.push(*base);
                }
                _ => return false,
            },
            ExprNode::Mul(children) | ExprNode::Add(children) => {
                stack.extend(children.iter().copied())
            }
            ExprNode::Neg(inner) => stack.push(*inner),
            ExprNode::Num(_) => {}
            _ => return false,
        }
    }
    true
}

/// Largest power of a polynomial other than `x` itself that
/// [`is_polynomial_in`] counts as a polynomial (by parts differentiates it
/// that many times).
const MAX_POLYNOMIAL_POWER: i64 = 16;

/// Check if `expr` is a linear function of `var` with **numeric** coefficients.
/// Returns `Some(a)` (the leading coefficient as `Ratio<BigInt>`) if linear, `None` otherwise.
#[allow(dead_code)]
fn linear_coeff_of(arena: &Arena, expr: ExprId, _var: ExprId, _var_sym: SymbolId) -> Option<Q> {
    // Try to convert to polynomial in var.
    let poly = crate::poly::polybridge::expr_to_poly(arena, expr, _var)?;
    // Must be degree exactly 1.
    if poly.degree()? != 1 {
        return None;
    }
    let a = poly.coeff(1);
    if a.is_zero() {
        return None;
    }
    Some(a)
}

/// Check if `expr` is a linear function of `var`: `a*var + b` where a ≠ 0,
/// with **symbolic** (possibly non-numeric) coefficients.
///
/// Returns `Some((a_expr, b_expr))` where `a_expr` is the coefficient of `var`
/// and `b_expr` is the constant term — both as `ExprId`s that are free of `var`.
fn symbolic_linear_coeff_of(
    arena: &mut Arena,
    expr: ExprId,
    var: ExprId,
    var_sym: SymbolId,
) -> Option<(ExprId, ExprId)> {
    // Fast path: try numeric first (covers the common numeric-coefficient case)
    if let Some(a) = linear_coeff_of(arena, expr, var, var_sym) {
        let a_id = arena.num_ratio(a.clone());
        // Also extract constant term
        if let Some(poly) = crate::poly::polybridge::expr_to_poly(arena, expr, var) {
            let b = poly.coeff(0);
            let b_id = arena.num_ratio(b.clone());
            return Some((a_id, b_id));
        }
        return Some((a_id, arena.zero));
    }

    // Case 1: expr == var → coefficient is 1, constant is 0
    if expr == var {
        return Some((arena.one, arena.zero));
    }

    // Case 2: Neg(inner) → negate coefficient and constant
    if let ExprNode::Neg(inner) = arena.node(expr).clone() {
        if let Some((coeff, constant)) = symbolic_linear_coeff_of(arena, inner, var, var_sym) {
            let neg_coeff = arena.neg(coeff);
            let neg_const = arena.neg(constant);
            return Some((neg_coeff, neg_const));
        }
        return None;
    }

    // Case 3: Mul containing var exactly once, all other factors free of var
    if let ExprNode::Mul(ref children) = arena.node(expr).clone() {
        let mut has_var = false;
        let mut other_factors: SmallVec<[ExprId; 4]> = SmallVec::new();
        let mut var_count = 0u32;
        let mut nontrivial = false;

        for &child in children {
            if child == var {
                var_count += 1;
                if var_count > 1 {
                    return None; // var² or higher
                }
                has_var = true;
            } else if contains_var(arena, child, var_sym) {
                nontrivial = true; // Non-trivial var dependence (see 3b)
            } else {
                other_factors.push(child);
            }
        }

        if has_var && var_count == 1 && !nontrivial {
            let coeff = match other_factors.len() {
                0 => arena.one,
                1 => other_factors[0],
                _ => arena.mul(&other_factors),
            };
            return Some((coeff, arena.zero));
        }

        // Case 3b: c·(a·x + b) — constant factors times one linear sum.
        // `∫ a·a^x = ∫ a^(x+1)` is rewritten `∫ e^{(x+1)·ln a}`, whose
        // exponent is such a product (before 0.30 it stayed unevaluated
        // while `∫ a^x` worked).
        let dependent: SmallVec<[ExprId; 2]> = children
            .iter()
            .copied()
            .filter(|&c| contains_var(arena, c, var_sym))
            .collect();
        if let [sum] = dependent[..]
            && matches!(arena.node(sum), ExprNode::Add(_))
            && let Some((a, b)) = linear_sum_parts(arena, sum, var, var_sym)
        {
            let c: SmallVec<[ExprId; 4]> = children.iter().copied().filter(|&f| f != sum).collect();
            let c = arena.mul(&c);
            let a = arena.mul(&[c, a]);
            let b = arena.mul(&[c, b]);
            return Some((a, b));
        }
    }

    // Case 4: Add → separate var-containing and var-free terms
    if matches!(arena.node(expr), ExprNode::Add(_)) {
        return linear_sum_parts(arena, expr, var, var_sym);
    }

    None
}

/// `(a, b)` for a sum `expr = a·var + b` with `a`, `b` free of `var` (the
/// sum case of [`symbolic_linear_coeff_of`]).
///
/// Every term with the variable must be `cᵢ·var` (or `var`); `a = Σ cᵢ`.
/// The canonical sum keeps `−t·√37/2 − t/2` as two terms (only rational
/// multiples of one term merge), so up to 0.31 `∫ e^{−t·√37/2 − t/2} dt`
/// stayed unevaluated while `∫ e^{−t·(√37 + 1)/2} dt` worked.
fn linear_sum_parts(
    arena: &mut Arena,
    expr: ExprId,
    var: ExprId,
    var_sym: SymbolId,
) -> Option<(ExprId, ExprId)> {
    {
        let ExprNode::Add(ref children) = arena.node(expr).clone() else {
            return None;
        };
        let mut var_terms: SmallVec<[ExprId; 4]> = SmallVec::new();
        let mut const_terms: SmallVec<[ExprId; 4]> = SmallVec::new();

        for &child in children {
            if contains_var(arena, child, var_sym) {
                var_terms.push(child);
            } else {
                const_terms.push(child);
            }
        }

        if var_terms.is_empty() {
            return None; // No var dependence — not linear in var
        }

        // Each var-containing term must be c*var; the coefficient is the
        // sum of the c's.
        let mut coeffs: SmallVec<[ExprId; 4]> = SmallVec::new();
        for &term in &var_terms {
            if term == var {
                coeffs.push(arena.one);
                continue;
            }
            let ExprNode::Mul(ref mul_children) = arena.node(term).clone() else {
                return None; // Can't decompose
            };
            let mut vc = 0u32;
            let mut other: SmallVec<[ExprId; 4]> = SmallVec::new();
            for &mc in mul_children {
                if mc == var {
                    vc += 1;
                } else if contains_var(arena, mc, var_sym) {
                    return None;
                } else {
                    other.push(mc);
                }
            }
            if vc != 1 {
                return None;
            }
            coeffs.push(match other.len() {
                0 => arena.one,
                1 => other[0],
                _ => arena.mul(&other),
            });
        }
        let coeff = match coeffs.len() {
            1 => coeffs[0],
            _ => arena.add(&coeffs),
        };
        if coeff == arena.zero {
            return None;
        }

        // Verify coefficient is free of var
        if contains_var(arena, coeff, var_sym) {
            return None;
        }

        let constant = match const_terms.len() {
            0 => arena.zero,
            1 => const_terms[0],
            _ => arena.add(&const_terms),
        };

        // Verify constant is free of var
        if contains_var(arena, constant, var_sym) {
            return None;
        }

        Some((coeff, constant))
    }
}

/// Extract symbolic quadratic coefficients from `cx² + dx + e`.
///
/// Given an expression that is quadratic in `var`, returns
/// `Some((c_expr, d_expr, e_expr))` where `c` is the coefficient of `var²`,
/// `d` is the coefficient of `var`, and `e` is the constant term — all as
/// `ExprId`s that are free of `var`.
///
/// Returns `None` if the expression is not quadratic in `var` (e.g., it
/// contains `var³` or non-polynomial dependence on `var`).
///
/// This is the quadratic analogue of [`symbolic_linear_coeff_of`], used when
/// [`expr_to_poly`](crate::poly::polybridge::expr_to_poly) fails because coefficients are irrational (e.g., `√5`).
fn symbolic_quadratic_coeffs(
    arena: &mut Arena,
    expr: ExprId,
    var: ExprId,
    var_sym: SymbolId,
) -> Option<(ExprId, ExprId, ExprId)> {
    // Fast path: try numeric first.
    tracing::trace!("symbolic_quadratic_coeffs: attempting to extract quadratic coefficients");
    if let Some(poly) = crate::poly::polybridge::expr_to_poly(arena, expr, var) {
        if poly.degree()? == 2 {
            let c = arena.num_ratio(poly.coeff(2).clone());
            let d = arena.num_ratio(poly.coeff(1).clone());
            let e = arena.num_ratio(poly.coeff(0).clone());
            return Some((c, d, e));
        }
        return None;
    }

    // Symbolic path: walk the Add children and classify each term.
    tracing::trace!("symbolic_quadratic_coeffs: rational path failed, trying symbolic extraction");
    let children = match arena.node(expr).clone() {
        ExprNode::Add(c) => c.to_vec(),
        _ => vec![expr],
    };

    let mut x2_terms: SmallVec<[ExprId; 4]> = SmallVec::new(); // coefficients of var²
    let mut x1_terms: SmallVec<[ExprId; 4]> = SmallVec::new(); // coefficients of var
    let mut x0_terms: SmallVec<[ExprId; 4]> = SmallVec::new(); // constant terms

    let two = arena.int(2);

    for &child in &children {
        if !contains_var(arena, child, var_sym) {
            // Constant term.
            x0_terms.push(child);
            continue;
        }

        // Check for var² or scalar * var²
        if child == arena.pow(var, two) {
            x2_terms.push(arena.one);
            continue;
        }

        // Check for Pow(var, 2)
        if let ExprNode::Pow(base, exp) = arena.node(child).clone()
            && base == var
        {
            if let Some(e) = arena.as_num(exp)
                && *e == num_rational::Ratio::from_integer(2.into())
            {
                x2_terms.push(arena.one);
                continue;
            }
            // var^(something else) — not quadratic
            return None;
        }

        // Check for Mul containing var² or var
        if let ExprNode::Mul(ref mul_children) = arena.node(child).clone() {
            let mul_children = mul_children.clone();
            let mut has_var_sq = false;
            let mut var_count = 0u32;
            let mut other_factors: SmallVec<[ExprId; 4]> = SmallVec::new();

            for &mc in &mul_children {
                if mc == var {
                    var_count += 1;
                    if var_count > 2 {
                        return None; // var³ or higher
                    }
                } else if let ExprNode::Pow(base, exp) = arena.node(mc).clone() {
                    if base == var {
                        {
                            let e = arena.as_num(exp)?;
                            if *e == num_rational::Ratio::from_integer(2.into()) {
                                has_var_sq = true;
                            } else if e.is_integer()
                                && *e > num_rational::Ratio::from_integer(2.into())
                            {
                                return None; // var³ or higher
                            } else {
                                // fractional power of var — not polynomial
                                return None;
                            }
                        }
                    } else if contains_var(arena, mc, var_sym) {
                        return None; // non-trivial var dependence
                    } else {
                        other_factors.push(mc);
                    }
                } else if contains_var(arena, mc, var_sym) {
                    return None; // non-trivial var dependence
                } else {
                    other_factors.push(mc);
                }
            }

            let scalar = match other_factors.len() {
                0 => arena.one,
                1 => other_factors[0],
                _ => arena.mul(&other_factors),
            };

            if has_var_sq || var_count == 2 {
                x2_terms.push(scalar);
            } else if var_count == 1 {
                x1_terms.push(scalar);
            } else {
                // No var at all in this Mul child — should have been caught
                // by the contains_var check above, but be safe.
                x0_terms.push(child);
            }
            continue;
        }

        // Check for bare var
        if child == var {
            x1_terms.push(arena.one);
            continue;
        }

        // Check for Neg(something)
        if let ExprNode::Neg(inner) = arena.node(child).clone() {
            if let Some((c, d, e)) = symbolic_quadratic_coeffs(arena, inner, var, var_sym) {
                x2_terms.push(arena.neg(c));
                x1_terms.push(arena.neg(d));
                x0_terms.push(arena.neg(e));
                continue;
            }
            return None;
        }

        // Unrecognized var-dependent term.
        return None;
    }

    // The expression must have a nonzero x² coefficient to be quadratic.
    if x2_terms.is_empty() {
        tracing::trace!("symbolic_quadratic_coeffs: no x² terms found, not quadratic");
        return None;
    }

    tracing::trace!(
        n_x2_terms = x2_terms.len(),
        n_x1_terms = x1_terms.len(),
        n_x0_terms = x0_terms.len(),
        "symbolic_quadratic_coeffs: classified terms"
    );

    let c_expr = match x2_terms.len() {
        1 => x2_terms[0],
        _ => arena.add(&x2_terms),
    };
    let d_expr = match x1_terms.len() {
        0 => arena.zero,
        1 => x1_terms[0],
        _ => arena.add(&x1_terms),
    };
    let e_expr = match x0_terms.len() {
        0 => arena.zero,
        1 => x0_terms[0],
        _ => arena.add(&x0_terms),
    };

    // Verify c is free of var.
    if contains_var(arena, c_expr, var_sym) {
        return None;
    }

    Some((c_expr, d_expr, e_expr))
}

// ═══════════════════════════════════════════════════════════════════════════
// General u-substitution
// ═══════════════════════════════════════════════════════════════════════════

/// Try general u-substitution on a product integrand.
///
/// For each dependent factor `g(u)` where `u = u(x)`, this checks
/// whether the remaining factors equal `du/dx` times a constant `c`.
/// When they do, `∫ c · (du/dx) · g(u) dx = c · G(u)` where `G` is
/// the antiderivative of `g` with respect to `u`.
///
/// The technique works by:
/// 1. Extracting candidate inner arguments from function / power nodes.
/// 2. Computing `du/dx` via [`crate::transforms::diff::diff`].
/// 3. Forming `remaining / du` and checking it is free of `var`.
/// 4. Substituting `u → var` in the factor, integrating, then
///    substituting back.
fn try_u_substitution(
    arena: &mut Arena,
    dependent: &[ExprId],
    var: ExprId,
    var_sym: SymbolId,
    depth: usize,
) -> Option<ExprId> {
    for (i, &factor) in dependent.iter().enumerate() {
        let candidates = u_sub_candidates(arena, factor, var_sym);

        for u_expr in candidates {
            // Skip the trivial u = var case (already handled elsewhere)
            if u_expr == var {
                continue;
            }

            // Compute du/dx
            let du = crate::transforms::diff::diff(arena, u_expr, var);
            if du == arena.zero {
                continue;
            }

            // Product of the remaining dependent factors
            let remaining_expr = remaining_product(arena, dependent, i);

            // quotient = remaining / du — if free of var, we have our constant
            let quotient = arena.div(remaining_expr, du);

            // Try the raw quotient first; fall back to polynomial cancellation,
            // then to trigonometric simplification (e.g. sec²/(1 + tan²) = 1).
            // A quotient that depends on `var` only through `u` joins the
            // factor: `∫ g(u)·h(u)·u′ dx` (up to 0.31 only a constant
            // quotient counted, and `∫ cos³x·(a + b·cos²x)³·sin x dx` came
            // out of the Weierstrass substitution with `tan(x/2)⁴²`).
            let placeholder = arena.symbol("__usub_u");
            let mut through_u: Option<ExprId> = None;
            let coeff = if !contains_var(arena, quotient, var_sym) {
                quotient
            } else {
                let cancelled = arena.cancel_expr(quotient, var);
                if !contains_var(arena, cancelled, var_sym) {
                    cancelled
                } else {
                    // No rewriting of `sin`, `cos`, … can make a quotient
                    // that provably depends on `var` constant.
                    let varies = var_outside_trig_arguments(arena, cancelled, var_sym)
                        || varies_numerically(arena, cancelled, var);
                    let trig = if varies {
                        cancelled
                    } else {
                        let trig = arena.trigsimp_expr(cancelled);
                        crate::transforms::eval::eval(arena, trig)
                    };
                    if !contains_var(arena, trig, var_sym) {
                        trig
                    } else {
                        // (For a linear `u` this is a renaming that adds
                        // nothing: every rule takes linear arguments.)
                        if !contains_var(arena, du, var_sym) {
                            continue;
                        }
                        let q_in_u = arena.subs_structural(quotient, u_expr, placeholder);
                        if contains_var(arena, q_in_u, var_sym) {
                            continue;
                        }
                        through_u = Some(quotient);
                        arena.one
                    }
                }
            };
            // `du` may be a constant that is zero without being so
            // structurally, and `trigsimp` shows it: `u = k·x + 1` with
            // `k = sin²1 + cos²1 − 1` gave the coefficient `zoo`, and
            // `∫ x/u dx = zoo` once the self-check stopped passing the
            // earlier candidate with the vanishing denominator `k`.
            if contains_non_finite(arena, coeff) {
                continue;
            }

            // The factor must depend on `var` only through `u`: with `u`
            // replaced by a fresh symbol nothing of `var` may remain
            // (otherwise `g(var)` below would silently absorb it).
            let factor = match through_u {
                Some(q) => arena.mul(&[factor, q]),
                None => factor,
            };
            let factor_in_u = arena.subs_structural(factor, u_expr, placeholder);
            if contains_var(arena, factor_in_u, var_sym) {
                continue;
            }

            // Replace u(x) → var inside the factor to get g(var),
            // integrate g(var) w.r.t. var, then substitute var → u(x) back.
            let g_of_var = arena.subs_structural(factor, u_expr, var);
            let g_integrated = integrate_node(arena, g_of_var, var, var_sym, depth);

            // If the inner integral is unevaluated, this candidate didn't help
            if matches!(arena.node(g_integrated), ExprNode::Integral(_, _)) {
                continue;
            }

            // G(u) — substitute var back to u(x)
            let antideriv = arena.subs_structural(g_integrated, var, u_expr);
            let antideriv = match continuous_through_tan_of_u(
                arena,
                g_integrated,
                antideriv,
                u_expr,
                var,
                var_sym,
            ) {
                Some(continuous) => continuous,
                None if jump_kept_undecided(arena, g_integrated, var_sym) => {
                    match tan_argument_of(arena, u_expr, var_sym) {
                        Some(w) => crate::transforms::trig_integ::atan_tan_terms_to_argument_in(
                            arena,
                            antideriv,
                            w,
                            Some(var_sym),
                        ),
                        None => antideriv,
                    }
                }
                None => continue,
            };
            tracing::debug!("u-substitution succeeded");
            return Some(arena.mul(&[coeff, antideriv]));
        }
    }
    None
}

/// The back-substituted `antideriv = G(u(x))` of a u-substitution, made
/// continuous across the poles of a `tan w` through which `u` depends on
/// `x` ([`crate::transforms::trig_integ::add_tan_floor`]).  `g` is `G` in
/// `var` (the stand-in for `u`).  Up to 0.37 `∫ tan x/(tan x + 2) dx` was
/// `… + 1/5·atan(tan x)`, which drops by `π/5` at every `x = π/2 + kπ`.
///
/// `antideriv` unchanged when `u` has no `tan` of `var`; `None` (the
/// candidate is not used) when `u` depends on `var` otherwise than through
/// one `tan w`, or the jump `G(U(+∞)) − G(U(−∞))` of `G(U(s))`, `u = U(tan w)`,
/// is not decided.
fn continuous_through_tan_of_u(
    arena: &mut Arena,
    g: ExprId,
    antideriv: ExprId,
    u_expr: ExprId,
    var: ExprId,
    var_sym: SymbolId,
) -> Option<ExprId> {
    let Some(w) = tan_argument_of(arena, u_expr, var_sym) else {
        return Some(antideriv);
    };
    let tan_w = arena.tan(w);
    let s = arena.symbol("__tan_s");
    let ExprNode::Symbol(s_sym) = *arena.node(s) else {
        return None;
    };
    let u_of_s = arena.subs_structural(u_expr, tan_w, s);
    if contains_var(arena, u_of_s, var_sym) {
        return None;
    }
    let h = arena.subs_structural(g, var, u_of_s);
    let (antideriv, jump) = match crate::transforms::trig_integ::infinity_jump(arena, h, s, s_sym) {
        Some(jump) => (antideriv, jump),
        // Parameters not declared real: the jump as for real ones, of the
        // answer with the logarithms the stage exit writes `ln u` (up to
        // 0.37 the answer was kept uncorrected: `∫ tan x/(a + tan x) dx`
        // stepped by `iπ·a/(a² + 1)` at every pole of `tan x`).
        None => {
            let all = crate::base::walk::free_symbols(arena, w)
                .into_iter()
                .any(|v| match *arena.node(v) {
                    ExprNode::Symbol(sid) => {
                        sid != var_sym
                            && !crate::transforms::realness::symbol_declared_real(arena, sid)
                    }
                    _ => true,
                });
            let g = crate::transforms::trig_integ::plain_logs(arena, g, var_sym, all);
            let h = arena.subs_structural(g, var, u_of_s);
            let jump =
                crate::transforms::trig_integ::infinity_jump_real_parameters(arena, h, s, s_sym)?;
            (arena.subs_structural(g, var, u_expr), jump)
        }
    };
    Some(crate::transforms::trig_integ::add_tan_floor_in(
        arena,
        antideriv,
        w,
        jump,
        Some(var_sym),
    ))
}

/// The argument `w` of the first `tan w` (with `w` depending on `var`) in
/// `u` (post-order).
fn tan_argument_of(arena: &Arena, u: ExprId, var_sym: SymbolId) -> Option<ExprId> {
    crate::base::walk::post_order_ids(arena, u)
        .into_iter()
        .find_map(|id| match *arena.node(id) {
            ExprNode::Tan(w) if contains_var(arena, w, var_sym) => Some(w),
            _ => None,
        })
}

/// Does `var` occur in `q` outside the arguments of its trigonometric and
/// hyperbolic functions (`x²·sin x`, `eˣ/cos x`)?  `trigsimp` rewrites
/// those functions only, so it cannot make such a `q` free of `var`: on a
/// sample of the Rubi suite (0.31) none of 4,550 such quotients became
/// constant (the canonical form already cancels equal factors).
fn var_outside_trig_arguments(arena: &Arena, q: ExprId, var_sym: SymbolId) -> bool {
    let mut stack = vec![q];
    let mut seen: FxHashSet<ExprId> = FxHashSet::default();
    while let Some(id) = stack.pop() {
        if !seen.insert(id) {
            continue;
        }
        match arena.node(id) {
            ExprNode::Sin(_)
            | ExprNode::Cos(_)
            | ExprNode::Tan(_)
            | ExprNode::Sinh(_)
            | ExprNode::Cosh(_)
            | ExprNode::Tanh(_) => {}
            ExprNode::Symbol(s) if *s == var_sym => return true,
            node => node.for_each_child(|c| stack.push(c)),
        }
    }
    false
}

/// Sample points for [`varies_numerically`].
const VARIES_POINTS: [(i64, i64); 2] = [(3, 7), (5, 11)];

/// Does `q` provably depend on `var`: does it take clearly different
/// values (to 15 digits) at two sample points, with its other free symbols
/// at the generic values of [`FTC_PARAMETER_VALUES`]?  `false` when it
/// does not evaluate at both points or the values agree.  No rewriting
/// can then make `q` free of `var`, and [`try_u_substitution`] skips
/// `trigsimp`, which tries seven strategies on each quotient and found a
/// constant in 1 of 9,500 calls on a sample of the Rubi suite (0.31;
/// `sin 2x/(8 sin x cos x) = 1/4`), while taking 50 % of the time of the
/// integrands that stay unevaluated.
///
/// Inside an `integrate` call the answer is remembered until the outermost
/// call ends ([`VARIES_MEMO`]).
fn varies_numerically(arena: &mut Arena, q: ExprId, var: ExprId) -> bool {
    let inside = NODE_BUDGET_DEPTH.with(std::cell::Cell::get) > 0;
    let key = (std::ptr::from_ref::<Arena>(arena) as usize, q, var);
    if inside && let Some(found) = VARIES_MEMO.with(|m| m.borrow().get(&key).copied()) {
        return found;
    }
    let varies = varies_numerically_uncached(arena, q, var);
    if inside {
        VARIES_MEMO.with(|m| m.borrow_mut().insert(key, varies));
    }
    varies
}

thread_local! {
    /// [`varies_numerically`] during the current top-level `integrate`
    /// (cleared with [`INTEGRATE_MEMO`]), by (arena, quotient, variable).
    /// The u-substitution meets the same quotients for every degenerate
    /// case of the parameters and every depth it is retried at: on the Rubi
    /// suite's 4.5.4.2 (0.38) its 45,000 tests took 6.5 s, a fifth of the
    /// integration time, and 24,700 of them were repeats.
    static VARIES_MEMO: std::cell::RefCell<FxHashMap<(usize, ExprId, ExprId), bool>> =
        std::cell::RefCell::new(FxHashMap::default());
}

/// [`varies_numerically`] without the memo.
fn varies_numerically_uncached(arena: &mut Arena, q: ExprId, var: ExprId) -> bool {
    let mut params: Vec<(String, ExprId)> = Vec::new();
    for s in crate::base::walk::free_symbols(arena, q) {
        if s == var {
            continue;
        }
        let ExprNode::Symbol(sid) = *arena.node(s) else {
            return false;
        };
        params.push((arena.symbol_name(sid).to_owned(), s));
    }
    if params.len() > FTC_PARAMETER_VALUES.len() {
        return false;
    }
    params.sort();
    let mut bound = q;
    for (k, &(_, s)) in params.iter().enumerate() {
        let (p, d) = FTC_PARAMETER_VALUES[k];
        let value = arena.rational(p, d);
        bound = crate::transforms::subs::subs(arena, bound, s, value);
    }
    let mut values = Vec::with_capacity(VARIES_POINTS.len());
    for &(p, d) in &VARIES_POINTS {
        let point = arena.rational(p, d);
        let at = crate::transforms::subs::subs(arena, bound, var, point);
        let at = crate::transforms::eval::eval(arena, at);
        if crate::base::walk::has_unevaluated(arena, at) {
            return false;
        }
        let Ok(v) = crate::transforms::evalf::evalf_complex(arena, at, 15) else {
            return false;
        };
        values.push(v);
    }
    let (Some(scale), Some(gap)) = (
        crate::transforms::evalf::abs_to_f64(&values[0]),
        crate::transforms::evalf::distance_to_f64(&values[0], &values[1]),
    ) else {
        return false;
    };
    scale.is_finite() && gap.is_finite() && gap > 1e-8 * scale.max(1.0)
}

/// Collect candidate `u`-expressions from a single factor.
///
/// For function nodes (`sin`, `cos`, `exp`, …) the inner argument and the
/// node itself are returned.  For `Pow(base, exp)` the base is returned
/// (enabling e.g. `u = x² + 1` inside `(x²+1)^{-1}`), and for `Pow` and
/// `Add` factors also the function nodes found inside them (`u = sin x`
/// for `(sin²x + 1)^{-1}` or `sin x + 1`), so that `∫ cos x·R(sin x) dx`
/// is a substitution rather than a Weierstrass problem.
fn u_sub_candidates(arena: &Arena, factor: ExprId, var_sym: SymbolId) -> SmallVec<[ExprId; 4]> {
    let mut out: SmallVec<[ExprId; 4]> = SmallVec::new();
    match arena.node(factor).clone() {
        ExprNode::Sin(inner)
        | ExprNode::Cos(inner)
        | ExprNode::Tan(inner)
        | ExprNode::Exp(inner)
        | ExprNode::Ln(inner)
        | ExprNode::Sinh(inner)
        | ExprNode::Cosh(inner)
        | ExprNode::Tanh(inner)
        | ExprNode::Asin(inner)
        | ExprNode::Acos(inner)
        | ExprNode::Atan(inner)
        | ExprNode::Asinh(inner)
        | ExprNode::Acosh(inner)
        | ExprNode::Atanh(inner)
        | ExprNode::Abs(inner)
            if contains_var(arena, inner, var_sym) =>
        {
            out.push(inner);
            // Also try the function node itself as a candidate.
            // E.g., for ln(x), try u = ln(x) (not just u = x).
            // This enables ∫ 1/(x·ln(x)) dx via u = ln(x), du = 1/x dx.
            out.push(factor);
        }
        ExprNode::Pow(base, _exp) if contains_var(arena, base, var_sym) => {
            out.push(base);
            inner_function_candidates(arena, base, var_sym, &mut out);
        }
        ExprNode::Add(_) => {
            inner_function_candidates(arena, factor, var_sym, &mut out);
        }
        _ => {}
    }
    out
}

/// Elementary function nodes (`sin g`, `exp g`, … with `g` depending on
/// `var`) inside `expr`, in post-order, deduplicated, at most four in total.
fn inner_function_candidates(
    arena: &Arena,
    expr: ExprId,
    var_sym: SymbolId,
    out: &mut SmallVec<[ExprId; 4]>,
) {
    for id in crate::base::walk::post_order_ids(arena, expr) {
        if out.len() >= 4 {
            return;
        }
        if id == expr || out.contains(&id) {
            continue;
        }
        let is_candidate = match arena.node(id) {
            ExprNode::Sin(inner)
            | ExprNode::Cos(inner)
            | ExprNode::Tan(inner)
            | ExprNode::Exp(inner)
            | ExprNode::Ln(inner)
            | ExprNode::Sinh(inner)
            | ExprNode::Cosh(inner)
            | ExprNode::Tanh(inner) => contains_var(arena, *inner, var_sym),
            _ => false,
        };
        if is_candidate {
            out.push(id);
        }
    }
}

/// Build the product of all elements in `children` except index `skip`.
fn remaining_product(arena: &mut Arena, children: &[ExprId], skip: usize) -> ExprId {
    let parts: SmallVec<[ExprId; 4]> = children
        .iter()
        .enumerate()
        .filter(|&(j, _)| j != skip)
        .map(|(_, &c)| c)
        .collect();
    match parts.len() {
        0 => arena.one,
        1 => parts[0],
        _ => arena.mul(&parts),
    }
}

// ═══════════════════════════════════════════════════════════════════════════
// Substitution strategies (v0.2 gap-fill)
// ═══════════════════════════════════════════════════════════════════════════

thread_local! {
    /// Nesting depth of substitution strategies that re-enter [`integrate`].
    static SUBST_DEPTH: std::cell::Cell<u8> = const { std::cell::Cell::new(0) };
}

/// Maximum nesting of substitution strategies.
const MAX_SUBST_DEPTH: u8 = 3;

thread_local! {
    /// Set while a rationalising substitution integrates its transformed
    /// integrand ([`integrate_nested_generic`]): no `Piecewise` cases there.
    static GENERIC_ONLY: std::cell::Cell<bool> = const { std::cell::Cell::new(false) };
}

/// [`integrate_nested`] for the integrand in the new variable of a
/// substitution whose answer is checked and wrapped in `x`: its generic
/// answer only.  The cases of the parameters there are cases of the
/// substitution (`b = 0` in `x = (t² − a)/b`), and the wrap of the outer
/// call finds the integrand's own; computing both nested a dozen
/// `Piecewise` levels and took seconds.
fn integrate_nested_generic(arena: &mut Arena, expr: ExprId, var: ExprId) -> Option<ExprId> {
    struct Restore(bool);
    impl Drop for Restore {
        fn drop(&mut self) {
            let _ = GENERIC_ONLY.try_with(|g| g.set(self.0));
        }
    }
    let restore = Restore(GENERIC_ONLY.with(|g| g.replace(true)));
    let result = integrate_nested(arena, expr, var);
    drop(restore);
    result
}

/// Run the full integration pipeline on a transformed integrand from
/// inside a substitution strategy, with a re-entrancy bound.
fn integrate_nested(arena: &mut Arena, expr: ExprId, var: ExprId) -> Option<ExprId> {
    /// Restores the substitution depth on drop, also when a panic unwinds.
    struct Restore(u8);
    impl Drop for Restore {
        fn drop(&mut self) {
            let _ = SUBST_DEPTH.try_with(|d| d.set(self.0));
        }
    }
    let depth = SUBST_DEPTH.with(|d| d.get());
    if depth >= MAX_SUBST_DEPTH {
        return None;
    }
    SUBST_DEPTH.with(|d| d.set(depth + 1));
    let restore = Restore(depth);
    let result = integrate(arena, expr, var);
    drop(restore);
    if crate::base::walk::has_unevaluated(arena, result) {
        None
    } else {
        Some(result)
    }
}

/// Try the substitution-based strategies in order.
fn try_substitution_strategies(
    arena: &mut Arena,
    expr: ExprId,
    var: ExprId,
    var_sym: SymbolId,
) -> Option<ExprId> {
    if let Some(r) = stage!(
        arena,
        "trig_rational",
        expr,
        try_trig_rational_substitution(arena, expr, var, var_sym)
    ) {
        return Some(r);
    }
    if let Some(r) = try_exp_rational_substitution(arena, expr, var, var_sym) {
        return Some(r);
    }
    if let Some(r) = try_exp_linear_substitution(arena, expr, var, var_sym) {
        return Some(r);
    }
    if let Some(r) = try_radical_substitution(arena, expr, var, var_sym) {
        return Some(r);
    }
    if let Some(r) = try_even_power_radicals(arena, expr, var, var_sym) {
        return Some(r);
    }
    if let Some(r) = try_mobius_radical_substitution(arena, expr, var, var_sym) {
        return Some(r);
    }
    if let Some(r) = try_exp_atanh_rewrite(arena, expr, var, var_sym) {
        return Some(r);
    }
    if let Some(r) = try_hyperbolic_to_exp(arena, expr, var, var_sym) {
        return Some(r);
    }
    None
}

/// `(c, n)` with `g = c·xⁿ` for `c`, `n` free of `x`, `n ≠ 0` (`x` itself,
/// `xⁿ`, `c·x`, `c·xⁿ`).
fn monomial_parts(
    arena: &mut Arena,
    g: ExprId,
    var: ExprId,
    var_sym: SymbolId,
) -> Option<(ExprId, ExprId)> {
    let power = |arena: &Arena, f: ExprId| -> Option<ExprId> {
        if f == var {
            return Some(arena.one);
        }
        match arena.node(f) {
            ExprNode::Pow(b, e)
                if *b == var
                    && !contains_var(arena, *e, var_sym)
                    && !arena.is_zero_structural(*e) =>
            {
                Some(*e)
            }
            _ => None,
        }
    };
    if let Some(n) = power(arena, g) {
        return Some((arena.one, n));
    }
    let ExprNode::Mul(factors) = arena.node(g).clone() else {
        return None;
    };
    let mut n: Option<ExprId> = None;
    let mut rest: SmallVec<[ExprId; 4]> = SmallVec::new();
    for f in factors {
        if let Some(k) = power(arena, f) {
            if n.replace(k).is_some() {
                return None;
            }
        } else if contains_var(arena, f, var_sym) {
            return None;
        } else {
            rest.push(f);
        }
    }
    let c = match rest.len() {
        0 => arena.one,
        1 => rest[0],
        _ => arena.mul(&rest),
    };
    Some((c, n?))
}

/// `∫ h(x, L) dx` for `L = ln(c·xⁿ)` inside a trigonometric, hyperbolic or
/// exponential function (`sin(ln x)`, `x²·cos(a + b·ln(c·xⁿ))²`,
/// `sinh(ln x)`), `x` occurring elsewhere only in powers: with `w = L`,
/// `x = K·e^{w/n}` (`K = c^{−1/n}`) and `dx = x/n·dw`, the integral is
/// `∫ h(K·e^{w/n}, w)·K·e^{w/n}/n dw`, an exponential times trigonometric
/// functions of `w`.  Every term of the integrand and of its answer
/// carries `Kᵐ` with `e^{m·w/n}`, and `Kᵐ·e^{m·w/n} = xᵐ`: the answer in
/// `x` and `L` is the same for every `K`, so it is computed with `K = 1`
/// and brought back with `e^{q·w} = x^{q·n}` (it satisfies `F′ = h` along
/// the curve of every `K`, whatever `c` and `n` are; the self-check
/// confirms it).  Up to 0.31 `∫ sin(ln x) dx` stayed unevaluated; SymPy:
/// `x·sin(log x)/2 − x·cos(log x)/2`.
fn try_log_substitution(
    arena: &mut Arena,
    expr: ExprId,
    var: ExprId,
    var_sym: SymbolId,
) -> Option<ExprId> {
    let order = crate::base::walk::post_order_ids(arena, expr);
    // The logarithm: one `ln(g)` of `x`, no other.
    let mut log: Option<(ExprId, ExprId)> = None;
    for &id in &order {
        if let ExprNode::Ln(g) = *arena.node(id)
            && contains_var(arena, g, var_sym)
        {
            match log {
                Some((l, _)) if l != id => return None,
                _ => log = Some((id, g)),
            }
        }
    }
    let (ln_node, g) = log?;
    let inside_function = order.iter().any(|&id| {
        matches!(arena.node(id),
            ExprNode::Sin(a) | ExprNode::Cos(a) | ExprNode::Tan(a) | ExprNode::Sinh(a)
            | ExprNode::Cosh(a) | ExprNode::Tanh(a) | ExprNode::Exp(a)
            if crate::base::walk::contains(arena, *a, ln_node))
    });
    if !inside_function {
        return None;
    }
    let w = arena.symbol("__lw");
    let ExprNode::Symbol(w_sym) = *arena.node(w) else {
        return None;
    };
    let Some((_, n)) = monomial_parts(arena, g, var, var_sym) else {
        return log_of_linear_substitution(arena, expr, ln_node, g, w, var, var_sym);
    };
    // x^m → e^{m·w/n}, x → e^{w/n}.
    let x_power = |arena: &mut Arena, m: ExprId| -> ExprId {
        let mw = arena.mul(&[m, w]);
        let mwn = arena.div(mw, n);
        arena.exp(mwn)
    };
    let mut sub = arena.subs_structural(expr, ln_node, w);
    for id in crate::base::walk::post_order_ids(arena, sub) {
        if let ExprNode::Pow(b, m) = *arena.node(id)
            && b == var
            && !contains_var(arena, m, var_sym)
        {
            let r = x_power(arena, m);
            sub = arena.subs_structural(sub, id, r);
        }
    }
    let one = arena.one;
    let x_w = x_power(arena, one);
    sub = arena.subs_structural(sub, var, x_w);
    if contains_var(arena, sub, var_sym) {
        return None;
    }
    let integrand = arena.mul(&[sub, x_w]);
    let integrand = arena.div(integrand, n);
    let integrand = crate::transforms::eval::eval(arena, integrand);
    let res = integrate_nested(arena, integrand, w)?;
    // e^{q·w + r} → e^r·x^{q·n}.
    let mut back = res;
    for id in crate::base::walk::post_order_ids(arena, res) {
        if let ExprNode::Exp(arg) = *arena.node(id)
            && crate::base::walk::has_free_symbol(arena, arg, w_sym)
        {
            let (q, r) = symbolic_linear_coeff_of(arena, arg, w, w_sym)?;
            let qn = arena.mul(&[q, n]);
            let x_qn = arena.pow(var, qn);
            let e_r = arena.exp(r);
            let repl = arena.mul(&[e_r, x_qn]);
            back = arena.subs_structural(back, id, repl);
        }
    }
    let back = crate::transforms::eval::eval(arena, back);
    let back = arena.subs_structural(back, w, ln_node);
    let back = crate::transforms::eval::eval(arena, back);
    if candidate_rejected(arena, expr, back, var, var_sym) {
        tracing::debug!("integrate: rejecting unverified logarithmic-substitution closed form");
        return None;
    }
    Some(back)
}

/// [`try_log_substitution`] for `L = ln(g)` with `g = α·x + β` linear
/// (`β ≠ 0`) and `x` nowhere outside `L` (`sin(ln(a + b·x))`): `w = L`,
/// `dx = e^w/α·dw`, and the answer comes back with `e^{q·w} = g^q`.
fn log_of_linear_substitution(
    arena: &mut Arena,
    expr: ExprId,
    ln_node: ExprId,
    g: ExprId,
    w: ExprId,
    var: ExprId,
    var_sym: SymbolId,
) -> Option<ExprId> {
    let ExprNode::Symbol(w_sym) = *arena.node(w) else {
        return None;
    };
    let (alpha, beta) = symbolic_linear_coeff_of(arena, g, var, var_sym)?;
    if arena.is_zero_structural(beta) {
        return None;
    }
    let sub = arena.subs_structural(expr, ln_node, w);
    if contains_var(arena, sub, var_sym) {
        return None;
    }
    let e_w = arena.exp(w);
    let integrand = arena.mul(&[sub, e_w]);
    let integrand = arena.div(integrand, alpha);
    let integrand = crate::transforms::eval::eval(arena, integrand);
    let res = integrate_nested(arena, integrand, w)?;
    let mut back = res;
    for id in crate::base::walk::post_order_ids(arena, res) {
        if let ExprNode::Exp(arg) = *arena.node(id)
            && crate::base::walk::has_free_symbol(arena, arg, w_sym)
        {
            let (q, r) = symbolic_linear_coeff_of(arena, arg, w, w_sym)?;
            let g_q = arena.pow(g, q);
            let e_r = arena.exp(r);
            let repl = arena.mul(&[e_r, g_q]);
            back = arena.subs_structural(back, id, repl);
        }
    }
    let back = crate::transforms::eval::eval(arena, back);
    let back = arena.subs_structural(back, w, ln_node);
    let back = crate::transforms::eval::eval(arena, back);
    if candidate_rejected(arena, expr, back, var, var_sym) {
        tracing::debug!("integrate: rejecting unverified logarithmic-substitution closed form");
        return None;
    }
    Some(back)
}

/// Collect the `exp(k·x)` nodes of `expr` (with numeric `k`).  Returns
/// `None` if some `exp` argument depends on `var` but is not of that form.
fn collect_exp_multiples(
    arena: &mut Arena,
    expr: ExprId,
    var: ExprId,
    var_sym: SymbolId,
) -> Option<Vec<(ExprId, Q)>> {
    let order = crate::base::walk::post_order_ids(arena, expr);
    let mut out = Vec::new();
    for id in order {
        if let ExprNode::Exp(arg) = arena.node(id).clone()
            && contains_var(arena, arg, var_sym)
        {
            let (alpha, beta) = symbolic_linear_coeff_of(arena, arg, var, var_sym)?;
            if !arena.is_zero_structural(beta) {
                return None;
            }
            let k = arena.as_num(alpha)?.clone();
            out.push((id, k));
        }
    }
    Some(out)
}

/// `∫ R(e^{ax}) dx` via `u = e^{ax}`: `∫ R(u)/(a·u) du` for a rational `R`.
///
/// `a` is chosen as the greatest common divisor of all exponent
/// coefficients so that every `e^{kx}` becomes an integer power of `u`.
fn try_exp_rational_substitution(
    arena: &mut Arena,
    expr: ExprId,
    var: ExprId,
    var_sym: SymbolId,
) -> Option<ExprId> {
    use num_integer::Integer;
    let exps = collect_exp_multiples(arena, expr, var, var_sym)?;
    if exps.is_empty() {
        return None;
    }
    // a = gcd(k_i) for rationals: gcd(numerators)/lcm(denominators).
    let mut num_gcd = num_bigint::BigInt::zero();
    let mut den_lcm = num_bigint::BigInt::one();
    for (_, k) in &exps {
        num_gcd = num_gcd.gcd(k.numer());
        den_lcm = den_lcm.lcm(k.denom());
    }
    if num_gcd.is_zero() {
        return None;
    }
    let a = num_rational::Ratio::new(num_gcd, den_lcm);

    let u = arena.symbol("__eu");
    let u_sym = match arena.node(u) {
        ExprNode::Symbol(s) => *s,
        _ => return None,
    };
    let mut sub = expr;
    for (node, k) in &exps {
        let power = k / &a; // integer
        let power_id = arena.num_ratio(power.clone());
        let u_pow = arena.pow(u, power_id);
        sub = arena.subs_structural(sub, *node, u_pow);
    }
    if contains_var(arena, sub, var_sym) {
        return None;
    }
    // Integrand in u: R(u)/(a u)
    let a_id = arena.num_ratio(a.clone());
    let a_u = arena.mul(&[a_id, u]);
    let integrand_u = arena.div(sub, a_u);
    let integrand_u = clear_nested_fractions(arena, integrand_u, u);
    // Must be rational in u.
    let (n, d) = crate::poly::polybridge::as_numer_denom(arena, integrand_u);
    if crate::poly::polybridge::expr_to_poly(arena, n, u).is_none()
        || crate::poly::polybridge::expr_to_poly(arena, d, u).is_none()
    {
        return None;
    }
    let res_u = integrate_node(arena, integrand_u, u, u_sym, 20);
    if crate::base::walk::has_unevaluated(arena, res_u) {
        return None;
    }
    // Back-substitute u → e^{ax}.
    let ax = arena.mul(&[a_id, var]);
    let e_ax = arena.exp(ax);
    let result = arena.subs_structural(res_u, u, e_ax);
    Some(crate::transforms::eval::eval(arena, result))
}

/// `∫ R(e^{L₁}, …, e^{Lₖ}) dx` for linear `Lᵢ = rᵢ·L + γᵢ` with rational
/// `rᵢ`, symbolic `L = α·x + β` (the first exponent) and constants `γᵢ`:
/// `u = e^{g·L}` (`g` the gcd of the `rᵢ`), `du = g·α·u·dx`, every
/// `e^{Lᵢ} = e^{γᵢ}·u^{rᵢ/g}`, and the integrand is rational in `u` over
/// `ℚ(parameters, e^{γᵢ})` (each `e^{γᵢ} ≠ 1` a fresh symbol while the
/// rational integrator runs).  [`try_exp_rational_substitution`] for
/// symbolic rates and shifts: `sinh(a + b·x)`, `sech(c + d·x)²`,
/// `coth(a + b·x)·coth(c + b·x)` (Rubi 6.x) stayed unevaluated.  `u`
/// moves monotonically along a ray for real `x`, so the logarithms of the
/// rational answer jump only at poles of the integrand.
fn try_exp_linear_substitution(
    arena: &mut Arena,
    expr: ExprId,
    var: ExprId,
    var_sym: SymbolId,
) -> Option<ExprId> {
    use num_integer::Integer;
    let mut exps: Vec<(ExprId, ExprId, ExprId)> = Vec::new();
    for id in crate::base::walk::post_order_ids(arena, expr) {
        if let ExprNode::Exp(arg) = *arena.node(id)
            && contains_var(arena, arg, var_sym)
        {
            let (alpha, beta) = symbolic_linear_coeff_of(arena, arg, var, var_sym)?;
            exps.push((id, alpha, beta));
        }
    }
    let &(_, alpha0, beta0) = exps.first()?;
    let mut ratios: Vec<Q> = Vec::with_capacity(exps.len());
    for &(_, alpha, _) in &exps {
        let r = arena.div(alpha, alpha0);
        let r = crate::transforms::eval::eval(arena, r);
        ratios.push(arena.as_num(r)?.clone());
    }
    let mut num_gcd = num_bigint::BigInt::zero();
    let mut den_lcm = num_bigint::BigInt::one();
    for r in &ratios {
        num_gcd = num_gcd.gcd(r.numer());
        den_lcm = den_lcm.lcm(r.denom());
    }
    if num_gcd.is_zero() {
        return None;
    }
    let g = Q::new(num_gcd, den_lcm);
    let u = arena.symbol("__elu");
    let ExprNode::Symbol(u_sym) = *arena.node(u) else {
        return None;
    };
    let mut constants: Vec<(ExprId, ExprId)> = Vec::new();
    let mut sub = expr;
    for (&(node, _, beta), r) in exps.iter().zip(&ratios) {
        let r_id = arena.num_ratio(r.clone());
        let r_beta0 = arena.mul(&[r_id, beta0]);
        let gamma = arena.sub(beta, r_beta0);
        let gamma = crate::transforms::eval::eval(arena, gamma);
        let k = arena.num_ratio(r / &g);
        let u_k = arena.pow(u, k);
        let repl = if arena.is_zero_structural(gamma) {
            u_k
        } else {
            let e_gamma = arena.exp(gamma);
            let kappa = match constants.iter().find(|&&(e, _)| e == e_gamma) {
                Some(&(_, s)) => s,
                None => {
                    let s = arena.symbol(&format!("__elk{}", constants.len()));
                    constants.push((e_gamma, s));
                    s
                }
            };
            arena.mul(&[kappa, u_k])
        };
        sub = arena.subs_structural(sub, node, repl);
    }
    if contains_var(arena, sub, var_sym) {
        return None;
    }
    let g_id = arena.num_ratio(g.clone());
    let du = arena.mul(&[g_id, alpha0, u]);
    let integrand = arena.div(sub, du);
    let integrand = crate::transforms::eval::eval(arena, integrand);
    if !is_rational_in(arena, integrand, u_sym) {
        return None;
    }
    let res = integrate_nested_generic(arena, integrand, u)?;
    let res = analytic_logs(arena, res, u_sym)?;
    let l = arena.mul(&[alpha0, var]);
    let l = arena.add(&[l, beta0]);
    let gl = arena.mul(&[g_id, l]);
    let e_gl = arena.exp(gl);
    let mut back = arena.subs_structural(res, u, e_gl);
    for &(e_gamma, kappa) in &constants {
        back = arena.subs_structural(back, kappa, e_gamma);
    }
    let back = crate::transforms::eval::eval(arena, back);
    if candidate_rejected(arena, expr, back, var, var_sym) {
        tracing::debug!("integrate: rejecting unverified exponential-substitution closed form");
        return None;
    }
    Some(back)
}

/// `∫ f(x, (κ·x²ʲ)^r, …) dx` (`κ` free of `x`, `r` not an integer, `m = 2j·r`
/// an integer): every such radical is `C·x^m` with `C = (κ·x²ʲ)^r·x^(−m)`,
/// whose derivative is 0 (an identity of analytic functions, so for every
/// value of the parameters), so `F = C·G` with `G = ∫ f·x^m/(κ·x²ʲ)^r dx` —
/// Rubi's device for these radicals (`√(b·x⁴)·x⁻²·(…)`).  For real `x`, `C`
/// is constant on each side of `x = 0` (`(κ·p)^r = κ^r·p^r` for `p ≥ 0`): the
/// same constant `κ^r` for an even `m`; for an odd one it changes sign
/// there, and `F = C·(G − G(0))` is continuous.  The Möbius substitution took
/// `s = x/√(b·x⁴)` for `√(b·x⁴)`, which jumps from `−∞` to `+∞` at `x = 0`:
/// `∫ √(b·x⁴)/(1 + x²) dx` stepped by `π·√b` there (`F(1) − F(−1)` = 3.0924
/// for 0.3717 at `b = 3/4`; Rubi 4.3.0 `√(b·tan⁴(c + d·x))` through `t = tan
/// u`).  `None` when no radical is of that form or `G` is not found.
fn try_even_power_radicals(
    arena: &mut Arena,
    expr: ExprId,
    var: ExprId,
    var_sym: SymbolId,
) -> Option<ExprId> {
    let two = num_bigint::BigInt::from(2);
    let mut out = expr;
    let mut constant: Vec<ExprId> = Vec::new();
    let mut odd = false;
    for id in crate::base::walk::post_order_ids(arena, expr) {
        let ExprNode::Pow(base, ex) = *arena.node(id) else {
            continue;
        };
        let Some(r) = arena.as_num(ex).cloned() else {
            continue;
        };
        if r.is_integer() || !contains_var(arena, base, var_sym) {
            continue;
        }
        let factors: Vec<ExprId> = match arena.node(base) {
            ExprNode::Mul(children) => children.to_vec(),
            _ => vec![base],
        };
        let mut power: Option<Q> = None;
        let mut kappa: Vec<ExprId> = Vec::new();
        for f in factors {
            if !contains_var(arena, f, var_sym) {
                kappa.push(f);
                continue;
            }
            match *arena.node(f) {
                ExprNode::Pow(b, e) if b == var && power.is_none() => {
                    power = arena.as_num(e).cloned();
                }
                _ => {
                    power = None;
                    break;
                }
            }
        }
        let Some(n) = power else {
            continue;
        };
        if !n.is_integer() || n.is_negative() || !(n.numer() % &two).is_zero() {
            continue;
        }
        let m = &n * &r;
        if !m.is_integer() {
            continue;
        }
        odd |= !(m.numer() % &two).is_zero();
        let m_id = arena.num_ratio(m.clone());
        let x_m = arena.pow(var, m_id);
        let minus_m = arena.num_ratio(-m);
        let x_minus_m = arena.pow(var, minus_m);
        constant.push(arena.mul(&[id, x_minus_m]));
        out = arena.subs_structural(out, id, x_m);
    }
    if constant.is_empty() {
        return None;
    }
    let out = crate::transforms::eval::eval(arena, out);
    tracing::debug!(rewritten = %arena.display(out), "integrate: radicals of even powers of the variable");
    let mut g = integrate_nested(arena, out, var)?;
    if odd {
        let at_zero = arena.subs_structural(g, var, arena.zero);
        let at_zero = crate::transforms::eval::eval(arena, at_zero);
        if contains_non_finite(arena, at_zero) || contains_var(arena, at_zero, var_sym) {
            return None;
        }
        let minus = arena.neg(at_zero);
        g = arena.add(&[g, minus]);
    }
    constant.push(g);
    let res = arena.mul(&constant);
    if candidate_rejected(arena, expr, res, var, var_sym) {
        return None;
    }
    Some(res)
}

/// `∫ f(x, x^{p/q}) dx` via `x = s^q`: `∫ q·s^{q−1} f(s^q, s^p) ds`.
fn try_radical_substitution(
    arena: &mut Arena,
    expr: ExprId,
    var: ExprId,
    var_sym: SymbolId,
) -> Option<ExprId> {
    use num_integer::Integer;
    let order = crate::base::walk::post_order_ids(arena, expr);
    let mut radicals: Vec<(ExprId, Q)> = Vec::new();
    let mut q_lcm = num_bigint::BigInt::one();
    for id in order {
        if let ExprNode::Pow(base, e) = arena.node(id).clone()
            && base == var
            && let Some(r) = arena.as_num(e).cloned()
            && !r.is_integer()
        {
            q_lcm = q_lcm.lcm(r.denom());
            radicals.push((id, r));
        }
    }
    if radicals.is_empty() {
        return None;
    }
    let q: i64 = q_lcm.to_string().parse().ok()?;
    if !(2..=6).contains(&q) {
        return None;
    }
    let s = arena.symbol("__rs");
    let mut sub = expr;
    for (node, r) in &radicals {
        let k = r * num_rational::Ratio::from_integer(num_bigint::BigInt::from(q));
        let k_id = arena.num_ratio(k.clone());
        let s_pow = arena.pow(s, k_id);
        sub = arena.subs_structural(sub, *node, s_pow);
    }
    let q_id = arena.int(q);
    let s_q = arena.pow(s, q_id);
    sub = arena.subs_structural(sub, var, s_q);
    if contains_var(arena, sub, var_sym) {
        return None;
    }
    // `s = x^{1/q}` is real only where `x ≥ 0` (for even `q`), so the
    // `s`-integrand may not contain anything whose value depends on `s`
    // being real — `|s|`, `sign(s)`, `H(s)`: `∫ |√x| dx` became
    // `∫ 2s·|s| ds = ⅔ s³ sign(s)`, wrong for x < 0 (fuzz_integrate).
    let s_sym = match arena.node(s) {
        ExprNode::Symbol(sid) => *sid,
        _ => return None,
    };
    let real_only = crate::base::walk::post_order_ids(arena, sub)
        .into_iter()
        .any(|id| match arena.node(id) {
            ExprNode::Abs(g) | ExprNode::Sign(g) | ExprNode::Heaviside(g) => {
                contains_var(arena, *g, s_sym)
            }
            _ => false,
        });
    if real_only {
        return None;
    }
    // dx = q s^{q−1} ds
    let qm1 = arena.int(q - 1);
    let s_qm1 = arena.pow(s, qm1);
    let integrand_s = arena.mul(&[q_id, s_qm1, sub]);
    let integrand_s = crate::transforms::eval::eval(arena, integrand_s);
    let res_s = integrate_nested(arena, integrand_s, s)?;
    // The `s`-integrand is analytic, but the rational integrator writes
    // `ln|v(s)|`, the *real* antiderivative — wrong once `s = x^{1/q}` is not
    // real (`∫ x^(−5/2)·atan(√x) dx` gained `−⅔ ln|√x|`, whose derivative
    // at x < 0 is not the integrand; found by `fuzz_integrate`).  Use the
    // analytic `ln v(s)`; any other `|·|`, `sign` or `H` of `s` is refused.
    let res_s = analytic_logs(arena, res_s, s_sym)?;
    // Back-substitute s → x^{1/q}.
    let inv_q = arena.rational(1, q);
    let root = arena.pow(var, inv_q);
    let result = arena.subs_structural(res_s, s, root);
    let result = crate::transforms::eval::eval(arena, result);
    // Verified like the other risky routes: the `s`-integral is computed by
    // the real-variable integrator, and a real-only step can still slip
    // through below the checks above — `(s⁻⁴)^{1/2}` flattened to `s⁻²` gave
    // `∫ cos(√x)/√(x⁻²) dx` a closed form whose derivative is wrong for
    // x < 0 (0.23, fuzz_integrate).
    if candidate_rejected(arena, expr, result, var, var_sym) {
        tracing::debug!("integrate: rejecting unverified radical-substitution closed form");
        return None;
    }
    Some(result)
}

/// `ln|g|` → `ln g` for every `g` depending on `s`; `None` when an `|·|`,
/// `sign` or `H` of `s` remains anywhere else.
fn analytic_logs(arena: &mut Arena, e: ExprId, s_sym: SymbolId) -> Option<ExprId> {
    let order = crate::base::walk::post_order_ids(arena, e);
    let mut out = e;
    for id in order {
        if let ExprNode::Ln(inner) = arena.node(id).clone()
            && let ExprNode::Abs(g) = arena.node(inner).clone()
            && contains_var(arena, g, s_sym)
        {
            let plain = arena.ln(g);
            out = arena.subs_structural(out, id, plain);
        }
    }
    let leftover = crate::base::walk::post_order_ids(arena, out)
        .into_iter()
        .any(|id| match arena.node(id) {
            ExprNode::Abs(g) | ExprNode::Sign(g) | ExprNode::Heaviside(g) => {
                contains_var(arena, *g, s_sym)
            }
            _ => false,
        });
    (!leftover).then_some(out)
}

// ═══════════════════════════════════════════════════════════════════════════
// Radicals of a Möbius function: t = B^{1/q}, t = B₁^{1/q}·B₂^{−1/q}
// ═══════════════════════════════════════════════════════════════════════════

/// Largest root index `q` [`try_mobius_radical_substitution`] takes (that
/// of [`try_radical_substitution`]).
const MAX_MOBIUS_ROOT: i64 = 6;

/// `m = (a·x + b)/(c·x + d)` with `a`, `b`, `c`, `d` free of `x`.
struct Mobius {
    a: ExprId,
    b: ExprId,
    c: ExprId,
    d: ExprId,
}

/// The coefficients of `m` as a Möbius function of `var` (after its
/// fractions are combined and cancelled), or `None`.
fn mobius_parts(arena: &mut Arena, m: ExprId, var: ExprId, var_sym: SymbolId) -> Option<Mobius> {
    let m = clear_nested_fractions(arena, m, var);
    let (numer, denom) = crate::poly::polybridge::as_numer_denom(arena, m);
    let mut linear = |e: ExprId| -> Option<(ExprId, ExprId)> {
        if contains_var(arena, e, var_sym) {
            symbolic_linear_coeff_of(arena, e, var, var_sym)
        } else {
            Some((arena.zero, e))
        }
    };
    let (a, b) = linear(numer)?;
    let (c, d) = linear(denom)?;
    if contains_var(arena, a, var_sym)
        || contains_var(arena, b, var_sym)
        || contains_var(arena, c, var_sym)
        || contains_var(arena, d, var_sym)
    {
        return None;
    }
    Some(Mobius { a, b, c, d })
}

/// `(node, base, e)` for every power `base^e` in `expr` whose base depends
/// on the variable and whose exponent is a rational number that is not an
/// integer; `None` when a power of such a base has a symbolic exponent or
/// one that depends on the variable.
fn radical_powers(
    arena: &Arena,
    expr: ExprId,
    var_sym: SymbolId,
) -> Option<Vec<(ExprId, ExprId, Q)>> {
    let mut out = Vec::new();
    for id in crate::base::walk::post_order_ids(arena, expr) {
        if let ExprNode::Pow(base, e) = *arena.node(id)
            && contains_var(arena, base, var_sym)
        {
            let r = arena.as_num(e)?;
            if !r.is_integer() {
                out.push((id, base, r.clone()));
            }
        } else if let ExprNode::Pow(_, e) = *arena.node(id)
            && contains_var(arena, e, var_sym)
        {
            return None;
        }
    }
    Some(out)
}

/// Denominators of at most this degree go to the rational integrators
/// cancelled and expanded ([`rational_in_factored_form`]); the one over
/// `ℚ(p₁, …)` takes up to this degree in that form.
const FACTORED_FORM_DEGREE: i64 = 10;

/// The largest exponent of `v` in the expanded polynomial `p`.
fn expanded_degree_in(arena: &Arena, p: ExprId, v: ExprId) -> i64 {
    let mut deg = 0;
    for id in crate::base::walk::post_order_ids(arena, p) {
        if id == v {
            deg = deg.max(1);
        } else if let ExprNode::Pow(b, k) = *arena.node(id)
            && b == v
            && let Some(k) = arena
                .as_num(k)
                .and_then(|k| i64::try_from(k.to_integer()).ok())
        {
            deg = deg.max(k);
        }
    }
    deg
}

/// A rational function `e` of `v` as one quotient: with parameters, the
/// numerator multiplied out over the denominator's factors as they come
/// (`(a − c·t²)⁸`), which the rational integrator over `ℚ(p₁, …)` uses
/// as its square-free decomposition; without, cancelled and expanded
/// ([`clear_nested_fractions`]).
fn rational_in_factored_form(arena: &mut Arena, e: ExprId, v: ExprId) -> ExprId {
    let e = crate::transforms::eval::eval(arena, e);
    let cleared = clear_nested_fractions(arena, e, v);
    let has_parameters = crate::base::walk::free_symbols(arena, cleared)
        .into_iter()
        .any(|s| s != v);
    let (_, d) = crate::poly::polybridge::as_numer_denom(arena, cleared);
    if !has_parameters || expanded_degree_in(arena, d, v) <= FACTORED_FORM_DEGREE {
        return cleared;
    }
    let (n, d) = crate::poly::polybridge::fraction_parts(arena, e);
    let n = crate::transforms::expand::expand(arena, n);
    let n = crate::transforms::eval::eval(arena, n);
    // Each factor multiplied out on its own: a Möbius image such as
    // `a·b·t² + a·(1 − b·t²)` is the constant `a`.
    let factors: SmallVec<[ExprId; 6]> = match arena.node(d) {
        ExprNode::Mul(children) => children.clone(),
        _ => SmallVec::from_slice(&[d]),
    };
    let mut expanded: SmallVec<[ExprId; 6]> = SmallVec::new();
    for f in factors {
        let (base, k) = match *arena.node(f) {
            ExprNode::Pow(b, k) => (b, Some(k)),
            _ => (f, None),
        };
        let base = crate::transforms::expand::expand(arena, base);
        let base = crate::transforms::eval::eval(arena, base);
        expanded.push(match k {
            Some(k) => arena.pow(base, k),
            None => base,
        });
    }
    let d = arena.mul(&expanded);
    arena.div(n, d)
}

/// Is `e` a rational function of the symbol `v` (sums, products and
/// integer powers of `v` and of constants)?
fn is_rational_in(arena: &Arena, e: ExprId, v: SymbolId) -> bool {
    let mut depends: FxHashMap<ExprId, bool> = FxHashMap::default();
    for id in crate::base::walk::post_order_ids(arena, e) {
        let node = arena.node(id);
        let mut below = matches!(node, ExprNode::Symbol(s) if *s == v);
        node.for_each_child(|c| below |= depends.get(&c).copied().unwrap_or(false));
        if below {
            let ok = match node {
                ExprNode::Symbol(_) | ExprNode::Add(_) | ExprNode::Mul(_) | ExprNode::Neg(_) => {
                    true
                }
                ExprNode::Pow(_, ex) => arena.as_num(*ex).is_some_and(|r| r.is_integer()),
                _ => false,
            };
            if !ok {
                return false;
            }
        }
        depends.insert(id, below);
    }
    true
}

/// `expr` with every product `B₁^{e₁}·B₂^{e₂}·r` (`e₁ + e₂` an integer)
/// written `t^{q·e₁}·B₂^{e₁+e₂}·r` — exact for `t = B₁^{1/q}·B₂^{−1/q}`,
/// since `B₁^{e₁} = (B₁^{1/q})^{q·e₁}` and `B₂^{e₂} = (B₂^{−1/q})^{−q·e₂}`
/// for principal powers, and `(B₂^{−1/q})^{−q·k} = B₂^k` for an integer
/// `k`.  `None` when a radical of `B₁` or `B₂` is left over (one without
/// its partner, or a pair whose exponents do not sum to an integer:
/// `∛(1 + x)·∛(1 − x)` is elliptic).
fn pair_radicals(
    arena: &mut Arena,
    expr: ExprId,
    b1: ExprId,
    b2: ExprId,
    t: ExprId,
    q: i64,
) -> Option<ExprId> {
    let radical_of = |arena: &Arena, id: ExprId, base: ExprId| -> Option<(ExprId, Q)> {
        match *arena.node(id) {
            ExprNode::Pow(b, e) if b == base => {
                let r = arena.as_num(e)?;
                (!r.is_integer()).then(|| (id, r.clone()))
            }
            _ => None,
        }
    };
    let q_ratio = Q::from_integer(q.into());
    let mut cur = expr;
    for _ in 0..64 {
        let mut hit = None;
        for id in crate::base::walk::post_order_ids(arena, cur) {
            if let ExprNode::Mul(children) = arena.node(id) {
                let p1 = children.iter().find_map(|&c| radical_of(arena, c, b1));
                let p2 = children.iter().find_map(|&c| radical_of(arena, c, b2));
                if let (Some(p1), Some(p2)) = (p1, p2) {
                    hit = Some((id, children.clone(), p1, p2));
                    break;
                }
            }
        }
        let Some((id, children, (n1, e1), (n2, e2))) = hit else {
            break;
        };
        let sum = &e1 + &e2;
        if !sum.is_integer() {
            return None;
        }
        let mut rest: SmallVec<[ExprId; 6]> = children
            .iter()
            .copied()
            .filter(|&c| c != n1 && c != n2)
            .collect();
        let k = arena.num_ratio(&e1 * &q_ratio);
        rest.push(arena.pow(t, k));
        let s = arena.num_ratio(sum);
        rest.push(arena.pow(b2, s));
        let replacement = arena.mul(&rest);
        cur = arena.subs_structural(cur, id, replacement);
    }
    let leftover = crate::base::walk::post_order_ids(arena, cur)
        .into_iter()
        .any(|id| radical_of(arena, id, b1).is_some() || radical_of(arena, id, b2).is_some());
    (!leftover).then_some(cur)
}

/// `∫ R(x, B^{p₁/q₁}, …) dx` for one base `B = (a·x + b)/(c·x + d)` (a
/// linear `a + b·x` among them), and `∫ R(x, B₁^{e₁}·B₂^{e₂}, …) dx` for
/// two bases whose quotient is such a function, with the radicals in
/// products whose exponents sum to integers (`√(1 + x)/√(1 − x)`,
/// `x^{−7/2}/√(a + b·x)`, `(a + b/x)^{3/2}`): the substitution
/// `t = B^{1/q}` (`t = B₁^{1/q}·B₂^{−1/q}`), `q` the least common
/// denominator of the exponents, makes the integrand rational,
/// `x = (d·tᵠ − b)/(a − c·tᵠ)` and `dx = q·t^{q−1}·(a·d − b·c)/(a − c·tᵠ)²·dt`
/// (SymPy's `sqrt_fractional_linear_rule` for one base; the pairing is the
/// classical one of Chebyshev's binomial integrals).
///
/// Exact for principal powers wherever `t` is: `tᵠ = B` (`B₁/B₂`) holds
/// as an identity of complex numbers, and every radical of the integrand is
/// an integer power of `t` times a rational function of `x` (see
/// [`pair_radicals`]), so the answer `G(t(x))` is an antiderivative at
/// complex values of the integrand too, and needs no `|·|` or `sign`
/// (SymPy writes `√(x + 1)/√(1 − x)` as `√((x + 1)/(1 − x))`, which differs
/// in sign for `x > 1`).  Where the integrand is real, `t` is real, and the
/// rational antiderivative `G` (logarithms at its poles, `atan` of
/// polynomials) is continuous between the poles of the `t`-integrand,
/// which are singularities of the integrand or `x = ∞`.
///
/// An integrand `xᵐ·h(xⁿ)` (`n ≥ 2` the gcd of the exponents of `x` in
/// `h`, `m` rational) is first written in `w = xⁿ`, `xᵐ·dx =
/// w^{(m+1−n)/n}·dw/n` ([`power_substituted`]): the binomial
/// `xᵐ·(a + b·xⁿ)ᵖ` becomes a radical of a linear function of `w` when
/// `(m + 1)/n` is an integer, and a pair with the radical of `w` itself when
/// `(m + 1)/n + p` is — Chebyshev's two elementary cases besides an
/// integer `p` (Gradshteyn–Ryzhik 2.202; Rubi 1.1.3.2).  The radicals of
/// `w` stand for powers of `x` (`w^{1/q}` is `x^{n/q}`, not `(xⁿ)^{1/q}`),
/// and the identities used hold for those as they do for principal powers
/// of `w`.  `t` then has the radical of `w` in its numerator, so that
/// `x = 0`, where `x^{−1}`-type powers change sign but the integrand may
/// be continuous (`√(a + b·x²)`), maps to the finite `t = 0`, not across
/// `t = ∞` (where an `atan` or a pair of complex logarithms of `G` jumps).
fn try_mobius_radical_substitution(
    arena: &mut Arena,
    expr: ExprId,
    var: ExprId,
    var_sym: SymbolId,
) -> Option<ExprId> {
    let back = match power_substituted(arena, expr, var, var_sym) {
        Some((f_w, w, n)) => {
            let ExprNode::Symbol(w_sym) = *arena.node(w) else {
                return None;
            };
            let g = mobius_core(arena, f_w, w, w_sym, true)?;
            unmap_power(arena, g, w, var, n)
        }
        None => match mobius_core(arena, expr, var, var_sym, false) {
            Some(g) => g,
            None => mobius_core_split(arena, expr, var, var_sym)?,
        },
    };
    let back = crate::transforms::eval::eval(arena, back);
    if candidate_rejected(arena, expr, back, var, var_sym) {
        tracing::debug!("integrate: rejecting unverified Möbius-radical closed form");
        return None;
    }
    Some(back)
}

/// [`mobius_core`] with every radical base written as monic linear factors
/// times a locally constant coefficient: `(a + b·x)ᵉ = K·(x + a/b)ᵉ` and,
/// for a quadratic `Q = α·x² + β·x + γ` whose discriminant is a square
/// `s²` in `ℚ[parameters]`, `Qᵉ = K·(x − r₁)ᵉ·(x − r₂)ᵉ` with
/// `r = (−β ± s)/(2α)` (`√(b·x + c·x²)`, `√(d² − e²·x²)`,
/// `√(c − a²·c·x²)`; Rubi 1.2.1, 7.3.6).  `K = Qᵉ·∏(x − rᵢ)^{−e}` has
/// derivative 0: it is integrated as a parameter and put back (Rubi's
/// "piecewise constant extraction").  For real parameters it changes
/// value only at a root, where the integrand passes from real to complex
/// — except at a double root (`√(a² + 2a·b·x + b²·x²) = K·(x + a/b)`,
/// real on both sides): there the antiderivative `K·G` is made continuous
/// by `G(r) = 0`, as the `P·|g|` rule does, or refused when `G(r)` is not
/// finite.
fn mobius_core_split(
    arena: &mut Arena,
    expr: ExprId,
    var: ExprId,
    var_sym: SymbolId,
) -> Option<ExprId> {
    let radicals = radical_powers(arena, expr, var_sym)?;
    if radicals.is_empty() {
        return None;
    }
    let mut replaced: Vec<(ExprId, ExprId)> = Vec::new();
    let mut constants: Vec<(ExprId, ExprId)> = Vec::new();
    let mut double_roots: Vec<(ExprId, ExprId)> = Vec::new();
    let two = arena.int(2);
    for (node, base, e) in &radicals {
        if replaced.iter().any(|&(n, _)| n == *node) {
            continue;
        }
        // Monic linear factors of the base, with multiplicities.
        let mut factors: SmallVec<[(ExprId, i64); 2]> = SmallVec::new();
        let mut double: Option<ExprId> = None;
        if let Some((alpha, beta)) = symbolic_linear_coeff_of(arena, *base, var, var_sym) {
            let r = arena.div(beta, alpha);
            let r = arena.neg(r);
            let r = crate::transforms::eval::eval(arena, r);
            factors.push((arena.sub(var, r), 1));
        } else if let Some((a2, a1, a0)) = symbolic_quadratic_coeffs(arena, *base, var, var_sym) {
            let a1_sq = arena.pow(a1, two);
            let four = arena.int(4);
            let prod = arena.mul(&[four, a2, a0]);
            let disc = arena.sub(a1_sq, prod);
            let disc = crate::transforms::expand::expand(arena, disc);
            let disc = crate::transforms::eval::eval(arena, disc);
            let s = crate::calculus::risch::polynomial_sqrt(arena, disc)?;
            let two_a2 = arena.mul(&[two, a2]);
            let neg_a1 = arena.neg(a1);
            if arena.is_zero_structural(s) {
                let r = arena.div(neg_a1, two_a2);
                let r = crate::transforms::eval::eval(arena, r);
                factors.push((arena.sub(var, r), 2));
                double = Some(r);
            } else {
                for sign_s in [arena.neg(s), s] {
                    let num = arena.add(&[neg_a1, sign_s]);
                    let r = arena.div(num, two_a2);
                    let r = crate::transforms::eval::eval(arena, r);
                    factors.push((arena.sub(var, r), 1));
                }
            }
        } else {
            return None;
        }
        let e_id = arena.num_ratio(e.clone());
        let mut k_parts: SmallVec<[ExprId; 3]> = SmallVec::new();
        k_parts.push(arena.pow(*base, e_id));
        let mut new_parts: SmallVec<[ExprId; 3]> = SmallVec::new();
        for &(l, mult) in &factors {
            let em = e * Q::from_integer(mult.into());
            let em_id = arena.num_ratio(em.clone());
            new_parts.push(arena.pow(l, em_id));
            let neg_em = arena.num_ratio(-em);
            k_parts.push(arena.pow(l, neg_em));
        }
        let k = arena.mul(&k_parts);
        let k = crate::transforms::eval::eval(arena, k);
        if k != arena.one {
            let kappa = arena.symbol(&format!("__mk{}", constants.len()));
            constants.push((kappa, k));
            if let Some(r) = double {
                double_roots.push((kappa, r));
            }
            new_parts.push(kappa);
        } else if double.is_some() {
            return None;
        }
        replaced.push((*node, arena.mul(&new_parts)));
    }
    if constants.is_empty() {
        return None;
    }
    let rewritten = arena.subs_map_structural(expr, &replaced);
    let rewritten = crate::transforms::eval::eval(arena, rewritten);
    let mut g = mobius_core(arena, rewritten, var, var_sym, false)?;
    for &(kappa, r) in &double_roots {
        let g1 = crate::transforms::diff::diff(arena, g, kappa);
        let at = arena.subs_structural(g1, var, r);
        let at = crate::transforms::eval::eval(arena, at);
        if contains_var(arena, at, var_sym)
            || contains_non_finite(arena, at)
            || crate::base::walk::has_unevaluated(arena, at)
        {
            return None;
        }
        let shift = arena.mul(&[kappa, at]);
        g = arena.sub(g, shift);
    }
    for &(kappa, k) in &constants {
        g = arena.subs_structural(g, kappa, k);
    }
    Some(g)
}

/// `(f_w, w, n)` with `∫ f dx = ∫ f_w dw` at `w = xⁿ`, `n ≥ 2`, for
/// `f = xᵐ·h` where `x` occurs in `h` only in integer powers `xᵏ` with
/// `n | k` (`m` rational, the exponent of a top-level factor `xᵐ`, or 0):
/// `f_w = w^{(m+1−n)/n}·h(w)/n`.  `None` when `n < 2` or `h` has `x`
/// elsewhere.
fn power_substituted(
    arena: &mut Arena,
    expr: ExprId,
    var: ExprId,
    var_sym: SymbolId,
) -> Option<(ExprId, ExprId, i64)> {
    use num_integer::Integer;
    let monomial_exponent = |arena: &Arena, f: ExprId| -> Option<Q> {
        if f == var {
            return Some(Q::one());
        }
        match *arena.node(f) {
            ExprNode::Pow(b, e) if b == var => arena.as_num(e).cloned(),
            _ => None,
        }
    };
    let (m, rest): (Q, SmallVec<[ExprId; 6]>) = match arena.node(expr) {
        ExprNode::Mul(children) => {
            let children = children.clone();
            let mut m = Q::zero();
            let mut rest = SmallVec::new();
            for c in children {
                match monomial_exponent(arena, c) {
                    Some(k) => m += k,
                    None => rest.push(c),
                }
            }
            (m, rest)
        }
        _ => (Q::zero(), SmallVec::from_slice(&[expr])),
    };
    let mut g = num_bigint::BigInt::zero();
    let mut found = false;
    for &r in &rest {
        for id in crate::base::walk::post_order_ids(arena, r) {
            let node = arena.node(id);
            if let ExprNode::Pow(b, e) = *node
                && b == var
            {
                let k = arena.as_num(e)?;
                if !k.is_integer() {
                    return None;
                }
                g = g.gcd(&k.to_integer());
                found = true;
                continue;
            }
            let mut bare = false;
            node.for_each_child(|c| bare |= c == var);
            if bare {
                return None;
            }
        }
    }
    let n = i64::try_from(&g).ok()?;
    if !found || !(2..=12).contains(&n) {
        return None;
    }
    let w = arena.symbol("__mw");
    let n_q = Q::from_integer(n.into());
    let mut pairs: Vec<(ExprId, ExprId)> = Vec::new();
    for &r in &rest {
        for id in crate::base::walk::post_order_ids(arena, r) {
            if let ExprNode::Pow(b, e) = *arena.node(id)
                && b == var
                && let Some(k) = arena.as_num(e).cloned()
                && !pairs.iter().any(|&(old, _)| old == id)
            {
                let k_w = arena.num_ratio(k / &n_q);
                let w_k = arena.pow(w, k_w);
                pairs.push((id, w_k));
            }
        }
    }
    let mut factors: SmallVec<[ExprId; 6]> = SmallVec::new();
    for &r in &rest {
        factors.push(arena.subs_map_structural(r, &pairs));
    }
    let e_w = arena.num_ratio((&m + Q::one() - &n_q) / &n_q);
    factors.push(arena.pow(w, e_w));
    factors.push(arena.rational(1, n));
    let f_w = arena.mul(&factors);
    if contains_var(arena, f_w, var_sym) {
        return None;
    }
    Some((f_w, w, n))
}

/// `e` in `w = xⁿ` written in `x`: `wʳ → x^{n·r}` (the radicals of
/// [`power_substituted`]'s `w` are powers of `x`), then `w → xⁿ`.
fn unmap_power(arena: &mut Arena, e: ExprId, w: ExprId, var: ExprId, n: i64) -> ExprId {
    let n_q = Q::from_integer(n.into());
    let mut pairs: Vec<(ExprId, ExprId)> = Vec::new();
    for id in crate::base::walk::post_order_ids(arena, e) {
        if let ExprNode::Pow(b, r) = *arena.node(id)
            && b == w
            && let Some(r) = arena.as_num(r).cloned()
            && !pairs.iter().any(|&(old, _)| old == id)
        {
            let nr = arena.num_ratio(r * &n_q);
            let x_nr = arena.pow(var, nr);
            pairs.push((id, x_nr));
        }
    }
    let e = arena.subs_map_structural(e, &pairs);
    let n_id = arena.int(n);
    let x_n = arena.pow(var, n_id);
    arena.subs_structural(e, w, x_n)
}

/// The substitution of [`try_mobius_radical_substitution`] in the variable
/// `var` (`x`, or `w = xⁿ`): the antiderivative in `var`, not yet checked.
/// `w_first`: in a pair, the radical of `var` itself goes into the
/// numerator of `t`.
fn mobius_core(
    arena: &mut Arena,
    expr: ExprId,
    var: ExprId,
    var_sym: SymbolId,
    w_first: bool,
) -> Option<ExprId> {
    use num_integer::Integer;
    let radicals = radical_powers(arena, expr, var_sym)?;
    let mut bases: SmallVec<[ExprId; 2]> = SmallVec::new();
    let mut q_lcm = num_bigint::BigInt::one();
    for (_, b, e) in &radicals {
        if !bases.contains(b) {
            bases.push(*b);
        }
        q_lcm = q_lcm.lcm(e.denom());
    }
    if bases.is_empty() || bases.len() > 2 {
        return None;
    }
    let q = i64::try_from(&q_lcm).ok()?;
    if !(2..=MAX_MOBIUS_ROOT).contains(&q) {
        return None;
    }
    let t = arena.symbol("__mt");
    let ExprNode::Symbol(t_sym) = *arena.node(t) else {
        return None;
    };
    let q_ratio = Q::from_integer(q.into());
    let inv_q = arena.rational(1, q);
    let (ratio, sub, t_of_x) = if let [b] = bases[..] {
        let mut sub = expr;
        for (node, _, e) in &radicals {
            let k = arena.num_ratio(e * &q_ratio);
            let tk = arena.pow(t, k);
            sub = arena.subs_structural(sub, *node, tk);
        }
        (b, sub, arena.pow(b, inv_q))
    } else {
        let (b1, b2) = if w_first && bases[1] == var {
            (bases[1], bases[0])
        } else {
            (bases[0], bases[1])
        };
        let sub = pair_radicals(arena, expr, b1, b2, t, q)?;
        let neg_inv_q = arena.rational(-1, q);
        let r1 = arena.pow(b1, inv_q);
        let r2 = arena.pow(b2, neg_inv_q);
        (arena.div(b1, b2), sub, arena.mul(&[r1, r2]))
    };
    let Mobius { a, b, c, d } = mobius_parts(arena, ratio, var, var_sym)?;
    let ad = arena.mul(&[a, d]);
    let bc = arena.mul(&[b, c]);
    let det = arena.sub(ad, bc);
    let det = crate::transforms::eval::eval(arena, det);
    if arena.is_zero_structural(det) {
        return None;
    }
    let q_id = arena.int(q);
    let t_q = arena.pow(t, q_id);
    let d_tq = arena.mul(&[d, t_q]);
    let x_num = arena.sub(d_tq, b);
    let c_tq = arena.mul(&[c, t_q]);
    let x_den = arena.sub(a, c_tq);
    let x_of_t = arena.div(x_num, x_den);
    let qm1 = arena.int(q - 1);
    let t_qm1 = arena.pow(t, qm1);
    let two = arena.int(2);
    let den_sq = arena.pow(x_den, two);
    let dx_num = arena.mul(&[q_id, t_qm1, det]);
    let dx_dt = arena.div(dx_num, den_sq);
    let sub = arena.subs_structural(sub, var, x_of_t);
    if contains_var(arena, sub, var_sym) {
        return None;
    }
    let integrand = arena.mul(&[sub, dx_dt]);
    let integrand = rational_in_factored_form(arena, integrand, t);
    if !is_rational_in(arena, integrand, t_sym) {
        return None;
    }
    tracing::debug!(integrand_t = %arena.display(integrand), "integrate: Möbius radical substitution");
    let res = integrate_nested_generic(arena, integrand, t)?;
    let res = analytic_logs(arena, res, t_sym)?;
    Some(arena.subs_structural(res, t, t_of_x))
}

/// `∫ f` with every `e^{k·atanh(u)}` (`k` rational) written
/// `(1 + u)^{k/2}·(1 − u)^{−k/2}`: `atanh u = ½·(ln(1 + u) − ln(1 − u))`
/// (DLMF 4.37.24; the principal branches symplex and SymPy evaluate, on
/// the cuts `|u| > 1` too), so the two agree as complex numbers.  The
/// rewritten integrand is algebraic — rational for an even `k` — and goes
/// through the whole pipeline (Rubi 7.3.6, and 7.4.2 with `acoth u =
/// atanh(1/u)`; Rubi's rules rewrite `e^{n·atanh(a·x)}` the same way).
fn try_exp_atanh_rewrite(
    arena: &mut Arena,
    expr: ExprId,
    var: ExprId,
    var_sym: SymbolId,
) -> Option<ExprId> {
    let mut rewritten = expr;
    for id in crate::base::walk::post_order_ids(arena, expr) {
        let ExprNode::Exp(arg) = *arena.node(id) else {
            continue;
        };
        if !contains_var(arena, arg, var_sym) {
            continue;
        }
        let (k, u) = match arena.node(arg).clone() {
            ExprNode::Atanh(u) => (Q::one(), u),
            ExprNode::Mul(fs) if fs.len() == 2 => {
                let (k, u) = match (arena.as_num(fs[0]), arena.node(fs[1])) {
                    (Some(k), ExprNode::Atanh(u)) => (k.clone(), *u),
                    _ => continue,
                };
                (k, u)
            }
            _ => continue,
        };
        let half_k = arena.num_ratio(&k / Q::from_integer(2.into()));
        let neg_half_k = arena.num_ratio(-&k / Q::from_integer(2.into()));
        let one = arena.one;
        let one_plus = arena.add(&[one, u]);
        let one_minus = arena.sub(one, u);
        let p1 = arena.pow(one_plus, half_k);
        let p2 = arena.pow(one_minus, neg_half_k);
        let repl = arena.mul(&[p1, p2]);
        rewritten = arena.subs_structural(rewritten, id, repl);
    }
    if rewritten == expr {
        return None;
    }
    let rewritten = crate::transforms::eval::eval(arena, rewritten);
    let res = integrate_nested(arena, rewritten, var)?;
    if candidate_rejected(arena, expr, res, var, var_sym) {
        tracing::debug!("integrate: rejecting unverified e^(k·atanh u) closed form");
        return None;
    }
    Some(res)
}

/// Rewrite `sinh`/`cosh`/`tanh` in terms of `exp` and retry (e.g.
/// `1/cosh x = 2e^x/(e^{2x}+1)` → `2 atan(e^x)`).
fn try_hyperbolic_to_exp(
    arena: &mut Arena,
    expr: ExprId,
    var: ExprId,
    var_sym: SymbolId,
) -> Option<ExprId> {
    let order = crate::base::walk::post_order_ids(arena, expr);
    let has_hyp = order.iter().any(|&id| {
        matches!(
            arena.node(id),
            ExprNode::Sinh(_) | ExprNode::Cosh(_) | ExprNode::Tanh(_)
        ) && contains_var(arena, id, var_sym)
    });
    if !has_hyp {
        return None;
    }
    let rewritten = arena.rewrite_as_exp_expr(expr);
    if rewritten == expr {
        return None;
    }
    let rewritten = crate::transforms::eval::eval(arena, rewritten);
    try_exp_rational_substitution(arena, rewritten, var, var_sym).or_else(|| {
        let r = try_exp_linear_substitution(arena, rewritten, var, var_sym)?;
        (!candidate_rejected(arena, expr, r, var, var_sym)).then_some(r)
    })
}

// ═══════════════════════════════════════════════════════════════════════════
// Algebraic reductions: P(x)·Q(x)^{k/2}
// ═══════════════════════════════════════════════════════════════════════════

/// Split the dependent factors into a rational-coefficient polynomial `P`
/// and a single factor `Q^{k/2}` (`k` odd, `Q` of degree 1 or 2).
fn split_poly_and_half_power(
    arena: &mut Arena,
    dependent: &[ExprId],
    var: ExprId,
) -> Option<(crate::poly::Poly, crate::poly::Poly, ExprId, Q)> {
    let mut half: Option<(ExprId, Q)> = None;
    let mut poly = crate::poly::Poly::from_int(1);
    for &d in dependent {
        if let ExprNode::Pow(base, e) = arena.node(d).clone()
            && let Some(r) = arena.as_num(e).cloned()
            && *r.denom() == num_bigint::BigInt::from(2)
        {
            if half.is_some() {
                return None;
            }
            half = Some((base, r));
            continue;
        }
        let p = crate::poly::polybridge::expr_to_poly(arena, d, var)?;
        poly = poly.mul(&p);
    }
    let (q_expr, k) = half?;
    let q = crate::poly::polybridge::expr_to_poly(arena, q_expr, var)?;
    let qd = q.degree()?;
    if !(1..=2).contains(&qd) {
        return None;
    }
    Some((poly, q, q_expr, k))
}

/// `∫ P(x)·Q(x)^{k/2} dx` for `k ∈ {−1, 1, 3}`: write `P·Q^{(k+1)/2} = P̃`, then
/// find a polynomial `R` and constant `c` with
/// `P̃ = (2R'Q + RQ')/2 + c`, so that the integral is `R√Q + c∫ dx/√Q`.
fn try_poly_times_half_power(
    arena: &mut Arena,
    dependent: &[ExprId],
    var: ExprId,
    var_sym: SymbolId,
    depth: usize,
) -> Option<ExprId> {
    let (p, q, q_expr, k) = split_poly_and_half_power(arena, dependent, var)?;
    let two = Q::from_integer(2.into());
    let k2 = &k * &two; // odd integer as rational
    let k2: i64 = k2.to_integer().to_string().parse().ok()?;
    if !matches!(k2, -1 | 1 | 3) {
        return None;
    }
    // P̃ = P · Q^{(k+1)/2}
    let mut p_tilde = p;
    for _ in 0..((k2 + 1) / 2) {
        p_tilde = p_tilde.mul(&q);
    }
    let pd = p_tilde.degree()?;
    let qd = q.degree()?;
    if pd == 0 && qd == 2 {
        return None; // plain 1/√Q: handled by the standard forms
    }
    // Unknowns: R = r_0 + … + r_m x^m (m = pd − qd + 1, or pd for linear Q), c.
    let m: i64 = if qd == 2 { pd as i64 - 1 } else { pd as i64 };
    let with_c = qd == 2;
    let n_unknowns = (m + 1).max(0) as usize + usize::from(with_c);
    let n_eq = pd + 1;
    if n_unknowns != n_eq {
        return None;
    }
    // Build the linear system: coefficient of x^j in (2R'Q + RQ')/2 + c.
    let q_prime = q.derivative();
    let mut rows: Vec<Vec<Q>> = vec![vec![Q::zero(); n_unknowns + 1]; n_eq];
    for i in 0..=(m.max(-1)) {
        if i < 0 {
            break;
        }
        let iu = i as usize;
        // basis monomial x^i for R
        let mut mono = vec![Q::zero(); iu + 1];
        mono[iu] = Q::one();
        let r_i = crate::poly::Poly::from_coeffs(mono);
        let term = r_i
            .derivative()
            .mul(&q)
            .scale(&two)
            .add(&r_i.mul(&q_prime))
            .scale(&Q::new(1.into(), 2.into()));
        for (j, row) in rows.iter_mut().enumerate() {
            row[iu] = term.coeff(j);
        }
    }
    if with_c {
        rows[0][n_unknowns - 1] = Q::one();
    }
    for (j, row) in rows.iter_mut().enumerate() {
        row[n_unknowns] = p_tilde.coeff(j);
    }
    let sol = solve_linear_system(rows, n_unknowns)?;
    // Assemble R√Q + c∫1/√Q.
    let r_coeffs: Vec<Q> = sol[..(m.max(-1) + 1) as usize].to_vec();
    let r_poly = crate::poly::Poly::from_coeffs(r_coeffs);
    let r_expr = crate::poly::polybridge::poly_to_expr(arena, &r_poly, var);
    let half = arena.rational(1, 2);
    let sqrt_q = arena.pow(q_expr, half);
    let mut result = arena.mul(&[r_expr, sqrt_q]);
    if with_c {
        let c = sol[n_unknowns - 1].clone();
        if !c.is_zero() {
            let neg_half = arena.rational(-1, 2);
            let inv_sqrt = arena.pow(q_expr, neg_half);
            let base_int = integrate_node(arena, inv_sqrt, var, var_sym, depth - 1);
            if crate::base::walk::has_unevaluated(arena, base_int) {
                return None;
            }
            let c_id = arena.num_ratio(c.clone());
            let c_term = arena.mul(&[c_id, base_int]);
            result = arena.add(&[result, c_term]);
        }
    }
    Some(result)
}

/// Gaussian elimination over ℚ on an augmented matrix (`n` unknowns).
fn solve_linear_system(mut rows: Vec<Vec<Q>>, n: usize) -> Option<Vec<Q>> {
    let m = rows.len();
    let mut pivot_row = 0;
    let mut pivot_cols: Vec<usize> = Vec::new();
    for col in 0..n {
        let Some(p) = (pivot_row..m).find(|&r| !rows[r][col].is_zero()) else {
            continue;
        };
        rows.swap(pivot_row, p);
        let inv = Q::one() / rows[pivot_row][col].clone();
        for v in rows[pivot_row].iter_mut() {
            *v = &*v * &inv;
        }
        let pivot = rows[pivot_row].clone();
        for (r, row) in rows.iter_mut().enumerate() {
            if r != pivot_row && !row[col].is_zero() {
                let f = row[col].clone();
                for (c, cell) in row.iter_mut().enumerate() {
                    let sub = &pivot[c] * &f;
                    *cell = &*cell - &sub;
                }
            }
        }
        pivot_cols.push(col);
        pivot_row += 1;
        if pivot_row == m {
            break;
        }
    }
    // Inconsistent rows?
    for row in rows.iter().skip(pivot_row) {
        if !row[n].is_zero() {
            return None;
        }
    }
    let mut sol = vec![Q::zero(); n];
    for (r, &col) in pivot_cols.iter().enumerate() {
        sol[col] = rows[r][n].clone();
    }
    Some(sol)
}

/// `∫ x^{−n} Q(x)^{−1/2} dx` (`n ≥ 1`, `Q` quadratic) via `x = 1/t`:
/// `= −∫ t^{n−2} (c t² + b t + a)^{−1/2} dt` for `Q = a x² + b x + c`.
fn try_reciprocal_sqrt_substitution(
    arena: &mut Arena,
    dependent: &[ExprId],
    var: ExprId,
    var_sym: SymbolId,
    depth: usize,
) -> Option<ExprId> {
    if dependent.len() != 2 {
        return None;
    }
    let mut n_neg: Option<i64> = None;
    let mut half: Option<(ExprId, Q)> = None;
    for &d in dependent {
        if let ExprNode::Pow(base, e) = arena.node(d).clone()
            && let Some(r) = arena.as_num(e).cloned()
        {
            if base == var && r.is_integer() && r.is_negative() {
                n_neg = Some(-r.to_integer().to_string().parse::<i64>().ok()?);
                continue;
            }
            if *r.denom() == num_bigint::BigInt::from(2) && contains_var(arena, base, var_sym) {
                half = Some((base, r));
                continue;
            }
        }
        return None;
    }
    let n = n_neg?;
    let (q_expr, k) = half?;
    if k != Q::new((-1).into(), 2.into()) || !(1..=4).contains(&n) {
        return None;
    }
    let q = crate::poly::polybridge::expr_to_poly(arena, q_expr, var)?;
    if q.degree()? != 2 {
        return None;
    }
    // Q(1/t) = (a + b t + c t²)/t²  ⇒  Q^{-1/2} = |t| (c t² + b t + a)^{-1/2};
    // x^{-n} = t^n, dx = −dt/t²  ⇒  integrand −|t|·t^{n−2}·(…)^{-1/2}
    //   = −sign(x)·t^{n−1}·(c t² + b t + a)^{-1/2}.
    // sign(x) is locally constant, so F(x) = sign(x)·G(1/x) with
    // G(t) = ∫ −t^{n−1} (c t² + b t + a)^{-1/2} dt.
    let t = arena.symbol("__rt");
    let t_sym = match arena.node(t) {
        ExprNode::Symbol(s) => *s,
        _ => return None,
    };
    let coeffs = q.coeffs().to_vec(); // [c, b, a]
    let reversed = crate::poly::Poly::from_coeffs(coeffs.iter().rev().cloned().collect());
    let q_rev = crate::poly::polybridge::poly_to_expr(arena, &reversed, t);
    let neg_half = arena.rational(-1, 2);
    let q_rev_pow = arena.pow(q_rev, neg_half);
    let t_pow_id = arena.int(n - 1);
    let t_pow = arena.pow(t, t_pow_id);
    let integrand_t = arena.mul(&[t_pow, q_rev_pow]);
    let neg_integrand = arena.neg(integrand_t);
    let res_t = integrate_node(arena, neg_integrand, t, t_sym, depth - 1);
    if crate::base::walk::has_unevaluated(arena, res_t) {
        return None;
    }
    let inv_x = arena.pow(var, arena.neg_one);
    let g_of_x = arena.subs_structural(res_t, t, inv_x);
    let sgn = arena.sign(var);
    let result = arena.mul(&[sgn, g_of_x]);
    Some(crate::transforms::eval::eval(arena, result))
}

/// `tanᵐ(g)·sec²(g)` → `tanᵐ⁺¹(g)/((m+1)·g')` and `secⁿ(g)·tan(g)` →
/// `secⁿ(g)/(n·g')` for linear `g`.
fn try_tan_sec_patterns(
    arena: &mut Arena,
    dependent: &[ExprId],
    var: ExprId,
    var_sym: SymbolId,
) -> Option<ExprId> {
    if dependent.len() != 2 {
        return None;
    }
    // Identify tan^m(g) and cos^{-n}(g).
    let mut tan_part: Option<(ExprId, Q)> = None;
    let mut sec_part: Option<(ExprId, Q)> = None;
    for &d in dependent {
        let (base, e) = if let ExprNode::Pow(b, e) = arena.node(d).clone() {
            (b, arena.as_num(e)?.clone())
        } else {
            (d, Q::one())
        };
        match arena.node(base).clone() {
            ExprNode::Tan(g) if e.is_integer() && e.is_positive() => tan_part = Some((g, e)),
            ExprNode::Cos(g) if e.is_integer() && e.is_negative() => sec_part = Some((g, -e)),
            _ => return None,
        }
    }
    let (g, m) = tan_part?;
    let (g2, n) = sec_part?;
    if g != g2 {
        return None;
    }
    let (a_expr, _) = symbolic_linear_coeff_of(arena, g, var, var_sym)?;
    let two = Q::from_integer(2.into());
    if n == two {
        // ∫ tan^m sec² = tan^{m+1}/(m+1)
        let m1 = &m + &Q::one();
        let m1_id = arena.num_ratio(m1.clone());
        let tan_g = arena.tan(g);
        let tp = arena.pow(tan_g, m1_id);
        let denom = arena.mul(&[m1_id, a_expr]);
        return Some(arena.div(tp, denom));
    }
    if m == Q::one() {
        // ∫ secⁿ tan = secⁿ/n = cos^{-n}/n
        let cos_g = arena.cos(g);
        let neg_n = arena.num_ratio(-n.clone());
        let sec_n = arena.pow(cos_g, neg_n);
        let n_id = arena.num_ratio(n.clone());
        let denom = arena.mul(&[n_id, a_expr]);
        return Some(arena.div(sec_n, denom));
    }
    None
}

// ═══════════════════════════════════════════════════════════════════════════
// Products: three-factor by parts, trig product-to-sum
// ═══════════════════════════════════════════════════════════════════════════

/// `∫ P(x)·g(x)·h(x) dx` with `P` polynomial: by parts with `u = P`,
/// `dv = g·h` (e.g. `x·eˣ·sin x`).
fn try_by_parts_poly_times_pair(
    arena: &mut Arena,
    dependent: &[ExprId],
    var: ExprId,
    var_sym: SymbolId,
    depth: usize,
) -> Option<ExprId> {
    let idx = dependent
        .iter()
        .position(|&d| is_polynomial_in(arena, d, var, var_sym))?;
    let u = dependent[idx];
    let dv = remaining_product(arena, dependent, idx);
    let v = integrate_node(arena, dv, var, var_sym, depth - 1);
    if crate::base::walk::has_unevaluated(arena, v) {
        return None;
    }
    let du = crate::transforms::diff::diff(arena, u, var);
    let v_du = arena.mul(&[v, du]);
    let u_dv = arena.mul(&[u, dv]);
    match by_parts_cycle(arena, u, v, u_dv, v_du, var_sym) {
        Cycle::Solved(result) => return Some(result),
        Cycle::Hopeless => return None,
        Cycle::No => {}
    }
    let v_du = crate::transforms::expand::expand(arena, v_du);
    let rest = integrate_node(arena, v_du, var, var_sym, depth - 1);
    if crate::base::walk::has_unevaluated(arena, rest) {
        return None;
    }
    let uv = arena.mul(&[u, v]);
    Some(arena.sub(uv, rest))
}

/// What [`by_parts_cycle`] found.
enum Cycle {
    /// `∫ v·du` is not a constant multiple of the integrand.
    No,
    /// `∫ v·du = c·I`: `I = u·v/(1 + c)`.
    Solved(ExprId),
    /// `∫ v·du = −I`: by parts says `I = u·v + I`, nothing.
    Hopeless,
}

/// Is the integral left by parts, `∫ v·du`, a constant multiple `c` of the
/// integrand `u·dv` itself?  Then `I = u·v − c·I` gives `I = u·v/(1 + c)`
/// at once (SymPy's `manualintegrate` solves such cyclic parts the same
/// way), and for `c = −1` by parts proves nothing.  Before, the integrator
/// integrated `v·du` — the same integral again — by parts again, one level
/// deeper each time down to the depth limit, every other strategy running
/// at every level: `∫ x²·sign(x)` (`v = x·sign(x)`, `v·du = 2x²·sign(x)`)
/// is the core of `∫ (√x + |x|)/(x + x⁻² + 1) dx`, which took 74 s to be
/// refused (`fuzz_integrate`, 2026-10-01).  The ratio is the canonical
/// quotient, so only a structural multiple is recognised.
fn by_parts_cycle(
    arena: &mut Arena,
    u: ExprId,
    v: ExprId,
    u_dv: ExprId,
    v_du: ExprId,
    var_sym: SymbolId,
) -> Cycle {
    let ratio = arena.div(v_du, u_dv);
    let c = crate::transforms::eval::eval(arena, ratio);
    if contains_var(arena, c, var_sym)
        || contains_non_finite(arena, c)
        || arena.is_zero_structural(c)
    {
        return Cycle::No;
    }
    let one = arena.one;
    let one_plus_c = arena.add(&[one, c]);
    let one_plus_c = crate::transforms::eval::eval(arena, one_plus_c);
    if arena.is_zero_structural(one_plus_c) {
        return Cycle::Hopeless;
    }
    tracing::debug!("by parts: the remaining integral is a multiple of the integrand");
    let uv = arena.mul(&[u, v]);
    Cycle::Solved(arena.div(uv, one_plus_c))
}

/// Integration by parts for a product of two dependent factors, one a
/// by-parts candidate `u` (a polynomial, a logarithm or an inverse
/// trigonometric function) and the other `dv` with a closed form:
/// `∫ u·dv = u·v − ∫ v·du`.  The LIATE-preferred ordering is tried first.
fn try_by_parts_pair(
    arena: &mut Arena,
    dependent: &[ExprId],
    var: ExprId,
    var_sym: SymbolId,
    depth: usize,
) -> Option<ExprId> {
    let orderings = {
        let r0 = liate_rank(arena, dependent[0], var, var_sym);
        let r1 = liate_rank(arena, dependent[1], var, var_sym);
        tracing::debug!(u_rank = r0, dv_rank = r1, "by-parts LIATE ordering");
        if r0 <= r1 {
            [(0usize, 1usize), (1, 0)]
        } else {
            [(1, 0), (0, 1)]
        }
    };
    for (u_idx, dv_idx) in orderings {
        let u = dependent[u_idx];
        let dv = dependent[dv_idx];

        // Check that u is a by-parts candidate (polynomial or ln)
        if !is_by_parts_candidate(arena, u, var, var_sym) {
            continue;
        }

        // Check that dv is directly integrable (deep check: reject
        // results that contain nested unevaluated Integral nodes,
        // e.g. Add(Integral(..), Integral(..)) which has a non-
        // Integral top node but is still not fully evaluated).
        let v = integrate_node(arena, dv, var, var_sym, depth - 1);
        if crate::base::walk::has_unevaluated(arena, v) {
            tracing::trace!("by-parts: v = ∫dv has unevaluated nodes, skipping this ordering");
            continue; // dv not integrable
        }

        // Compute du = d(u)/dx
        let du = crate::transforms::diff::diff(arena, u, var);

        // Compute ∫ v·du dx
        let v_du = arena.mul(&[v, du]);
        let u_dv = arena.mul(&[u, dv]);
        match by_parts_cycle(arena, u, v, u_dv, v_du, var_sym) {
            Cycle::Solved(result) => return Some(result),
            Cycle::Hopeless => continue,
            Cycle::No => {}
        }
        let integral_v_du = integrate_node(arena, v_du, var, var_sym, depth - 1);

        // Check if the remaining integral was resolved (deep check:
        // an Add of unevaluated Integrals should not be accepted).
        if crate::base::walk::has_unevaluated(arena, integral_v_du) {
            tracing::trace!("by-parts: ∫v·du has unevaluated nodes, skipping this ordering");
            continue; // Remaining integral not solvable
        }

        // Success: ∫ u·dv = u·v - ∫ v·du
        tracing::debug!("integration by parts succeeded");
        let u_v = arena.mul(&[u, v]);
        return Some(arena.sub(u_v, integral_v_du));
    }
    None
}

/// `∫ P₁(x)·P₂(x)·…·g(x) dx` with two or more polynomial factors: their
/// product multiplied out, and the integrand with one polynomial factor
/// retried.  `∫ x·(1 + a²x²)·atan(a·x) dx` (even `∫ x·(1 + x²)·atan x dx`)
/// stayed unevaluated: the three-factor rule takes `u = x`, while by parts
/// needs `dv = x·(1 + a²x²)` (0.31, the complex-parameter hunt).
fn try_merge_polynomial_factors(
    arena: &mut Arena,
    dependent: &[ExprId],
    var: ExprId,
    var_sym: SymbolId,
    depth: usize,
) -> Option<ExprId> {
    let (polys, mut rest): (Vec<ExprId>, Vec<ExprId>) = dependent
        .iter()
        .partition(|&&d| is_polynomial_in(arena, d, var, var_sym));
    if polys.len() < 2 || rest.is_empty() {
        return None;
    }
    let p = arena.mul(&polys);
    let p = crate::transforms::expand::expand(arena, p);
    rest.push(p);
    let merged = arena.mul(&rest);
    let r = integrate_node(arena, merged, var, var_sym, depth - 1);
    (!crate::base::walk::has_unevaluated(arena, r)).then_some(r)
}

/// `∫ (s₁ + … + s_k)·g dx = Σ ∫ sᵢ·g dx` for a product with a sum factor
/// (or a square to fourth power of a non-polynomial sum, multiplied out),
/// when every piece has a closed form (the first piece without one ends
/// the attempt).  A sum that is not a polynomial in the variable is taken
/// first: polynomial factors are the `u` of by parts.  Linearity only split
/// sums at the top: `∫ (sin t + cos t)·eᵗ dt` stayed unevaluated (by parts
/// wants a polynomial or a logarithm for `u`, and the cyclic rule does not
/// see `(−cos t − sin t)·eᵗ` as `−1` times the integrand) while
/// `∫ (eᵗ·sin t + eᵗ·cos t) dt` worked (0.31, normal-form hunt).
fn try_distribute_sum_factor(
    arena: &mut Arena,
    dependent: &[ExprId],
    var: ExprId,
    var_sym: SymbolId,
    depth: usize,
) -> Option<ExprId> {
    if dependent.len() < 2 || depth < 2 {
        return None;
    }
    // A radical of the variable (`√(sec x)`, `(a + b·x)^m`) makes every
    // piece as hard as the product, whose substitutions see it whole: on
    // the Rubi suite such attempts cost 30 s and found almost nothing.
    let radical = dependent.iter().any(|&d| {
        crate::base::walk::post_order_ids(arena, d)
            .iter()
            .any(|&id| {
                matches!(arena.node(id), ExprNode::Pow(b, e)
                if !arena.as_num(*e).is_some_and(|q| q.is_integer())
                    && contains_var(arena, *b, var_sym))
            })
    });
    if radical {
        return None;
    }
    // A rational function over ℚ is the rational integrator's (Hermite and
    // Rothstein–Trager are complete there); its pieces only repeat that
    // work — inside the algebraic-remainder fallback of
    // `try_risch_rational`, five nested splittings made `∫ sinh x·tanh 4x`
    // twenty times slower.
    let product = arena.mul(dependent);
    let (numer, denom) = crate::poly::polybridge::as_numer_denom(arena, product);
    if crate::poly::polybridge::expr_to_poly(arena, numer, var).is_some()
        && crate::poly::polybridge::expr_to_poly(arena, denom, var).is_some()
    {
        return None;
    }
    let is_sum = |arena: &Arena, d: ExprId| matches!(arena.node(d), ExprNode::Add(_));
    // A small power of a sum that is not a polynomial, `(a + b·sin u)³`,
    // multiplied out is a sum as well.
    let is_power_of_sum = |arena: &Arena, d: ExprId| {
        matches!(arena.node(d), ExprNode::Pow(b, n)
        if is_sum(arena, *b)
            && !is_polynomial_in(arena, *b, var, var_sym)
            && arena.as_num(*n).is_some_and(|q| {
                q.is_integer() && *q >= Q::from_integer(2.into()) && *q <= Q::from_integer(4.into())
            }))
    };
    let idx = dependent
        .iter()
        .position(|&d| is_sum(arena, d) && !is_polynomial_in(arena, d, var, var_sym))
        .or_else(|| dependent.iter().position(|&d| is_sum(arena, d)))
        .or_else(|| dependent.iter().position(|&d| is_power_of_sum(arena, d)))?;
    let sum = if is_sum(arena, dependent[idx]) {
        dependent[idx]
    } else {
        crate::transforms::expand::expand(arena, dependent[idx])
    };
    let ExprNode::Add(terms) = arena.node(sum).clone() else {
        return None;
    };
    let rest = remaining_product(arena, dependent, idx);
    let mut parts: SmallVec<[ExprId; 6]> = SmallVec::new();
    for &term in terms.iter() {
        let piece = arena.mul(&[term, rest]);
        let big_f = integrate_node(arena, piece, var, var_sym, depth - 1);
        if crate::base::walk::has_unevaluated(arena, big_f) {
            return None;
        }
        parts.push(big_f);
    }
    Some(arena.add(&parts))
}

/// Rewrite products of `sin`/`cos` factors via product-to-sum identities
/// and retry (e.g. `x·sin x·cos x = x·sin(2x)/2`).
fn try_trig_product_to_sum(
    arena: &mut Arena,
    expr: ExprId,
    dependent: &[ExprId],
    var: ExprId,
    var_sym: SymbolId,
    depth: usize,
) -> Option<ExprId> {
    let trig_count = dependent
        .iter()
        .filter(|&&d| matches!(arena.node(d), ExprNode::Sin(_) | ExprNode::Cos(_)))
        .count();
    if trig_count < 2 {
        return None;
    }
    let combined = arena.trig_combine_expr(expr);
    let combined = crate::transforms::eval::eval(arena, combined);
    if combined == expr {
        return None;
    }
    let combined = crate::transforms::expand::expand(arena, combined);
    let result = integrate_node(arena, combined, var, var_sym, depth - 1);
    if crate::base::walk::has_unevaluated(arena, result) {
        return None;
    }
    Some(result)
}

// ═══════════════════════════════════════════════════════════════════════════
// |g|, sign(g), Heaviside(g), Piecewise
// ═══════════════════════════════════════════════════════════════════════════

/// The real roots of `g` (as expressions) when all of them are known;
/// `None` otherwise.  [`try_abs_sign_product`] takes the sign of `g`
/// constant between the roots it is given, so a root missing here makes
/// an antiderivative that jumps there:
///
/// * `g` with a `sin` or `cos` of the variable is refused.  Such a `g` has
///   as a rule infinitely many real roots, and the solver returns the
///   principal branches only: `sin(eˣ) = 0` gave `x = ln π` alone, and
///   `∫ sign(sin eˣ) dx` was `(x − ln π)·sign(sin eˣ)` — its derivative is
///   the integrand, but it jumps at `x = ln(kπ)` for every `k ≥ 2`, so
///   `F(b) − F(a)` was wrong across any of them (also `cos(eˣ)`,
///   `eˣ·|sin(eˣ)|`, `sin(e⁻ˣ)`).
/// * For a polynomial over `ℚ` the roots found must be as many as its
///   distinct real roots (Sturm).
/// * A root that does not evaluate is not taken for a complex one: it is
///   refused unless it evaluates to a value off the real axis.
fn real_roots(arena: &mut Arena, g: ExprId, var: ExprId) -> Option<Vec<ExprId>> {
    let var_sym = match arena.node(var) {
        ExprNode::Symbol(s) => *s,
        _ => return None,
    };
    let poly = crate::poly::polybridge::expr_to_poly(arena, g, var);
    if poly.is_none()
        && crate::base::walk::post_order_ids(arena, g)
            .into_iter()
            .any(|id| match arena.node(id) {
                ExprNode::Sin(a) | ExprNode::Cos(a) => contains_var(arena, *a, var_sym),
                _ => false,
            })
    {
        return None;
    }
    let sols = crate::transforms::solve::solve(arena, g, var);
    if sols.is_empty() && poly.is_none() {
        return None;
    }
    let mut roots = Vec::new();
    for s in sols {
        if !crate::base::walk::free_symbols(arena, s.value).is_empty() {
            return None; // parametric root: cannot decide
        }
        match crate::transforms::evalf::eval_const_f64(arena, s.value) {
            Some(v) if v.is_finite() => roots.push(s.value),
            Some(_) => return None,
            None => {
                let value = crate::transforms::eval::eval(arena, s.value);
                match crate::transforms::evalf::evalf_complex64(arena, value) {
                    Ok(z) if z.im != 0.0 && z.re.is_finite() && z.im.is_finite() => {} // complex root
                    _ => return None,
                }
            }
        }
    }
    if let Some(p) = &poly
        && p.degree().unwrap_or(0) > 0
        && crate::poly::sturm::SturmChain::new(p).count_real_roots() != roots.len()
    {
        return None;
    }
    Some(roots)
}

/// `∫ N(x)/(a·x + b) dx` for a polynomial `N` with rational coefficients and
/// a linear denominator whose `a`, `b` are constants that are not both
/// rational (`x + π`, `x + √2`, `x + c`, `x + sin 2`): with `x₀ = −b/a`,
/// synthetic division gives `N(x) = (x − x₀)·Q(x) + N(x₀)`, so the
/// antiderivative is `(1/a)·[∫Q + N(x₀)·ln|a·x + b|]`.  The rational
/// integrator handles all-rational denominators and is left alone for them;
/// 0.22 returned `∫ x/(x + π) dx` unevaluated (and searched for 12 s on
/// `∫ x·ln(x + sin 2) dx`, whose by-parts step needs it).
fn try_poly_over_symbolic_linear(
    arena: &mut Arena,
    expr: ExprId,
    var: ExprId,
    var_sym: SymbolId,
) -> Option<ExprId> {
    let (num, den) = crate::poly::polybridge::as_numer_denom(arena, expr);
    if !contains_var(arena, den, var_sym) {
        return None;
    }
    let (a, b) = symbolic_linear_coeff_of(arena, den, var, var_sym)?;
    if contains_var(arena, a, var_sym)
        || contains_var(arena, b, var_sym)
        || arena.is_zero_structural(a)
        || arena.as_num(a).is_some() && arena.as_num(b).is_some()
    {
        return None;
    }
    let p = crate::poly::polybridge::expr_to_poly(arena, num, var)?;
    let coeffs: Vec<ExprId> = p
        .coeffs()
        .iter()
        .map(|c| arena.num_ratio(c.clone()))
        .collect();
    let n = coeffs.len().checked_sub(1)?;
    // x₀ = −b/a; Horner from the top: q_{n−1} = c_n, q_{k−1} = c_k + x₀·q_k.
    let neg_b = arena.neg(b);
    let x0 = arena.div(neg_b, a);
    let mut q = vec![arena.zero; n];
    let mut carry = coeffs[n];
    for k in (1..=n).rev() {
        q[k - 1] = carry;
        let prod = arena.mul(&[x0, carry]);
        carry = arena.add(&[coeffs[k - 1], prod]);
    }
    let remainder = crate::transforms::eval::eval(arena, carry);
    // ∫Q = Σ q_k x^{k+1}/(k+1).
    let mut terms = Vec::with_capacity(n + 1);
    for (k, &qk) in q.iter().enumerate() {
        let e = arena.int(k as i64 + 1);
        let xp = arena.pow(var, e);
        let inv = arena.rational(1, k as i64 + 1);
        terms.push(arena.mul(&[inv, qk, xp]));
    }
    if !arena.is_zero_structural(remainder) {
        let abs_den = arena.abs(den);
        let log = arena.ln(abs_den);
        terms.push(arena.mul(&[remainder, log]));
    }
    let sum = arena.add(&terms);
    let inv_a = arena.pow(a, arena.neg_one());
    let result = arena.mul(&[inv_a, sum]);
    let result = crate::transforms::eval::eval(arena, result);
    (!candidate_rejected(arena, expr, result, var, var_sym)).then_some(result)
}

/// `∫ N(x)/(c·x² + d·x + e) dx` with `deg N ≥ 2` and constant coefficients
/// that are not all rational (`∫ 2x⁴/(sin(−1) − 2x²) dx`, the radical
/// substitution of `∫ x^(3/2)/(sin(−1) − 2x) dx`; `∫ x²·cos 4/(1 + cos²4·x²)`,
/// by parts from `∫ x·atan(x·cos 4) dx`).  Divides `N` by the quadratic over
/// the field of constant expressions, integrates the quotient termwise and
/// hands the linear remainder over the quadratic back to the integrator
/// (`try_linear_over_quadratic`).  The rational-coefficient case belongs
/// to the rational integrator and is left to it.  Checked by
/// differentiation.
fn try_poly_over_symbolic_quadratic(
    arena: &mut Arena,
    expr: ExprId,
    var: ExprId,
    var_sym: SymbolId,
    depth: usize,
) -> Option<ExprId> {
    /// Quotients of higher degree are left to the other routes.
    const MAX_NUMERATOR_DEGREE: usize = 16;
    let (num, den) = crate::poly::polybridge::as_numer_denom(arena, expr);
    if !contains_var(arena, den, var_sym) {
        return None;
    }
    if crate::poly::polybridge::expr_to_poly(arena, den, var).is_some()
        && crate::poly::polybridge::expr_to_poly(arena, num, var).is_some()
    {
        return None;
    }
    let dense = |arena: &mut Arena, e: ExprId| -> Option<Vec<ExprId>> {
        let terms = crate::poly::polybridge::symbolic_multipoly_terms(arena, e, &[var])?;
        let degree = terms.iter().map(|(exps, _)| exps[0] as usize).max()?;
        if degree > MAX_NUMERATOR_DEGREE {
            return None;
        }
        let mut coeffs = vec![arena.zero; degree + 1];
        for (exps, c) in terms {
            if contains_var(arena, c, var_sym) {
                return None;
            }
            coeffs[exps[0] as usize] = c;
        }
        Some(coeffs)
    };
    let d = dense(arena, den)?;
    if d.len() != 3 || arena.is_zero_structural(d[2]) {
        return None;
    }
    let mut rem = dense(arena, num)?;
    if rem.len() < 3 {
        return None;
    }
    // rem ← rem − q_k·x^k·(c x² + d x + e), from the top.
    let mut quotient = vec![arena.zero; rem.len() - 2];
    for k in (2..rem.len()).rev() {
        let qk = arena.div(rem[k], d[2]);
        let qk = crate::transforms::eval::eval(arena, qk);
        quotient[k - 2] = qk;
        for (j, &dj) in d.iter().enumerate().take(2) {
            let prod = arena.mul(&[qk, dj]);
            let diff = arena.sub(rem[k - 2 + j], prod);
            rem[k - 2 + j] = crate::transforms::eval::eval(arena, diff);
        }
        rem[k] = arena.zero;
    }
    let mut terms: Vec<ExprId> = Vec::with_capacity(quotient.len() + 1);
    for (j, &qj) in quotient.iter().enumerate() {
        let e = arena.int(i64::try_from(j).ok()? + 1);
        let xp = arena.pow(var, e);
        let inv = arena.rational(1, i64::try_from(j).ok()? + 1);
        terms.push(arena.mul(&[inv, qj, xp]));
    }
    let r1x = arena.mul(&[rem[1], var]);
    let linear = arena.add(&[r1x, rem[0]]);
    let linear = crate::transforms::eval::eval(arena, linear);
    if !arena.is_zero_structural(linear) {
        let inv_den = arena.pow(den, arena.neg_one());
        let piece = arena.mul(&[linear, inv_den]);
        let piece_integral = integrate_node(arena, piece, var, var_sym, depth.saturating_sub(1));
        if crate::base::walk::has_unevaluated(arena, piece_integral) {
            return None;
        }
        terms.push(piece_integral);
    }
    let result = arena.add(&terms);
    let result = crate::transforms::eval::eval(arena, result);
    (!candidate_rejected(arena, expr, result, var, var_sym)).then_some(result)
}

/// Does `e` contain `nan`, `zoo` or `±∞`?
fn contains_non_finite(arena: &Arena, e: ExprId) -> bool {
    crate::base::walk::post_order_ids(arena, e)
        .into_iter()
        .any(|id| {
            matches!(
                arena.node(id),
                ExprNode::NaN
                    | ExprNode::ComplexInfinity
                    | ExprNode::Infinity
                    | ExprNode::NegInfinity
            )
        })
}

/// Is `e` real *and continuous* for every real value of the integration
/// variable, under the declared assumptions of the other symbols?  The
/// `|g|`/`sign(g)` route needs both: `g` may change sign only at its real
/// roots.  Conservative: sums, products, non-negative integer powers (a
/// negative power only of a variable-free base), and `sin`/`cos`/`exp`/
/// `atan`/`sinh`/`cosh`/`tanh`/`abs` of such; roots, logarithms, `tan`,
/// reciprocals of the variable and `sign` are refused.  (`∫ |π/(4 cos x)| dx`
/// came back as `(π/4)·ln|sec x + tan x|`, wrong wherever `cos x < 0` —
/// `c/cos x` has no roots but changes sign at its poles; found by
/// `fuzz_integrate`.)  A symbol other than the variable counts only when
/// it is declared real (decision D4, 0.31): up to 0.30 every symbol did,
/// and [`flatten_nested_pow`] rewrote `√((x + a)²)` to `|x + a|` for an
/// unassumed `a` — `∫ √((x + a)²) dx` came back as the unevaluated
/// `∫ |x + a| dx`, a different integral for a non-real `a`.
fn real_on_reals(arena: &Arena, e: ExprId, var_sym: SymbolId) -> bool {
    crate::base::walk::post_order_ids(arena, e)
        .into_iter()
        .all(|id| match arena.node(id) {
            ExprNode::Symbol(s) => {
                *s == var_sym || crate::transforms::realness::symbol_declared_real(arena, *s)
            }
            ExprNode::Num(_)
            | ExprNode::Pi
            | ExprNode::E
            | ExprNode::EulerGamma
            | ExprNode::Catalan
            | ExprNode::GoldenRatio
            | ExprNode::Add(_)
            | ExprNode::Mul(_)
            | ExprNode::Sin(_)
            | ExprNode::Cos(_)
            | ExprNode::Exp(_)
            | ExprNode::Atan(_)
            | ExprNode::Sinh(_)
            | ExprNode::Cosh(_)
            | ExprNode::Tanh(_)
            | ExprNode::Abs(_) => true,
            ExprNode::Pow(base, exp) => arena.as_num(*exp).is_some_and(|r| {
                r.is_integer() && (!r.is_negative() || !contains_var(arena, *base, var_sym))
            }),
            _ => false,
        })
}

/// `∫ P(x)·|g(x)| dx`, `∫ P(x)·sign(g(x)) dx`, `∫ P(x)·H(g(x)) dx` where
/// `g` has at most one simple real root `r` (or none):
///
/// * one root:  `sign(g)·(G(x) − G(r))` with `G = ∫ P·g` (for `|g|`),
///   `sign(g)·(F(x) − F(r))` with `F = ∫ P` (for `sign`), and
///   `H(g)·(F(x) − F(r))` for `H` — each continuous at `r`;
/// * no root: `sign(g(x₀))` is constant and the factor is replaced by
///   `±g`, `±1` or `0/1` respectively.
fn try_abs_sign_product(
    arena: &mut Arena,
    dependent: &[ExprId],
    var: ExprId,
    var_sym: SymbolId,
    depth: usize,
) -> Option<ExprId> {
    let idx = dependent.iter().position(|&d| {
        matches!(
            arena.node(d),
            ExprNode::Abs(_) | ExprNode::Sign(_) | ExprNode::Heaviside(_)
        ) && contains_var(arena, d, var_sym)
    })?;
    let node = arena.node(dependent[idx]).clone();
    let g = match node {
        ExprNode::Abs(g) | ExprNode::Sign(g) | ExprNode::Heaviside(g) => g,
        _ => return None,
    };
    // `|g| = sign(g)·g` and the root-shift below assume `g` is real at every
    // real `x`; `|√x|` is `√|x|`, not `sign(√x)·√x` (0.22.2 returned
    // `2/3·x^(3/2)·sign(√x)`, found by `fuzz_integrate`).
    if !real_on_reals(arena, g, var_sym) {
        return None;
    }
    let rest = remaining_product(arena, dependent, idx);
    let roots = real_roots(arena, g, var)?;
    if roots.len() > 1 {
        return None;
    }
    let root = roots.first().copied();
    // The "smooth" integrand whose antiderivative gets the sign factor.
    let smooth = match node {
        ExprNode::Abs(_) => arena.mul(&[rest, g]),
        _ => rest,
    };
    let smooth_int = integrate_node(arena, smooth, var, var_sym, depth - 1);
    if crate::base::walk::has_unevaluated(arena, smooth_int) {
        return None;
    }
    match root {
        Some(r) => {
            let at_r = crate::transforms::subs::subs(arena, smooth_int, var, r);
            let at_r = crate::transforms::eval::eval(arena, at_r);
            // The shift needs a finite G(r); an antiderivative singular at
            // the root (`ln|x|` at 0) made `nan` of the whole answer.
            if contains_non_finite(arena, at_r) {
                return None;
            }
            let shifted = arena.sub(smooth_int, at_r);
            let factor = match node {
                ExprNode::Heaviside(_) => arena.heaviside(g),
                _ => arena.sign(g),
            };
            Some(arena.mul(&[factor, shifted]))
        }
        None => {
            // Constant sign: sample g at a point.
            let sample = crate::transforms::subs::subs(arena, g, var, arena.zero);
            let sample = crate::transforms::eval::eval(arena, sample);
            let sgn = crate::transforms::evalf::eval_const_f64(arena, sample)?;
            if sgn == 0.0 || !sgn.is_finite() {
                return None;
            }
            let positive = sgn > 0.0;
            match node {
                ExprNode::Abs(_) | ExprNode::Sign(_) => {
                    if positive {
                        Some(smooth_int)
                    } else {
                        Some(arena.neg(smooth_int))
                    }
                }
                _ => {
                    if positive {
                        Some(smooth_int)
                    } else {
                        Some(arena.zero)
                    }
                }
            }
        }
    }
}

/// `∫ Piecewise((fᵢ, cᵢ)) dx = Piecewise((Fᵢ + kᵢ, cᵢ))`.
///
/// When the conditions form a chain `x < c₁, x < c₂, …, otherwise` (any
/// of `<`, `≤`) with increasing constants, the constants `kᵢ` are chosen so
/// that the antiderivative is continuous at every breakpoint.  For other
/// condition shapes the branch antiderivatives are returned without
/// matching constants (still a valid antiderivative on each branch).
fn integrate_piecewise(
    arena: &mut Arena,
    pairs: &[(ExprId, ExprId)],
    var: ExprId,
    var_sym: SymbolId,
    depth: usize,
) -> Option<ExprId> {
    let mut antis: Vec<ExprId> = Vec::with_capacity(pairs.len());
    for &(val, _) in pairs {
        let f = integrate_node(arena, val, var, var_sym, depth - 1);
        if crate::base::walk::has_unevaluated(arena, f) {
            return None;
        }
        antis.push(f);
    }
    // Chain detection: condition i (< last) is `x < c_i` or `x ≤ c_i`,
    // i.e. Gt(c_i, x) / Ge(c_i, x) with c_i free of var.
    let mut breakpoints: Vec<ExprId> = Vec::new();
    let mut chain = true;
    for &(_, cond) in &pairs[..pairs.len().saturating_sub(1)] {
        match arena.node(cond).clone() {
            ExprNode::Gt(c, v) | ExprNode::Ge(c, v)
                if v == var && !contains_var(arena, c, var_sym) =>
            {
                breakpoints.push(c);
            }
            _ => {
                chain = false;
                break;
            }
        }
    }
    let mut out: Vec<(ExprId, ExprId)> = Vec::with_capacity(pairs.len());
    if chain && pairs.len() >= 2 {
        let mut k = arena.zero;
        out.push((antis[0], pairs[0].1));
        for i in 1..pairs.len() {
            let c = breakpoints[i - 1];
            // k_i = k_{i-1} + F_{i-1}(c) − F_i(c)
            let prev_at_c = crate::transforms::subs::subs(arena, antis[i - 1], var, c);
            let cur_at_c = crate::transforms::subs::subs(arena, antis[i], var, c);
            let diff = arena.sub(prev_at_c, cur_at_c);
            k = arena.add(&[k, diff]);
            k = crate::transforms::eval::eval(arena, k);
            let branch = arena.add(&[antis[i], k]);
            out.push((branch, pairs[i].1));
        }
    } else {
        for (i, &(_, cond)) in pairs.iter().enumerate() {
            out.push((antis[i], cond));
        }
    }
    Some(arena.piecewise(&out))
}

// ═══════════════════════════════════════════════════════════════════════════
// Piecewise parametric wrapping
// ═══════════════════════════════════════════════════════════════════════════

/// Attempt to wrap the integration result in a `Piecewise` for parametric
/// degenerate cases.
///
/// When the result contains denominators involving free symbols (parameters
/// other than the integration variable), we check if setting those parameters
/// to specific values would cause division by zero.  For each such degenerate
/// value, we substitute back into the original integrand, re-integrate the
/// simplified form, and build a `Piecewise` node with explicit conditions.
fn try_piecewise_wrap(
    arena: &mut Arena,
    result: ExprId,
    original_integrand: ExprId,
    var: ExprId,
    var_sym: SymbolId,
) -> ExprId {
    // If result is an unevaluated Integral, nothing to wrap.
    if matches!(arena.node(result), ExprNode::Integral(_, _)) {
        return result;
    }
    // The integrand of a rationalising substitution: the degenerate cases
    // are those of the integrand in `x`, which the outer call wraps.
    if GENERIC_ONLY.with(std::cell::Cell::get) {
        return result;
    }

    // A result that is already such a case analysis — from the wrap of a
    // nested `integrate`, as a substitution re-enters the pipeline — keeps
    // it: its degenerate values count as handled, and only its generic
    // branch is searched for denominators.  `∫ sin(a·ln x) dx` came out with
    // the cases `a = i` and `a = −i` nested twice each (0.31).
    let mut generic = result;
    let mut handled: Vec<(ExprId, ExprId)> = Vec::new();
    while let ExprNode::Piecewise(pairs) = arena.node(generic).clone()
        && pairs.len() == 2
        && pairs[1].1 == arena.bool_true
        && let ExprNode::Ne(p, v) = *arena.node(pairs[0].1)
    {
        handled.push((p, v));
        handled.push((v, p));
        generic = pairs[0].0;
    }

    // Collect denominator expressions from the result.
    let denoms = collect_denominators(arena, generic);
    if denoms.is_empty() {
        return result;
    }

    let mut wrapped = result;
    // The handled pairs with the denominator they came from.
    let mut handled_by_denom: Vec<(ExprId, ExprId, ExprId)> = Vec::new();
    // The `(parameter, value)` cases whose re-integration found no closed
    // form.  The same case met again through another denominator (`a = b`
    // from `a − b` and from `a² − b²`) is the same integrand in the same
    // context and fails again (on the Rubi suite's 4.5.4.2, 3,852 of 8,948
    // failed cases were such repeats; 0.38).
    let mut failed: Vec<(ExprId, ExprId)> = Vec::new();

    for denom in &denoms {
        let denom_syms = crate::base::walk::free_symbols(arena, *denom);
        for sym_expr in &denom_syms {
            // Skip the integration variable.
            if let ExprNode::Symbol(sid) = arena.node(*sym_expr)
                && *sid == var_sym
            {
                continue;
            }
            // Only parameters of the integrand can be degenerate.  A symbol
            // that occurs in the result alone (the bound variable of a
            // `RootSum`, a substitution symbol) would leave the integrand
            // unchanged and re-integrate the same problem forever.
            if !crate::base::walk::contains(arena, original_integrand, *sym_expr) {
                continue;
            }

            // Solve denom = 0 for this parameter symbol.
            let solutions = crate::transforms::solve::solve(arena, *denom, *sym_expr);
            for sol in &solutions {
                let degen_val = sol.value;
                // A degenerate value is a constant.  A denominator in both
                // the parameter and the variable (`(a + 1)·x + a`, from a
                // partial answer) has the "solution" `a = −x/(x + 1)`, and
                // substituting it made a zero denominator in disguise that
                // panicked the rational integrator (found by the
                // complex-parameter hunter, 0.31).
                if contains_var(arena, degen_val, var_sym) || contains_non_finite(arena, degen_val)
                {
                    continue;
                }
                // Nor a value in a symbol the integrand does not have: the
                // bound variable of a `RootSum` in a denominator of its body.
                if crate::base::walk::free_symbols(arena, degen_val)
                    .iter()
                    .any(|&s| !crate::base::walk::contains(arena, original_integrand, s))
                {
                    continue;
                }

                // Avoid duplicate wrapping for the same (param, value) pair.
                if handled
                    .iter()
                    .any(|&(p, v)| p == *sym_expr && v == degen_val)
                    || failed.contains(&(*sym_expr, degen_val))
                {
                    continue;
                }
                // Nor for a value whose points are already covered: `b = a`
                // after `a = b` (the denominator `a − b` solved for either
                // symbol), `b = a²/4` after `a = ±2√b`.  Each such wrap nested
                // an unreachable copy of the whole case analysis: the
                // parametric rational integrator's `∫ dx/((x + a)(x + b)(x + c))`
                // came out six levels deep (0.31).
                if degenerate_value_covered(arena, &handled_by_denom, *denom, *sym_expr, degen_val)
                {
                    continue;
                }
                // Nor for a value that an enclosing degenerate case rules
                // out: inside the branch `c = b²/(4a)` the parameter `a` is
                // not 0.  Its integrand at `a = 0` came out as `0` (the
                // `1/(b²x⁴/(4·0) + …)²` of the substituted denominator is
                // `1/zoo²`), and `∫ x²(d + e·x² + f·x⁴ + g·x⁶)/(a + b·x² +
                // c·x⁴)² dx` carried an unreachable `Piecewise(…, (0, True))`
                // (0.31).
                if excluded_by_enclosing_case(arena, *sym_expr, degen_val) {
                    continue;
                }
                // Nor for a non-real constant value of a parameter declared
                // real: `a = ±i√2` in `∫ dx/(a² + 1 + cos x)` (an unreachable
                // branch, and one `piecewise_simplify` cannot drop: `i√2 ≠ −3`
                // after substituting `a = −3` stayed undecided).
                if nonreal_value_of_real_symbol(arena, *sym_expr, degen_val) {
                    continue;
                }

                // Filter: skip if substituting this value makes the original
                // integrand singular (these are poles of the problem, not
                // artifacts of the antiderivative formula).
                let integrand_at_degen =
                    crate::transforms::subs::subs(arena, original_integrand, *sym_expr, degen_val);
                let integrand_at_degen = crate::transforms::eval::eval(arena, integrand_at_degen);
                if has_zero_denominator(arena, integrand_at_degen) {
                    continue;
                }

                // Re-integrate the simplified integrand at the degenerate value.
                tracing::debug!(
                    integrand = %arena.display(integrand_at_degen),
                    "try_piecewise_wrap: integrating a degenerate case"
                );
                let nonzero = NonzeroInCase::enter(arena, collect_denominators(arena, degen_val));
                // A value that real parameters cannot take (`b = 3i/n`, the
                // resonance of `∫ x²·sin(a + b·ln(c·xⁿ)) dx`) gets a small
                // step budget: on the Rubi suite (0.31) such cases were 2,932
                // failed re-integrations taking 34 s (SymPy leaves them
                // unevaluated too) and 223 successes of at most 18 steps.
                let _cap = (!real_at_generic_values(arena, degen_val))
                    .then(|| StepCap::enter(NONREAL_CASE_STEPS));
                let degen_result = stage!(
                    arena,
                    "degenerate_case",
                    integrand_at_degen,
                    integrate(arena, integrand_at_degen, var)
                );
                drop(nonzero);
                let degen_result = crate::transforms::eval::eval(arena, degen_result);

                // Skip if re-integration returned unevaluated, also in part:
                // `x²/2 + ∫ 1/(−x/(x + 1) + x·(−x/(x + 1) + 1)) dx` (an integrand
                // undefined at the degenerate value) made the whole answer
                // unevaluated (0.31, the parametric-rational hunt).
                if crate::base::walk::has_unevaluated(arena, degen_result) {
                    failed.push((*sym_expr, degen_val));
                    continue;
                }

                // Build Piecewise: [(generic, Ne(param, degen)), (degen_result, True)]
                let condition = arena.ne_(*sym_expr, degen_val);
                let true_cond = arena.bool_true;
                wrapped = arena.piecewise(&[(wrapped, condition), (degen_result, true_cond)]);

                handled.push((*sym_expr, degen_val));
                handled_by_denom.push((*denom, *sym_expr, degen_val));
            }
        }
    }

    wrapped
}

/// The step budget ([`StepCap`]) of a degenerate case whose value is not
/// real at real parameter values.
const NONREAL_CASE_STEPS: usize = 20;

/// Is the parameter value `val` real for some real values of its own
/// parameters: the generic values of [`FTC_PARAMETER_VALUES`] (in name
/// order) with every combination of signs (`sqrt(−a/b)` is real for
/// `a/b < 0`; `3i/n`, `(−1/2 + i√3/2)·∛(−a/b)` are real for none)?
/// `true` when it does not evaluate, or has more than three parameters.
fn real_at_generic_values(arena: &mut Arena, val: ExprId) -> bool {
    let mut params: Vec<(String, ExprId)> = Vec::new();
    for s in crate::base::walk::free_symbols(arena, val) {
        let ExprNode::Symbol(sid) = *arena.node(s) else {
            return true;
        };
        params.push((arena.symbol_name(sid).to_owned(), s));
    }
    if params.len() > 3 {
        return true;
    }
    params.sort();
    for signs in 0u32..(1 << params.len()) {
        let mut bound = val;
        for (k, &(_, s)) in params.iter().enumerate() {
            let (p, q) = FTC_PARAMETER_VALUES[k];
            let p = if signs & (1 << k) == 0 { p } else { -p };
            let value = arena.rational(p, q);
            bound = crate::transforms::subs::subs(arena, bound, s, value);
        }
        let bound = crate::transforms::eval::eval(arena, bound);
        match crate::transforms::evalf::evalf_complex(arena, bound, 15) {
            Ok(v) if !crate::transforms::evalf::is_real_to_digits(&v, 12) => {}
            _ => return true,
        }
    }
    false
}

thread_local! {
    /// The denominators of the degenerate values of the enclosing
    /// [`try_piecewise_wrap`] cases on this thread (`a` for `c = b²/(4a)`):
    /// non-zero wherever the case's answer applies.
    static NONZERO_IN_CASE: std::cell::RefCell<Vec<(usize, ExprId)>> =
        const { std::cell::RefCell::new(Vec::new()) };
}

/// The denominators of a degenerate value pushed onto [`NONZERO_IN_CASE`]
/// for the re-integration of its case; popped on drop, also when a panic
/// unwinds.
struct NonzeroInCase(usize);

impl NonzeroInCase {
    fn enter(arena: &Arena, denominators: Vec<ExprId>) -> Self {
        let key = std::ptr::from_ref::<Arena>(arena) as usize;
        NONZERO_IN_CASE.with(|s| {
            let mut s = s.borrow_mut();
            let len = s.len();
            s.extend(denominators.into_iter().map(|d| (key, d)));
            NonzeroInCase(len)
        })
    }
}

impl Drop for NonzeroInCase {
    fn drop(&mut self) {
        let _ = NONZERO_IN_CASE.try_with(|s| {
            if let Ok(mut s) = s.try_borrow_mut() {
                s.truncate(self.0);
            }
        });
    }
}

/// Does `sym = val` make one of the enclosing cases' non-zero
/// denominators ([`NONZERO_IN_CASE`]) vanish?
fn excluded_by_enclosing_case(arena: &mut Arena, sym: ExprId, val: ExprId) -> bool {
    let key = std::ptr::from_ref::<Arena>(arena) as usize;
    let nonzero: Vec<ExprId> = NONZERO_IN_CASE.with(|s| {
        s.borrow()
            .iter()
            .filter(|&&(k, _)| k == key)
            .map(|&(_, d)| d)
            .collect()
    });
    nonzero.into_iter().any(|d| {
        crate::base::walk::contains(arena, d, sym) && {
            let at = crate::transforms::subs::subs(arena, d, sym, val);
            let at = crate::transforms::expand::expand(arena, at);
            let at = crate::transforms::eval::eval(arena, at);
            arena.is_zero_structural(at)
        }
    })
}

/// Is `sym` declared real and `val` a constant that is not real?
fn nonreal_value_of_real_symbol(arena: &mut Arena, sym: ExprId, val: ExprId) -> bool {
    let ExprNode::Symbol(sid) = *arena.node(sym) else {
        return false;
    };
    crate::transforms::realness::symbol_declared_real(arena, sid)
        && crate::base::walk::free_symbols(arena, val).is_empty()
        && crate::transforms::evalf::evalf_complex64(arena, val)
            .is_ok_and(|z| z.im.is_finite() && z.im.abs() > 1e-9 * z.norm().max(1.0))
}

/// Is every point with `sym = val` already a handled degenerate case of
/// [`try_piecewise_wrap`]: does `p − v` vanish there for one handled pair
/// `(p, v)`, or the product of `p − v` over the pairs handled for the same
/// denominator `denom` (its solutions for one symbol cover its zero set)?
fn degenerate_value_covered(
    arena: &mut Arena,
    handled: &[(ExprId, ExprId, ExprId)],
    denom: ExprId,
    sym: ExprId,
    val: ExprId,
) -> bool {
    let vanishes_at = |arena: &mut Arena, e: ExprId| {
        let at = crate::transforms::subs::subs(arena, e, sym, val);
        let at = crate::transforms::expand::expand(arena, at);
        let at = crate::transforms::eval::eval(arena, at);
        arena.is_zero_structural(at)
    };
    let mut same_denom: Vec<ExprId> = Vec::new();
    for &(d, p, v) in handled {
        let diff = arena.sub(p, v);
        if vanishes_at(arena, diff) {
            return true;
        }
        if d == denom {
            same_denom.push(diff);
        }
    }
    if same_denom.len() >= 2 {
        let product = arena.mul(&same_denom);
        return vanishes_at(arena, product);
    }
    false
}

/// Collect all denominator sub-expressions from an expression tree.
///
/// A "denominator" is the base of any `Pow(base, exp)` node where `exp`
/// is a negative rational number.
fn collect_denominators(arena: &Arena, expr: ExprId) -> Vec<ExprId> {
    let mut denoms = Vec::new();
    let mut stack: Vec<ExprId> = vec![expr];
    let mut visited: FxHashSet<ExprId> = FxHashSet::default();

    while let Some(id) = stack.pop() {
        if !visited.insert(id) {
            continue;
        }
        if let ExprNode::Pow(base, exp) = arena.node(id).clone()
            && let Some(r) = arena.as_num(exp)
            && r.is_negative()
        {
            denoms.push(base);
        }
        arena.node(id).for_each_child(|c| stack.push(c));
    }

    denoms
}

/// Check if an expression contains a sub-expression that evaluates to
/// division by zero (a denominator that is structurally zero, or NaN /
/// ComplexInfinity atoms).
fn has_zero_denominator(arena: &Arena, expr: ExprId) -> bool {
    let mut stack: Vec<ExprId> = vec![expr];
    let mut visited: FxHashSet<ExprId> = FxHashSet::default();

    while let Some(id) = stack.pop() {
        if !visited.insert(id) {
            continue;
        }
        if matches!(arena.node(id), ExprNode::NaN | ExprNode::ComplexInfinity) {
            return true;
        }
        if let ExprNode::Pow(base, exp) = arena.node(id).clone()
            && let Some(r) = arena.as_num(exp)
            && r.is_negative()
            && arena.is_zero_structural(base)
        {
            return true;
        }
        arena.node(id).for_each_child(|c| stack.push(c));
    }

    false
}

// ═══════════════════════════════════════════════════════════════════════════
// Special function integration table
// ═══════════════════════════════════════════════════════════════════════════

/// Try to match the integrand against known special function patterns.
///
/// Handles:
/// - `sin(x)/x` → `Si(x)` (sine integral)
/// - `cos(x)/x` → `Ci(x)` (cosine integral)
/// - `exp(x)/x` → `Ei(x)` (exponential integral)
/// - `exp(-x)/x` → `-Ei(-x)`
fn try_special_function_integral(
    arena: &mut Arena,
    dependent: &[ExprId],
    constants: &[ExprId],
    var: ExprId,
    _var_sym: SymbolId,
) -> Option<ExprId> {
    if dependent.len() != 2 {
        return None;
    }

    // Identify which factor is Pow(var, -1) and which is the function.
    let (func_factor, _inv_factor) = if is_inv_of_var(arena, dependent[0], var) {
        (dependent[1], dependent[0])
    } else if is_inv_of_var(arena, dependent[1], var) {
        (dependent[0], dependent[1])
    } else {
        return None;
    };

    // Match the function factor against known special functions.
    let sf_result = match arena.node(func_factor).clone() {
        ExprNode::Sin(inner) if inner == var => Some(arena.si(var)),
        ExprNode::Cos(inner) if inner == var => Some(arena.ci(var)),
        // sinh(x)/x → Shi(x), cosh(x)/x → Chi(x)  (0.9 special functions)
        ExprNode::Sinh(inner) if inner == var => Some(special_apply(arena, FN_SHI, var)),
        ExprNode::Cosh(inner) if inner == var => Some(special_apply(arena, FN_CHI, var)),
        ExprNode::Exp(inner) if inner == var => Some(arena.ei(var)),
        ExprNode::Exp(inner) => {
            // exp(-x)/x → -Ei(-x)
            if let ExprNode::Neg(neg_inner) = arena.node(inner).clone()
                && neg_inner == var
            {
                let neg_var = arena.neg(var);
                let ei = arena.ei(neg_var);
                let neg_ei = arena.neg(ei);
                return Some(wrap_with_constants(arena, neg_ei, constants));
            }
            None
        }
        _ => None,
    };

    sf_result.map(|r| wrap_with_constants(arena, r, constants))
}

/// The `Apply` node of a named special function with one argument.
fn special_apply(arena: &mut Arena, name: &str, arg: ExprId) -> ExprId {
    let sid = arena.symbols.intern(name);
    arena.intern(ExprNode::Apply(sid, std::iter::once(arg).collect()))
}

/// Check if `expr` is `Pow(var, -1)`.
fn is_inv_of_var(arena: &Arena, expr: ExprId, var: ExprId) -> bool {
    if let ExprNode::Pow(base, exp) = arena.node(expr)
        && *base == var
        && let Some(r) = arena.as_num(*exp)
    {
        return *r == num_rational::Ratio::<num_bigint::BigInt>::from_integer((-1).into());
    }
    false
}

/// Split the factors of a product into those free of `var` and those
/// depending on it.  Dependent factors have their nested powers flattened
/// (`Pow(Pow(a, m), n)` → `Pow(a, m·n)`, or `Pow(|a|, m·n)` when that is
/// the real-valued identity, e.g. `sqrt(x²) = |x|`): the canon layer only
/// merges integer exponents (branch-cut safety), but for integration we
/// need e.g. `Pow(Pow(x²+1, 1/2), -1)` → `Pow(x²+1, -1/2)`.
fn partition_factors(
    arena: &mut Arena,
    children: &[ExprId],
    var_sym: SymbolId,
) -> (SmallVec<[ExprId; 4]>, SmallVec<[ExprId; 4]>) {
    let mut constants: SmallVec<[ExprId; 4]> = SmallVec::new();
    let mut dependent: SmallVec<[ExprId; 4]> = SmallVec::new();
    for &child in children {
        if contains_var(arena, child, var_sym) {
            let flat = flatten_nested_pow(arena, child, var_sym)
                .or_else(|| exp_power_as_exp(arena, child, var_sym))
                .unwrap_or(child);
            dependent.push(flat);
        } else {
            constants.push(child);
        }
    }
    (constants, dependent)
}

/// `exp(u)^c` as `exp(c·u)` (`c` free of the variable), which holds for
/// an integer `c`, and for every `c` when `u` is real at every real value
/// of the variable ([`real_for_real_variable`]): then `ln(eᵘ) = u`.  The
/// canonical form keeps `exp(x)^√37` (for a complex `x` the identity
/// fails), and up to 0.31 `∫ exp(x)^√37·cos 3x dx` stayed unevaluated
/// while `∫ e^{√37·x}·cos 3x dx` worked (normal-form hunt).
fn exp_power_as_exp(arena: &mut Arena, expr: ExprId, var_sym: SymbolId) -> Option<ExprId> {
    let ExprNode::Pow(base, c) = arena.node(expr).clone() else {
        return None;
    };
    let ExprNode::Exp(u) = arena.node(base).clone() else {
        return None;
    };
    if contains_var(arena, c, var_sym) {
        return None;
    }
    let integer = arena.as_num(c).is_some_and(|q| q.is_integer());
    if !integer && !real_for_real_variable(arena, u, var_sym) {
        return None;
    }
    let cu = arena.mul(&[c, u]);
    Some(arena.exp(cu))
}

/// Is `u` real at every real value of the variable?  Its variable-dependent
/// nodes must be real-to-real operations defined on the whole line (those
/// of [`real_on_reals`]); its maximal variable-free subexpressions are
/// decided by [`constant_is_real`] (`√37`, a declared-real `a`).
fn real_for_real_variable(arena: &mut Arena, u: ExprId, var_sym: SymbolId) -> bool {
    let mut reals = crate::base::assumptions::AssumptionCache::new();
    let mut stack = vec![u];
    let mut seen: FxHashSet<ExprId> = FxHashSet::default();
    while let Some(id) = stack.pop() {
        if !seen.insert(id) {
            continue;
        }
        if !contains_var(arena, id, var_sym) {
            if !constant_is_real(arena, id, &mut reals) {
                return false;
            }
            continue;
        }
        let whole_line = match arena.node(id) {
            ExprNode::Symbol(s) => *s == var_sym,
            ExprNode::Add(_)
            | ExprNode::Mul(_)
            | ExprNode::Sin(_)
            | ExprNode::Cos(_)
            | ExprNode::Exp(_)
            | ExprNode::Atan(_)
            | ExprNode::Sinh(_)
            | ExprNode::Cosh(_)
            | ExprNode::Tanh(_)
            | ExprNode::Abs(_) => true,
            ExprNode::Pow(_, exp) => arena
                .as_num(*exp)
                .is_some_and(|r| r.is_integer() && !r.is_negative()),
            _ => false,
        };
        if !whole_line {
            return false;
        }
        arena.node(id).for_each_child(|c| stack.push(c));
    }
    true
}

/// Largest degree of a product that [`expand_polynomial_product`] expands.
const MAX_EXPANDED_DEGREE: u32 = 64;

/// The product of `dependent` multiplied out when every factor is a
/// polynomial in the variable (sums, products and non-negative integer
/// powers of it and of constants) and one is a power of a sum, `(a +
/// b·x²)³` — a sum of monomials integrates term by term.  Up to 0.31
/// `∫ x³·(a + b·x²)³ dx` went through by parts three times (a nested
/// answer), and the substitution `u = cos x` of `∫ cos³x·(a + b·cos²x)³·sin x`
/// did not finish within its depth.  `None` otherwise or beyond
/// [`MAX_EXPANDED_DEGREE`].
fn expand_polynomial_product(
    arena: &mut Arena,
    dependent: &[ExprId],
    var_sym: SymbolId,
) -> Option<ExprId> {
    if dependent.len() < 2 {
        return None;
    }
    let mut has_power_of_sum = false;
    let mut degree: u32 = 0;
    for &d in dependent {
        // (the degree of the factor, bounded by exponent products)
        let mut stack: Vec<(ExprId, u32)> = vec![(d, 1)];
        let mut factor_degree: u32 = 0;
        while let Some((id, mult)) = stack.pop() {
            if !contains_var(arena, id, var_sym) {
                continue;
            }
            match arena.node(id) {
                ExprNode::Symbol(_) => factor_degree = factor_degree.max(mult),
                ExprNode::Add(ch) => stack.extend(ch.iter().map(|&c| (c, mult))),
                ExprNode::Mul(ch) => {
                    // A product's degree is at most the sum over its factors:
                    // bound it by the factor count times the largest.
                    let k = u32::try_from(ch.len()).ok()?;
                    stack.extend(ch.iter().map(|&c| (c, mult.saturating_mul(k))));
                }
                ExprNode::Pow(b, n) => {
                    let k = arena
                        .as_num(*n)
                        .filter(|q| q.is_integer() && !q.is_negative())?;
                    let k = u32::try_from(k.to_integer()).ok()?;
                    if matches!(arena.node(*b), ExprNode::Add(_)) && k >= 2 {
                        has_power_of_sum = true;
                    }
                    stack.push((*b, mult.saturating_mul(k)));
                }
                _ => return None,
            }
        }
        degree = degree.saturating_add(factor_degree);
    }
    if !has_power_of_sum || degree > MAX_EXPANDED_DEGREE {
        return None;
    }
    let product = arena.mul(dependent);
    let expanded = crate::transforms::expand::expand(arena, product);
    (expanded != product).then_some(expanded)
}

/// The product of `dependent` with its exponential factors whose exponents
/// are polynomials in the variable merged into one, `exp(u)·exp(v) =
/// exp(u + v)` (true for all complex `u`, `v`); `None` when fewer than two
/// such factors.  The canonical form keeps `exp(x − 2)·exp(−x)` and
/// `exp(√5·x)·exp(−x/3 − 1)`, whose integrals stayed unevaluated up to 0.31
/// (the first is the constant `e⁻²`).  Exponentials of other exponents
/// stay apart: `exp(x)·exp(exp(x))` is the substitution `u = eˣ`.
fn merge_exponential_factors(
    arena: &mut Arena,
    dependent: &[ExprId],
    var: ExprId,
    var_sym: SymbolId,
) -> Option<ExprId> {
    let mut exponents: SmallVec<[ExprId; 4]> = SmallVec::new();
    let mut rest: SmallVec<[ExprId; 4]> = SmallVec::new();
    for &d in dependent {
        match arena.node(d) {
            ExprNode::Exp(u) if is_polynomial_in(arena, *u, var, var_sym) => exponents.push(*u),
            _ => rest.push(d),
        }
    }
    if exponents.len() < 2 {
        return None;
    }
    let sum = arena.add(&exponents);
    let merged = arena.exp(sum);
    rest.push(merged);
    Some(arena.mul(&rest))
}

/// `(c, f)` with `expr = c·f` when `expr` is a product with factors `c` free
/// of the variable and at least one factor `f` that depends on it (nested
/// powers flattened as in [`partition_factors`]); `None` otherwise.
fn split_constant_factors(
    arena: &mut Arena,
    expr: ExprId,
    var_sym: SymbolId,
) -> Option<(SmallVec<[ExprId; 4]>, ExprId)> {
    let ExprNode::Mul(children) = arena.node(expr).clone() else {
        return None;
    };
    let (constants, dependent) = partition_factors(arena, &children, var_sym);
    if constants.is_empty() || dependent.is_empty() {
        return None;
    }
    let f = if dependent.len() == 1 {
        dependent[0]
    } else {
        arena.mul(&dependent)
    };
    Some((constants, f))
}

/// Multiply a result by constant factors (if any).
fn wrap_with_constants(arena: &mut Arena, result: ExprId, constants: &[ExprId]) -> ExprId {
    if constants.is_empty() {
        result
    } else {
        let mut all: SmallVec<[ExprId; 4]> = constants.iter().copied().collect();
        all.push(result);
        arena.mul(&all)
    }
}

// ═══════════════════════════════════════════════════════════════════════════
// Nested powers over the reals
// ═══════════════════════════════════════════════════════════════════════════

/// Flattening of `Pow(Pow(g, m), n)` with rational `m`, `n` that keeps the
/// value — on the principal branch, and on the real line of the
/// integration variable.
///
/// The canon layer merges an integer outer exponent `n` (since 0.25; before,
/// only integer `m` and `n`); here also `−1 < m ≤ 1` and the real-line
/// `|g|` forms.  `(g^m)^n = g^{m·n}` holds
/// for every complex `g` when `n` is an integer or `−1 < m ≤ 1` (the
/// condition of simplify's `pow_pow`); for `g` real on the real line and `m`
/// an even integer, `g^m = |g|^m ≥ 0` and `(g^m)^n = |g|^{m·n}` (`√(x²) =
/// |x|`), which is `g^{m·n}` again when `m·n` is an even integer.  Anything
/// else stays nested (`None`): `(1/x)^{1/2} ≠ x^{−1/2}` for `x < 0` (`i/√|x|`
/// against `−i/√|x|`), and `(g^{2/3})` is not `|g|^{2/3}` for `g < 0` —
/// before 0.23 both were flattened (the second under the real-root
/// convention the evaluator no longer uses), and `∫ √x·√(1/x) dx` came out
/// `x`, whose derivative is wrong for `x < 0` (found by `fuzz_integrate`).
fn flatten_nested_pow(arena: &mut Arena, expr: ExprId, var_sym: SymbolId) -> Option<ExprId> {
    let ExprNode::Pow(base, exp) = arena.node(expr).clone() else {
        return None;
    };
    let ExprNode::Pow(inner_base, inner_exp) = arena.node(base).clone() else {
        return None;
    };
    let (m, n) = (arena.as_num(inner_exp)?.clone(), arena.as_num(exp)?.clone());
    let combined = &m * &n;
    let two = num_bigint::BigInt::from(2);
    let even_integer = |q: &crate::base::numeric::Q| q.is_integer() && (q.numer() % &two).is_zero();
    let principal =
        n.is_integer() || (m > crate::base::numeric::qi(-1) && m <= crate::base::numeric::qi(1));
    let abs_form = even_integer(&m) && real_on_reals(arena, inner_base, var_sym);
    let combined_id = arena.num_ratio(combined.clone());
    if principal || (abs_form && even_integer(&combined)) {
        Some(arena.pow(inner_base, combined_id))
    } else if abs_form {
        let abs_base = arena.abs(inner_base);
        Some(arena.pow(abs_base, combined_id))
    } else {
        None
    }
}

// ═══════════════════════════════════════════════════════════════════════════
// Numeric verification of candidate antiderivatives
// ═══════════════════════════════════════════════════════════════════════════

/// Sample points for [`check_antiderivative`]: small rationals of both
/// signs, none of them a root of the denominators met in practice.
const FTC_SAMPLE_POINTS: [(i64, i64); 6] = [(1, 3), (-5, 7), (13, 11), (-17, 5), (7, 5), (-2, 1)];

/// The second round of sample points, tried only when the first found no
/// point where `F′ = f`: nearer to 0 and farther out, for integrands that
/// are real only on part of the line (`√(x − 5)` is complex at every
/// point of the first round, and `F′` may legitimately differ from it
/// there under the real-variable convention).
const FTC_RETRY_POINTS: [(i64, i64); 6] =
    [(1, 19), (-3, 23), (37, 4), (-29, 3), (211, 7), (-307, 9)];

/// Decimal digits requested from `evalf` when checking `F′ − f`: the
/// working precision behind 30 digits is ~50 digits, which separates an
/// exact antiderivative (`F′ − f` at roundoff, ~1e-45) from one built on
/// pseudo-exact decimal coefficients (`nsimplify`'d roots, ~1e-13).
const FTC_CHECK_DIGITS: u32 = 30;

/// Tolerance on `|F′(x₀) − f(x₀)| / max(1, |f(x₀)|)` at [`FTC_CHECK_DIGITS`].
const FTC_CHECK_REL_TOL: f64 = 1e-20;

/// How far from the tolerance the distance of the separately evaluated
/// `F′(x₀)` and `f(x₀)` must lie to decide a point of [`ftc_point`] without
/// evaluating `F′ − f` as one expression.  Both values are certified to
/// [`FTC_CHECK_DIGITS`] digits, ten orders of magnitude below the
/// tolerance, so any factor above 1 is safe; this one leaves room for the
/// `f64` rounding of the distance and of the tolerance.
const FTC_DECISIVE_FACTOR: f64 = 16.0;

/// What [`check_antiderivative`] found out about a candidate `F` for `∫ f`.
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
enum FtcVerdict {
    /// `F′ = f` at one sample point at least, where `F` evaluates too, and
    /// `F′ ≠ f` at none where `f` is real.
    Verified,
    /// `F′ ≠ f` at a sample point where `f` is real, or `F′ − f` is a
    /// non-zero constant.
    Wrong,
    /// `f` evaluates at some sample point, but `F′` agrees with it at none:
    /// `F′` does not evaluate there, it differs from `f` only where `f` is
    /// complex, or it agrees only where `F` itself does not evaluate.
    Undecided,
    /// No numeric test is possible: `F` or `F′` has an unevaluated node, a
    /// parameter has declared assumptions, or `f` itself evaluates at no
    /// sample point.
    Untestable,
}

/// `true` when the candidate `big_f` for `∫ f d(var)` must not be returned.
///
/// A candidate is accepted on **evidence**, not for the lack of it.
/// [`check_antiderivative`] compares `F′` with `f` at sample points, and:
///
/// - [`FtcVerdict::Verified`] — accepted.
/// - [`FtcVerdict::Wrong`] — rejected.
/// - [`FtcVerdict::Undecided`] — **rejected**.  `f` evaluates at some sample
///   point but `F′` agrees with it at none, even after a second round of
///   points ([`FTC_RETRY_POINTS`]).  That is what a quotient by a
///   difference that cancels to 0 looks like: since 0.26 `evalf` refuses
///   such a value with `PrecisionExhausted` instead of returning noise, and
///   up to 0.28.0 such candidates passed unchecked, because "no point
///   evaluates" counted as "not wrong".  An `F′` that is undefined at a
///   generic point where `f` is defined is not the derivative of an
///   antiderivative of `f` there; nor is an `F` that is undefined wherever
///   its `F′` agrees with `f` (the vanishing denominator cancelled in
///   `F′`) an antiderivative.  A difference only where `f` is complex is
///   excused by the real-variable convention but verifies nothing:
///   `ln|x − c|` for `∫ dx/(x − c)` with an imaginary `c` differs from
///   `f` at every point.  A retry at higher precision would
///   add nothing: `evalf` already re-evaluates up to twice the working
///   precision plus 256 bits before it refuses.
/// - [`FtcVerdict::Untestable`] — accepted.  When `f` itself evaluates at no
///   sample point, `F` contains an unevaluated `Integral` (a partial
///   answer, which says so), `F′` a derivative `diff` could not take, or a
///   parameter carries declared assumptions none of the generic values
///   satisfies, no candidate could ever be tested; the answer stands as
///   the route derived it.
///
/// Free parameters are bound to generic positive rationals
/// ([`FTC_PARAMETER_VALUES`]) before sampling; up to 0.28.0 a parameter
/// skipped the check altogether.  A verified candidate with parameters
/// that are not declared real then faces a second round with those
/// parameters at generic **complex** values (decision D4, 0.31; see
/// [`check_antiderivative`]), which rejects the real-parameter forms
/// (`ln|a·x + 1|`, `|a|`, `sign(a)`) that the first round cannot tell from
/// the principal ones.
///
/// Reached through [`candidate_rejected`], by the routes that check their own
/// candidates and by every stage of `integrate_impl`, so that no closed form
/// leaves `integrate` without facing this rule.  The tight tolerance
/// [`FTC_CHECK_REL_TOL`] relies on the certified digits of `evalf`, which
/// refuses a value it cannot certify (the point then says nothing).  On
/// the Rubi suite (0.28) the stage answers came out 8,952 verified and 752
/// untestable (670 of them partial answers), none wrong or undecided.
fn antiderivative_rejected(
    arena: &mut Arena,
    f: ExprId,
    big_f: ExprId,
    var: ExprId,
    var_sym: SymbolId,
) -> bool {
    // A route's accepted candidate is usually its stage's answer too, and
    // is then judged again at the stage's exit: the verdict is remembered
    // for the rest of the top-level call (cleared with `INTEGRATE_MEMO`).
    let key = (std::ptr::from_ref::<Arena>(arena) as usize, f, big_f, var);
    let verdict = match VERDICT_MEMO.with(|m| m.borrow().get(&key).copied()) {
        Some(verdict) => verdict,
        None => {
            let verdict = stage!(
                arena,
                "verify",
                big_f,
                check_antiderivative(arena, f, big_f, var, var_sym)
            );
            VERDICT_MEMO.with(|m| m.borrow_mut().insert(key, verdict));
            verdict
        }
    };
    match verdict {
        FtcVerdict::Verified | FtcVerdict::Untestable => false,
        FtcVerdict::Wrong | FtcVerdict::Undecided => {
            tracing::debug!(?verdict, "integrate: candidate antiderivative rejected");
            true
        }
    }
}

thread_local! {
    /// [`check_antiderivative`] verdicts during the current top-level
    /// `integrate`, by (arena, `f`, `F`, variable).
    static VERDICT_MEMO: std::cell::RefCell<FxHashMap<(usize, ExprId, ExprId, ExprId), FtcVerdict>> =
        std::cell::RefCell::new(FxHashMap::default());
}

/// Generic values for the free parameters of a checked candidate, handed
/// out in the order of the parameters' names: distinct, positive,
/// non-integer, with pairwise different prime denominators, so that no
/// accidental relation (`a = b`, `m + 1 = n`, `a·b = 1`) holds between
/// them.  None is a value of the Rubi harness's parameter table, so the
/// harness stays an independent check.
const FTC_PARAMETER_VALUES: [(i64, i64); 8] = [
    (17, 13),
    (7, 11),
    (23, 17),
    (5, 19),
    (31, 23),
    (11, 29),
    (41, 31),
    (13, 37),
];

/// Imaginary parts of the complex values of the second round of
/// [`check_antiderivative`]: the k-th parameter that is not declared real
/// takes `FTC_PARAMETER_VALUES[k] + i·FTC_PARAMETER_IMAG[k]`.
/// Prime denominators unlike those of the real parts, so the values keep
/// clear of accidental relations; moderate imaginary parts (0.3 to 0.5)
/// and positive real parts, see [`complex_round_differs`].
const FTC_PARAMETER_IMAG: [(i64, i64); 8] = [
    (13, 41),
    (19, 43),
    (17, 47),
    (23, 53),
    (19, 59),
    (29, 61),
    (23, 67),
    (31, 71),
];

/// Which values [`bind_parameters`] gives the parameters.
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
enum ParameterValues {
    /// The k-th parameter at the k-th value of [`FTC_PARAMETER_VALUES`]
    /// or its negative, whichever satisfies its declaration.
    Real,
    /// A parameter that is not declared real at that value plus
    /// `i·FTC_PARAMETER_IMAG[k]` where that satisfies its declaration (always,
    /// for one without declared assumptions); the others as in `Real`.
    Complex,
}

/// `f` and `big_f` with their parameters bound, and whether any of them
/// may be complex (is not declared real), and so is bound to a complex
/// value in the [`ParameterValues::Complex`] round.
struct BoundCandidate {
    f: ExprId,
    big_f: ExprId,
    may_be_complex: bool,
}

/// `f` and `big_f` with every free symbol other than `var` bound to a
/// value derived from [`FTC_PARAMETER_VALUES`] ([`ParameterValues`]): the
/// k-th parameter in name order takes the k-th value, its negative, or (in
/// the complex round, for a parameter not declared real) that value plus
/// `i·FTC_PARAMETER_IMAG[k]` — the first of these that provably satisfies
/// every declared property (a parameter without assumptions takes any; a
/// `real` or `positive` one is sampled at `17/13`, a `negative` one at
/// `−17/13`).  `None` when no candidate does (an `integer` symbol must not
/// be sampled at `17/13`) or there are more parameters than values.  Up to
/// 0.30 any declared parameter made the candidate untestable.  `subs`
/// replaces free occurrences only, so a `RootOf(a⁵ − a + 1, 0)` or a sum
/// over `a` keeps its bound `a` (0.28.0 renamed such binders here first,
/// when `subs` did not respect them).
fn bind_parameters(
    arena: &mut Arena,
    f: ExprId,
    big_f: ExprId,
    var: ExprId,
    mode: ParameterValues,
) -> Option<BoundCandidate> {
    let mut params: Vec<(String, ExprId)> = Vec::new();
    for root in [f, big_f] {
        for s in crate::base::walk::free_symbols(arena, root) {
            if s == var || params.iter().any(|&(_, p)| p == s) {
                continue;
            }
            let ExprNode::Symbol(sid) = *arena.node(s) else {
                return None;
            };
            params.push((arena.symbol_name(sid).to_owned(), s));
        }
    }
    if params.len() > FTC_PARAMETER_VALUES.len() {
        return None;
    }
    params.sort();
    let (mut f, mut big_f) = (f, big_f);
    let mut may_be_complex = false;
    let mut facts = crate::base::assumptions::AssumptionCache::new();
    for (k, &(_, s)) in params.iter().enumerate() {
        let ExprNode::Symbol(sid) = *arena.node(s) else {
            return None;
        };
        let mut declared = arena.symbol_assumptions(sid);
        declared.normalize_declared();
        let complex = declared.query(crate::base::assumptions::Props::REAL) != Some(true);
        may_be_complex |= complex;
        let (p, q) = FTC_PARAMETER_VALUES[k];
        let re = arena.rational(p, q);
        let mut candidates: SmallVec<[ExprId; 3]> = SmallVec::new();
        if mode == ParameterValues::Complex && complex {
            let (r, t) = FTC_PARAMETER_IMAG[k];
            let im = arena.rational(r, t);
            let i = arena.i_unit();
            let im = arena.mul(&[im, i]);
            candidates.push(arena.add(&[re, im]));
        }
        candidates.push(re);
        candidates.push(arena.rational(-p, q));
        let value = candidates
            .into_iter()
            .find(|&v| value_satisfies(arena, v, declared, &mut facts))?;
        f = crate::transforms::subs::subs(arena, f, s, value);
        big_f = crate::transforms::subs::subs(arena, big_f, s, value);
    }
    Some(BoundCandidate {
        f,
        big_f,
        may_be_complex,
    })
}

/// Does the constant `value` provably have every property `declared`
/// asserts and provably lack every one it denies?
fn value_satisfies(
    arena: &mut Arena,
    value: ExprId,
    declared: crate::base::assumptions::Assumptions,
    facts: &mut crate::base::assumptions::AssumptionCache,
) -> bool {
    declared
        .known_true
        .iter()
        .all(|flag| facts.query(arena, value, flag) == Some(true))
        && declared
            .known_false
            .iter()
            .all(|flag| facts.query(arena, value, flag) == Some(false))
}

/// The numeric FTC check behind [`antiderivative_rejected`]: `F′` against
/// `f` at [`FTC_SAMPLE_POINTS`], then, if no point agreed, at
/// [`FTC_RETRY_POINTS`].
///
/// At each point `f` is evaluated first; a point where it does not
/// evaluate says nothing.  Then `F′` on its own, which decides the point
/// when its distance from `f` is clear of the tolerance (see
/// [`ftc_point`]); otherwise `F′ − f` is evaluated as one expression (its
/// exact cancellation to 0 is what `evalf`'s zero detection is built for).
/// `|F′ − f| ≤ tol·max(1, |f|)` is an agreement, real or complex; a larger
/// difference is
/// [`FtcVerdict::Wrong`] where `f` is real and no evidence where it is
/// complex (the real-variable convention: `ln|x|` for `∫ dx/x` differs
/// from `1/x` for `x < 0` only in a complex continuation, and the
/// continuation of `f` is what is compared there).
///
/// That first round binds every parameter to a real rational
/// ([`ParameterValues::Real`]), where `ln|a·x + 1|/a` and `ln(a·x + 1)/a`
/// both pass.  A verified candidate with parameters that are not declared
/// real — complex numbers in the crate's model — faces a second round with
/// them at complex values ([`complex_round_differs`]); a difference there
/// makes it [`FtcVerdict::Wrong`] (decision D4, 0.31).
fn check_antiderivative(
    arena: &mut Arena,
    f: ExprId,
    big_f: ExprId,
    var: ExprId,
    var_sym: SymbolId,
) -> FtcVerdict {
    if crate::base::walk::has_unevaluated(arena, big_f) {
        return FtcVerdict::Untestable;
    }
    let Some(bound) = bind_parameters(arena, f, big_f, var, ParameterValues::Real) else {
        return FtcVerdict::Untestable;
    };
    let mut real_domain: Vec<ExprId> = Vec::new();
    let verdict =
        check_bound_antiderivative(arena, bound.f, bound.big_f, var, var_sym, &mut real_domain);
    if verdict != FtcVerdict::Verified || !bound.may_be_complex {
        return verdict;
    }
    // The complex round tells apart forms that are not analytic in the
    // parameters; an `f` and `F` built from analytic functions of them
    // alone agree there as they do at the real values (the continuation
    // argument of [`complex_round_differs`]).  It was half of the cost of
    // the check (0.31: 4.5 of 9.7 s on a sample of the Rubi suite's
    // answers, and none of its 72,000 integrands met a candidate the
    // round rejected that is analytic in this sense).
    if analytic_in_parameters(arena, f, var_sym) && analytic_in_parameters(arena, big_f, var_sym) {
        return verdict;
    }
    let Some(complex) = bind_parameters(arena, f, big_f, var, ParameterValues::Complex) else {
        return verdict;
    };
    if real_domain.is_empty() {
        real_domain = real_domain_points(arena, bound.f, var);
    }
    if complex_round_differs(arena, complex.f, complex.big_f, var, var_sym, &real_domain) {
        tracing::debug!(
            "integrate: candidate antiderivative fails the FTC check at complex parameter values"
        );
        return FtcVerdict::Wrong;
    }
    verdict
}

/// Is `e` analytic in its parameters (the free symbols other than the
/// variable): does every node that is not an analytic function of its
/// arguments — `|·|`, `sign`, `re`, `arg`, `Piecewise`, a relation, an
/// unknown function, … — have no parameter below it?  (`ln|x|` is;
/// `ln|a·x + 1|` and `sign(a)` are not.)  Elementary functions, `erf`,
/// `Ei`, `li`, `Si`, `Ci`, `Γ`, `ζ` and `RootSum` (a symmetric function of
/// the roots) count as analytic: their principal branches are analytic off
/// their cuts, and crossing a cut changes `F` by a constant, not `F′`.
fn analytic_in_parameters(arena: &Arena, e: ExprId, var_sym: SymbolId) -> bool {
    let mut has_param: FxHashMap<ExprId, bool> = FxHashMap::default();
    for id in crate::base::walk::post_order_ids(arena, e) {
        let node = arena.node(id);
        let mut below = matches!(node, ExprNode::Symbol(s) if *s != var_sym);
        node.for_each_child(|c| below |= has_param.get(&c).copied().unwrap_or(false));
        let analytic = matches!(
            node,
            ExprNode::Num(_)
                | ExprNode::Symbol(_)
                | ExprNode::Pi
                | ExprNode::E
                | ExprNode::ImaginaryUnit
                | ExprNode::EulerGamma
                | ExprNode::Catalan
                | ExprNode::GoldenRatio
                | ExprNode::Add(_)
                | ExprNode::Mul(_)
                | ExprNode::Pow(..)
                | ExprNode::Neg(_)
                | ExprNode::Sin(_)
                | ExprNode::Cos(_)
                | ExprNode::Tan(_)
                | ExprNode::Exp(_)
                | ExprNode::Ln(_)
                | ExprNode::Asin(_)
                | ExprNode::Acos(_)
                | ExprNode::Atan(_)
                | ExprNode::Sinh(_)
                | ExprNode::Cosh(_)
                | ExprNode::Tanh(_)
                | ExprNode::Asinh(_)
                | ExprNode::Acosh(_)
                | ExprNode::Atanh(_)
                | ExprNode::Gamma(_)
                | ExprNode::Erf(_)
                | ExprNode::Erfc(_)
                | ExprNode::Si(_)
                | ExprNode::Ci(_)
                | ExprNode::Ei(_)
                | ExprNode::Li(_)
                | ExprNode::Zeta(_)
                | ExprNode::RootSum(..)
        );
        if below && !analytic {
            return false;
        }
        has_param.insert(id, below);
    }
    true
}

/// The points of [`FTC_SAMPLE_POINTS`] and [`FTC_RETRY_POINTS`] where the
/// integrand `f` (parameters bound to real values) evaluates to a real
/// number.
fn real_domain_points(arena: &mut Arena, f: ExprId, var: ExprId) -> Vec<ExprId> {
    let mut out = Vec::new();
    for &(p, q) in FTC_SAMPLE_POINTS.iter().chain(FTC_RETRY_POINTS.iter()) {
        let point = arena.rational(p, q);
        let f_at = crate::transforms::subs::subs(arena, f, var, point);
        if numeric_value(arena, f_at)
            .is_some_and(|v| crate::transforms::evalf::is_real_to_digits(&v, FTC_CHECK_DIGITS))
        {
            out.push(point);
        }
    }
    out
}

/// Points of the complex round that must agree before it gives up
/// looking for a difference.
const FTC_COMPLEX_AGREEMENTS: usize = 3;

/// The second round of [`check_antiderivative`]: `f` and `big_f` with the
/// parameters that are not declared real at complex values
/// ([`ParameterValues::Complex`]), compared at `real_domain` — the real
/// sample points where the integrand is real for the real values of the
/// first round.  `true` when `F′ ≠ f` at one of them.
///
/// Why the comparison is sound although `f` is complex at every point now,
/// where the first round excuses a difference (the real-variable
/// convention): `x` is real and only the parameters moved off the real
/// axis.  At a point where the integrand is real for real parameters,
/// `F′ = f` holds for the parameters on a real interval, and both sides
/// are analytic in the parameters there, so the identity continues to
/// complex parameter values near that interval — unless `F` is not
/// analytic in them, which is exactly what a real-parameter form is:
/// `d/dx ln|a·x + 1| = re(conj(u)·a)/|u|²` differs from `a/u` at every point
/// where `u` is not real; so do `|a|` and `sign(a)`.  The allowance of the
/// first round is kept where it belongs: a point where the integrand is
/// complex for real parameters (`√(x − 5)` at `x = 1/3`) is not in
/// `real_domain` and is not compared, so `ln|x + √(x² − 1)|`-type parts
/// that depend on `x` alone keep their convention whatever their
/// coefficients.  The complex values have positive real parts
/// ([`FTC_PARAMETER_IMAG`]): a principal form such as `√a` has its cut on
/// the negative axis, and values next to the positive reals continue the
/// identity from there without crossing it.  An undecidable point (`F′`
/// or `f` does not evaluate at the complex values) says nothing; the round
/// stops after [`FTC_COMPLEX_AGREEMENTS`] agreeing points.
fn complex_round_differs(
    arena: &mut Arena,
    f: ExprId,
    big_f: ExprId,
    var: ExprId,
    var_sym: SymbolId,
    real_domain: &[ExprId],
) -> bool {
    let d_big_f = crate::transforms::diff::diff(arena, big_f, var);
    if crate::base::walk::has_unevaluated(arena, d_big_f) {
        return false;
    }
    let residual = arena.sub(d_big_f, f);
    if !contains_var(arena, residual, var_sym) {
        return residual_abs(arena, residual).is_some_and(|r| r > FTC_CHECK_REL_TOL);
    }
    let mut agreements = 0;
    for &point in real_domain {
        match ftc_point(arena, f, d_big_f, residual, var, point) {
            FtcPoint::Differs { .. } => {
                tracing::debug!(
                    point = %arena.display(point),
                    "integrate: F′ ≠ f at complex parameter values"
                );
                return true;
            }
            FtcPoint::Agrees { .. } => {
                agreements += 1;
                if agreements >= FTC_COMPLEX_AGREEMENTS {
                    return false;
                }
            }
            FtcPoint::IntegrandUnevaluable | FtcPoint::DerivativeUnevaluable => {}
        }
    }
    false
}

/// The first round of [`check_antiderivative`], on `f` and `big_f` with
/// their parameters bound.  Every sample point where `f` is real and
/// `F′ = f` is appended to `real_domain`.
fn check_bound_antiderivative(
    arena: &mut Arena,
    f: ExprId,
    big_f: ExprId,
    var: ExprId,
    var_sym: SymbolId,
    real_domain: &mut Vec<ExprId>,
) -> FtcVerdict {
    let d_big_f = crate::transforms::diff::diff(arena, big_f, var);
    if crate::base::walk::has_unevaluated(arena, d_big_f) {
        return FtcVerdict::Untestable;
    }
    let residual = arena.sub(d_big_f, f);
    if !contains_var(arena, residual, var_sym)
        && let Some(r) = residual_abs(arena, residual)
    {
        // A constant residual: anything but zero is a wrong constant term
        // in F′.  Zero (`F′ ≡ f`, often structurally) still needs an `F`
        // that is defined somewhere.  One that does not evaluate is
        // sampled below.
        if r > FTC_CHECK_REL_TOL {
            return FtcVerdict::Wrong;
        }
        return if evaluates_at_a_sample_point(arena, big_f, var) {
            FtcVerdict::Verified
        } else if evaluates_at_a_sample_point(arena, f, var) {
            FtcVerdict::Undecided
        } else {
            FtcVerdict::Untestable
        };
    }
    let mut integrand_evaluates = false;
    for points in [&FTC_SAMPLE_POINTS, &FTC_RETRY_POINTS] {
        let mut agrees = false;
        for &(p, q) in points {
            let point = arena.rational(p, q);
            match ftc_point(arena, f, d_big_f, residual, var, point) {
                FtcPoint::IntegrandUnevaluable => {}
                FtcPoint::Agrees { f_real } => {
                    integrand_evaluates = true;
                    if f_real {
                        real_domain.push(point);
                    }
                    // `F′ = f` proves nothing about an `F` that is undefined
                    // (`x·e^{kx}/k − e^{kx}/k²` with a `k` that is 0 without
                    // being so structurally has `F′ = x·e^{kx}` exactly).
                    if !agrees {
                        let big_f_at = crate::transforms::subs::subs(arena, big_f, var, point);
                        agrees = numeric_value(arena, big_f_at).is_some();
                    }
                }
                FtcPoint::DerivativeUnevaluable | FtcPoint::Differs { f_real: false } => {
                    integrand_evaluates = true;
                }
                FtcPoint::Differs { f_real: true } => {
                    tracing::debug!(
                        point = %arena.display(point),
                        "integrate: candidate antiderivative fails the numeric FTC check"
                    );
                    return FtcVerdict::Wrong;
                }
            }
        }
        if agrees {
            return FtcVerdict::Verified;
        }
    }
    if integrand_evaluates {
        FtcVerdict::Undecided
    } else {
        FtcVerdict::Untestable
    }
}

/// The comparison of `F′` with `f` at one sample point.
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
enum FtcPoint {
    /// `f` does not evaluate here: no information.
    IntegrandUnevaluable,
    /// `f` evaluates, `F′` (and `F′ − f`) does not.
    DerivativeUnevaluable,
    /// `|F′ − f| ≤ tol·max(1, |f|)`, with `f` real or complex here.
    Agrees { f_real: bool },
    /// `|F′ − f| > tol·max(1, |f|)`, with `f` real or complex here.
    Differs { f_real: bool },
}

fn ftc_point(
    arena: &mut Arena,
    f: ExprId,
    d_big_f: ExprId,
    residual: ExprId,
    var: ExprId,
    point: ExprId,
) -> FtcPoint {
    let f_at = crate::transforms::subs::subs(arena, f, var, point);
    let Some(f_val) = numeric_value(arena, f_at) else {
        return FtcPoint::IntegrandUnevaluable;
    };
    let Some(f_abs) = crate::transforms::evalf::abs_to_f64(&f_val).filter(|v| v.is_finite()) else {
        return FtcPoint::IntegrandUnevaluable;
    };
    let f_real = crate::transforms::evalf::is_real_to_digits(&f_val, FTC_CHECK_DIGITS);
    let tol = FTC_CHECK_REL_TOL * f_abs.max(1.0);

    // `F′` on its own first.  Both values are certified to
    // [`FTC_CHECK_DIGITS`] digits, so their distance is `|F′ − f|` to within
    // `10⁻³⁰·(|F′| + |f|)`, far below the tolerance: a distance clear of it
    // by [`FTC_DECISIVE_FACTOR`] either way decides the point as `F′ − f`
    // evaluated as one expression would.  That expression is a true zero
    // for a right answer, which `evalf` can only settle by re-evaluating
    // the whole of `F′` at up to two and a half times the working precision
    // (the zero search to its cap), where `F′` alone settles in one pass:
    // up to 0.38 those re-evaluations were half of the integrator's time on
    // the Rubi suite's trigonometric chapters.  A distance near the
    // tolerance, or an `F′` that does not evaluate on its own, still goes
    // to the residual.
    let d_at = crate::transforms::subs::subs(arena, d_big_f, var, point);
    let d_val = numeric_value(arena, d_at);
    if let Some(d) = &d_val
        && let Some(gap) = crate::transforms::evalf::distance_to_f64(d, &f_val)
        && !gap.is_nan()
    {
        if gap * FTC_DECISIVE_FACTOR <= tol {
            return FtcPoint::Agrees { f_real };
        }
        if gap >= tol * FTC_DECISIVE_FACTOR {
            return FtcPoint::Differs { f_real };
        }
    }

    let r_at = crate::transforms::subs::subs(arena, residual, var, point);
    let gap = match residual_abs(arena, r_at) {
        Some(gap) => gap,
        None => {
            let Some(d_val) = d_val else {
                return FtcPoint::DerivativeUnevaluable;
            };
            match crate::transforms::evalf::distance_to_f64(&d_val, &f_val) {
                Some(gap) if !gap.is_nan() => gap,
                _ => return FtcPoint::DerivativeUnevaluable,
            }
        }
    };
    if gap <= tol {
        FtcPoint::Agrees { f_real }
    } else {
        FtcPoint::Differs { f_real }
    }
}

/// Does `e` (a function of `var` only) evaluate at one of the sample
/// points?
fn evaluates_at_a_sample_point(arena: &mut Arena, e: ExprId, var: ExprId) -> bool {
    FTC_SAMPLE_POINTS
        .iter()
        .chain(FTC_RETRY_POINTS.iter())
        .any(|&(p, q)| {
            let point = arena.rational(p, q);
            let e_at = crate::transforms::subs::subs(arena, e, var, point);
            numeric_value(arena, e_at).is_some()
        })
}

/// `e` with every `RootSum` whose polynomial and body are numeric and whose
/// body is a rational function of the root replaced by its exact value
/// ([`crate::calculus::risch::log_to_real::numeric_rootsum_rational_body`]):
/// the derivative of a `RootSum` answer at a sample point.  `eval` would
/// solve the polynomial in radicals at every point instead.
fn exact_numeric_root_sums(arena: &mut Arena, e: ExprId) -> ExprId {
    let order = crate::base::walk::post_order_ids(arena, e);
    let mut out = e;
    for id in order {
        if let ExprNode::RootSum(poly, body, sumvar) = *arena.node(id)
            && let Some(value) = crate::calculus::risch::log_to_real::numeric_rootsum_rational_body(
                arena, poly, body, sumvar,
            )
        {
            out = arena.subs_structural(out, id, value);
        }
    }
    out
}

/// A variable-free expression evaluated to [`FTC_CHECK_DIGITS`] correct
/// digits (after exact simplification); `None` when it does not evaluate
/// to a finite complex number.
fn numeric_value(arena: &mut Arena, e: ExprId) -> Option<crate::base::bigcomplex::Complex> {
    let e = exact_numeric_root_sums(arena, e);
    let e = crate::transforms::eval::eval(arena, e);
    if crate::base::walk::has_unevaluated(arena, e) {
        return None;
    }
    crate::transforms::evalf::evalf_complex(arena, e, FTC_CHECK_DIGITS).ok()
}

/// `|r|` for a variable-free `F′ − f` sample, evaluated at
/// [`FTC_CHECK_DIGITS`] so that a ~1e-13 discrepancy is not lost; `None`
/// when it does not evaluate to a finite complex number.
fn residual_abs(arena: &mut Arena, residual: ExprId) -> Option<f64> {
    let r = exact_numeric_root_sums(arena, residual);
    let r = crate::transforms::eval::eval(arena, r);
    if crate::base::walk::has_unevaluated(arena, r) {
        return None;
    }
    let v = if let Some(q) = arena.as_num(r) {
        crate::base::numeric::ratio_to_f64(q)?.abs()
    } else {
        let z = crate::transforms::evalf::evalf_complex(arena, r, FTC_CHECK_DIGITS).ok()?;
        crate::transforms::evalf::abs_to_f64(&z)?
    };
    v.is_finite().then_some(v)
}

// ═══════════════════════════════════════════════════════════════════════════
// Rational functions with a biquadratic denominator
// ═══════════════════════════════════════════════════════════════════════════

/// `∫ N(x) / (x⁴ + p·x² + q) dx` with `deg N ≤ 3` and rational `p`, `q`,
/// for the two shapes without real roots:
///
/// ```text
///   p² < 4q:            x⁴ + p·x² + q = (x² − a·x + c)(x² + a·x + c),
///                                        c = √q,  a = √(2c − p)
///   p² > 4q, p, q > 0:  x⁴ + p·x² + q = (x² + r₁)(x² + r₂),
///                                        r₁,₂ = (p ∓ √(p² − 4q))/2 > 0
/// ```
///
/// followed by partial fractions over the corresponding real radical field
/// and the closed forms
/// `∫ (A·x + B)/(x² + a·x + c) = (A/2)·ln(x² + a·x + c)
///   + (2B − a·A)/√(4c − a²) · atan((2x + a)/√(4c − a²))`,
/// `∫ (A·x + B)/(x² + r) = (A/2)·ln(x² + r) + (B/√r)·atan(x/√r)`.
///
/// This is the route the general rational integrator gets wrong when the
/// Rothstein–Trager resultant has nested-radical roots (the `re(…)`/`im(…)`
/// closed forms of the 0.21 audit; also the denominators the Weierstrass
/// substitution produces for `∫ 1/(a·sin²x + b) dx`).  Here every constant
/// is an explicit real radical.  Returns `None` when `expr` is not of
/// either shape.
fn try_biquadratic_rational(
    arena: &mut Arena,
    expr: ExprId,
    var: ExprId,
    var_sym: SymbolId,
) -> Option<ExprId> {
    let (numer_id, denom_id) = crate::poly::polybridge::as_numer_denom(arena, expr);
    if denom_id == arena.one {
        return None;
    }
    let numer_id = crate::transforms::expand::expand(arena, numer_id);
    let numer_id = crate::transforms::eval::eval(arena, numer_id);
    let denom_id = crate::transforms::expand::expand(arena, denom_id);
    let denom_id = crate::transforms::eval::eval(arena, denom_id);
    let numer = crate::poly::polybridge::expr_to_poly(arena, numer_id, var)?;
    let denom = crate::poly::polybridge::expr_to_poly(arena, denom_id, var)?;
    if denom.degree() != Some(4) || numer.is_zero() {
        return None;
    }
    if !denom.coeff(3).is_zero() || !denom.coeff(1).is_zero() {
        return None;
    }
    let lead = denom.coeff(4);
    if lead.is_zero() {
        return None;
    }
    // Improper fraction: N = Q·D + R, ∫ N/D = ∫ Q + ∫ R/D with ∫ Q by the
    // power rule (Σ qₖ x^{k+1}/(k+1)).
    let (quotient, numer) = if numer.degree().unwrap_or(0) > 3 {
        let (quot, rem) = numer.div_rem(&denom);
        (Some(quot), rem)
    } else {
        (None, numer)
    };
    let poly_part = quotient.filter(|q| !q.is_zero()).map(|q| {
        let deg = q.degree().unwrap_or(0);
        let mut coeffs: Vec<Q> = vec![Q::zero(); deg + 2];
        for (k, c) in coeffs.iter_mut().enumerate().skip(1) {
            *c = q.coeff(k - 1) / Q::from_integer(k.into());
        }
        let antiderivative = Poly::from_coeffs(coeffs);
        crate::poly::polybridge::poly_to_expr(arena, &antiderivative, var)
    });
    if numer.is_zero() {
        // N was a polynomial multiple of D.
        return poly_part;
    }
    let p = denom.coeff(2) / &lead;
    let q = denom.coeff(0) / &lead;
    let n_ids: [ExprId; 4] = [
        arena.num_ratio(numer.coeff(0) / &lead),
        arena.num_ratio(numer.coeff(1) / &lead),
        arena.num_ratio(numer.coeff(2) / &lead),
        arena.num_ratio(numer.coeff(3) / &lead),
    ];
    let disc = &p * &p - Q::from_integer(4.into()) * &q;
    let quadratics: SmallVec<[(ExprId, ExprId, ExprId, ExprId); 2]> = if disc.is_negative() {
        tracing::debug!(p = %p, q = %q, "integrate: biquadratic denominator, x² ± a·x + c");
        biquadratic_conjugate_quadratics(arena, &p, &q, &n_ids)
    } else if disc.is_positive() && p.is_positive() && q.is_positive() {
        tracing::debug!(p = %p, q = %q, "integrate: biquadratic denominator, (x² + r₁)(x² + r₂)");
        biquadratic_even_quadratics(arena, &p, &disc, &n_ids)
    } else {
        // Real roots (or a repeated factor): the general integrator's business.
        return None;
    };

    // ∫ (A x + B)/(x² + a x + c) = (A/2) ln(x² + a x + c)
    //                              + (2B − aA)/k · atan((2x + a)/k),  k = √(4c − a²)
    let two = arena.int(2);
    let four = arena.int(4);
    let half = arena.rational(1, 2);
    let x_sq = arena.pow(var, two);
    let two_x = arena.mul(&[two, var]);
    let mut terms: SmallVec<[ExprId; 4]> = SmallVec::new();
    for &(a, c, lin, cst) in quadratics.iter() {
        let a_x = arena.mul(&[a, var]);
        let quad = arena.add(&[x_sq, a_x, c]);
        // Both quadratics are positive on the whole line: no |·| in the ln.
        let ln_quad = arena.ln(quad);
        let half_lin = arena.mul(&[half, lin]);
        terms.push(arena.mul(&[half_lin, ln_quad]));
        let four_c = arena.mul(&[four, c]);
        let a_sq = arena.mul(&[a, a]);
        let k_sq = arena.sub(four_c, a_sq);
        let k = arena.sqrt(k_sq);
        let two_cst = arena.mul(&[two, cst]);
        let a_lin = arena.mul(&[a, lin]);
        let atan_coeff_num = arena.sub(two_cst, a_lin);
        let atan_coeff = arena.div(atan_coeff_num, k);
        let atan_arg_num = arena.add(&[two_x, a]);
        let atan_arg = arena.div(atan_arg_num, k);
        let atan_val = arena.atan(atan_arg);
        terms.push(arena.mul(&[atan_coeff, atan_val]));
    }
    if let Some(poly_part) = poly_part {
        terms.push(poly_part);
    }
    let result = arena.add(&terms);
    let result = crate::transforms::eval::eval(arena, result);
    // The closed form is exact by construction; the check guards the radical
    // arithmetic above (a wrong sign here would be a silent wrong answer).
    if candidate_rejected(arena, expr, result, var, var_sym) {
        tracing::debug!("integrate: biquadratic closed form failed verification");
        return None;
    }
    Some(result)
}

/// The two factors `(a, c, A, B)` of `N/(x⁴ + p x² + q)` = `Σ (A x + B)/(x² + a x + c)`
/// when `p² < 4q`: `c = √q`, `a = ∓√(2c − p)`, and from
/// `N = (A x + B)(x² + a x + c) + (C x + D)(x² − a x + c)`:
/// `A + C = n₃`, `a(A − C) + (B + D) = n₂`, `c(A + C) + a(B − D) = n₁`, `c(B + D) = n₀`.
fn biquadratic_conjugate_quadratics(
    arena: &mut Arena,
    p: &Q,
    q: &Q,
    n: &[ExprId; 4],
) -> SmallVec<[(ExprId, ExprId, ExprId, ExprId); 2]> {
    let p_id = arena.num_ratio(p.clone());
    let q_id = arena.num_ratio(q.clone());
    let two = arena.int(2);
    let half = arena.rational(1, 2);
    let c = arena.sqrt(q_id);
    let two_c = arena.mul(&[two, c]);
    let a_sq = arena.sub(two_c, p_id);
    let a = arena.sqrt(a_sq);
    let neg_a = arena.neg(a);

    let sum_bd = arena.div(n[0], c); // B + D = n₀/c
    let sum_ac = n[3]; // A + C = n₃
    let diff_ac = {
        let t = arena.sub(n[2], sum_bd);
        arena.div(t, a)
    }; // A − C = (n₂ − n₀/c)/a
    let diff_bd = {
        let c_n3 = arena.mul(&[c, n[3]]);
        let t = arena.sub(n[1], c_n3);
        arena.div(t, a)
    }; // B − D = (n₁ − c·n₃)/a
    let coeff_a = {
        let s = arena.add(&[sum_ac, diff_ac]);
        arena.mul(&[half, s])
    };
    let coeff_c = {
        let s = arena.sub(sum_ac, diff_ac);
        arena.mul(&[half, s])
    };
    let coeff_b = {
        let s = arena.add(&[sum_bd, diff_bd]);
        arena.mul(&[half, s])
    };
    let coeff_d = {
        let s = arena.sub(sum_bd, diff_bd);
        arena.mul(&[half, s])
    };
    // (A x + B)/(x² − a x + c) + (C x + D)/(x² + a x + c)
    let mut out = SmallVec::new();
    out.push((neg_a, c, coeff_a, coeff_b));
    out.push((a, c, coeff_c, coeff_d));
    out
}

/// The two factors `(0, r, A, B)` of `N/(x⁴ + p x² + q)` = `Σ (A x + B)/(x² + r)`
/// when `p² > 4q` and `p, q > 0`: `r₁,₂ = (p ∓ √disc)/2`, and from
/// `N = (A x + B)(x² + r₂) + (C x + D)(x² + r₁)`:
/// `A = (n₁ − n₃ r₁)/(r₂ − r₁)`, `C = n₃ − A`, `B = (n₀ − n₂ r₁)/(r₂ − r₁)`, `D = n₂ − B`.
fn biquadratic_even_quadratics(
    arena: &mut Arena,
    p: &Q,
    disc: &Q,
    n: &[ExprId; 4],
) -> SmallVec<[(ExprId, ExprId, ExprId, ExprId); 2]> {
    let p_id = arena.num_ratio(p.clone());
    let disc_id = arena.num_ratio(disc.clone());
    let half = arena.rational(1, 2);
    let sqrt_disc = arena.sqrt(disc_id);
    let r1 = {
        let t = arena.sub(p_id, sqrt_disc);
        arena.mul(&[half, t])
    };
    let r2 = {
        let t = arena.add(&[p_id, sqrt_disc]);
        arena.mul(&[half, t])
    };
    // r₂ − r₁ = √disc
    let coeff_a = {
        let n3_r1 = arena.mul(&[n[3], r1]);
        let t = arena.sub(n[1], n3_r1);
        arena.div(t, sqrt_disc)
    };
    let coeff_c = arena.sub(n[3], coeff_a);
    let coeff_b = {
        let n2_r1 = arena.mul(&[n[2], r1]);
        let t = arena.sub(n[0], n2_r1);
        arena.div(t, sqrt_disc)
    };
    let coeff_d = arena.sub(n[2], coeff_b);
    let zero = arena.zero;
    let mut out = SmallVec::new();
    out.push((zero, r1, coeff_a, coeff_b));
    out.push((zero, r2, coeff_c, coeff_d));
    out
}

#[cfg(test)]
mod tests {
    use super::*;
    use crate::base::arena::Arena;

    fn sym(a: &mut Arena, name: &str) -> ExprId {
        a.symbol(name)
    }

    fn display(a: &Arena, id: ExprId) -> String {
        a.display(id).to_string()
    }

    #[test]
    fn integrate_constant() {
        let mut a = Arena::new();
        let x = sym(&mut a, "x");
        let five = a.int(5);
        let result = integrate(&mut a, five, x);
        assert_eq!(display(&a, result), "5*x");
    }

    #[test]
    fn integrate_x() {
        let mut a = Arena::new();
        let x = sym(&mut a, "x");
        let result = integrate(&mut a, x, x);
        assert_eq!(display(&a, result), "1/2*x^2");
    }

    #[test]
    fn integrate_x_squared() {
        let mut a = Arena::new();
        let x = sym(&mut a, "x");
        let two = a.int(2);
        let x2 = a.pow(x, two);
        let result = integrate(&mut a, x2, x);
        assert_eq!(display(&a, result), "1/3*x^3");
    }

    #[test]
    fn integrate_x_inv() {
        let mut a = Arena::new();
        let x = sym(&mut a, "x");
        let neg_one = a.int(-1);
        let x_inv = a.pow(x, neg_one);
        let result = integrate(&mut a, x_inv, x);
        assert_eq!(display(&a, result), "ln(abs(x))");
    }

    #[test]
    fn integrate_sin_x() {
        let mut a = Arena::new();
        let x = sym(&mut a, "x");
        let expr = a.sin(x);
        let result = integrate(&mut a, expr, x);
        assert_eq!(display(&a, result), "-cos(x)");
    }

    #[test]
    fn integrate_cos_x() {
        let mut a = Arena::new();
        let x = sym(&mut a, "x");
        let expr = a.cos(x);
        let result = integrate(&mut a, expr, x);
        assert_eq!(display(&a, result), "sin(x)");
    }

    #[test]
    fn integrate_exp_x() {
        let mut a = Arena::new();
        let x = sym(&mut a, "x");
        let expr = a.exp(x);
        let result = integrate(&mut a, expr, x);
        assert_eq!(display(&a, result), "exp(x)");
    }

    #[test]
    fn integrate_sum() {
        let mut a = Arena::new();
        let x = sym(&mut a, "x");
        // ∫ (x + 1) dx = x^2/2 + x
        let one = a.one;
        let sum = a.add(&[x, one]);
        let result = integrate(&mut a, sum, x);
        let s = display(&a, result);
        assert!(s.contains("x^2"), "should contain x^2: {s}");
        assert!(s.contains("x"), "should contain x: {s}");
    }

    #[test]
    fn integrate_constant_times_x() {
        let mut a = Arena::new();
        let x = sym(&mut a, "x");
        let three = a.int(3);
        let expr = a.mul(&[three, x]);
        let result = integrate(&mut a, expr, x);
        assert_eq!(display(&a, result), "3/2*x^2");
    }

    #[test]
    fn integrate_other_symbol_is_constant() {
        let mut a = Arena::new();
        let x = sym(&mut a, "x");
        let y = sym(&mut a, "y");
        let result = integrate(&mut a, y, x);
        assert_eq!(display(&a, result), "x*y");
    }

    #[test]
    fn integrate_unevaluated_for_unknown() {
        let mut a = Arena::new();
        let x = sym(&mut a, "x");
        // tan(x) is now integrable — verify we get the antiderivative
        let expr = a.tan(x);
        let result = integrate(&mut a, expr, x);
        assert_eq!(display(&a, result), "-ln(abs(cos(x)))");
    }

    #[test]
    fn integrate_x_sin_x_by_parts() {
        let mut a = Arena::new();
        let x = sym(&mut a, "x");
        // ∫ x·sin(x) dx = sin(x) - x·cos(x)
        let sin_x = a.sin(x);
        let expr = a.mul(&[x, sin_x]);
        let result = integrate(&mut a, expr, x);
        let s = display(&a, result);
        // Should contain both sin(x) and cos(x) terms
        assert!(s.contains("sin(x)"), "should contain sin(x): {s}");
        assert!(s.contains("cos(x)"), "should contain cos(x): {s}");
    }

    #[test]
    fn integrate_x_exp_x_by_parts() {
        let mut a = Arena::new();
        let x = sym(&mut a, "x");
        // ∫ x·exp(x) dx = x·exp(x) - exp(x) = (x-1)·exp(x)
        let exp_x = a.exp(x);
        let expr = a.mul(&[x, exp_x]);
        let result = integrate(&mut a, expr, x);
        let s = display(&a, result);
        assert!(s.contains("exp(x)"), "should contain exp(x): {s}");
    }

    #[test]
    fn integrate_x_cos_x_by_parts() {
        let mut a = Arena::new();
        let x = sym(&mut a, "x");
        // ∫ x·cos(x) dx = x·sin(x) + cos(x)
        let cos_x = a.cos(x);
        let expr = a.mul(&[x, cos_x]);
        let result = integrate(&mut a, expr, x);
        let s = display(&a, result);
        assert!(s.contains("sin(x)"), "should contain sin(x): {s}");
        assert!(s.contains("cos(x)"), "should contain cos(x): {s}");
    }

    #[test]
    fn integrate_sin_2x() {
        let mut a = Arena::new();
        let x = sym(&mut a, "x");
        let two = a.int(2);
        let two_x = a.mul(&[two, x]);
        let expr = a.sin(two_x);
        let result = integrate(&mut a, expr, x);
        let s = display(&a, result);
        // ∫ sin(2x) dx = -cos(2x)/2
        assert!(s.contains("cos"), "should contain cos: {s}");
        assert!(
            s.contains("1/2") || s.contains("2"),
            "should have factor of 1/2: {s}"
        );
    }

    #[test]
    fn integrate_cos_3x_plus_1() {
        let mut a = Arena::new();
        let x = sym(&mut a, "x");
        let three = a.int(3);
        let one = a.one;
        let three_x = a.mul(&[three, x]);
        let inner = a.add(&[three_x, one]);
        let expr = a.cos(inner);
        let result = integrate(&mut a, expr, x);
        let s = display(&a, result);
        assert!(s.contains("sin"), "should contain sin: {s}");
    }

    #[test]
    fn integrate_exp_2x() {
        let mut a = Arena::new();
        let x = sym(&mut a, "x");
        let two = a.int(2);
        let two_x = a.mul(&[two, x]);
        let expr = a.exp(two_x);
        let result = integrate(&mut a, expr, x);
        let s = display(&a, result);
        assert!(s.contains("exp"), "should contain exp: {s}");
    }

    // ═══════════════════════════════════════════════════════════════════
    // Sprint A – new tests
    // ═══════════════════════════════════════════════════════════════════

    #[test]
    fn integrate_tan_x() {
        let mut a = Arena::new();
        let x = sym(&mut a, "x");
        let expr = a.tan(x);
        let result = integrate(&mut a, expr, x);
        assert_eq!(display(&a, result), "-ln(abs(cos(x)))");
    }

    #[test]
    fn integrate_ln_x() {
        let mut a = Arena::new();
        let x = sym(&mut a, "x");
        let expr = a.ln(x);
        let result = integrate(&mut a, expr, x);
        let s = display(&a, result);
        // ∫ ln(x) dx = x·ln(x) - x
        // Canonical form might be: -x + x*ln(x)  or  x*ln(x) + -x  etc.
        assert!(s.contains("ln(x)"), "should contain ln(x): {s}");
        assert!(s.contains("x"), "should contain x: {s}");
        // Verify both the x*ln(x) and the -x terms are present
        assert!(
            s.contains("x*ln(x)") || s.contains("ln(x)*x"),
            "should contain x*ln(x): {s}"
        );
    }

    #[test]
    fn integrate_atan_form() {
        let mut a = Arena::new();
        let x = sym(&mut a, "x");
        // ∫ 1/(x²+1) dx = atan(x)
        let two = a.int(2);
        let x2 = a.pow(x, two);
        let one = a.one;
        let base = a.add(&[x2, one]);
        let neg_one = a.int(-1);
        let expr = a.pow(base, neg_one);
        let result = integrate(&mut a, expr, x);
        let s = display(&a, result);
        assert!(s.contains("atan(x)"), "should be atan(x), got: {s}");
    }

    #[test]
    fn integrate_asin_form() {
        let mut a = Arena::new();
        let x = sym(&mut a, "x");
        // ∫ 1/sqrt(1-x²) dx = (1-x²)^(-1/2) = asin(x)
        let two = a.int(2);
        let x2 = a.pow(x, two);
        let one = a.one;
        let base = a.sub(one, x2); // 1 - x²
        let neg_half = a.rational(-1, 2);
        let expr = a.pow(base, neg_half);
        let result = integrate(&mut a, expr, x);
        let s = display(&a, result);
        assert!(s.contains("asin(x)"), "should be asin(x), got: {s}");
    }

    #[test]
    fn integrate_tan_2x() {
        let mut a = Arena::new();
        let x = sym(&mut a, "x");
        // ∫ tan(2x) dx = -ln|cos(2x)| / 2
        let two = a.int(2);
        let two_x = a.mul(&[two, x]);
        let expr = a.tan(two_x);
        let result = integrate(&mut a, expr, x);
        let s = display(&a, result);
        assert!(
            s.contains("ln") && s.contains("cos"),
            "should contain ln and cos: {s}"
        );
        assert!(
            s.contains("1/2") || s.contains("2"),
            "should have factor involving 2: {s}"
        );
    }

    #[test]
    fn integrate_ln_3x_plus_1() {
        let mut a = Arena::new();
        let x = sym(&mut a, "x");
        // ∫ ln(3x+1) dx = ((3x+1)·ln(3x+1) - (3x+1)) / 3
        let three = a.int(3);
        let one = a.one;
        let three_x = a.mul(&[three, x]);
        let inner = a.add(&[three_x, one]);
        let expr = a.ln(inner);
        let result = integrate(&mut a, expr, x);
        let s = display(&a, result);
        assert!(s.contains("ln"), "should contain ln: {s}");
        assert!(!s.contains("Integral"), "should not be unevaluated: {s}");
    }

    #[test]
    fn integrate_tanh_x() {
        let mut a = Arena::new();
        let x = sym(&mut a, "x");
        let expr = a.tanh(x);
        let result = integrate(&mut a, expr, x);
        let s = display(&a, result);
        assert!(
            s.contains("ln") && s.contains("cosh"),
            "∫ tanh(x) dx should be ln(cosh(x)), got: {s}"
        );
    }

    #[test]
    fn integrate_tanh_2x() {
        let mut a = Arena::new();
        let x = sym(&mut a, "x");
        let two = a.int(2);
        let two_x = a.mul(&[two, x]);
        let expr = a.tanh(two_x);
        let result = integrate(&mut a, expr, x);
        let s = display(&a, result);
        assert!(
            s.contains("ln") && s.contains("cosh"),
            "∫ tanh(2x) dx should involve ln(cosh(2x)), got: {s}"
        );
    }

    #[test]
    fn integrate_sinh_2x() {
        let mut a = Arena::new();
        let x = sym(&mut a, "x");
        let two = a.int(2);
        let two_x = a.mul(&[two, x]);
        let expr = a.sinh(two_x);
        let result = integrate(&mut a, expr, x);
        let s = display(&a, result);
        // ∫ sinh(2x) dx = cosh(2x)/2
        assert!(
            s.contains("cosh"),
            "∫ sinh(2x) dx should involve cosh, got: {s}"
        );
    }

    #[test]
    fn integrate_cosh_3x() {
        let mut a = Arena::new();
        let x = sym(&mut a, "x");
        let three = a.int(3);
        let three_x = a.mul(&[three, x]);
        let expr = a.cosh(three_x);
        let result = integrate(&mut a, expr, x);
        let s = display(&a, result);
        // ∫ cosh(3x) dx = sinh(3x)/3
        assert!(
            s.contains("sinh"),
            "∫ cosh(3x) dx should involve sinh, got: {s}"
        );
    }

    #[test]
    fn integrate_2x_plus_1_cubed() {
        let mut a = Arena::new();
        let x = sym(&mut a, "x");
        let two = a.int(2);
        let one = a.one;
        let two_x = a.mul(&[two, x]);
        let inner = a.add(&[two_x, one]);
        let three = a.int(3);
        let expr = a.pow(inner, three);
        let result = integrate(&mut a, expr, x);
        let s = display(&a, result);
        // ∫ (2x+1)^3 dx = (2x+1)^4 / 8
        assert!(!s.contains("Integral"), "should not be unevaluated: {s}");
    }

    #[test]
    fn integrate_x_plus_1_squared() {
        let mut a = Arena::new();
        let x = sym(&mut a, "x");
        let one = a.one;
        let inner = a.add(&[x, one]);
        let two = a.int(2);
        let expr = a.pow(inner, two);
        let result = integrate(&mut a, expr, x);
        let s = display(&a, result);
        // ∫ (x+1)^2 dx should be resolved (linear sub or expand)
        assert!(!s.contains("Integral"), "should not be unevaluated: {s}");
    }

    #[test]
    fn integrate_asin_x() {
        let mut a = Arena::new();
        let x = sym(&mut a, "x");
        let expr = a.asin(x);
        let result = integrate(&mut a, expr, x);
        let s = display(&a, result);
        assert!(s.contains("asin"), "should contain asin: {s}");
    }

    #[test]
    fn integrate_atan_x() {
        let mut a = Arena::new();
        let x = sym(&mut a, "x");
        let expr = a.atan(x);
        let result = integrate(&mut a, expr, x);
        let s = display(&a, result);
        assert!(s.contains("atan"), "should contain atan: {s}");
    }

    #[test]
    fn integrate_acos_x() {
        let mut a = Arena::new();
        let x = sym(&mut a, "x");
        let expr = a.acos(x);
        let result = integrate(&mut a, expr, x);
        let s = display(&a, result);
        assert!(s.contains("acos"), "should contain acos: {s}");
    }

    // ═══════════════════════════════════════════════════════════════════
    // u-substitution tests
    // ═══════════════════════════════════════════════════════════════════

    #[test]
    fn integrate_2x_exp_x_squared_u_sub() {
        // ∫ 2x·exp(x²) dx = exp(x²)   [u = x², du = 2x dx]
        let mut a = Arena::new();
        let x = sym(&mut a, "x");
        let two = a.int(2);
        let two_x = a.mul(&[two, x]);
        let x2 = a.pow(x, two);
        let exp_x2 = a.exp(x2);
        let expr = a.mul(&[two_x, exp_x2]);
        let result = integrate(&mut a, expr, x);
        let s = display(&a, result);
        assert!(
            s.contains("exp"),
            "∫ 2x·exp(x²) dx should contain exp, got: {s}"
        );
        assert!(
            !s.contains("Integral"),
            "∫ 2x·exp(x²) dx should not be unevaluated, got: {s}"
        );
    }

    #[test]
    fn integrate_cos_x_exp_sin_x_u_sub() {
        // ∫ cos(x)·exp(sin(x)) dx = exp(sin(x))   [u = sin(x), du = cos(x) dx]
        let mut a = Arena::new();
        let x = sym(&mut a, "x");
        let sin_x = a.sin(x);
        let cos_x = a.cos(x);
        let exp_sin_x = a.exp(sin_x);
        let expr = a.mul(&[cos_x, exp_sin_x]);
        let result = integrate(&mut a, expr, x);
        let s = display(&a, result);
        assert!(
            s.contains("exp"),
            "∫ cos(x)·exp(sin(x)) dx should contain exp, got: {s}"
        );
        assert!(
            !s.contains("Integral"),
            "∫ cos(x)·exp(sin(x)) dx should not be unevaluated, got: {s}"
        );
    }

    #[test]
    fn integrate_x_over_x2_plus_1_u_sub() {
        // ∫ x/(x²+1) dx = ½·ln(x²+1)   [u = x²+1, du = 2x dx]
        let mut a = Arena::new();
        let x = sym(&mut a, "x");
        let two = a.int(2);
        let x2 = a.pow(x, two);
        let one = a.one;
        let x2_plus_1 = a.add(&[x2, one]);
        let expr = a.div(x, x2_plus_1);
        let result = integrate(&mut a, expr, x);
        let s = display(&a, result);
        assert!(
            s.contains("ln"),
            "∫ x/(x²+1) dx should contain ln, got: {s}"
        );
        assert!(
            !s.contains("Integral"),
            "∫ x/(x²+1) dx should not be unevaluated, got: {s}"
        );
    }

    #[test]
    fn integrate_complete_square() {
        // ∫ 1/(x²+2x+5) dx — should use completing the square
        let mut a = Arena::new();
        let x = sym(&mut a, "x");
        let two = a.int(2);
        let five = a.int(5);
        let x2 = a.pow(x, two);
        let two_x = a.mul(&[two, x]);
        let quadratic = a.add(&[x2, two_x, five]);
        let neg_one = a.int(-1);
        let integrand = a.pow(quadratic, neg_one);
        let result = integrate(&mut a, integrand, x);
        let s = display(&a, result);
        assert!(s.contains("atan"), "should use atan: {s}");
    }

    #[test]
    fn integrate_complete_square_simple() {
        // ∫ 1/(x²+x+1) dx
        let mut a = Arena::new();
        let x = sym(&mut a, "x");
        let two = a.int(2);
        let x2 = a.pow(x, two);
        let one = a.one;
        let quadratic = a.add(&[x2, x, one]);
        let neg_one = a.int(-1);
        let integrand = a.pow(quadratic, neg_one);
        let result = integrate(&mut a, integrand, x);
        let s = display(&a, result);
        assert!(s.contains("atan"), "should use atan: {s}");
    }

    #[test]
    fn symbolic_linear_coeff_of_mul_a_x() {
        // a*x should be detected as linear in x with coefficient a
        let mut a = Arena::new();
        let x = sym(&mut a, "x");
        let param_a = sym(&mut a, "a");
        let ax = a.mul(&[param_a, x]);
        let var_sym = match a.node(x) {
            ExprNode::Symbol(sid) => *sid,
            _ => panic!("x should be a symbol"),
        };
        let result = super::symbolic_linear_coeff_of(&mut a, ax, x, var_sym);
        assert!(
            result.is_some(),
            "a*x should be recognized as linear in x, node: {:?}",
            a.node(ax)
        );
        let (coeff, constant) = result.unwrap();
        assert_eq!(
            coeff,
            param_a,
            "coefficient should be a, got {}",
            display(&a, coeff)
        );
        assert_eq!(
            constant,
            a.zero,
            "constant should be 0, got {}",
            display(&a, constant)
        );
    }

    #[test]
    fn symbolic_linear_coeff_of_add_ax_b() {
        // a*x + b should be detected as linear in x with coefficient a, constant b
        let mut a = Arena::new();
        let x = sym(&mut a, "x");
        let param_a = sym(&mut a, "a");
        let param_b = sym(&mut a, "b");
        let ax = a.mul(&[param_a, x]);
        let ax_plus_b = a.add(&[ax, param_b]);
        let var_sym = match a.node(x) {
            ExprNode::Symbol(sid) => *sid,
            _ => panic!("x should be a symbol"),
        };
        let result = super::symbolic_linear_coeff_of(&mut a, ax_plus_b, x, var_sym);
        assert!(
            result.is_some(),
            "a*x+b should be recognized as linear in x, expr: {}",
            display(&a, ax_plus_b)
        );
        let (coeff, constant) = result.unwrap();
        assert_eq!(
            coeff,
            param_a,
            "coefficient should be a, got {}",
            display(&a, coeff)
        );
        assert_eq!(
            constant,
            param_b,
            "constant should be b, got {}",
            display(&a, constant)
        );
    }

    #[test]
    fn symbolic_linear_coeff_of_bare_var() {
        // x alone should be linear with coefficient 1
        let mut a = Arena::new();
        let x = sym(&mut a, "x");
        let var_sym = match a.node(x) {
            ExprNode::Symbol(sid) => *sid,
            _ => panic!("x should be a symbol"),
        };
        let result = super::symbolic_linear_coeff_of(&mut a, x, x, var_sym);
        assert!(result.is_some(), "x should be recognized as linear in x");
        let (coeff, constant) = result.unwrap();
        assert_eq!(coeff, a.one, "coefficient should be 1");
        assert_eq!(constant, a.zero, "constant should be 0");
    }

    #[test]
    fn integrate_sin_symbolic_coeff() {
        // ∫ sin(a*x) dx should not be unevaluated
        let mut a = Arena::new();
        let x = sym(&mut a, "x");
        let param_a = sym(&mut a, "a");
        let ax = a.mul(&[param_a, x]);
        let sin_ax = a.sin(ax);
        let result = integrate(&mut a, sin_ax, x);
        let s = display(&a, result);
        assert!(
            !s.contains("Integral"),
            "∫sin(a*x)dx should not be unevaluated: {s}"
        );
        assert!(s.contains("cos"), "should contain cos: {s}");
    }

    #[test]
    fn integrate_exp_symbolic_coeff() {
        // ∫ exp(a*x) dx should not be unevaluated
        let mut a = Arena::new();
        let x = sym(&mut a, "x");
        let param_a = sym(&mut a, "a");
        let ax = a.mul(&[param_a, x]);
        let exp_ax = a.exp(ax);
        let result = integrate(&mut a, exp_ax, x);
        let s = display(&a, result);
        assert!(
            !s.contains("Integral"),
            "∫exp(a*x)dx should not be unevaluated: {s}"
        );
        assert!(s.contains("exp"), "should contain exp: {s}");
    }

    #[test]
    fn integrate_cosh_symbolic_coeff() {
        // ∫ cosh(a*x) dx should not be unevaluated
        let mut a = Arena::new();
        let x = sym(&mut a, "x");
        let param_a = sym(&mut a, "a");
        let ax = a.mul(&[param_a, x]);
        let cosh_ax = a.cosh(ax);
        let result = integrate(&mut a, cosh_ax, x);
        let s = display(&a, result);
        assert!(
            !s.contains("Integral"),
            "∫cosh(a*x)dx should not be unevaluated: {s}"
        );
    }

    // ── Inverse hyperbolic integration tests ───────────────────────

    /// Helper: substitute a rational value for a symbol and evaluate to f64.
    /// Returns None if evaluation fails.
    fn eval_at(
        arena: &mut Arena,
        expr: ExprId,
        var: ExprId,
        numer: i64,
        denom: i64,
    ) -> Option<f64> {
        let val = arena.rational(numer, denom);
        let substituted = crate::transforms::subs::subs(arena, expr, var, val);
        let evaled = crate::transforms::eval::eval(arena, substituted);
        let s = crate::transforms::evalf::evalf(arena, evaled, 15).ok()?;
        s.parse::<f64>().ok()
    }

    /// Helper: verify FTC at multiple points — d/dx(F(x)) ≈ f(x).
    /// `integrand` is f(x), `antideriv` is F(x) = ∫f(x)dx.
    /// Checks at each test point that |F'(point) - f(point)| < tol.
    fn assert_ftc(
        arena: &mut Arena,
        integrand: ExprId,
        antideriv: ExprId,
        var: ExprId,
        test_points: &[(i64, i64)],
        tol: f64,
        name: &str,
    ) {
        let deriv = crate::transforms::diff::diff(arena, antideriv, var);
        let deriv_simplified = crate::simplify::simplify_engine::smart_simplify(arena, deriv);
        for &(n, d) in test_points {
            let f_val = eval_at(arena, integrand, var, n, d);
            let fp_val = eval_at(arena, deriv_simplified, var, n, d);
            match (f_val, fp_val) {
                (Some(f), Some(fp)) => {
                    assert!(
                        (f - fp).abs() < tol,
                        "FTC failed for {name} at x={n}/{d}: f(x)={f}, F'(x)={fp}, diff={}",
                        (f - fp).abs()
                    );
                }
                _ => {
                    // If numerical eval fails at this point, skip it
                    // (e.g., acosh at x < 1 is undefined)
                }
            }
        }
    }

    #[test]
    fn integrate_asinh_direct() {
        // ∫ asinh(x) dx = x·asinh(x) - √(x²+1)
        let mut a = Arena::new();
        let x = sym(&mut a, "x");
        let asinh_x = a.asinh(x);
        let result = integrate(&mut a, asinh_x, x);

        // Structural: must not be unevaluated
        assert!(
            !matches!(a.node(result), ExprNode::Integral(_, _)),
            "asinh integration should return a closed form, not Integral"
        );
        let s = display(&a, result);
        assert!(s.contains("asinh"), "result should contain asinh: {s}");
        assert!(s.contains("sqrt"), "result should contain sqrt: {s}");

        // Numerical FTC: d/dx(result) ≈ asinh(x) at multiple points
        assert_ftc(
            &mut a,
            asinh_x,
            result,
            x,
            &[(1, 2), (3, 2), (5, 1)],
            1e-8,
            "∫asinh(x)dx",
        );
    }

    #[test]
    fn integrate_acosh_direct() {
        // ∫ acosh(x) dx = x·acosh(x) - √(x²-1)
        let mut a = Arena::new();
        let x = sym(&mut a, "x");
        let acosh_x = a.acosh(x);
        let result = integrate(&mut a, acosh_x, x);

        // Structural: must not be unevaluated
        assert!(
            !matches!(a.node(result), ExprNode::Integral(_, _)),
            "acosh integration should return a closed form, not Integral"
        );
        let s = display(&a, result);
        assert!(s.contains("acosh"), "result should contain acosh: {s}");

        // Numerical FTC: test at x > 1 only (acosh domain)
        assert_ftc(
            &mut a,
            acosh_x,
            result,
            x,
            &[(3, 2), (2, 1), (5, 1)],
            1e-8,
            "∫acosh(x)dx",
        );
    }

    #[test]
    fn integrate_atanh_direct() {
        // ∫ atanh(x) dx = x·atanh(x) + ½·ln(1-x²)
        let mut a = Arena::new();
        let x = sym(&mut a, "x");
        let atanh_x = a.atanh(x);
        let result = integrate(&mut a, atanh_x, x);

        // Structural: must not be unevaluated
        assert!(
            !matches!(a.node(result), ExprNode::Integral(_, _)),
            "atanh integration should return a closed form, not Integral"
        );
        let s = display(&a, result);
        assert!(s.contains("atanh"), "result should contain atanh: {s}");
        assert!(s.contains("ln"), "result should contain ln: {s}");

        // Numerical FTC: test at |x| < 1 only (atanh domain)
        assert_ftc(
            &mut a,
            atanh_x,
            result,
            x,
            &[(1, 4), (1, 2), (3, 4)],
            1e-8,
            "∫atanh(x)dx",
        );
    }

    /// [`check_antiderivative`] of `big_f` for `∫ f dx`, both parsed; `K`
    /// in either stands for `sin(1)² + cos(1)² − 1`, which is 0 without
    /// being so structurally.
    fn ftc_verdict(f: &str, big_f: &str) -> FtcVerdict {
        let k = "(sin(1)^2 + cos(1)^2 - 1)";
        let ctx = crate::api::context::Context::new();
        let f = ctx.parse(&f.replace('K', k)).unwrap().id();
        let big_f = ctx.parse(&big_f.replace('K', k)).unwrap().id();
        ctx.with_arena_mut(|a| {
            let x = a.symbol("x");
            let ExprNode::Symbol(x_sym) = *a.node(x) else {
                unreachable!()
            };
            check_antiderivative(a, f, big_f, x, x_sym)
        })
    }

    #[test]
    fn ftc_check_vanishing_denominator_is_undecided_not_passed() {
        // Up to 0.28.0 no sample point evaluated `F′` (a quotient by K = 0)
        // and "no evidence" counted as "not wrong".
        assert_eq!(
            ftc_verdict("x/(K*x + 1)", "(x - ln(abs(K*x + 1))/K)/K"),
            FtcVerdict::Undecided
        );
        // `F′ = x·e^{Kx}` exactly, but `F` is undefined everywhere.
        assert_eq!(
            ftc_verdict("x*exp(K*x)", "x*exp(K*x)/K - exp(K*x)/K^2"),
            FtcVerdict::Undecided
        );
        // `f` itself evaluates nowhere: nothing can be tested.
        assert_eq!(ftc_verdict("x/K", "x^2/(2*K)"), FtcVerdict::Untestable);
    }

    #[test]
    fn ftc_check_samples_parameters() {
        // Up to 0.28.0 a free parameter skipped the check.  Up to 0.30
        // `ln|x + a|` was verified here too (the parameter took real values
        // only); an unassumed `a` is complex (decision D4, 0.31), and the
        // complex round rejects it.
        assert_eq!(ftc_verdict("1/(x + a)", "ln(x + a)"), FtcVerdict::Verified);
        assert_eq!(
            ftc_verdict("1/(x + a)", "ln(abs(x + a))"),
            FtcVerdict::Wrong
        );
        assert_eq!(
            ftc_verdict("1/(x + a)", "ln(abs(x + a))/a"),
            FtcVerdict::Wrong
        );
    }

    #[test]
    fn ftc_check_complex_integrand() {
        // `c = √(1/2 − √5/2)` is imaginary: `f` is complex at every real
        // `x`, the principal `ln(x − c)` agrees with it, `ln|x − c|` does
        // not (its derivative is `Re f`).
        let f = "1/(x - sqrt(1/2 - sqrt(5)/2))";
        assert_eq!(
            ftc_verdict(f, "ln(x - sqrt(1/2 - sqrt(5)/2))"),
            FtcVerdict::Verified
        );
        assert_eq!(
            ftc_verdict(f, "ln(abs(x - sqrt(1/2 - sqrt(5)/2)))"),
            FtcVerdict::Undecided
        );
        // Real-variable convention: `ln|x|` differs from `1/x` nowhere
        // where it is real; `√x·x` against `(2/5)·x^{5/2}` agrees at
        // `x > 0` and in the principal continuation.
        assert_eq!(ftc_verdict("1/x", "ln(abs(x))"), FtcVerdict::Verified);
        assert_eq!(ftc_verdict("1/x", "ln(abs(x)) + x"), FtcVerdict::Wrong);
        assert_eq!(
            ftc_verdict("sqrt(x - 5)", "2/3*(x - 5)^(3/2)"),
            FtcVerdict::Verified
        );
    }

    #[test]
    fn ftc_check_samples_through_binders() {
        // `subs` alone turns `RootOf(x⁵ − x + 1, 1)` into `RootOf(163/243,
        // 1)` at `x = 1/3`, which does not evaluate; the check renames the
        // bound `x` first.
        let f = "1/(x - RootOf(x^5 - x + 1, 1))";
        assert_eq!(
            ftc_verdict(f, "ln(x - RootOf(x^5 - x + 1, 1))"),
            FtcVerdict::Verified
        );
        assert_eq!(
            ftc_verdict(f, "2*ln(x - RootOf(x^5 - x + 1, 1))"),
            FtcVerdict::Undecided
        );
    }

    #[test]
    fn contains_var_respects_binders() {
        let ctx = crate::api::context::Context::new();
        let cases = [
            ("RootOf(x^5 - x + 1, 0)", false),
            ("x - RootOf(x^5 - x + 1, 0)", true),
            // A parametric `RootOf` binds its variable only (up to 0.28 it
            // named none and bound nothing).
            ("RootOf(x^3 + a*x + 1, x, 0)", false),
            ("RootOf(x^3 + a*x + 1, a, 0)", true),
            ("Sum(x^k, k, 0, 3)", true),
            ("Sum(k*x, x, 0, 3)", false),
            ("Sum(k*x, x, 0, x)", true),
            ("Integral(x, x)", true),
        ];
        for (src, expected) in cases {
            let e = ctx.parse(src).unwrap().id();
            let got = ctx.with_arena_mut(|a| {
                let x = a.symbol("x");
                let ExprNode::Symbol(x_sym) = *a.node(x) else {
                    unreachable!()
                };
                contains_var(a, e, x_sym)
            });
            assert_eq!(got, expected, "contains_var({src}, x)");
        }
    }

    #[test]
    fn constant_realness_is_exact_or_certified() {
        let ctx = crate::api::context::Context::new();
        // Decision D4 (0.31): `a`, `b` are unassumed, hence complex
        // parameters (`a*b + 3` counted as real up to 0.30); `r`, `s` are
        // declared real.
        ctx.symbol_with("r", &[crate::base::assumptions::Assumption::Real])
            .unwrap();
        ctx.symbol_with("s", &[crate::base::assumptions::Assumption::Positive])
            .unwrap();
        let cases = [
            ("sqrt(2)", true),
            ("a*b + 3", false),
            ("abs(a) + 3", true),
            ("r*s + 3", true),
            ("ln(3)", true),
            ("sqrt(3 - sqrt(5))", true),
            ("sqrt(1/2 - sqrt(5)/2)", false),
            ("exp(pi*I/8)", false),
            ("RootOf(x^5 - x + 1, 1)", false),
            // A real parameter of unknown sign.
            ("sqrt(r)", false),
            ("sqrt(-r)", false),
            ("sqrt(s)", true),
            ("sqrt(a)", false),
        ];
        for (src, expected) in cases {
            let e = ctx.parse(src).unwrap().id();
            let got = ctx.with_arena_mut(|a| {
                let mut reals = crate::base::assumptions::AssumptionCache::new();
                constant_is_real(a, e, &mut reals)
            });
            assert_eq!(got, expected, "constant_is_real({src})");
        }
    }

    /// Which candidates the complex round of the self-check can tell apart
    /// from their real-parameter look-alikes: those with a non-analytic
    /// function of a parameter (`|a·x + 1|`, `sign(a)`); `|x|` alone, and
    /// analytic functions of the parameters, cannot differ there.
    #[test]
    fn analytic_in_parameters_finds_real_parameter_forms() {
        let ctx = crate::api::context::Context::new();
        for (src, analytic) in [
            ("ln(a*x + 1)/a", true),
            ("ln(abs(x)) + a*x", true),
            ("atan(x/sqrt(a))/sqrt(a) + exp(b*x)*sin(x)", true),
            ("ln(abs(a*x + 1))/a", false),
            ("sign(a)*x", false),
            ("abs(a)*x^2/2", false),
            ("re(a)*x", false),
        ] {
            let e = ctx.parse(src).unwrap().id();
            let got = ctx.with_arena_mut(|a| {
                let x = a.symbol("x");
                let ExprNode::Symbol(x_sym) = *a.node(x) else {
                    unreachable!()
                };
                analytic_in_parameters(a, e, x_sym)
            });
            assert_eq!(got, analytic, "{src}");
        }
    }

    /// The verifier's complex round (decision D4, 0.31).  Up to 0.30 the
    /// parameters were bound to positive rationals only, where
    /// `ln|a·x + 1|/a` passes as an antiderivative of `1/(a·x + 1)`; and a
    /// declared parameter made every candidate untestable.  `r` is declared
    /// declared real, `n` an integer (no generic value satisfies that), `z`
    /// declared complex (which does not make it real), `m` negative.
    #[test]
    fn ftc_check_binds_unassumed_parameters_to_complex_values() {
        use crate::base::assumptions::Assumption;
        let ctx = crate::api::context::Context::new();
        ctx.symbol_with("r", &[Assumption::Real]).unwrap();
        ctx.symbol_with("n", &[Assumption::Integer]).unwrap();
        ctx.symbol_with("z", &[Assumption::Complex]).unwrap();
        ctx.symbol_with("m", &[Assumption::Negative]).unwrap();
        let cases = [
            ("1/(z*x + 1)", "ln(abs(z*x + 1))/z", FtcVerdict::Wrong),
            ("1/(z*x + 1)", "ln(z*x + 1)/z", FtcVerdict::Verified),
            ("1/(x - m)", "ln(abs(x - m))", FtcVerdict::Verified),
            // Wrong for a negative `m`, right for a positive one: up to 0.30
            // untestable, now sampled at `m = −17/13`.
            ("sqrt(m^2)", "m*x", FtcVerdict::Wrong),
            ("1/(a*x + 1)", "ln(abs(a*x + 1))/a", FtcVerdict::Wrong),
            ("1/(a*x + 1)", "ln(a*x + 1)/a", FtcVerdict::Verified),
            ("1/(r*x + 1)", "ln(abs(r*x + 1))/r", FtcVerdict::Verified),
            ("1/(x - 2)", "ln(abs(x - 2))", FtcVerdict::Verified),
            ("a*tan(x)", "-a*ln(abs(cos(x)))", FtcVerdict::Verified),
            // A part that depends on `x` alone keeps the real-variable
            // convention whatever its coefficient.
            (
                "a/sqrt(x^2 - 1)",
                "a*ln(abs(x + sqrt(x^2 - 1)))",
                FtcVerdict::Verified,
            ),
            ("a", "abs(a)*x", FtcVerdict::Wrong),
            ("exp(a*x)", "exp(a*x)/a", FtcVerdict::Verified),
            ("x^n", "x^(n + 1)/(n + 1)", FtcVerdict::Untestable),
        ];
        for (f_src, big_f_src, expected) in cases {
            let f = ctx.parse(f_src).unwrap().id();
            let big_f = ctx.parse(big_f_src).unwrap().id();
            let got = ctx.with_arena_mut(|a| {
                let x = a.symbol("x");
                let ExprNode::Symbol(x_sym) = *a.node(x) else {
                    unreachable!()
                };
                check_antiderivative(a, f, big_f, x, x_sym)
            });
            assert_eq!(got, expected, "∫ {f_src} = {big_f_src}");
        }
    }
}