gbif-name-parser 0.3.0

A faithful Rust port of the scientific name parser from the Global Biodiversity Information Facility (GBIF): parses biological scientific names into their structured components (genus, epithets, authorship, rank, nomenclatural code).
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
// SPDX-License-Identifier: Apache-2.0
//! Java `org.gbif.nameparser.pipeline.StripAndStash` — the pre-tokenisation stripper.
//! Removes annotations from the working string and stashes them onto
//! `ParseContext`/`ParsedName`. Per Java's own class doc: order matters — markers are
//! stripped from the most specific to the most general so that, for instance, a
//! "[sic, porphyria]" comment doesn't leak through the plainer "[sic]" path. [`run`] is
//! the explicit, ordered list of 55 strip steps; each step is a self-contained function
//! that takes the working string, mutates the [`ParseContext`] as needed, and returns
//! the (possibly shortened/rewritten) working string.
//!
//! **Phase 1 Slice 2, batches 1 + 2b + 2c + 2d + 2e (this batch, FINAL): all 55 steps
//! ported.** [`run`] dispatches all 55 steps in Java's exact `StripAndStash.run(ParseContext)`
//! order — that order is load-bearing and was locked in by Task 2 — steps 1-19 (leading
//! normalizers + flaggers, batch 1), 20-30 (candidatus, cultivar Group/grex/quoted, extinct
//! dagger, t.infr., doubtful-genus brackets, sic/corrig, synonym bracket, bracketed + bare
//! nom-note, batch 2b), 31-44 (authorship placeholders, trailing-species, pro parte /
//! pro sp. / approved-lists, mihi, anon, the six-step taxonomic-note family, aggregate
//! suffix, batch 2c), 45-52 (published-in page/in-press/in-author-in-parens/
//! in-author-citation/IPNI/period-separated-reference/comma-prefixed-reference/
//! manuscript-marker, batch 2d), and 53-55 (suprarank prefix, leading infrageneric marker,
//! phrase name, batch 2e) all now carry their faithful port.
//! Landing batch 2e flips the golden harness (`tests/parse_golden.rs`) from a deferred
//! baseline print to an asserted-0 gate over the 10 downstream-independent fields — see
//! that file's own module doc.
//!
//! Step 13, `replace_homoglyphs`, delegates to `crate::unicode`'s full port of Java's
//! `UnicodeUtils` homoglyph table (Phase 1 Slice 4) — see that step's own doc comment.
//! Separately, Java's `stripAuthorshipMarkers` — an auxiliary-authorship
//! reimplementation that duplicates a handful of this file's own strip steps but is NOT
//! part of this ordered `run()` dispatch at all — is ported further down this same file
//! (`strip_authorship_markers`, Phase 1 Slice 4 Task 4) as its own, shorter, ordered step
//! list, invoked on the caller-supplied `authorship` string from `pipeline::mod`'s
//! aux-authorship path.

use std::borrow::Cow;
use std::sync::LazyLock;

use fancy_regex::Regex as FancyRegex;
use regex::Regex;

use crate::model::{warnings, NamePart, NameType, NomCode, ParsedName, Rank};
use crate::pipeline::ParseContext;
use crate::token;
use crate::unicode::java_trim;
use unicode_normalization::UnicodeNormalization;

/// Java `StripAndStash.run(ParseContext ctx)`. Ordered dispatcher: threads the working
/// string through all 55 steps in Java's exact order (`StripAndStash.java:568-626`),
/// each step consuming the string by value and returning the (possibly
/// shortened/rewritten) result; steps also mutate `ctx` (`ctx.name`, `ctx.pending*`, …)
/// as a side effect for the ones that stash annotations rather than just discard them.
/// All 55 steps (batches 1, 2b, 2c, 2d, 2e) now carry a faithful port — see the module
/// doc.
pub(crate) fn run(ctx: &mut ParseContext) {
    let mut s = ctx.working.clone();
    s = repair_colon_diacritics(ctx, s);
    s = flag_uncertain_authorship(ctx, s);
    s = extract_generic_author(ctx, s);
    s = strip_quoted_monomial(ctx, s);
    s = apply_missing_genus_placeholder(ctx, s);
    s = strip_leading_genus_qualifier(ctx, s);
    s = strip_rank_lineage(ctx, s);
    s = strip_leading_species_label(ctx, s);
    s = strip_infra_rank_letters(ctx, s);
    s = normalise_letter_subdivision_marker(ctx, s);
    s = repair_question_mark_in_word(ctx, s);
    s = strip_strain_designation(ctx, s);
    s = stash_trailing_rank_marker_code(ctx, s);
    s = stash_organism_label_tail(ctx, s);
    s = stash_trailing_strain_code(ctx, s);
    s = stash_trailing_culture_accession(ctx, s);
    s = stash_bracketed_annotation(ctx, s);
    s = stash_underscore_designation(ctx, s);
    s = split_underscore_binomial(s);
    s = GLUED_ABBREVIATED_AUTHOR.replace(&s, "$1 $2$3").into_owned();
    s = strip_imprint_years(ctx, s);
    s = strip_null_between_epithets(ctx, s);
    s = normalise_hyphens(ctx, s);
    s = split_hyphen_glued_author(ctx, s);
    s = replace_homoglyphs(ctx, s);
    s = repair_win1252_artefacts(ctx, s);
    s = normalise_double_underscores(ctx, s);
    s = stash_trailing_otu_code(ctx, s);
    s = strip_serovar_serotype(ctx, s);
    s = strip_angle_bracket_authorship(ctx, s);
    s = strip_html(ctx, s);
    s = strip_candidatus(ctx, s);
    s = normalise_hort_ex_placeholder(ctx, s);
    s = strip_cultivar_group_grex(ctx, s);
    s = lower_shouted_qualifier(s);
    s = strip_rank_nova(ctx, s);
    s = strip_quoted_attributed_author(s);
    s = strip_quoted_cultivar(ctx, s);
    s = strip_extinct_dagger(ctx, s);
    s = strip_tinfr_marker(ctx, s);
    s = strip_doubtful_genus_brackets(ctx, s);
    s = strip_sic_and_corrig(ctx, s);
    s = stash_synonym_bracket(ctx, s);
    s = strip_quoted_spelling_variant(ctx, s);
    s = strip_bracketed_nom_note(ctx, s);
    s = strip_nom_note(ctx, s);
    s = strip_not_validly_published(ctx, s);
    s = strip_authorship_placeholders(ctx, s);
    s = strip_trailing_species_word(ctx, s);
    s = strip_pro_parte(ctx, s);
    s = strip_pro_sp_annotation(ctx, s);
    s = strip_approved_lists(ctx, s);
    s = strip_mihi(ctx, s);
    s = normalise_anon(ctx, s);
    s = strip_colon_concept_reference(ctx, s);
    s = strip_bracketed_tax_note(ctx, s);
    s = strip_paren_tax_note(ctx, s);
    s = strip_sensu_lato_remainder(ctx, s);
    s = strip_sensu_stricto_ss(ctx, s);
    s = strip_tax_note(ctx, s);
    s = strip_aggregate_suffix(ctx, s);
    s = strip_published_page(ctx, s);
    s = strip_in_press(ctx, s);
    s = strip_in_author_citations(ctx, s);
    s = strip_ipni_citation(ctx, s);
    s = strip_period_separated_reference(ctx, s);
    s = strip_comma_prefixed_reference(ctx, s);
    s = strip_manuscript_marker(ctx, s);
    s = strip_supra_rank_prefix(ctx, s);
    s = strip_leading_infrageneric_marker(ctx, s);
    s = stash_phrase_name(ctx, s);
    ctx.working = s;
}

// ===================================================================================
// Batch 1 (steps 1-19): leading normalizers + flaggers. Java StripAndStash.java's
// `flagUncertainAuthorship` through `stripHtml`. Ported (Phase 1 Slice 2, Task 3).
//
// Per-pattern flag rule applied throughout (see `pipeline::preflight`'s module doc for the
// rule spelled out in full, and `regexes.rs`'s module doc for the possessive-quantifier
// note): Java `Pattern.UNICODE_CHARACTER_CLASS` -> keep the crate's default Unicode
// `\d\s\w\b`; otherwise ASCII-scope every `\s`/`\d`/`\w`/`\b` atom via `(?-u:…)` (the WHOLE
// alternation when there's no `\p{…}` class AND no unescaped wildcard `.` anywhere in the
// pattern; only the individual atoms when either is present); `\p{Lu}`/`\p{Ll}`/`\p{L}`
// always Unicode; `CASE_INSENSITIVE` -> `(?i)`. A handful of patterns carry lookaround or a
// backreference the linear `regex` crate can't express at all — those use `fancy_regex`
// verbatim (each one's own doc comment explains why a restructuring was rejected, following
// `regexes.rs`'s `CORRIG` precedent) except where the ONLY call site is a boolean
// existence check (`.find()`/`.matches()`, never `.replaceAll()`), in which case dropping
// the lookahead is a sound restructuring (same class as Preflight's `PURE_ALPHANUM`).
//
// Every worked example below was spot-checked against the real Java CLI oracle
// (`name-parser-cli-4.2.0-SNAPSHOT-shaded.jar`) on adjunct test input — not just traced by
// hand — since the corpus golden harness alone can't validate step-level behaviour for
// fields the tokenizer/authorship-parser/Assemble stages would otherwise surface.
// ===================================================================================

/// Java `hasEarlierYear(String, int)` (StripAndStash.java:362-365): true if a 4-digit year
/// appears anywhere in `s[0, end)`. `end` is a byte offset from a prior match's `.start()`,
/// always a valid UTF-8 char boundary.
///
/// Java YEAR_4DIGIT (StripAndStash.java:161): `\b\d{4}\b`, no flags. Has `\b`/`\d`, no
/// `\p{...}`, no unescaped wildcard -> whole pattern ASCII-scoped.
static YEAR_4DIGIT: LazyLock<Regex> = LazyLock::new(|| Regex::new(r"(?-u:\b\d{4}\b)").unwrap());

fn has_earlier_year(s: &str, end: usize) -> bool {
    YEAR_4DIGIT.is_match(&s[..end])
}

/// Generalised non-overlapping `.replace_all` for a `fancy_regex::Regex`, tolerant of a
/// match error (breaks rather than propagating/panicking — this pipeline must never panic
/// on arbitrary, possibly-malformed input; `fancy_regex::Regex::replace_all` itself
/// `.unwrap()`s internally on any match error, so it is deliberately NOT used here). Mirrors
/// `regexes::strip_corrig_fancy`'s manual find_iter+splice loop, generalised with a
/// per-match closure so a caller needing to reinsert a captured group (`GREEK_MARKER`'s
/// "$1 " replacement) and a caller needing only a fixed replacement (`STAR_MARKER`,
/// `NULL_EPITHET_MID`) can share one implementation.
fn fancy_replace_all(
    re: &FancyRegex,
    s: &str,
    replacement: impl Fn(&fancy_regex::Captures<'_, str>) -> String,
) -> String {
    let mut result = String::with_capacity(s.len());
    let mut last = 0usize;
    for m in re.captures_iter(s) {
        let caps = match m {
            Ok(c) => c,
            Err(_) => break,
        };
        let whole = caps.get(0).expect("group 0 is always present in a match");
        result.push_str(&s[last..whole.start()]);
        result.push_str(&replacement(&caps));
        last = whole.end();
    }
    result.push_str(&s[last..]);
    result
}

// ---- Step 1: flagUncertainAuthorship ----

/// Java TRAILING_QMARK (StripAndStash.java:298): `\s\?\s*$`, no flags. Has `\s`, no
/// `\p{...}`, no unescaped wildcard -> whole pattern ASCII-scoped (trailing `$` left
/// outside the wrap, per convention — anchors aren't `u`-sensitive either way).
static TRAILING_QMARK: LazyLock<Regex> = LazyLock::new(|| Regex::new(r"(?-u:\s\?\s*)$").unwrap());

/// Java UNCERTAIN_AUTHOR_QMARK (StripAndStash.java:302-303):
/// `\p{L}\?(?=\s*(?:$|[&,]))`, `Pattern.UNICODE_CHARACTER_CLASS` (keep default Unicode
/// `\s`). RESTRUCTURED: the trailing lookahead is dropped. The `regex` crate has no
/// lookaround at all, but the ONLY call site (`flag_uncertain_authorship` below) uses this
/// pattern solely as a boolean `.find()` gate — never `.replaceAll()` — so consuming the
/// lookahead's content instead of merely peeking at it is unobservable: existence of a
/// match is identical either way. (Same restructuring class as Preflight's
/// `PURE_ALPHANUM`.)
static UNCERTAIN_AUTHOR_QMARK: LazyLock<Regex> =
    LazyLock::new(|| Regex::new(r"\p{L}\?\s*(?:$|[&,])").unwrap());

/// Java UNCERTAIN_AUTHOR_OR (StripAndStash.java:304-305): `\p{Lu}\p{L}*\s+or\s+\p{Lu}`,
/// `Pattern.UNICODE_CHARACTER_CLASS` -> keep default Unicode, ported verbatim.
static UNCERTAIN_AUTHOR_OR: LazyLock<Regex> =
    LazyLock::new(|| Regex::new(r"\p{Lu}\p{L}*\s+or\s+\p{Lu}").unwrap());

/// Java UNCERTAIN_AUTHOR_SLASH (StripAndStash.java:306-307): `\p{L}\s*/\s*\p{L}`,
/// `Pattern.UNICODE_CHARACTER_CLASS` -> keep default Unicode, ported verbatim.
static UNCERTAIN_AUTHOR_SLASH: LazyLock<Regex> =
    LazyLock::new(|| Regex::new(r"\p{L}\s*/\s*\p{L}").unwrap());

/// Java `StripAndStash.flagUncertainAuthorship` (StripAndStash.java:538-551). Flags
/// open-nomenclature uncertainty before any of it is normalised away. A trailing standalone
/// "?" ("… (Author, 1886) ?") is dropped but marks the name doubtful. A "?" glued to an
/// author word ("Sess?", "Smith?") or alternative authors joined by "or" / "/" ("Jarocki or
/// Schinz", "Smith/Jones") mark the authorship uncertain WITHOUT stripping anything — the
/// "?"/"or"/"/" stay in the working string (spot-checked against the Java CLI oracle: "Aus
/// bus Sess?" keeps the literal "Sess?" through this step — the "?" is only later dropped by
/// the tokenizer; "Aus bus Jarocki or Schinz, 1900" keeps the literal " or "
/// in the author text all the way to the final parse). Internal "letter?letter"
/// transcription artefacts ("Istv?nffi") are left to `repair_question_mark_in_word` (step 7).
fn flag_uncertain_authorship(ctx: &mut ParseContext, mut s: String) -> String {
    if TRAILING_QMARK.is_match(&s) {
        ctx.name.doubtful = true;
        ctx.name.add_warning(warnings::QUESTION_MARKS_REMOVED);
        s = java_trim(&TRAILING_QMARK.replace_all(&s, "")).to_string();
    }
    if UNCERTAIN_AUTHOR_QMARK.is_match(&s)
        || UNCERTAIN_AUTHOR_OR.is_match(&s)
        || UNCERTAIN_AUTHOR_SLASH.is_match(&s)
    {
        ctx.name.doubtful = true;
        ctx.name.add_warning(warnings::UNCERTAIN_AUTHORSHIP);
    }
    s
}

// ---- Step 2: extractGenericAuthor ----

/// Java INFRAGEN_AUTHOR_BEFORE_MARKER (StripAndStash.java:211-216),
/// `Pattern.UNICODE_CHARACTER_CLASS` -> keep default Unicode, ported verbatim. "Cordia
/// (Adans.) Kuntze sect. Salimori" — authorship placed BEFORE an infrageneric rank marker.
/// group(1)=genus, group(2)=author span (optional parenthesised basionym + combination
/// author words), group(3)=marker + sectional epithet. Rust-only: the genus may carry its hybrid
/// sign ("XAgroelymus Lapage sect. Agroelinelymus"), where Java lost the author, and the marker its
/// notho prefix ("Aconitum W. Mucher nothosect. Acopellus").
static INFRAGEN_AUTHOR_BEFORE_MARKER: LazyLock<Regex> = LazyLock::new(|| {
    Regex::new(
        r"^((?:[×xX]\s?)?\p{Lu}[\p{Ll}]+)\s+((?:\(\s*[^()]*\)\s*)?\p{Lu}[\p{L}.'\-]*(?:\s+\p{Lu}[\p{L}.'\-]*)*)\s+((?:notho)?(?:subg|subgen|subgenus|sect|subsect|supersect|ser|subser|superser|divisio|div|tr|subtr|unr)\.?\s+\p{Lu}[\p{Ll}]+)$",
    )
    .unwrap()
});

/// Java `StripAndStash.extractGenericAuthor` (StripAndStash.java:559-566). Splits off an
/// authorship placed before an infrageneric rank marker as the genus author: "Cordia
/// (Adans.) Kuntze sect. Salimori" leaves "Cordia sect. Salimori" for the pipeline (the
/// sectional epithet is not read as an author) and stashes "(Adans.) Kuntze" in
/// `ctx.pending_generic_author` for `Pipeline` to apply as the generic
/// authorship — the section itself is unauthored.
fn extract_generic_author(ctx: &mut ParseContext, s: String) -> String {
    // Java calls `.matches()` (full-string match); the pattern's own `^…$` anchors make
    // `.captures()` here equivalent (a match can only ever span the whole string).
    if let Some(caps) = INFRAGEN_AUTHOR_BEFORE_MARKER.captures(&s) {
        let author = caps.get(2).unwrap().as_str();
        ctx.pending_generic_author = Some(java_trim(author).to_string());
        return format!(
            "{} {}",
            caps.get(1).unwrap().as_str(),
            caps.get(3).unwrap().as_str()
        );
    }
    s
}

// ---- Step 3: stripQuotedMonomial ----

/// Java QUOTED_MONOMIAL (StripAndStash.java:162-164):
/// `^(['"])\s*([\p{Lu}][\p{L}-]+)\s*\1(\s+.+)?$`, `Pattern.UNICODE_CHARACTER_CLASS` -> keep
/// default Unicode (fancy_regex's own default, so no scoping needed either way). Contains a
/// BACKREFERENCE (`\1`, matching whichever quote char group 1 captured) -> needs
/// `fancy_regex` (the `regex` crate has no backreferences at all). Contains a literal `"`
/// -> `r#"…"#` raw string.
static QUOTED_MONOMIAL: LazyLock<FancyRegex> =
    LazyLock::new(|| FancyRegex::new(r#"^(['"])\s*([\p{Lu}][\p{L}-]+)\s*\1(\s+.+)?$"#).unwrap());

/// Java `StripAndStash.stripQuotedMonomial` (StripAndStash.java:655-666). A leading
/// monomial wrapped in quotes ("'Prosthète' Hesse, 1861" / "\"Foo\" Bar, 2000") marks a
/// word that is not an available scientific name. Strips the quotes for parsing, remembers
/// the quote char in `ctx.quoted_monomial` (so `Assemble` can re-wrap the
/// parsed uninomial — confirmed against the Java CLI oracle: the final `uninomial` comes
/// back as `'Prosthète'`, quotes and all), and flags doubtful.
fn strip_quoted_monomial(ctx: &mut ParseContext, s: String) -> String {
    if let Ok(Some(caps)) = QUOTED_MONOMIAL.captures(&s) {
        ctx.quoted_monomial = Some(caps.get(1).unwrap().as_str().to_string());
        ctx.name.doubtful = true;
        let tail = caps.get(3).map(|m| m.as_str()).unwrap_or("");
        return java_trim(&format!("{}{}", caps.get(2).unwrap().as_str(), tail)).to_string();
    }
    s
}

// ---- Step 4: applyMissingGenusPlaceholder ----

/// Java MISSING_GENUS_EPITHET (StripAndStash.java:341-342): `^[a-z][a-z\-]+\s+\p{Lu}.*`, no
/// flags. Has `\s` and `\p{Lu}` -> only `\s` ASCII-scoped. Called via `.matches()` in Java
/// -> trailing `$` added (the pattern already opens with `^`).
static MISSING_GENUS_EPITHET: LazyLock<Regex> =
    LazyLock::new(|| Regex::new(r"^[a-z][a-z\-]+(?-u:\s+)\p{Lu}.*$").unwrap());

/// Java MISSING_GENUS_NOTE_KEYWORD (StripAndStash.java:343-344):
/// `^(?:non|nec|not|sensu|sec|auct|auctt|fide|emend|ss|s|cf|aff|hort)\b.*`, no flags. Has
/// `\b` and an unescaped wildcard `.*` -> only `\b` ASCII-scoped (never whole-wrapped,
/// since that would also flip `.`'s Unicode-scalar-vs-byte meaning). Called via
/// `.matches()` -> trailing `$` added.
static MISSING_GENUS_NOTE_KEYWORD: LazyLock<Regex> = LazyLock::new(|| {
    Regex::new(r"^(?:non|nec|not|sensu|sec|auct|auctt|fide|emend|ss|s|cf|aff|hort)(?-u:\b).*$")
        .unwrap()
});

/// Java `StripAndStash.firstWord` (StripAndStash.java:649-653): the leading non-whitespace
/// run, per Java's own `Character.isWhitespace` semantics (not Rust's broader default) —
/// reuses `token::is_whitespace_java`.
fn first_word(s: &str) -> &str {
    match s.find(token::is_whitespace_java) {
        Some(idx) => &s[..idx],
        None => s,
    }
}

/// Java `StripAndStash.applyMissingGenusPlaceholder` (StripAndStash.java:668-701).
/// Missing-genus placeholder forms — the user-facing genus is replaced by "?":
///   `"denheyeri Eghbalian, …, 2017"`         -> `"? denheyeri Eghbalian, …, 2017"` (+ warning)
///   `"Missing penchinati Bourguignat, 1870"` -> `"? penchinati Bourguignat, 1870"` (no warning)
///   `"\"? gryphoidis"`, `"? alba Smith"`     -> `"? gryphoidis"`, `"? alba Smith"` (no warning)
/// Emits `NameType::Placeholder` for all three forms; `Warnings::MISSING_GENUS` only for
/// the inferred (third) form, since the other two carry an explicit "?"/"Missing" marker
/// the user wrote on purpose — all three spot-checked against the Java CLI oracle. Skips
/// the inferred form when the first word is a known taxonomic-note keyword that's NOT a
/// real epithet, or a surname particle ("van Berg") — a particle-led input is an author
/// name, not an epithet whose genus went missing.
fn apply_missing_genus_placeholder(ctx: &mut ParseContext, s: String) -> String {
    let mut missing: Option<String> = None;
    let mut emit_warning = false;
    if s.starts_with("\"? ") || s.starts_with("\"?\t") {
        let rest: String = s.chars().skip(3).collect();
        missing = Some(format!("? {}", java_trim(&rest)));
    } else if let Some(rest) = s
        .strip_prefix('?')
        .map(java_trim)
        .filter(|r| r.chars().next().is_some_and(char::is_lowercase))
    {
        // "? alba Smith", "?alba": the same explicit mark without the quote. Rust-only: Java
        // parsed a SCIENTIFIC name with the genus "?".
        missing = Some(format!("? {rest}"));
    } else if s.starts_with("Missing ") {
        let rest: String = s.chars().skip(8).collect();
        if rest.chars().next().is_some_and(|c| c.is_lowercase()) {
            missing = Some(format!("? {rest}"));
        }
    } else if s.chars().count() > 1
        && s.chars().next().is_some_and(|c| c.is_lowercase())
        && MISSING_GENUS_EPITHET.is_match(&s)
        && !MISSING_GENUS_NOTE_KEYWORD.is_match(&s)
        && !token::is_particle(first_word(&s))
    {
        missing = Some(format!("? {s}"));
        emit_warning = true;
    }
    if let Some(missing) = missing {
        ctx.name.type_ = NameType::Placeholder;
        if emit_warning {
            ctx.name.add_warning(warnings::MISSING_GENUS);
        }
        return missing;
    }
    s
}

/// A qualifier in front of a capitalised genus: a question mark, glued or spaced (`?Sydonia alba`,
/// `? Dudresnaya sp.`, `?Monotremata`), or an open-nomenclature `cf.`/`aff.` (`cf. Platypeltis
/// croftii`, `aff. Tetradonia sp. BOLD:AEF5834`). Tokenised as is, the `?` / `Cf` became the
/// uninomial and the real genus was read as an author. Mirrors the in-name `Sydonia? alba` /
/// `Abies cf. alba` handling — the mark becomes the GENERIC epithet qualifier (`cf.`/`aff.`
/// normalised to lowercase with a dot) and a `?` also flags the name doubtful; `Pipeline::run` adds
/// INFORMAL once a species epithet is parsed (see `ParseContext::qualified_genus`). A `?` before a
/// lowercase epithet (`? alba`) is the missing-genus placeholder handled by
/// [`apply_missing_genus_placeholder`] and never reaches this capitalised form.
static LEADING_GENUS_QUALIFIER: LazyLock<Regex> = LazyLock::new(|| {
    // the genus may still carry HTML (`cf. <em>Dicopia</em> fragilis`) — strip_html runs later
    Regex::new(r"^(?:(\?)(?-u:\s*)|(?i:(cf|aff))\.?(?-u:\s+))((?:<[^>]+>)?\p{Lu}\p{Ll}.*)$")
        .unwrap()
});

/// See [`LEADING_GENUS_QUALIFIER`].
fn strip_leading_genus_qualifier(ctx: &mut ParseContext, s: String) -> String {
    let Some(caps) = LEADING_GENUS_QUALIFIER.captures(&s) else {
        return s;
    };
    if caps.get(1).is_some() {
        ctx.name.set_epithet_qualifier(NamePart::Generic, "?");
        ctx.name.doubtful = true;
        ctx.name.add_warning(warnings::QUESTION_MARKS_REMOVED);
    } else {
        let q = format!("{}.", caps[2].to_ascii_lowercase());
        ctx.name.set_epithet_qualifier(NamePart::Generic, &q);
    }
    ctx.qualified_genus = true;
    caps[3].to_string()
}

/// A classification path written as abbreviated rank markers, `supf. Arrenuroidea fam. Arrenuridae`
/// / `phy. Annelida cla. Polychaeta` / `(supergen. Allopsontus)`: the last taxon is the name, at
/// the last marker's rank; every earlier `marker. Taxon` pair is dropped. Read as is, the first
/// marker became the uninomial (`Supf`) and the rest its author. Only the lowercase, dotted
/// abbreviations seen in the wild count, so a capitalised `Gen. Nov.` or a real genus never does.
/// (`trib.`/`subtrib.`/`subfam.` keep their own step, [`strip_supra_rank_prefix`].)
static LINEAGE_HEAD_PAIR: LazyLock<Regex> = LazyLock::new(|| {
    Regex::new(&format!(
        r"^(?:{LINEAGE_MARKERS})\.(?-u:\s+)[\p{{Lu}}][\p{{L}}]+(?-u:\s+)((?:{LINEAGE_MARKERS})\..+)$"
    ))
    .unwrap()
});
static LINEAGE_LAST: LazyLock<Regex> = LazyLock::new(|| {
    Regex::new(&format!(
        r"^(?:\(({LINEAGE_MARKERS})\.(?-u:\s+)([\p{{Lu}}][\p{{L}}]+)\)|({LINEAGE_MARKERS})\.(?-u:\s+)([\p{{Lu}}][\p{{L}}]+(?:(?-u:\s).*)?))$"
    ))
    .unwrap()
});
const LINEAGE_MARKERS: &str =
    "phy|subphy|cla|subc|infc|supo|ord|subo|info|supf|fam|subf|supergen|gen";

fn lineage_marker_rank(marker: &str) -> Option<Rank> {
    Some(match marker {
        "phy" => Rank::Phylum,
        "subphy" => Rank::Subphylum,
        "cla" => Rank::Class,
        "subc" => Rank::Subclass,
        "infc" => Rank::Infraclass,
        "supo" => Rank::Superorder,
        "ord" => Rank::Order,
        "subo" => Rank::Suborder,
        "info" => Rank::Infraorder,
        "supf" => Rank::Superfamily,
        "fam" => Rank::Family,
        "subf" => Rank::Subfamily,
        "supergen" => Rank::Supergenus,
        "gen" => Rank::Genus,
        _ => return None,
    })
}

/// See [`LINEAGE_LAST`].
fn strip_rank_lineage(ctx: &mut ParseContext, s: String) -> String {
    let mut path = s.as_str();
    while let Some(caps) = LINEAGE_HEAD_PAIR.captures(path) {
        path = caps.get(1).unwrap().as_str();
    }
    let Some(caps) = LINEAGE_LAST.captures(path) else {
        return s;
    };
    let (marker, taxon) = match (caps.get(1), caps.get(3)) {
        (Some(m), _) => (m.as_str(), caps.get(2).unwrap().as_str()),
        (None, Some(m)) => (m.as_str(), caps.get(4).unwrap().as_str()),
        (None, None) => return s,
    };
    match lineage_marker_rank(marker) {
        Some(rank) => {
            ctx.name.rank = rank;
            taxon.to_string()
        }
        None => s,
    }
}

/// A stray species label in front of a binomial or trinomial, `Sp. Abacobius jekelii` /
/// `spec. Abacobius jekelii` (~900 CLB names): read as is, `Sp` became the uninomial and the name
/// its author. The label is dropped; a plain binomial head gets the SPECIES rank it announces,
/// anything richer keeps the rank parsing infers.
static LEADING_SPECIES_LABEL: LazyLock<Regex> = LazyLock::new(|| {
    Regex::new(
        r"^(?:[Ss]p|[Ss]pec)\.(?-u:\s+)([\p{Lu}][\p{L}.]*(?:(?-u:\s+)\([\p{Lu}][\p{L}]*\))?(?-u:\s+)[\p{Ll}].*)$",
    )
    .unwrap()
});
static BINOMIAL_HEAD: LazyLock<Regex> = LazyLock::new(|| {
    Regex::new(
        r"^[\p{Lu}][\p{L}.]*(?:(?-u:\s+)\([\p{Lu}][\p{L}]*\))?(?-u:\s+)[\p{Ll}][\p{L}\-]*(?:(?-u:\s+)[^\p{Ll}].*)?$",
    )
    .unwrap()
});

/// See [`LEADING_SPECIES_LABEL`].
fn strip_leading_species_label(ctx: &mut ParseContext, s: String) -> String {
    let Some(caps) = LEADING_SPECIES_LABEL.captures(&s) else {
        return s;
    };
    let name = caps[1].to_string();
    if BINOMIAL_HEAD.is_match(&name) {
        ctx.name.rank = Rank::Species;
    }
    name
}

// ---- Step 5: stripInfraRankLetters ----

/// Java GREEK_MARKER_TEST (StripAndStash.java:316-317):
/// `.*[\p{Ll}.]\s*[α-ω⍺](?:\s+|\.\s*)\p{Ll}.*`, no flags. Has `\s` (x2) and
/// `\p{Ll}` -> only `\s` ASCII-scoped. Called via `.matches()` on a `.*CORE.*` pattern —
/// equivalent to an unanchored `is_match` on CORE alone (dropping the `.*` bookends) since
/// `.` matches any non-newline char and no name string embeds a newline — restructured to
/// the core-only form.
static GREEK_MARKER_TEST: LazyLock<Regex> = LazyLock::new(|| {
    Regex::new(r"[\p{Ll}.](?-u:\s*)[\x{03B1}-\x{03C9}\x{237A}](?:(?-u:\s+)|\.(?-u:\s*))\p{Ll}")
        .unwrap()
});

/// Java STAR_MARKER_TEST (StripAndStash.java:318-319): `.*\p{Ll}\s+\*+\s+\p{Ll}.*`, no
/// flags. Has `\s` (x2) and `\p{Ll}` -> only `\s` ASCII-scoped. Same `.*CORE.*` ->
/// core-only restructuring as `GREEK_MARKER_TEST`.
static STAR_MARKER_TEST: LazyLock<Regex> =
    LazyLock::new(|| Regex::new(r"\p{Ll}(?-u:\s+)\*+(?-u:\s+)\p{Ll}").unwrap());

/// Java GREEK_MARKER (StripAndStash.java:320-321):
/// `([\p{Ll}.])\s*[α-ω⍺](?:\s+|\.\s*)(?=[\p{Ll}])`, no flags (so Java's own `\s` here is
/// ASCII-only). Has a trailing LOOKAHEAD (not consumed by the match, so the replacement's
/// "$1 " leaves the following lowercase letter untouched right after it) -> needs
/// `fancy_regex` (the `regex` crate has no lookaround at all). NOT restructured to a
/// captured-and-reinserted group (unlike the `_TEST` sibling above): this pattern is used
/// for `.replaceAll`, and Java's zero-width lookahead lets a SECOND marker reuse the same
/// letter as ITS trailing-lookahead target when markers are adjacent — a capturing/consuming
/// rewrite would swallow that letter on the first match and miss the second (the same
/// adjacency asymmetry `regexes::CORRIG`'s doc comment documents at length). Greek-letter
/// rank markers are rare enough that the corpus gate is unlikely to exercise (and so could
/// not catch) such a subtle divergence, so the safer verbatim port is used instead.
/// `fancy_regex` has NO ASCII/non-Unicode mode at all — `(?-u:…)` is a hard parse error in
/// it, unconditionally (`fancy_regex::parse`'s flag parser rejects `-u` outright, unlike the
/// `regex` crate) — so ASCII-only `\s` is spelled out here as the literal Java ASCII
/// whitespace set `[ \t\n\x0B\f\r]` (space/tab/LF/VT/FF/CR) instead of the `\s` shorthand,
/// rather than attempting to scope it.
static GREEK_MARKER: LazyLock<FancyRegex> = LazyLock::new(|| {
    FancyRegex::new(
        r"([\p{Ll}.])[ \t\n\x0B\f\r]*[\x{03B1}-\x{03C9}\x{237A}](?:[ \t\n\x0B\f\r]+|\.[ \t\n\x0B\f\r]*)(?=[\p{Ll}])",
    )
    .unwrap()
});

/// Java STAR_MARKER (StripAndStash.java:322-323): `(?<=\p{Ll})\s+\*+\s+(?=\p{Ll})`, no
/// flags (ASCII-only `\s` in Java). Both boundaries are lookaround (lookbehind AND
/// lookahead) -> `fancy_regex`, same adjacency reasoning as `GREEK_MARKER`. Same
/// `fancy_regex`-has-no-ASCII-mode constraint as `GREEK_MARKER` -> `\s` spelled out as the
/// literal ASCII whitespace set rather than `(?-u:…)`-scoped.
static STAR_MARKER: LazyLock<FancyRegex> = LazyLock::new(|| {
    FancyRegex::new(r"(?<=\p{Ll})[ \t\n\x0B\f\r]+\*+[ \t\n\x0B\f\r]+(?=\p{Ll})").unwrap()
});

/// Java `StripAndStash.stripInfraRankLetters` (StripAndStash.java:703-717). Strips
/// Greek-like single-letter rank markers (α, β, …, and the APL-alpha lookalike U+237A) and
/// informal "***" markers sitting between two lowercase epithets — fungal rank markers
/// that must not be converted to ASCII letters or taken as authorship by downstream passes.
/// E.g. "Foo bar α baz" -> "Foo bar baz" and "Foo bar *** baz" -> "Foo bar baz" (both
/// spot-checked against the Java CLI oracle, which then parses the collapsed three-word
/// form as a normal trinomial).
fn strip_infra_rank_letters(_ctx: &mut ParseContext, s: String) -> String {
    if s.contains('\u{237A}') || GREEK_MARKER_TEST.is_match(&s) || STAR_MARKER_TEST.is_match(&s) {
        let s = fancy_replace_all(&GREEK_MARKER, &s, |caps| format!("{} ", &caps[1]));
        return fancy_replace_all(&STAR_MARKER, &s, |_| " ".to_string());
    }
    s
}

// ---- Step 6: normaliseLetterSubdivisionMarker ----

/// Java LETTER_SUBDIVISION_MARKER (StripAndStash.java:131-135),
/// `Pattern.UNICODE_CHARACTER_CLASS` -> keep default Unicode, ported verbatim. Old floras
/// subdivide a species informally with letters ("a.", "b.", "a.b.") between the species
/// name and a trailing epithet.
static LETTER_SUBDIVISION_MARKER: LazyLock<Regex> = LazyLock::new(|| {
    Regex::new(
        r"^(\p{Lu}[\p{Ll}-]+\s+[\p{Ll}][\p{Ll}-]+(?:\s+\p{Lu}[\p{Ll}]*\.?)*)\s+((?:[a-z]\.){1,3}[a-z]?)\s+([\p{Ll}][\p{Ll}-]{2,})\s*$",
    )
    .unwrap()
});

/// Java `RankMarkers.LETTER_SUBDIVISION` (RankMarkers.java:21): the synthetic single-token
/// marker `StripAndStash` substitutes for informal letter-based species subdivisions, so
/// the rank-marker machinery treats the trailing epithet as an
/// infraspecific of the unmappable rank `Rank::Other`. Never appears in user input.
const LETTER_SUBDIVISION: &str = "infrasubdivision";

/// Java `RankMarkers.matchInfraspecific(String) != null` — MINIMAL existence-only port.
/// This is a small pre-existing stand-in for the real `RankMarkers.INFRASPECIFIC` map (word
/// -> `Rank`), predating `rank_markers.rs` (the dedicated rank-handling module, which now
/// carries the full word -> `Rank` map); only the boolean null-check this one call site
/// (`normalise_letter_subdivision_marker` below) needs is kept here rather than routed
/// through that module (see `rank_markers.rs`'s own module doc for the cross-reference).
/// Key set transcribed verbatim from `RankMarkers.java`'s `INFRASPECIFIC` map (including
/// `LETTER_SUBDIVISION` itself, which Java's own map also carries as a key, and the
/// non-letter `"*"` key, which this call site can never actually produce). In practice the
/// calling regex can only ever split a SINGLE ASCII lowercase letter into `segments[0]`
/// (see the doc comment below), so only the `"f"` entry is reachable here — the full key
/// set is nonetheless transcribed in full (not hand-trimmed down to just "f") so this stays
/// an honest stand-in for the real map, not a call-site-specific shortcut.
const KNOWN_INFRASPECIFIC_MARKERS: &[&str] = &[
    LETTER_SUBDIVISION,
    "subsp",
    "ssp",
    "var",
    "subvar",
    "subv",
    "f",
    "forma",
    "form",
    "fo",
    "subf",
    "subforma",
    "pv",
    "pathovar",
    "bv",
    "biovar",
    "ct",
    "chemoform",
    "sv",
    "serovar",
    "morph",
    "morphovar",
    "phagovar",
    "nat",
    "natio",
    "mut",
    "mutatio",
    "agamosp",
    "agamossp",
    "agamovar",
    "conv",
    "convar",
    "subspec",
    "variety",
    "fm",
    "fma",
    "prol",
    "proles",
    "ab",
    "aberration",
    "strain",
    "str",
    "st",
    "*",
];

fn is_known_infraspecific_marker(word: &str) -> bool {
    KNOWN_INFRASPECIFIC_MARKERS.contains(&word.to_lowercase().as_str())
}

/// Java `StripAndStash.normaliseLetterSubdivisionMarker` (StripAndStash.java:719-737).
/// Rewrites an informal letter-based subdivision marker ("a.", "b.", "a.b.") to the
/// synthetic `LETTER_SUBDIVISION` token, UNLESS the "letter" is itself a real rank marker
/// ("f." = forma), in which case the input is left alone for the normal rank-marker path.
/// Any abbreviated author before the marker is left in place (dropped by the mid-name-author
/// logic downstream — not this step's concern). Both branches spot-checked against the Java
/// CLI oracle: "Graphis scripta L. a.b pulverulenta" comes back `rank=OTHER` (rewritten),
/// "Graphis scripta L. f. pulverulenta" comes back `rank=FORM` (left alone).
fn normalise_letter_subdivision_marker(_ctx: &mut ParseContext, s: String) -> String {
    if let Some(caps) = LETTER_SUBDIVISION_MARKER.captures(&s) {
        let marker = caps.get(2).unwrap().as_str();
        // Java: `m.group(2).split("[^a-z]+")`. The only non-"[a-z]" character `marker` can
        // ever contain is '.' (its own capturing group is `(?:[a-z]\.){1,3}[a-z]?`), so
        // splitting on '.' and dropping empty pieces reproduces Java's regex-split +
        // trailing-empty-discard exactly for this constrained shape (consecutive dots can't
        // occur either, so no internal empty pieces are possible).
        let segments: Vec<&str> = marker.split('.').filter(|seg| !seg.is_empty()).collect();
        let real_marker = segments.len() == 1 && is_known_infraspecific_marker(segments[0]);
        if !real_marker {
            let g1 = caps.get(1).unwrap().as_str();
            let g3 = caps.get(3).unwrap().as_str();
            return format!("{g1} {LETTER_SUBDIVISION} {g3}");
        }
    }
    s
}

// ---- Step 7: repairQuestionMarkInWord ----

/// Java LETTER_QMARK_LETTER (StripAndStash.java:295): `.*\p{L}\?\p{L}.*`, no flags. Has
/// `\p{L}` and an unescaped wildcard `.*` bookends, no `\s`/`\d`/`\w`/`\b` atoms at all ->
/// nothing to ASCII-scope. Called via `.matches()` on a `.*CORE.*` shape -> restructured to
/// the core-only `is_match` form (same reasoning as `GREEK_MARKER_TEST`). Shared with
/// `stripAuthorshipMarkers` (StripAndStash.java:440, ported below as
/// `strip_authorship_markers`) — defining it once here makes it directly reusable by that
/// call site too.
static LETTER_QMARK_LETTER: LazyLock<Regex> =
    LazyLock::new(|| Regex::new(r"\p{L}\?\p{L}").unwrap());

/// Java QMARK_BETWEEN_LETTERS (StripAndStash.java:296): `(\p{L})\?(\p{L})`, no flags. No
/// `\s`/`\d`/`\w`/`\b` atoms -> nothing to scope, ported verbatim. Shared with
/// `stripAuthorshipMarkers` (ported below as `strip_authorship_markers`), same as its
/// sibling above.
static QMARK_BETWEEN_LETTERS: LazyLock<Regex> =
    LazyLock::new(|| Regex::new(r"(\p{L})\?(\p{L})").unwrap());

/// U+FFFD REPLACEMENT CHARACTER(s) between two letters.
static LETTER_FFFD_LETTER: LazyLock<Regex> =
    LazyLock::new(|| Regex::new(r"(\p{L})\x{FFFD}+(\p{L})").unwrap());

/// The replacement character a broken encoding leaves for a letter ("Fusinus eucos\u{FFFD}nius",
/// "Guen\u{FFFD}e 1857") is a missing letter, like a "?" inside a word: removed, it no longer
/// splits the word in two. Flags doubtful + `UNUSUAL_CHARACTERS`.
fn remove_replacement_characters(name: &mut ParsedName, mut s: String) -> String {
    if s.contains('\u{FFFD}') && LETTER_FFFD_LETTER.is_match(&s) {
        while LETTER_FFFD_LETTER.is_match(&s) {
            s = LETTER_FFFD_LETTER.replace_all(&s, "$1$2").into_owned();
        }
        name.doubtful = true;
        name.add_warning(warnings::UNUSUAL_CHARACTERS);
    }
    s
}

/// Removes every "?" between two letters. Matches of [`QMARK_BETWEEN_LETTERS`] share their letters
/// ("D?s?gl."), so one pass leaves every second one — Java's did, and a later step then took the
/// rest of the word's punctuation with it ("Dsgl").
fn remove_qmarks_between_letters(mut s: String) -> String {
    while LETTER_QMARK_LETTER.is_match(&s) {
        s = QMARK_BETWEEN_LETTERS.replace_all(&s, "$1$2").into_owned();
    }
    s
}

/// Java `StripAndStash.repairQuestionMarkInWord` (StripAndStash.java:739-748). A "?" inside
/// a word is a transcription artefact for a missing letter ("Istv?nffi") — strips the "?"
/// and glues the surrounding word parts directly together (no placeholder letter is
/// guessed: "Istv?nffi" -> "Istvnffi"), flagging doubtful + `QUESTION_MARKS_REMOVED`. (The
/// identical inline logic also opens the separate `stripAuthorshipMarkers`
/// auxiliary-authorship path (ported below as `strip_authorship_markers`) —
/// `StripAndStash.java` duplicates it rather than sharing a helper, so this port does too,
/// reusing the same static patterns.)
fn repair_question_mark_in_word(ctx: &mut ParseContext, s: String) -> String {
    let s = remove_replacement_characters(&mut ctx.name, s);
    if s.contains('?') && LETTER_QMARK_LETTER.is_match(&s) {
        let s = remove_qmarks_between_letters(s);
        ctx.name.doubtful = true;
        ctx.name.add_warning(warnings::QUESTION_MARKS_REMOVED);
        return s;
    }
    s
}

// ---- Step 8: stripStrainDesignation ----

/// Java STRAIN_DESIGNATION (StripAndStash.java:175-179):
/// `\s+(?:str|strain)\b\s*\.?(?:\s+(?:str|strain)\b\s*\.?)*\s*(['"])(.+?)\1\s*$`,
/// `Pattern.CASE_INSENSITIVE` (so Java's `\s`/`\b` here are ASCII-only). Has a BACKREFERENCE
/// (`\1`, matching whichever quote char group 1 captured) -> needs `fancy_regex` (the
/// `regex` crate has no backreferences at all). Contains a literal `"` -> `r#"…"#` raw
/// string. `fancy_regex` has no ASCII/non-Unicode mode at all (`(?-u:…)` is a hard parse
/// error, unconditionally — see `GREEK_MARKER`'s doc comment for the same constraint), so
/// `\s` is spelled out as the literal ASCII whitespace set `[ \t\n\x0B\f\r]` rather than
/// scoped; `\b` is left as `fancy_regex`'s only option (Unicode word-boundary) — a divergence
/// from Java's ASCII `\b` only for a "str"/"strain" token directly abutting a non-ASCII
/// word character with no space, vanishingly rare in practice and forced by this crate's
/// architecture rather than a faithfulness lapse.
static STRAIN_DESIGNATION: LazyLock<FancyRegex> = LazyLock::new(|| {
    FancyRegex::new(
        r#"(?i)[ \t\n\x0B\f\r]+(?:str|strain)\b[ \t\n\x0B\f\r]*\.?(?:[ \t\n\x0B\f\r]+(?:str|strain)\b[ \t\n\x0B\f\r]*\.?)*[ \t\n\x0B\f\r]*(['"])(.+?)\1[ \t\n\x0B\f\r]*$"#,
    )
    .unwrap()
});

/// Java `StripAndStash.stripStrainDesignation` (StripAndStash.java:628-647). A quoted
/// strain designation after a "str"/"strain" marker ("Aphanizomenon flos-aquae
/// str .'Aph K2'") is kept intact as `ctx.name.phrase` (type=INFORMAL) rather than let leak
/// into the authorship parser or get reinterpreted as a cultivar epithet. The remaining
/// "Genus species str." is left for NameTokens, which resolves the
/// trailing "str" marker to `Rank::Strain` — spot-checked against the Java CLI oracle:
/// `rank=STRAIN, phrase="Aph K2", type=INFORMAL`. Only fires when a plausible name (a
/// capitalised genus) precedes the marker, never on junk.
fn strip_strain_designation(ctx: &mut ParseContext, s: String) -> String {
    if let Ok(Some(caps)) = STRAIN_DESIGNATION.captures(s.as_str()) {
        let whole = caps.get(0).unwrap();
        let prefix = java_trim(&s[..whole.start()]).to_string();
        if !prefix.is_empty() && prefix.chars().next().is_some_and(|c| c.is_uppercase()) {
            ctx.name.phrase = Some(java_trim(&caps[2]).to_string());
            ctx.name.type_ = NameType::Informal;
            return format!("{prefix} str.");
        }
    }
    s
}

// ---- Step 9: stashTrailingStrainCode ----

/// Java TRAILING_STRAIN_CODE (StripAndStash.java:165-169),
/// `Pattern.UNICODE_CHARACTER_CLASS` -> keep default Unicode.
///
/// 5.0.0 divergence: `:` joins `_` and `-` in the code's character class, so a colon-separated
/// identifier is recognised as the strain code it is. `Bacteroides caccae CAG21` already stashed
/// `CAG21` as the phrase, but the far commoner written form `Bacteroides caccae CAG:21` (a
/// co-abundance-gene-group MAG bin) fell through to `strip_published_page` 36 steps later, which
/// split it into the bogus author "CAG" AND the bogus page 21. The pattern is anchored
/// `^Genus species CODE$` and the code must start uppercase and contain a digit, so widening it
/// cannot reach a sanctioning author (`Agaricus campestris L. : Fr.` has dots and spaces the class
/// does not admit).
///
/// Divergence (gbif/name-parser-rust#16): a THIRD alternative admits a code that leads
/// with a digit — `Prunus domestica 6`, `Escherichia coli 18-41`, `Bacteroidetes bacterium 20/6`.
/// Java's two alternatives both require a leading letter, so a digit-leading code fell through
/// this step into the authorship parser, which disposed of it in three silent ways: a 1-2 digit
/// number hit `AuthorshipParser.parseAuthors`' final "unknown token" skip, a 3-4 digit one became
/// a bogus authorship YEAR, and `5a` split into a dropped `5` plus a fabricated author `a`. In
/// every case `state` stayed COMPLETE and `type` SCIENTIFIC with an empty `unparsed`, so the
/// truncated result was byte-identical to a DIFFERENT real taxon and collapsed onto it in any
/// names index — which is how ChecklistBank's ArchisBotany import ended up with a usage parented
/// under its own grandchild (CatalogueOfLife/checklistbank#1725). Routing these through the same
/// phrase/INFORMAL path the uppercase codes already take keeps the code visible in the canonical
/// rendering, so the collision cannot form. The code itself may not end on punctuation, but a
/// single full stop closing the whole string is tolerated (`Prunus domestica 6.`) and left OUT of
/// the captured phrase — it is sentence punctuation, not part of the code, and without the `\.?`
/// that one character was enough to put the name back on the silent-truncation path. The guards
/// below exempt a bare year and a numeral-prefixed epithet. Rust-only too: a qualifier may stand
/// before the epithet ("Gemmula cf. cosmoi NP-2008", "Acalymma nr. blomorum JJG229") and a hyphen
/// before the code's digits, where the code became an author.
static TRAILING_STRAIN_CODE: LazyLock<Regex> = LazyLock::new(|| {
    Regex::new(
        r"^([\p{Lu}][\p{Ll}]+\s+(?:(?:cf|aff|nr|near)\.?\s+)?[\p{Ll}]+)\s+([dr]?RNA[a-zA-Z0-9_\-]*|[\p{Lu}][\p{L}\d:\-]*\d[\p{L}\d_\-:]*|\d(?:[\p{L}\d_:/.\-]*[\p{L}\d])?)\.?\s*$",
    )
    .unwrap()
});

/// Replaces Java DIGITS_ONLY (StripAndStash.java:357) as the guard on
/// [`stash_trailing_strain_code`]. Java's `\d+` was provably unreachable there (both of its code
/// alternatives start with a letter, so `code` could never be digits-only) and was ported verbatim
/// anyway as a dead guard; the digit-leading alternative added for #16 makes it reachable, and
/// digits-only is now exactly the shape we DO want to stash (`Acinetobacter baumannii 1237893`).
/// What survives is that guard's stated intent — "never consume a single trailing year" — narrowed
/// to the only shape that can actually BE one: a bare 4-digit `1xxx`/`2xxx`, matching the
/// year test `AuthorshipSplit.hasYearToken` already uses. So `Prunus domestica 1888` keeps
/// `combinationAuthorship.year=1888` exactly as before, while `Actinomycetota bacterium 4327`
/// (not year-shaped) becomes the strain phrase it is.
static TRAILING_YEAR: LazyLock<Regex> = LazyLock::new(|| Regex::new(r"^(?-u:[12]\d{3})$").unwrap());

/// A taxon, a generic organism label as its epithet and whatever follows it ("Acidimicrobiales
/// bacterium JGI 01_E13", "Wolbachia endosymbiont of Leptogenys gracilis", "Candidatus
/// Abawacabacteria bacterium"). Group 1 = taxon + label, group 2 = the tail.
static ORGANISM_LABEL_TAIL: LazyLock<Regex> = LazyLock::new(|| {
    Regex::new(
        r"^((?:Candidatus\s+)?\p{Lu}\p{Ll}+\s+\p{Ll}*(?:bacteri(?:um|a)|archae(?:on|a|ote)|symbionts?))(?:\s+(.+?))?\s*$",
    )
    .unwrap()
});

/// An [`ORGANISM_LABEL_TAIL`] is a provisional name, INFORMAL like the "Genus species CODE" of
/// [`stash_trailing_strain_code`]: the label stays its epithet, the tail — a strain code, a host,
/// several words — becomes the phrase. Java read the tail as authors ("JGI E13", "of Leptogenys
/// gracilis") and the bare label as a species.
fn stash_organism_label_tail(ctx: &mut ParseContext, s: String) -> String {
    let Some(caps) = ORGANISM_LABEL_TAIL.captures(&s) else {
        return s;
    };
    match caps.get(2) {
        // an author behind it makes the label a real epithet: the diatom "Navicula bacterium
        // Frenguelli"
        Some(tail) if LABEL_TAIL_AUTHOR.is_match(tail.as_str()) => s,
        Some(tail) => {
            ctx.name.type_ = NameType::Informal;
            ctx.name.phrase = Some(tail.as_str().to_string());
            caps[1].to_string()
        }
        // alone, a symbiont, or a bacterium of a Candidatus or higher taxon ("Candidatus
        // Abawacabacteria bacterium", "Acidimicrobiales bacterium"); "Navicula bacterium" is a
        // species
        None => {
            if s.ends_with("symbiont")
                || s.ends_with("symbionts")
                || LABEL_HIGHER_ANCHOR.is_match(&s)
            {
                ctx.name.type_ = NameType::Informal;
            }
            s
        }
    }
}

/// An authorship behind an organism label: a capitalised surname, perhaps a team and a year.
static LABEL_TAIL_AUTHOR: LazyLock<Regex> = LazyLock::new(|| {
    Regex::new(
        r"^\(?\p{Lu}\p{Ll}[\p{L}'.\-]*(?:(?:,? | & | et )\p{Lu}[\p{L}'.\-]+)*(?:,? (?:1[5-9]\d\d|20[0-2]\d))?\)?$",
    )
    .unwrap()
});

/// A Candidatus name or a taxon above the genus, by its ending, before an organism label.
static LABEL_HIGHER_ANCHOR: LazyLock<Regex> = LazyLock::new(|| {
    Regex::new(r"^(?:Candidatus\s+\p{Lu}\p{Ll}+|\p{Lu}\p{Ll}*(?:ales|aceae|ota|etes|ia|ae|mycetes|phyta))\s").unwrap()
});

/// Java `StripAndStash.stashTrailingStrainCode` (StripAndStash.java:750-768). A trailing
/// strain-code suffix on a binomial ("Candida albicans RNA_CTR0-3", "Armillaria ostoyae
/// RNA1", and since #16 "Prunus domestica 6" / "Escherichia coli 18-41") becomes
/// `ctx.name.phrase` (type=INFORMAL), reducing the working string to "Genus species" —
/// spot-checked against the Java CLI oracle. See [`TRAILING_YEAR`] for what became of
/// Java's `DIGITS_ONLY` guard.
fn stash_trailing_strain_code(ctx: &mut ParseContext, s: String) -> String {
    if let Some(caps) = TRAILING_STRAIN_CODE.captures(&s) {
        let head = caps.get(1).unwrap().as_str();
        let code = caps.get(2).unwrap().as_str();
        if !TRAILING_YEAR.is_match(code)
            && !token::is_numeral_epithet(code)
            && !is_indet_species_marker(second_word(head))
        {
            ctx.name.phrase = Some(code.to_string());
            ctx.name.type_ = NameType::Informal;
            return head.to_string();
        }
    }
    s
}

/// The second whitespace-separated word of a `TRAILING_STRAIN_CODE` head — i.e. the token
/// sitting in the species-epithet slot of the matched "Genus species CODE".
fn second_word(head: &str) -> &str {
    head.split_whitespace().nth(1).unwrap_or("")
}

/// True when the species-epithet slot is really the INDETERMINATE SPECIES MARKER — the bare
/// undotted `sp`/`spec`/`species` that `NameTokens` recognises (`name_tokens.rs:384-386`).
/// "Allium species 1" is an indeterminate Allium numbered 1, not a strain "1" of a species
/// called "species", and NameTokens already builds exactly the right thing for it —
/// `rank=SPECIES`, `phrase="species 1"`, marker kept verbatim (`name_tokens.rs:442`).
/// Without this guard the widened code alternative reaches it first and strips the "1" on
/// its own, dropping the marker and rendering "Allium 1" — caught by the `manuscript_names`
/// golden test. The guard covers all three code alternatives, which also repairs the same
/// latent truncation on the uppercase path ("Allium species AB1" likewise lost its marker,
/// and 55 CLB names of that shape gain theirs back).
///
/// Deliberately NOT extended to the other rank markers (`RankMarkers`' infraspecific /
/// infrageneric maps). `strain`/`str`/`st` sit in the infraspecific map, but nothing
/// downstream handles the bare undotted "Genus strain CODE" — guarding it merely put the
/// code back on the silent-truncation path this change exists to close ("Trachelomonas
/// strain T101" regressed to `SCIENTIFIC specificEpithet="strain"` with T101 gone, found in
/// the CLB corpus diff). Only the markers NameTokens can actually finish belong here.
fn is_indet_species_marker(w: &str) -> bool {
    w.eq_ignore_ascii_case("sp")
        || w.eq_ignore_ascii_case("spp")
        || w.eq_ignore_ascii_case("spec")
        || w.eq_ignore_ascii_case("species")
}

/// gbif/name-parser-rust#16 (no Java counterpart): an INDETERMINATE INFRAGENERIC OR
/// INFRASPECIFIC name, numbered — `Allium sect 1`, `Allium sect. 1`, `Trachelomonas strain T101`.
/// A rank marker sitting in the epithet slot of "Genus <word> CODE" is not an epithet, so the whole
/// `<marker> CODE` tail is the designation: it becomes the verbatim `phrase` (type INFORMAL) and
/// the working string reduces to the bare genus, so `taxon + " " + phrase` round-trips the input.
///
/// Every one of these was losing something. `Allium sect 1` dropped the marker and rendered
/// "Allium 1"; the commoner DOTTED spellings `Allium sect. 1` and `Allium subg. 3` dropped the
/// whole tail and came back as a plain SCIENTIFIC "Allium" — the same silent truncation as #16's
/// headline case, just one token longer. `Trachelomonas strain T101` did keep its code, but only
/// by reading "strain" as the species epithet.
///
/// The genus-only reduction is what distinguishes this from [`stash_trailing_strain_code`], which
/// keeps a two-word `Genus species` head; the marker must leave the working string, or NameTokens
/// reads it as an epithet. `sp`/`spec`/`species`/`indet` are excluded — NameTokens owns those
/// (see [`is_indet_species_marker`]) and produces a better-ranked result for them.
///
/// Neither the [`TRAILING_YEAR`] nor the [`TRAILING_NUMERAL_EPITHET`] guard applies here: both
/// exist to protect readings that need an authorship or an epithet slot, and a rank marker in that
/// slot rules out both — there is no author for `Allium sect 1888` to have a publication year, and
/// no epithet position left for a numeral-prefixed word to occupy.
static TRAILING_RANK_MARKER_CODE: LazyLock<Regex> = LazyLock::new(|| {
    Regex::new(
        r"^([\p{Lu}][\p{Ll}]+)\s+([\p{Ll}]+)\.?\s+([dr]?RNA[a-zA-Z0-9_\-]*|[\p{Lu}][\p{L}\d:]*\d[\p{L}\d_\-:]*|\d(?:[\p{L}\d_:/.\-]*[\p{L}\d])?)\.?\s*$",
    )
    .unwrap()
});

/// See [`TRAILING_RANK_MARKER_CODE`].
fn stash_trailing_rank_marker_code(ctx: &mut ParseContext, s: String) -> String {
    let Some(caps) = TRAILING_RANK_MARKER_CODE.captures(&s) else {
        return s;
    };
    let marker = caps.get(2).unwrap();
    if is_indet_species_marker(marker.as_str()) || !is_rank_marker_word(marker.as_str()) {
        return s;
    }
    // The phrase is the verbatim source text from the marker to the end of the code, so the
    // original spelling and spacing survive ("sect. 1", "strain T101") and the input round-trips.
    let code_end = caps.get(3).unwrap().end();
    ctx.name.phrase = Some(s[marker.start()..code_end].to_string());
    ctx.name.type_ = NameType::Informal;
    // Only an INFRASPECIFIC marker's rank is applied. An infrageneric one must NOT be: at an
    // infrageneric rank Assemble reads the single remaining name word as the infrageneric
    // EPITHET, so "Allium sect 1" came back as `infragenericEpithet="Allium"` with no genus at
    // all, and rendered "sect. Allium sect 1". Allium is the GENUS here — the section is the
    // unnamed thing, and no field can hold an unnamed one. The marker stays verbatim in the
    // phrase either way, so leaving the rank alone costs nothing and keeps the name parts honest.
    if let Some(rank) = super::rank_markers::match_infraspecific(marker.as_str()) {
        ctx.name.rank = rank;
    }
    caps.get(1).unwrap().as_str().to_string()
}

/// `Uninomial [Word]` — one capitalised word in square brackets after a uninomial, nothing else:
/// WoRMS' `Acanthoecidae [Nudiform]`, `Leptocephalus [Moringuidae]`. Read as an authorship, the word
/// became the author; it is an annotation (a morphotype, the family of a larval form), so it moves to
/// the phrase and the name turns INFORMAL. Square brackets only — `(Müller)` stays a basionym author
/// — and without a year: an anonymous-work author is bracketed too, but cited with its year
/// (`[Hübner], 1806`, ICZN Recommendation 51D).
static BRACKETED_ANNOTATION: LazyLock<Regex> = LazyLock::new(|| {
    Regex::new(r"^([\p{Lu}][\p{Ll}]+)(?-u:\s+)(\[[\p{Lu}][\p{L}\-]+\])(?-u:\s*)$").unwrap()
});

/// See [`BRACKETED_ANNOTATION`].
fn stash_bracketed_annotation(ctx: &mut ParseContext, s: String) -> String {
    let Some(caps) = BRACKETED_ANNOTATION.captures(&s) else {
        return s;
    };
    ctx.name.phrase = Some(caps[2].to_string());
    ctx.name.type_ = NameType::Informal;
    caps[1].to_string()
}

/// Underscore-glued provisional designations from barcoding / survey papers, optionally followed by
/// a bracketed source citation: `Aulocalyx n_sp_NIWA_SO254 [of Dohrmann et al., 2023]`,
/// `Eurythenes sp_DISCOLL_PAP_B`, `Farrea occa n_ssp_NIWA_SO254`. The tokenizer keeps the
/// underscores inside one word, so the designation was read as the epithet and the citation as the
/// authors `of Dohrmann` + `al.`. The designation plus citation become the phrase (INFORMAL), the
/// working string the anchor — a genus, or a `Genus species` head for a subspecies designation.
static UNDERSCORE_DESIGNATION: LazyLock<Regex> = LazyLock::new(|| {
    Regex::new(
        r"^([\p{Lu}][\p{Ll}]+(?:(?-u:\s+)[\p{Ll}]+)?)(?-u:\s+)((?:n_)?(sp|ssp|subsp)_[\p{L}\d_]+(?:(?-u:\s+)\[[^\]]*\])?)(?-u:\s*)$",
    )
    .unwrap()
});
/// A new genus glued onto its family, `Rossellidae_n_gen`, with an optional designation/citation
/// tail (`Rossellidae_n_gen n_sp_NIWA_SO254 [of …]`): the family is the anchor, the rest the phrase.
static GLUED_NEW_GENUS: LazyLock<Regex> =
    LazyLock::new(|| Regex::new(r"^([\p{Lu}][\p{Ll}]+)_(n_gen(?:(?-u:\s+).*)?)$").unwrap());
static NEW_SPECIES_TAG: LazyLock<Regex> =
    LazyLock::new(|| Regex::new(r"(?-u:\b)(?:n_)?sp_").unwrap());

/// A genus joined to its epithet by an underscore for the space ("Calopteryx_splendens
/// splendens", "Oxalis_barrelieri ined.?"), which made one genus "Calopteryx_splendens".
static UNDERSCORE_BINOMIAL: LazyLock<Regex> =
    LazyLock::new(|| Regex::new(r"^(\p{Lu}\p{Ll}+)_(\p{Ll}{3,})(\s|$)").unwrap());

/// An abbreviated author glued to the species epithet ("Pentapanax angelicifoliusGriseb.",
/// "Caralluma praegracilisOberm."). Only with its abbreviation dot: an undotted capital inside an
/// epithet is mostly a misread letter ("stimuUferum", "trulIaeformis").
static GLUED_ABBREVIATED_AUTHOR: LazyLock<Regex> =
    LazyLock::new(|| Regex::new(r"^(\p{Lu}\p{Ll}+\s+\p{Ll}{4,})(\p{Lu}\p{Ll}+\.)(\s|$)").unwrap());

/// Splits an [`UNDERSCORE_BINOMIAL`]; a family's "_gen"/"_genus" placeholder or a "_sp" tag is no
/// epithet and stays.
fn split_underscore_binomial(s: String) -> String {
    match UNDERSCORE_BINOMIAL.captures(&s) {
        Some(caps) if !matches!(&caps[2], "gen" | "genus" | "sp" | "spp" | "ssp" | "subsp") => {
            UNDERSCORE_BINOMIAL.replace(&s, "$1 $2$3").into_owned()
        }
        _ => s,
    }
}

/// See [`UNDERSCORE_DESIGNATION`] and [`GLUED_NEW_GENUS`].
fn stash_underscore_designation(ctx: &mut ParseContext, s: String) -> String {
    if let Some(caps) = GLUED_NEW_GENUS.captures(&s) {
        let tail = java_trim(&caps[2]).to_string();
        ctx.name.rank = if NEW_SPECIES_TAG.is_match(&tail) {
            Rank::Species
        } else {
            Rank::Genus
        };
        ctx.name.phrase = Some(tail);
        ctx.name.type_ = NameType::Informal;
        return caps[1].to_string();
    }
    let Some(caps) = UNDERSCORE_DESIGNATION.captures(&s) else {
        return s;
    };
    ctx.name.rank = if &caps[3] == "sp" {
        Rank::Species
    } else {
        Rank::Subspecies
    };
    ctx.name.phrase = Some(caps[2].to_string());
    ctx.name.type_ = NameType::Informal;
    caps[1].to_string()
}

/// A separately supplied authorship that is nothing but a bracketed family-group name
/// (`[Ophichthidae]`, WoRMS' leptocephalus larvae): an annotation, not an author. Unlike in the name
/// string a bare bracketed word is NOT enough here — `[Renier]`, `[Boucek]`, `[Röding]` are common
/// anonymous-work authors in that column — so only the family-group suffixes count.
static BRACKETED_FAMILY_GROUP: LazyLock<Regex> = LazyLock::new(|| {
    Regex::new(r"^\[[\p{Lu}][\p{Ll}]+(?:idae|inae|oidea|oideae|aceae)\]$").unwrap()
});

/// Moves a [`BRACKETED_FAMILY_GROUP`] authorship into the name's phrase (INFORMAL) and returns
/// `true`, or leaves `name` alone and returns `false`.
pub(crate) fn stash_bracketed_family_group_authorship(
    authorship: &str,
    name: &mut crate::model::ParsedName,
) -> bool {
    let a = java_trim(authorship);
    if !BRACKETED_FAMILY_GROUP.is_match(a) {
        return false;
    }
    name.phrase = Some(match name.phrase.take() {
        // once: sources repeat it in the name string ("Leptocephalus [Ophichthidae]")
        Some(p) if p.contains(a) => p,
        Some(p) => format!("{p} {a}"),
        None => a.to_string(),
    });
    name.type_ = NameType::Informal;
    true
}

/// A bare undotted infrageneric / infraspecific rank marker (`sect`, `subg`, `var`, `strain`, …).
/// The head's marker slot is matched as `[\p{Ll}]+`, so only these undotted forms reach here.
fn is_rank_marker_word(w: &str) -> bool {
    rank_of_marker(w).is_some()
}

/// Does this word name a rank at all — infrageneric or infraspecific? Only membership matters
/// here; see [`stash_trailing_rank_marker_code`] for why only the infraspecific half of the answer
/// is turned into an actual `rank`.
fn rank_of_marker(w: &str) -> Option<Rank> {
    super::rank_markers::match_infrageneric(w)
        .or_else(|| super::rank_markers::match_infraspecific(w))
}

/// 5.0.0 (no Java counterpart): a curated culture-collection accession TRAILING a binomial
/// ("Aquimarina muelleri DSM 19832", "Bacillus subtilis DSM 10", "Escherichia coli ATCC 11775") is
/// a strain annotation, NOT authorship. Unlike [`TRAILING_STRAIN_CODE`] (whose code group forbids a
/// space, so "DSM 19832" slips through and "DSM" is later swallowed as an author), this matches an
/// `<acronym> <accession>` with the space intact. Group 1 is the binomial, group 2 the whole
/// verbatim accession (acronym included) — stashed on `ctx.name.phrase` (type INFORMAL, binomial
/// core kept so the result stays Parsed), consistent with the other trailing-strain paths and with
/// the standalone `NameType::Identifier` path in `preflight` (shared `culture_collections` list).
static TRAILING_CULTURE_ACCESSION: LazyLock<Regex> = LazyLock::new(|| {
    Regex::new(&format!(
        r"^([\p{{Lu}}][\p{{Ll}}]+[ ]+[\p{{Ll}}]+)[ ]+({}[ :=_\-]*(?:[A-Z]{{1,4}}\-)?[0-9][0-9A-Za-z.:\-]*)$",
        super::culture_collections::acronym_alternation()
    ))
    .unwrap()
});

/// See [`TRAILING_CULTURE_ACCESSION`].
fn stash_trailing_culture_accession(ctx: &mut ParseContext, s: String) -> String {
    if let Some(caps) = TRAILING_CULTURE_ACCESSION.captures(&s) {
        ctx.name.phrase = Some(caps.get(2).unwrap().as_str().to_string());
        ctx.name.type_ = NameType::Informal;
        return caps.get(1).unwrap().as_str().to_string();
    }
    s
}

// ---- Step 10: stripImprintYears ----

/// Java IMPRINT_YEAR_QUOTED (StripAndStash.java:180-181):
/// `\s*[\[\(]\s*"(\d{4}(?:[-–]\d{4})?)"\s*[\]\)]\s*\.?\s*$`, no flags. Has `\s`/`\d`, no
/// `\p{...}`, no unescaped wildcard `.` (only an escaped literal `\.?`) — but it DOES embed
/// a non-ASCII literal (the en dash `\x{2013}`) inside the custom class `[-\x{2013}]`. Java's
/// `UNICODE_CHARACTER_CLASS` flag only governs PREDEFINED shorthand classes (`\d`/`\s`/`\w`/
/// `\b`/POSIX `\p{Alpha}` etc.) — a literal/custom class like `[-\x{2013}]` always matches
/// exactly those code points in Java regardless of the flag, so it must stay OUTSIDE any
/// `(?-u:…)` scoping here too (`regex-syntax` rejects a non-ASCII literal inside a
/// `(?-u:…)` group outright: "Unicode not allowed here" — discovered when this pattern was
/// first run, not anticipated from the flag rule alone). Only the individual `\s`/`\d`
/// atoms are ASCII-scoped; the whole-pattern-wrap this port's rule would otherwise prefer
/// (no `\p{...}`, no unescaped wildcard) does not apply once a non-ASCII custom-class
/// literal is present. Contains a literal `"` -> `r#"…"#` raw string.
static IMPRINT_YEAR_QUOTED: LazyLock<Regex> = LazyLock::new(|| {
    Regex::new(r#"(?-u:\s*)[\[\(](?-u:\s*)"((?-u:\d{4})(?:[-\x{2013}](?-u:\d{4}))?)"(?-u:\s*)[\]\)](?-u:\s*)\.?(?-u:\s*)$"#).unwrap()
});

/// Java IMPRINT_YEAR_KEYWORD (StripAndStash.java:182-184):
/// `\s*\(\s*(?:imprint|not)\s+(\d{4}(?:[-–]\d{4})?)\s*\)\s*\.?\s*$`,
/// `Pattern.CASE_INSENSITIVE`. Same embedded-non-ASCII-literal situation as
/// `IMPRINT_YEAR_QUOTED` above (the `[-\x{2013}]` en-dash alternative) -> atom-only `\s`/`\d`
/// scoping, `[-\x{2013}]` left outside any `(?-u:…)` group.
static IMPRINT_YEAR_KEYWORD: LazyLock<Regex> = LazyLock::new(|| {
    Regex::new(r"(?i)(?-u:\s*)\((?-u:\s*)(?:imprint|not)(?-u:\s+)((?-u:\d{4})(?:[-\x{2013}](?-u:\d{4}))?)(?-u:\s*)\)(?-u:\s*)\.?(?-u:\s*)$")
        .unwrap()
});

/// Java IMPRINT_YEAR_ALT (StripAndStash.java:185-186): `\s+&\s+(\d{4})\s*\.?\s*$`, no
/// flags. Has `\s`/`\d`, no `\p{...}`, no unescaped wildcard -> whole-wrap.
static IMPRINT_YEAR_ALT: LazyLock<Regex> =
    LazyLock::new(|| Regex::new(r"(?-u:\s+&\s+(\d{4})\s*\.?\s*)$").unwrap());

/// Java `StripAndStash.stripImprintYears` (StripAndStash.java:770-808). By definition the
/// imprint year is a SECONDARY year cited alongside the publication year:
///   `"Storr, 1970 [\"1969\"]"`      -> `pending_imprint_year = "1969"` (quoted, always strips)
///   `"Storr, 1970 (imprint 1969)"`  -> `pending_imprint_year = "1969"` (explicit keyword, always strips)
///   `"Wagener, 1959 & 1961"`        -> `pending_imprint_year = "1961"` (bare "& YYYY", only
///                                      when another 4-digit year appears earlier)
/// All three spot-checked against the Java CLI oracle's `combinationAuthorship.imprintYear`.
/// The three checks run SEQUENTIALLY, each against the (possibly already-shortened) result
/// of the previous one — not all three against the original string.
fn strip_imprint_years(ctx: &mut ParseContext, mut s: String) -> String {
    if let Some(caps) = IMPRINT_YEAR_QUOTED.captures(&s) {
        let whole = caps.get(0).unwrap();
        ctx.set_pending_imprint_year(&caps[1]);
        s = java_trim(&s[..whole.start()]).to_string();
    }
    if let Some(caps) = IMPRINT_YEAR_KEYWORD.captures(&s) {
        let whole = caps.get(0).unwrap();
        ctx.set_pending_imprint_year(&caps[1]);
        s = java_trim(&s[..whole.start()]).to_string();
    }
    if let Some(caps) = IMPRINT_YEAR_ALT.captures(&s) {
        let whole = caps.get(0).unwrap();
        if has_earlier_year(&s, whole.start()) {
            ctx.set_pending_imprint_year(&caps[1]);
            s = java_trim(&s[..whole.start()]).to_string();
        }
    }
    s
}

// ---- Step 11: stripNullBetweenEpithets ----

/// Java NULL_EPITHET_TEST (StripAndStash.java:324-325): `.*[a-z]\s+null\s+[a-z]+.*`, no
/// flags. Has `\s` (x2), no `\p{...}`, unescaped wildcard `.*` bookends -> only `\s`
/// ASCII-scoped. `.matches()` on `.*CORE.*` -> restructured to core-only `is_match`.
static NULL_EPITHET_TEST: LazyLock<Regex> =
    LazyLock::new(|| Regex::new(r"[a-z](?-u:\s+)null(?-u:\s+)[a-z]+").unwrap());

/// Java NULL_EPITHET_MID (StripAndStash.java:326-327): `(?<=[a-z])\s+null\s+(?=[a-z])`, no
/// flags (ASCII-only `\s` in Java). Lookbehind AND lookahead (both flanking letters are
/// zero-width, not consumed) -> `fancy_regex`, same adjacency-preserving reasoning as
/// `GREEK_MARKER`/`STAR_MARKER` above (a chain like "a null b null c" needs the shared
/// letter 'b' available to both matches). Same `fancy_regex`-has-no-ASCII-mode constraint
/// as `GREEK_MARKER` -> `\s` spelled out as the literal ASCII whitespace set rather than
/// `(?-u:…)`-scoped.
static NULL_EPITHET_MID: LazyLock<FancyRegex> = LazyLock::new(|| {
    FancyRegex::new(r"(?<=[a-z])[ \t\n\x0B\f\r]+null[ \t\n\x0B\f\r]+(?=[a-z])").unwrap()
});

/// Java `StripAndStash.stripNullBetweenEpithets` (StripAndStash.java:810-821). A bare
/// "null" between two lowercase epithets ("Austrorhynchus pectatus null pectatus") is a
/// data-quality artefact — dropped, flagging doubtful + `NULL_EPITHET` (spot-checked
/// against the Java CLI oracle). A single "null" epithet followed by an author span
/// ("Abies null Hood") is NOT touched here — left for `Assemble::flagBlacklistedEpithets`.
fn strip_null_between_epithets(ctx: &mut ParseContext, s: String) -> String {
    if NULL_EPITHET_TEST.is_match(&s) {
        let s = fancy_replace_all(&NULL_EPITHET_MID, &s, |_| " ".to_string());
        ctx.name.doubtful = true;
        ctx.name.add_warning(warnings::NULL_EPITHET);
        return s;
    }
    s
}

// ---- Step 12: normaliseHyphens (structural — no Pattern) ----

/// Java `StripAndStash.normaliseHyphens` (StripAndStash.java:823-837). Normalises Unicode
/// hyphen variants (U+2010 HYPHEN, U+2011 NON-BREAKING HYPHEN, U+2012 FIGURE DASH, U+2013 EN
/// DASH, U+2014 EM DASH) to ASCII '-' so downstream tokenisation and canonical output use a
/// consistent character, flagging `HOMOGLYHPS` (spot-checked against the Java CLI oracle:
/// "Aus bus\u{2010}fer Mill." -> `specificEpithet="bus-fer"`, warning "homoglyphs
/// replaced") when anything actually changed.
fn normalise_hyphens(ctx: &mut ParseContext, s: String) -> String {
    let before = s.clone();
    let s = s.replace(
        ['\u{2010}', '\u{2011}', '\u{2012}', '\u{2013}', '\u{2014}'],
        "-",
    );
    if s != before {
        ctx.name.add_warning(warnings::HOMOGLYHPS);
    }
    // A numeral epithet written with a dot for its hyphen ("Rhynchophorus 13.punctatus Herbst",
    // "Curculio 4.maculatus Villers"), which split into a number and an author.
    DOTTED_NUMERAL_EPITHET
        .replace_all(&s, "$1$2-$3$4")
        .into_owned()
}

/// A one- or two-digit number, a dot and a lower-case word: [`normalise_hyphens`].
static DOTTED_NUMERAL_EPITHET: LazyLock<Regex> =
    LazyLock::new(|| Regex::new(r"(\s)(\d{1,2})\.(\p{Ll}{4,})(\s|$)").unwrap());

// ---- Step 13: replaceHomoglyphs ----

/// Java `StripAndStash.replaceHomoglyphs` (StripAndStash.java:839-854):
/// ```java
/// if (UnicodeUtils.containsHomoglyphs(s)) {
///   String repl = UnicodeUtils.replaceHomoglyphs(s, false);
///   if (!repl.equals(s)) {
///     ctx.name.addWarning(Warnings.HOMOGLYHPS);
///     s = repl;
///   }
/// }
/// ```
/// Delegates to [`crate::unicode::contains_homoglyphs`]/[`crate::unicode::replace_homoglyphs`]
/// — the full codepoint -> canonical-char table port (`UnicodeUtils.java:58-139`'s
/// `~175`-line `unicode/homoglyphs.txt` loader; see that module's own doc comment for the
/// loader/table details) — flagging `HOMOGLYHPS` only when the string actually changed.
/// `inclHyphens=false` at this (the table's only) call site: Unicode hyphen variants are
/// already normalised to ASCII by the immediately-preceding `normalise_hyphens` (step 12),
/// per Java's own comment on this method ("Hyphen homoglyphs are intentionally excluded —
/// those are normalised above already"). Both the outer `contains_homoglyphs` fast-path
/// check and the inner `repl != s` re-check are redundant in the overwhelmingly common case
/// (a table hit always changes the string, since no row's canonical ever equals one of its
/// own look-alikes) but ported verbatim anyway, mirroring Java's exact structure.
fn replace_homoglyphs(ctx: &mut ParseContext, s: String) -> String {
    let s = match OCR_ZERO.replace_all(&s, "${1}O${2}${3}") {
        Cow::Owned(repl) => {
            ctx.name.add_warning(warnings::HOMOGLYHPS);
            repl
        }
        Cow::Borrowed(_) => s,
    };
    if crate::unicode::contains_homoglyphs(&s) {
        let repl = crate::unicode::replace_homoglyphs(&s);
        if repl != s {
            ctx.name.add_warning(warnings::HOMOGLYHPS);
            return repl;
        }
    }
    s
}

/// A zero scanned for the capital O that opens a word of lower-case letters: "Phyllodoce mucosa
/// 0ersted, 1843", "Attelabus 0l.", "Acrobothrium 0lsson 1872". Rust-only: Java dropped the zero
/// and kept "ersted". Codes that carry more digits stay ("Anabaena sp. 0tu39s7", "Shewanella sp.
/// 0m-11").
static OCR_ZERO: LazyLock<Regex> =
    LazyLock::new(|| Regex::new(r"(^|[\s(\[,&])0(\p{Ll}+)([\s.,;)\]]|$)").unwrap());

/// A genus with its author glued on by a hyphen, and nothing but the year after it: "Ambrysus-Stål,
/// 1862", "Leptocysta-Stal, 1873", "Vesperides-Coues 1875". Rust-only: Java read one genus
/// "Ambrysus-Stål" with a year and no author. Only on the name string — in an authorship the same
/// shape is a hyphenated surname ("Saint-Hilaire, 1830").
static HYPHEN_GLUED_AUTHOR: LazyLock<Regex> = LazyLock::new(|| {
    Regex::new(r"^(\p{Lu}\p{Ll}+)-(\p{Lu}[\p{L}'.]*,?(?-u:\s+)\(?(?-u:\d{4})\)?)$").unwrap()
});

fn split_hyphen_glued_author(_ctx: &mut ParseContext, s: String) -> String {
    let s = HYPHEN_GLUED_AUTHOR.replace(&s, "$1 $2");
    DASH_BEFORE_EPITHET.replace(&s, "$1 $2").into_owned()
}

/// A dash in front of the species epithet: "Abryna -petri Paiva, 1860", "Allotheronia -guttata
/// Ashm." (61 ChecklistBank names). Dropped, as a dash after the epithet ("Abryna petri- Paiva")
/// always was. Rust-only: Java read the epithet as an author ("petri Paiva").
static DASH_BEFORE_EPITHET: LazyLock<Regex> =
    LazyLock::new(|| Regex::new(r"^(\p{Lu}\p{Ll}+)(?-u:\s+)-(\p{Ll})").unwrap());
// ---- Step 14: repairWin1252Artefacts (structural — no Pattern; shared w/ stripAuthorshipMarkers) ----

/// Java `StripAndStash.repairWin1252Artefacts(ParsedName, String)`
/// (StripAndStash.java:856-876). Win-1252 -> UTF-8 transcription artefacts the homoglyph
/// table doesn't cover (e.g. "Plesn¡k" should read as "Plesnik") — maps a small set of
/// high-bit punctuation characters to their Latin look-alikes, flagging `HOMOGLYHPS` when
/// anything changed (spot-checked against the Java CLI oracle: "Aus bus Plesn¡k, 1900" ->
/// `authors=["Plesnik"]`, warning "homoglyphs replaced"). Java's real signature takes
/// `ParsedName` directly (shared with the `stripAuthorshipMarkers` auxiliary-authorship
/// path, ported below as `strip_authorship_markers`) — ported with that same signature here
/// (`_name` suffix) so that call site can reuse it directly, which it does;
/// `repair_win1252_artefacts` below is the uniform `(ctx, s)`-shaped wrapper `run`'s
/// dispatcher needs.
fn repair_win1252_artefacts_name(name: &mut ParsedName, s: String) -> String {
    if s.contains('\u{00A1}')
        || s.contains('\u{00A2}')
        || s.contains('\u{00A3}')
        || s.contains('\u{201A}')
        || s.contains('\u{201E}')
        || s.contains('\u{2030}')
    {
        let before = s.clone();
        let s = s
            .replace('\u{00A1}', "i")
            .replace('\u{00A2}', "c")
            .replace('\u{00A3}', "L")
            .replace('\u{201A}', "e")
            .replace('\u{201E}', "a")
            .replace('\u{2030}', "e");
        if s != before {
            name.add_warning(warnings::HOMOGLYHPS);
        }
        s
    } else {
        s
    }
}

fn repair_win1252_artefacts(ctx: &mut ParseContext, s: String) -> String {
    repair_win1252_artefacts_name(&mut ctx.name, s)
}

/// A letter, a colon and one digit coding its diacritic, as some bryophyte sources write authors
/// (8.6k ChecklistBank authorships): "C. Mu:2ller" (Müller), "A:1ngstro:2m" (Ångström), "The:4riot"
/// (Thériot), "Podpe:3ra" (Podpěra), "Mun:6oz" (Muñoz), "Corbie:9re" (Corbière). Java read the
/// colon as a sanctioning author's. Rust-only.
static COLON_DIACRITIC: LazyLock<Regex> =
    LazyLock::new(|| Regex::new(r"[A-Za-z]:[123469]").unwrap());

/// Restores the letters [`COLON_DIACRITIC`] codes, flagging `HOMOGLYHPS`. A code followed by
/// another digit ("DOI:10", "names:864424") or one that makes no precomposed letter stays. The
/// first step on either string: coded, a lone author looks like a strain code ("A:1ngstro:2m").
fn repair_colon_diacritics(ctx: &mut ParseContext, s: String) -> String {
    if !COLON_DIACRITIC.is_match(&s) {
        return s;
    }
    let mut out = String::with_capacity(s.len());
    let mut last = 0;
    for m in COLON_DIACRITIC.find_iter(&s) {
        if s[m.end()..].starts_with(|c: char| c.is_ascii_digit()) {
            continue;
        }
        let letter = &m.as_str()[..1];
        let mark = match &m.as_str()[2..] {
            "1" => '\u{030A}',
            "2" => '\u{0308}',
            "3" => '\u{030C}',
            "4" => '\u{0301}',
            "6" => '\u{0303}',
            _ => '\u{0300}',
        };
        let composed: String = format!("{letter}{mark}").nfc().collect();
        if composed.chars().count() == 1 {
            out.push_str(&s[last..m.start()]);
            out.push_str(&composed);
            last = m.end();
        }
    }
    if last == 0 {
        return s;
    }
    out.push_str(&s[last..]);
    ctx.name.add_warning(warnings::HOMOGLYHPS);
    ctx.coded_diacritics = true;
    out
}

// ---- Step 15: normaliseDoubleUnderscores ----

/// Java DOUBLE_UNDERSCORE (StripAndStash.java:328): `_{2,}`, no flags, no shorthand atoms
/// at all -> nothing to scope, ported verbatim.
static DOUBLE_UNDERSCORE: LazyLock<Regex> = LazyLock::new(|| Regex::new(r"_{2,}").unwrap());

/// Java `StripAndStash.normaliseDoubleUnderscores` (StripAndStash.java:878-885). Runs of 2+
/// underscores between letters ("Pseudocercospora__dendrobii") collapse to a single space
/// (spot-checked against the Java CLI oracle: parses clean as genus=Pseudocercospora,
/// specificEpithet=dendrobii, no warning — Java's method itself never calls `addWarning`).
fn normalise_double_underscores(_ctx: &mut ParseContext, s: String) -> String {
    if s.contains("__") {
        java_trim(&DOUBLE_UNDERSCORE.replace_all(&s, " ")).to_string()
    } else {
        s
    }
}

// ---- Step 16: stashTrailingOtuCode ----

/// Java TRAILING_OTU_CODE (StripAndStash.java:187-188): `\s+([A-Z0-9]{3,}_\d{3,})$`, no
/// flags. Has `\s`/`\d` (the `[A-Z0-9]` range is explicit, unaffected either way) -> whole
/// pattern ASCII-scoped (`$` left outside the wrap, per convention).
static TRAILING_OTU_CODE: LazyLock<Regex> =
    LazyLock::new(|| Regex::new(r"(?-u:\s+([A-Z0-9]{3,}_\d{3,}))$").unwrap());

/// Java `StripAndStash.stashTrailingOtuCode` (StripAndStash.java:887-898). Strips a
/// trailing OTU-code identifier ("Oxalis barrelieri XXZ_21243") into
/// `ctx.pending_unparsed` (first-writer-wins) so the name portion still parses normally —
/// spot-checked against the Java CLI oracle (`unparsed="XXZ_21243"`).
fn stash_trailing_otu_code(ctx: &mut ParseContext, s: String) -> String {
    if s.contains(' ') && ctx.pending_unparsed.is_none() {
        if let Some(caps) = TRAILING_OTU_CODE.captures(&s) {
            let code = caps.get(1).unwrap().as_str().to_string();
            let whole = caps.get(0).unwrap();
            let prefix = java_trim(&s[..whole.start()]).to_string();
            ctx.set_pending_unparsed(&code);
            // Mark it a specimen tag, not an unparsable remainder: Assemble folds it back onto
            // the phrase if the name turns out to be an indet informal. The `is_none()` guard
            // above means this write always took, so the flag cannot mislabel someone else's.
            ctx.pending_unparsed_trailing_tag = true;
            return prefix;
        }
    }
    s
}

// ---- Step 17: stripSerovarSerotype ----

/// Java SEROVAR_TEST (StripAndStash.java:349-350): `.*\b(?:serotype|serovar)\b.*`,
/// `Pattern.CASE_INSENSITIVE`. Has `\b` (x2), unescaped wildcard `.*` bookends -> only `\b`
/// ASCII-scoped. `.matches()` on `.*CORE.*` -> restructured to core-only `is_match`.
static SEROVAR_TEST: LazyLock<Regex> =
    LazyLock::new(|| Regex::new(r"(?i)(?-u:\b)(?:serotype|serovar)(?-u:\b)").unwrap());

/// Java SEROVAR_PAREN (StripAndStash.java:189-191):
/// `\s*\(\s*(?:serotype|serovar)\s+[^)]+\)\s*\.?\s*$`, `Pattern.CASE_INSENSITIVE`. Has `\s`
/// (ASCII-scoped individually) and a custom negated class `[^)]` — NOT a predefined
/// shorthand class, so Java's `UNICODE_CHARACTER_CLASS`/ASCII distinction never applies to
/// it at all (it always matches "any code point but `)`" in Java, flag or no flag) and it
/// must stay OUTSIDE any `(?-u:…)` scoping. (`[^)]` inside `(?-u:…)` also happens to be
/// independently rejected by `regex-syntax` — "pattern can match invalid UTF-8", since a
/// negated class in byte/ASCII mode could match a lone continuation byte of a multi-byte
/// UTF-8 sequence — discovered when this pattern was first run, not anticipated from the
/// flag rule alone; leaving `[^)]` unscoped, as Java semantics require anyway, sidesteps
/// that too.) So: atom-only `\s` scoping, not the whole-pattern-wrap this port's rule would
/// otherwise prefer for a `\p{...}`-free, wildcard-free pattern.
static SEROVAR_PAREN: LazyLock<Regex> = LazyLock::new(|| {
    Regex::new(
        r"(?i)(?-u:\s*)\((?-u:\s*)(?:serotype|serovar)(?-u:\s+)[^)]+\)(?-u:\s*)\.?(?-u:\s*)$",
    )
    .unwrap()
});

/// Java SEROVAR_BARE (StripAndStash.java:192-194):
/// `\s+(?:serotype|serovar)\s+\S+(?:\s+(?:str\.?|strain)\s+\S+)?\s*\.?\s*$`,
/// `Pattern.CASE_INSENSITIVE`. Has `\s` (ASCII-scoped individually) and `\S`, the NEGATION
/// of the predefined `\s` shorthand. Unlike positive `\s`/`\d`/`\w`, a negated predefined
/// class (`\S`/`\D`/`\W`) genuinely can't be `(?-u:…)`-scoped in the `regex` crate at all —
/// same "matches invalid UTF-8" rejection as a negated custom class (see `SEROVAR_PAREN`
/// above). Fix: spell out Java's ASCII `\S` as its literal definition, NEGATED as an
/// ordinary (Unicode-default-scope) custom class — `[^\t\n\x0B\f\r ]` — which is exactly
/// "any code point that isn't one of these 6 ASCII whitespace chars", identical to what
/// Java's ASCII `\S` matches over full Unicode text; no `(?-u:…)` needed or wanted for it.
static SEROVAR_BARE: LazyLock<Regex> = LazyLock::new(|| {
    Regex::new(
        r"(?i)(?-u:\s+)(?:serotype|serovar)(?-u:\s+)[^\t\n\x0B\f\r ]+(?:(?-u:\s+)(?:str\.?|strain)(?-u:\s+)[^\t\n\x0B\f\r ]+)?(?-u:\s*)\.?(?-u:\s*)$",
    )
    .unwrap()
});

/// Java `StripAndStash.stripSerovarSerotype` (StripAndStash.java:900-921). Bacterial
/// serovar/serotype/strain annotations on a binomial are sub-species-level epidemiological
/// designators, not formal taxonomic ranks — stripped silently so the underlying binomial
/// parses cleanly, e.g. "Leptospira interrogans serovar Fugis" -> "Leptospira interrogans",
/// "Aggregatibacter actinomycetemcomitans serotype d str. SA508" ->
/// "Aggregatibacter actinomycetemcomitans" (both spot-checked against the Java CLI oracle:
/// clean binomials, no warnings). `SEROVAR_PAREN` and `SEROVAR_BARE` both run in sequence
/// (not else-if), the second against the (possibly already-shortened) result of the first.
fn strip_serovar_serotype(_ctx: &mut ParseContext, mut s: String) -> String {
    if SEROVAR_TEST.is_match(&s) {
        if let Some(m) = SEROVAR_PAREN.find(&s) {
            s = java_trim(&s[..m.start()]).to_string();
        }
        if let Some(m) = SEROVAR_BARE.find(&s) {
            s = java_trim(&s[..m.start()]).to_string();
        }
    }
    s
}

// ---- Step 18: stripAngleBracketAuthorship ----

/// Java ANGLE_BRACKET_AUTHORSHIP (StripAndStash.java:195-197):
/// `\s+<\s*(\p{Lu}[^>]*\s[^>]*)>\s*$`, `Pattern.UNICODE_CHARACTER_CLASS` -> keep default
/// Unicode, ported verbatim.
static ANGLE_BRACKET_AUTHORSHIP: LazyLock<Regex> =
    LazyLock::new(|| Regex::new(r"\s+<\s*(\p{Lu}[^>]*\s[^>]*)>\s*$").unwrap());

/// Java `StripAndStash.stripAngleBracketAuthorship` (StripAndStash.java:923-938). An
/// angle-bracketed authorship placeholder ("Doradidae <Unspecified Agent>") — the
/// bracketed text starts with a capital and contains spaces (i.e. isn't an HTML tag) — is
/// stripped, flagging `AUTHORSHIP_REMOVED` + `UNUSUAL_CHARACTERS` and marking doubtful so
/// callers know the authorship couldn't be parsed (spot-checked against the Java CLI
/// oracle: `uninomial="Doradidae"`, `doubtful=true`,
/// `warnings=["authorship placeholder removed","unusual characters"]`).
fn strip_angle_bracket_authorship(ctx: &mut ParseContext, s: String) -> String {
    if s.contains('<') {
        if let Some(m) = ANGLE_BRACKET_AUTHORSHIP.find(&s) {
            ctx.name.add_warning(warnings::AUTHORSHIP_REMOVED);
            ctx.name.add_warning(warnings::UNUSUAL_CHARACTERS);
            ctx.name.doubtful = true;
            return java_trim(&s[..m.start()]).to_string();
        }
    }
    s
}

// ---- Step 19: stripHtml ----

/// Java HTML_TAG (StripAndStash.java:329): `<[^>]+>`, no flags, no shorthand atoms at all
/// -> nothing to scope, ported verbatim.
static HTML_TAG: LazyLock<Regex> = LazyLock::new(|| Regex::new(r"<[^>]+>").unwrap());

/// Java MULTI_SPACE (StripAndStash.java:289): `\s{2,}`, no flags. Has `\s`, no `\p{...}`
/// -> whole-wrap.
static MULTI_SPACE: LazyLock<Regex> = LazyLock::new(|| Regex::new(r"(?-u:\s{2,})").unwrap());

/// An `&amp;` entity broken by a space or missing its semicolon ("K.C.Lu & amp; Y.H.Tseng",
/// "& amp  Y.H.Tseng"), which a plain entity decode misses.
static BROKEN_AMP: LazyLock<Regex> =
    LazyLock::new(|| Regex::new(r"&(?-u:\s*)amp(?-u:\b);?").unwrap());

/// An accented-letter entity ("&eacute;", "&uuml;", "&Oslash;"), also without its semicolon as
/// sources often write it ("Fern&aacutendez", "P.J&oslashrg."), and a numeric one ("&#246;",
/// "&#x000FB;", "&#039;").
static LETTER_ENTITY: LazyLock<Regex> = LazyLock::new(|| {
    Regex::new(concat!(
        r"&(?:([A-Za-z])(acute|grave|circ|uml|tilde|ring|cedil|slash|caron)",
        r"|(szlig|aelig|AElig|oelig|OElig|eth|ETH|thorn|THORN|quot|apos)",
        r"|#([0-9]{1,6})|#[xX]([0-9A-Fa-f]{1,6}));?"
    ))
    .unwrap()
});

/// Decodes the entities [`LETTER_ENTITY`] matches; an unknown or invalid one stays as it is.
fn decode_letter_entities(s: &str) -> std::borrow::Cow<'_, str> {
    LETTER_ENTITY.replace_all(s, |c: &regex::Captures| {
        let decoded = if let (Some(letter), Some(mark)) = (c.get(1), c.get(2)) {
            let base = letter.as_str().chars().next().unwrap_or(' ');
            match (base, mark.as_str()) {
                ('o', "slash") => Some('ø'),
                ('O', "slash") => Some('Ø'),
                (_, mark) => {
                    let combining = match mark {
                        "acute" => '\u{301}',
                        "grave" => '\u{300}',
                        "circ" => '\u{302}',
                        "uml" => '\u{308}',
                        "tilde" => '\u{303}',
                        "ring" => '\u{30A}',
                        "cedil" => '\u{327}',
                        "caron" => '\u{30C}',
                        _ => '\0',
                    };
                    unicode_normalization::char::compose(base, combining)
                }
            }
        } else if let Some(name) = c.get(3) {
            match name.as_str() {
                "szlig" => Some('ß'),
                "aelig" => Some('æ'),
                "AElig" => Some('Æ'),
                "oelig" => Some('œ'),
                "OElig" => Some('Œ'),
                "eth" => Some('ð'),
                "ETH" => Some('Ð'),
                "thorn" => Some('þ'),
                "THORN" => Some('Þ'),
                "quot" => Some('"'),
                _ => Some('\''),
            }
        } else {
            let code = match (c.get(4), c.get(5)) {
                (Some(dec), _) => dec.as_str().parse::<u32>().ok(),
                (_, Some(hex)) => u32::from_str_radix(hex.as_str(), 16).ok(),
                _ => None,
            };
            code.and_then(char::from_u32).filter(|ch| !ch.is_control())
        };
        decoded.map_or_else(|| c[0].to_string(), String::from)
    })
}

/// Java `StripAndStash.stripHtml` (StripAndStash.java:940-961). Strips HTML tags (keeping
/// their text content, so "<i>sensu</i> Fabricius, 1780" becomes "sensu Fabricius, 1780"
/// and is picked up as a taxonomic note by the normal note handling downstream) and decodes
/// 4 basic HTML entities, flagging `XML_TAGS`/`HTML_ENTITIES` respectively when either
/// actually fired (both spot-checked against the Java CLI oracle). The final
/// whitespace-cleanup (collapse runs to one space + trim) always runs whenever the outer
/// `<`/`&` guard is true, even when neither replacement changed anything.
fn strip_html(ctx: &mut ParseContext, s: String) -> String {
    if s.contains('<') || s.contains('&') {
        let before_tags = s.clone();
        let mut s = HTML_TAG.replace_all(&s, "").into_owned();
        if s != before_tags {
            ctx.name.add_warning(warnings::XML_TAGS);
        }
        let before_entities = s.clone();
        s = BROKEN_AMP.replace_all(&s, "&").into_owned();
        s = decode_letter_entities(&s)
            .into_owned()
            .replace("&amp;", "&")
            .replace("&lt;", "<")
            .replace("&gt;", ">")
            .replace("&nbsp;", " ");
        if s != before_entities {
            ctx.name.add_warning(warnings::HTML_ENTITIES);
        }
        return java_trim(&MULTI_SPACE.replace_all(&s, " ")).to_string();
    }
    s
}

// ---------------------------------------------------------------------------------
// Batch 2 (steps 20-30): candidatus, cultivar Group/grex/quoted, extinct, t.infr.,
// doubtful-genus brackets, sic/corrig, synonym bracket, bracketed + bare nom-note.
// Ported (Phase 1 Slice 2, batch 2b). This batch introduced the first `Rank` variants
// beyond the Unranked/Species/Subspecies trio that existed at the time (`model::enums::Rank`
// is now the full 117-constant enumeration — see its own doc comment) — `rank`/`code` are
// shared (B) fields also written by the downstream stages, so they're not part of THIS
// slice's gate, but are set here faithfully anyway since those stages consume them.
// ---------------------------------------------------------------------------------

/// Java WHITESPACE (StripAndStash.java:288): `\s+`, no flags. Has `\s`, no `\p{...}` ->
/// whole-wrap. Distinct from batch 1's `MULTI_SPACE` (`\s{2,}`, only 2+ runs collapse) —
/// this pattern ALSO normalises a single non-space whitespace char (tab, newline, …) to a
/// plain space, which `MULTI_SPACE` alone would leave untouched. Shared by
/// `strip_extinct_dagger` (step 24), `strip_sic_and_corrig` (step 27, both the
/// SIC_WITH_COMMENT inner-squish — replacement `""`, not `" "` — and the CORRIG collapse),
/// and `normalise_nom_note` (steps 29/30).
static WHITESPACE: LazyLock<Regex> = LazyLock::new(|| Regex::new(r"(?-u:\s+)").unwrap());

/// Java's repeated `WHITESPACE.matcher(x).replaceAll(" ").trim()` idiom: collapse every
/// run of (ASCII) whitespace to a single space, then `java_trim`.
fn collapse_whitespace(s: &str) -> String {
    java_trim(&WHITESPACE.replace_all(s, " ")).to_string()
}

// ---- Step 20: stripCandidatus ----

/// Java CANDIDATUS_PREFIX (StripAndStash.java:198-199): `^["']?(?:Candidatus|Ca\.)\s+`,
/// `Pattern.CASE_INSENSITIVE`. Has `\s`, no `\p{...}`, no unescaped wildcard (only an
/// escaped `\.`) -> whole pattern ASCII-scoped (leading `^` left outside the wrap, same
/// convention as leaving a trailing `$` outside — anchors aren't `u`-sensitive either way).
static CANDIDATUS_PREFIX: LazyLock<Regex> =
    LazyLock::new(|| Regex::new(r#"(?i)^(?-u:["']?(?:Candidatus|Ca\.)\s+)"#).unwrap());

/// Java `StripAndStash.stripCandidatus` (StripAndStash.java:963-973). A leading
/// "Candidatus "/"Ca. " prefix (optionally quoted, e.g. `"Candidatus Something`) marks a
/// provisional bacterial taxon name under the *Candidatus* category: stashes
/// `candidatus = true` and `code = BACTERIAL`, and strips the prefix — plus a trailing
/// quote character, if one is present, regardless of whether it matches the leading quote
/// (Java doesn't check for a match, just presence; ported literally) — from the working
/// string.
fn strip_candidatus(ctx: &mut ParseContext, s: String) -> String {
    if let Some(m) = CANDIDATUS_PREFIX.find(&s) {
        ctx.name.candidatus = true;
        ctx.name.code = Some(NomCode::Bacterial);
        let mut rest = s[m.end()..].to_string();
        if rest.ends_with('"') || rest.ends_with('\'') {
            rest.pop();
        }
        return rest;
    }
    s
}

// ---- Step 21: normaliseHortExPlaceholder ----

/// Java CV_EX (StripAndStash.java:332): `\bcv\.(?=\s+ex\s+)`, no flags (ASCII `\s`/`\b` in
/// Java). Trailing lookahead (not consumed, so the following " ex " text survives
/// untouched for a possible later match too) -> `fancy_regex`. `fancy_regex` has no ASCII
/// mode at all -> `\s` spelled out as the literal ASCII whitespace set; `\b` is left as
/// `fancy_regex`'s only option (Unicode word-boundary), the same forced, vanishingly-rare
/// divergence documented at `STRAIN_DESIGNATION` in batch 1.
static CV_EX: LazyLock<FancyRegex> =
    LazyLock::new(|| FancyRegex::new(r"\bcv\.(?=[ \t\n\x0B\f\r]+ex[ \t\n\x0B\f\r]+)").unwrap());

/// Java HORT_EX (StripAndStash.java:308): `\bHort\.(?=\s+ex\s+)`, no flags — note the
/// literal capital "Hort" (NOT case-insensitive). Same fancy_regex/ASCII-whitespace
/// reasoning as `CV_EX`. Shared with `stripAuthorshipMarkers` (ported below as
/// `strip_authorship_markers`).
static HORT_EX: LazyLock<FancyRegex> =
    LazyLock::new(|| FancyRegex::new(r"\bHort\.(?=[ \t\n\x0B\f\r]+ex[ \t\n\x0B\f\r]+)").unwrap());

/// Java HORTUS_EX (StripAndStash.java:309): `\bhortus[a]?\b(?=\s+ex\s+)`, no flags. Same
/// fancy_regex/ASCII-whitespace reasoning as `CV_EX`. Shared with `stripAuthorshipMarkers`
/// (ported below as `strip_authorship_markers`).
static HORTUS_EX: LazyLock<FancyRegex> = LazyLock::new(|| {
    FancyRegex::new(r"\bhortus[a]?\b(?=[ \t\n\x0B\f\r]+ex[ \t\n\x0B\f\r]+)").unwrap()
});

/// Java HT_MARKER (StripAndStash.java:333): `\bht\.`, no flags. No lookaround or
/// backreference -> plain `regex` crate. Has `\b`, no `\p{...}`, no unescaped wildcard ->
/// whole-wrap.
static HT_MARKER: LazyLock<Regex> = LazyLock::new(|| Regex::new(r"(?-u:\bht\.)").unwrap());

/// Java `StripAndStash.normaliseHortExPlaceholder` (StripAndStash.java:975-988).
/// Working-string-only (no `ctx.name` mutation, no warnings): normalises every spelling
/// of the horticultural "ex" placeholder author — "cv. ex", "Hort. ex", "hortus(a) ex",
/// and the bare "ht." abbreviation — to the canonical lower-case "hort.", so the
/// downstream authorship parser recognises one consistent marker regardless of which
/// variant the source data used. Four SEQUENTIAL replacements, each against the
/// (possibly already-rewritten) result of the previous one.
fn normalise_hort_ex_placeholder(_ctx: &mut ParseContext, s: String) -> String {
    let s = fancy_replace_all(&CV_EX, &s, |_| "hort.".to_string());
    let s = fancy_replace_all(&HORT_EX, &s, |_| "hort.".to_string());
    let s = fancy_replace_all(&HORTUS_EX, &s, |_| "hort.".to_string());
    HT_MARKER.replace_all(&s, "hort.").into_owned()
}

// ---- Step 22: stripCultivarGroupGrex ----

/// Java CULTIVAR_GROUP_GREX (StripAndStash.java:200-202),
/// `Pattern.UNICODE_CHARACTER_CLASS` -> keep default Unicode, ported verbatim.
static CULTIVAR_GROUP_GREX: LazyLock<Regex> = LazyLock::new(|| {
    Regex::new(r"\s+([\p{Lu}][\p{L}]+(?:\s+[\p{Lu}][\p{L}]+)*)\s+(Group|grex|gx)\s*$").unwrap()
});

/// Java `StripAndStash.stripCultivarGroupGrex` (StripAndStash.java:990-1002). A trailing
/// "... CapWord(s) (Group|grex|gx)" names a Cultivar Group or grex rather than a single
/// cultivar: the capitalised epithet sequence becomes `cultivarEpithet`, `code` is pinned
/// to CULTIVARS, and `rank` to CULTIVAR_GROUP for the exact (case-sensitive) literal
/// "Group" or GREX for either "grex" or "gx" — matching Java's `"Group".equals(...)`
/// ternary, which folds every OTHER alternative the pattern can capture to GREX.
fn strip_cultivar_group_grex(ctx: &mut ParseContext, s: String) -> String {
    if let Some(caps) = CULTIVAR_GROUP_GREX.captures(&s) {
        ctx.name.cultivar_epithet = Some(java_trim(caps.get(1).unwrap().as_str()).to_string());
        ctx.name.code = Some(NomCode::Cultivars);
        ctx.name.rank = if caps.get(2).unwrap().as_str() == "Group" {
            Rank::CultivarGroup
        } else {
            Rank::Grex
        };
        let whole = caps.get(0).unwrap();
        return java_trim(&s[..whole.start()]).to_string();
    }
    s
}

// ---- Step 23: stripQuotedCultivar ----

/// Java QUOTED_CULTIVAR_END (StripAndStash.java:203-204):
/// `\s+(cv\.?\s+)?(['"])([^'"]+)\2\s*$`, no flags (ASCII `\s` in Java). BACKREFERENCE
/// (`\2`, the closing quote must match the opening one) -> `fancy_regex`. `[^'"]` is a
/// NEGATED custom class; Java's `UNICODE_CHARACTER_CLASS` flag never governs a
/// literal/custom class anyway, and `fancy_regex` (always Unicode text, no byte/ASCII
/// mode) has no analogous "matches invalid UTF-8" restriction to worry about here either
/// way. `fancy_regex` has no ASCII mode for `\s` -> spelled out as the literal ASCII
/// whitespace set. Group 1 = optional "cv. " prefix, group 2 = quote char, group 3 =
/// cultivar epithet content.
static QUOTED_CULTIVAR_END: LazyLock<FancyRegex> = LazyLock::new(|| {
    FancyRegex::new(r#"[ \t\n\x0B\f\r]+(cv\.?[ \t\n\x0B\f\r]+)?(['"])([^'"]+)\2[ \t\n\x0B\f\r]*$"#)
        .unwrap()
});

/// Java RANK_MARKER_SUFFIX (StripAndStash.java:336-337):
/// `.*\b(?:sp|spec|subsp|ssp|var|form|f)\.?$`, no flags, called via `.matches()`.
/// RESTRUCTURED: under `.matches()` the leading `.*` imposes no real constraint (it can
/// always stretch to cover whatever precedes the `$`-anchored suffix), so an unanchored
/// `is_match` on the suffix alone is existence-equivalent — the same class of
/// restructuring as the `.*CORE.*` -> `CORE` cases elsewhere in this file, just one-sided.
/// Has `\b`, no `\p{...}`, and (after dropping the leading `.*`) no remaining unescaped
/// wildcard -> whole-wrap (`$` left outside per convention).
static RANK_MARKER_SUFFIX: LazyLock<Regex> =
    LazyLock::new(|| Regex::new(r"(?-u:\b(?:sp|spec|subsp|ssp|var|form|f)\.?)$").unwrap());

/// Java QUOTED_CULTIVAR_MID (StripAndStash.java:205-207):
/// `\s+(?:cv\.?\s+)?(['"])([^'"]+)\1(\s+[\p{Lu}].*)$`, `Pattern.UNICODE_CHARACTER_CLASS`
/// -> keep default Unicode `\s` (fancy_regex's own default, so no ASCII spelling-out
/// needed here, unlike `QUOTED_CULTIVAR_END`). BACKREFERENCE (`\1`) -> `fancy_regex`.
/// Group 1 = quote char, group 2 = cultivar epithet content, group 3 = the trailing
/// author span (kept verbatim for splicing back onto the name part). Rust-only: the author may
/// start with a particle behind a capitalised epithet ("Acer saccharinum L. cv. 'Asplenifolium' de
/// Bie"), groups 4 to 6 then; a quoted lower-case word before one is no cultivar (`Haplochromis
/// "black" van Oijen, 1982`, a fish).
static QUOTED_CULTIVAR_MID: LazyLock<FancyRegex> = LazyLock::new(|| {
    FancyRegex::new(concat!(
        r#"\s+(?:cv\.?\s+)?(['"])([^'"]+)\1(\s+[\p{Lu}].*)$"#,
        r#"|\s+(?:cv\.?\s+)?(['"])(\p{Lu}[^'"]*)\4(\s+(?:(?:de|den|der|van|von|du|da|dos|la|le|ten|ter|zu|zur)\s+){1,2}[\p{Lu}].*)$"#,
    ))
    .unwrap()
});

/// Java AUTHOR_START (StripAndStash.java:283-285):
/// `^([\p{Lu}][\p{Ll}]+(?:\s+[\p{Ll}]+)?)\s+([\p{Lu}][\p{L}.]+.*)$`,
/// `Pattern.UNICODE_CHARACTER_CLASS` -> keep default Unicode, ported verbatim (no
/// backreference, no lookaround -> plain `regex` crate). Rust-only: the epithet may carry a
/// hybrid sign ("Symphoricarpos x chenaultii Rehder cv. 'Erect' Door. ex Koppeschaar").
static AUTHOR_START: LazyLock<Regex> = LazyLock::new(|| {
    Regex::new(r"^([\p{Lu}][\p{Ll}]+(?:\s+(?:[×x]\s?)?[\p{Ll}]+)?)\s+([\p{Lu}][\p{L}.]+.*)$")
        .unwrap()
});

/// Java `StripAndStash.findAuthorStart` (StripAndStash.java:1650-1657): the byte offset of
/// group 2 (the author span) within a "Genus[ species] Author..." prefix, or `None` when
/// the prefix doesn't have that shape (Java: `int`, -1 sentinel). The pattern's own `^…$`
/// anchors make `.captures()` here equivalent to Java's `.matches()`. Shared, in Java
/// itself, by TWO call sites: `stripQuotedCultivar` (this batch, 2b, StripAndStash.java:
/// 1035) and `stashPhraseName` (step 55, batch 2e, StripAndStash.java:1609) — ported once
/// here and reused by both, matching Java's own one-method-two-callers shape.
fn find_author_start(prefix: &str) -> Option<usize> {
    AUTHOR_START
        .captures(prefix)
        .map(|caps| caps.get(2).unwrap().start())
}

/// Java QUOTED_CULTIVAR_OPEN (StripAndStash.java:217-219):
/// `\s+(cv\.?\s+)?(['"])(\p{Ll}[\p{Ll} ]*)\s*$`, `Pattern.UNICODE_CHARACTER_CLASS` -> keep
/// default Unicode. No backreference (this is the UNCLOSED-quote fallback: content runs to
/// end of string, no closing quote required) and no lookaround -> plain `regex` crate.
/// Group 1 = optional "cv. " prefix, group 2 = quote char, group 3 = epithet content
/// (lowercase letters/spaces only, so this never swallows a capitalised or
/// punctuation-carrying apostrophe-author).
static QUOTED_CULTIVAR_OPEN: LazyLock<Regex> =
    LazyLock::new(|| Regex::new(r#"\s+(cv\.?\s+)?(['"])(\p{Ll}[\p{Ll} ]*)\s*$"#).unwrap());

/// Java TRAILING_CV (StripAndStash.java:334): `\s+cv\.?\s*$`, no flags. Has `\s` (x2), no
/// `\p{...}`, no unescaped wildcard -> whole-wrap (`$` left outside).
static TRAILING_CV: LazyLock<Regex> = LazyLock::new(|| Regex::new(r"(?-u:\s+cv\.?\s*)$").unwrap());

/// Java CV_MARKER (StripAndStash.java:335): `\s+cv\.?(?=\s|$)`, no flags (ASCII `\s`).
/// Trailing lookahead (boundary not consumed) -> `fancy_regex`, ASCII whitespace spelled
/// out (no ASCII mode in `fancy_regex`).
static CV_MARKER: LazyLock<FancyRegex> =
    LazyLock::new(|| FancyRegex::new(r"[ \t\n\x0B\f\r]+cv\.?(?=[ \t\n\x0B\f\r]|$)").unwrap());

/// An upper-case "CF"/"AFF" qualifier after the genus or an epithet, before an epithet or the end:
/// "Diodora dorsata CF", "Diodora CF dorsata". Group 1 = the name before it, 2 = the qualifier, 3 =
/// what follows.
static SHOUTED_QUALIFIER: LazyLock<Regex> = LazyLock::new(|| {
    Regex::new(r"^(\p{Lu}\p{Ll}+(?:\s+\p{Ll}+)?\s+)(CF|AFF)\.?(\s+\p{Ll}.*|\s*)$").unwrap()
});

/// Lower-cases a [`SHOUTED_QUALIFIER`], which was read as an author "Cf" — not after an indet marker,
/// where it is a strain code ("Bacillus sp. CF"), nor among authors' initials ("Dubois, CF 1839").
fn lower_shouted_qualifier(s: String) -> String {
    match SHOUTED_QUALIFIER.captures(&s) {
        Some(c)
            if !c[1]
                .split_whitespace()
                .any(|w| matches!(w, "sp" | "spp" | "spec")) =>
        {
            format!("{}{}.{}", &c[1], c[2].to_lowercase(), &c[3])
        }
        _ => s,
    }
}

/// An infraspecific rank marker with "n." (nova) before its epithet: "Acidalia remutaria ab. n.
/// undularia", "Abies alba var. n. alpina". Group 1 = the marker, group 2 = the epithet.
static RANK_NOVA: LazyLock<Regex> = LazyLock::new(|| {
    Regex::new(r"\s(ab|var|f|forma|subsp|ssp|morpha)\.\s+n\.\s+(\p{Ll}{3,})(\s|$)").unwrap()
});

/// Moves a [`RANK_NOVA`]'s "n." into the nomenclatural note as "ab. n."; Java read "n" as the
/// epithet and the real one as an author.
fn strip_rank_nova(ctx: &mut ParseContext, s: String) -> String {
    let Some(caps) = RANK_NOVA.captures(&s) else {
        return s;
    };
    ctx.name
        .add_nomenclatural_note(&format!("{}. n.", &caps[1]));
    RANK_NOVA.replace(&s, " $1. $2$3").into_owned()
}

/// A double-quoted author between the epithet and the authorship (`Verpericola megasoma "Dall"
/// Pils.`, `Vespa anglica "Leach" Sm., 1843`, `Limea bengalensis "Stuardo, 1968" Huber, 2010`):
/// group 1 = the name, group 2 = the quoted author, group 3 = its year, group 4 = the authorship.
static QUOTED_ATTRIBUTED_AUTHOR: LazyLock<Regex> = LazyLock::new(|| {
    Regex::new(
        r#"^(\p{Lu}\p{Ll}+(?:\s+\(\p{Lu}\p{Ll}+\))?\s+\p{Ll}[\p{Ll}-]+(?:\s+\p{Ll}[\p{Ll}-]+)?)\s+"+(\p{Lu}[\p{L}.'\-]*(?:\s\p{Lu}[\p{L}.'\-]*)?)(,?\s+\d{4})?"\s+(\p{Lu}.*)$"#,
    )
    .unwrap()
});

/// The [`QUOTED_ATTRIBUTED_AUTHOR`] is the author of the manuscript name, the one after it
/// published it, as malacologists write it — no cultivar, which Java made it ("a land snail").
/// Rewritten as the "Dall MS, Pils." that the authorship parser reads as an ex citation casting no
/// botanical vote. Its own year goes; the name's is the publishing author's. Not after an indet
/// marker ('Phytophthora species "Tokoroa" McAlonan' is a provisional name).
fn strip_quoted_attributed_author(s: String) -> String {
    let Some(caps) = QUOTED_ATTRIBUTED_AUTHOR.captures(&s) else {
        return s;
    };
    let last = caps[1].split_whitespace().last().unwrap_or_default();
    if matches!(last, "sp" | "spp" | "species" | "spec") {
        return s;
    }
    format!("{} {} MS, {}", &caps[1], &caps[2], &caps[4])
}

/// [`QUOTED_ATTRIBUTED_AUTHOR`] leading a separately supplied authorship (`"Dall" Pils.`).
static AUTHORSHIP_QUOTED_ATTRIBUTED: LazyLock<Regex> = LazyLock::new(|| {
    Regex::new(r#"^"+(\p{Lu}[\p{L}.'\-]*(?:\s\p{Lu}[\p{L}.'\-]*)?)(?:,?\s+\d{4})?"\s+(\p{Lu}.*)$"#)
        .unwrap()
});

/// Java `StripAndStash.stripQuotedCultivar` (StripAndStash.java:1004-1068). A quoted
/// cultivar epithet — " 'Name'" / " \"Name\"", optionally preceded by an explicit "cv."
/// marker — becomes `cultivarEpithet` (`code = CULTIVARS`, `rank = CULTIVAR`). Three
/// shapes, tried in order (an `if`/else-if/else-if chain in Java; ported here as
/// sequential checks with early returns for the first two):
///   1. **At end of input** (`QUOTED_CULTIVAR_END`): "Acer campestre 'Elsrijk'" ->
///      cultivarEpithet "Elsrijk". Skipped when the quote is immediately preceded by a
///      bare rank marker with no explicit "cv." (`RANK_MARKER_SUFFIX` on the trimmed
///      preceding text) — that shape is a phrase name, not a cultivar.
///   2. **Mid-string, followed by an author span** (`QUOTED_CULTIVAR_MID`, tried only
///      when shape 1 didn't apply): "Acer campestre L. cv. 'Elsrijk' Broerse" ->
///      cultivarEpithet "Elsrijk", author "Broerse". Any species author preceding the
///      epithet is split off via `find_author_start` and stashed as
///      `ctx.pending_specific_author` (e.g. the "L." above) rather than left attached to
///      the binomial.
///   3. **Unclosed trailing quote** (`QUOTED_CULTIVAR_OPEN`, tried only when shapes 1 and
///      2 didn't apply): " 'albino" (opening quote, no closing one — common in
///      aquarium/horticultural trade lists), same rank-marker-prefix guard as shape 1.
///
/// All three spot-checked against the Java CLI oracle's `cultivarEpithet`/`rank`/`code`/
/// `specificAuthorship` output shape.
fn strip_quoted_cultivar(ctx: &mut ParseContext, mut s: String) -> String {
    let cm = QUOTED_CULTIVAR_END.captures(&s).ok().flatten();
    let cm_found = cm.is_some();
    let has_cv_marker = cm.as_ref().is_some_and(|c| c.get(1).is_some());
    let preceding = cm
        .as_ref()
        .map(|c| java_trim(&s[..c.get(0).unwrap().start()]).to_string());
    let is_rank_marker_prefix = !has_cv_marker
        && preceding
            .as_deref()
            .is_some_and(|p| RANK_MARKER_SUFFIX.is_match(p));
    if cm_found && !is_rank_marker_prefix {
        let caps = cm.unwrap();
        let match_start = caps.get(0).unwrap().start();
        let epithet = java_trim(caps.get(3).unwrap().as_str()).to_string();
        ctx.name.cultivar_epithet = Some(epithet);
        ctx.name.code = Some(NomCode::Cultivars);
        ctx.name.rank = Rank::Cultivar;
        s = java_trim(&s[..match_start]).to_string();
        s = java_trim(&TRAILING_CV.replace_all(&s, "")).to_string();
        return s;
    }

    if let Some(caps) = QUOTED_CULTIVAR_MID.captures(&s).ok().flatten() {
        let match_start = caps.get(0).unwrap().start();
        let group = |k: usize| caps.get(k).or_else(|| caps.get(k + 3)).unwrap().as_str();
        let epithet = java_trim(group(2)).to_string();
        let tail = group(3).to_string();
        let prefix = java_trim(&s[..match_start]).to_string();
        ctx.name.cultivar_epithet = Some(epithet);
        ctx.name.code = Some(NomCode::Cultivars);
        ctx.name.rank = Rank::Cultivar;
        let name_part = match find_author_start(&prefix) {
            Some(author_start) if author_start > 0 => {
                ctx.pending_specific_author = Some(java_trim(&prefix[author_start..]).to_string());
                java_trim(&prefix[..author_start]).to_string()
            }
            _ => prefix,
        };
        s = java_trim(&format!("{name_part}{tail}")).to_string();
        s = java_trim(&fancy_replace_all(&CV_MARKER, &s, |_| String::new())).to_string();
        return s;
    }

    if let Some(caps) = QUOTED_CULTIVAR_OPEN.captures(&s) {
        let has_cv = caps.get(1).is_some();
        let match_start = caps.get(0).unwrap().start();
        let epithet = java_trim(caps.get(3).unwrap().as_str()).to_string();
        let preceding_open = java_trim(&s[..match_start]).to_string();
        let is_rank_prefix = !has_cv && RANK_MARKER_SUFFIX.is_match(&preceding_open);
        if !is_rank_prefix {
            ctx.name.cultivar_epithet = Some(epithet);
            ctx.name.code = Some(NomCode::Cultivars);
            ctx.name.rank = Rank::Cultivar;
            s = java_trim(&s[..match_start]).to_string();
            s = java_trim(&TRAILING_CV.replace_all(&s, "")).to_string();
        }
    }
    s
}

// ---- Step 24: stripExtinctDagger ----

/// Java DAGGER (StripAndStash.java:330): `[†✝]`, no flags. A custom class holding
/// non-ASCII literals — Java's `UNICODE_CHARACTER_CLASS` flag never governs a
/// literal/custom class anyway (only predefined shorthand classes), and a non-ASCII
/// literal inside a `regex` crate `(?-u:…)` group is a hard parse error regardless (see
/// `IMPRINT_YEAR_QUOTED` in batch 1) — no shorthand atoms to scope here either, so this
/// ports verbatim with no scoping at all.
static DAGGER: LazyLock<Regex> = LazyLock::new(|| Regex::new(r"[†✝]").unwrap());

/// Java `StripAndStash.stripExtinctDagger` (StripAndStash.java:1070-1077). An extinction
/// dagger ("†" or "✝") anywhere in the string — possibly more than one — marks the taxon
/// extinct; ALL occurrences are stripped (replaced by a space, then whitespace
/// collapsed+trimmed, so e.g. "Foo †bar" doesn't leave a glued "Foobar").
fn strip_extinct_dagger(ctx: &mut ParseContext, s: String) -> String {
    if s.contains('†') || s.contains('✝') {
        ctx.name.extinct = true;
        let no_dagger = DAGGER.replace_all(&s, " ");
        return collapse_whitespace(&no_dagger);
    }
    s
}

// ---- Step 25: stripTinfrMarker ----

/// Java TINFR_MARKER (StripAndStash.java:331): `\b[tT]\.?\s*infr\.?\s+`, no flags. Has
/// `\b`/`\s` (x2), no `\p{...}`, no unescaped wildcard (dots are escaped) -> whole-wrap.
static TINFR_MARKER: LazyLock<Regex> =
    LazyLock::new(|| Regex::new(r"(?-u:\b[tT]\.?\s*infr\.?\s+)").unwrap());

/// Java `StripAndStash.stripTinfrMarker` (StripAndStash.java:1079-1087). The Hieracium
/// "t.infr." infraspecific-epithet notation (e.g. "Hieracium alpinum t.infr. foobarum")
/// is stripped so downstream tokenisation sees a plain space-separated word run instead
/// of the marker — spot-checked against the Java CLI oracle: with a genus+species BEFORE
/// the marker, the trailing word is later read as a rankless `INFRASPECIFIC_NAME`
/// epithet ("Hieracium alpinum t.infr. foobarum" -> infraspecificEpithet "foobarum");
/// with only a bare genus before it, the trailing word instead reads as an ordinary
/// specific epithet ("Hieracium t.infr. foobarum" -> specificEpithet "foobarum") — this
/// step itself does neither classification, it only removes the marker text.
fn strip_tinfr_marker(_ctx: &mut ParseContext, s: String) -> String {
    if s.contains("infr") {
        return TINFR_MARKER.replace_all(&s, "").into_owned();
    }
    s
}

// ---- Step 26: stripDoubtfulGenusBrackets ----

/// Java DOUBTFUL_GENUS_BRACKET (StripAndStash.java:220-222):
/// `^\[\s*([\p{Lu}][\p{L}\-]+)\s*\](\s|$)`, `Pattern.UNICODE_CHARACTER_CLASS` -> keep
/// default Unicode, ported verbatim.
static DOUBTFUL_GENUS_BRACKET: LazyLock<Regex> =
    LazyLock::new(|| Regex::new(r"^\[\s*([\p{Lu}][\p{L}\-]+)\s*\](\s|$)").unwrap());

/// Java `StripAndStash.stripDoubtfulGenusBrackets` (StripAndStash.java:1089-1099). A
/// leading bracketed genus ("[Acontia] chia ..." or just "[Dexia]") marks the genus
/// assignment as doubtful — the source questions whether the specimen truly belongs to
/// that genus. Drops the brackets (keeping the genus text and the single separator
/// char/end-of-string that followed them), flags doubtful + `DOUBTFUL_GENUS`.
fn strip_doubtful_genus_brackets(ctx: &mut ParseContext, s: String) -> String {
    if let Some(caps) = DOUBTFUL_GENUS_BRACKET.captures(&s) {
        ctx.name.doubtful = true;
        ctx.name.add_warning(warnings::DOUBTFUL_GENUS);
        let whole = caps.get(0).unwrap();
        let g1 = caps.get(1).unwrap().as_str();
        let g2 = caps.get(2).unwrap().as_str();
        return java_trim(&format!("{g1}{g2}{}", &s[whole.end()..])).to_string();
    }
    s
}

// ---- Step 27: stripSicAndCorrig ----

/// Java SIC_WITH_COMMENT (StripAndStash.java:32-33): `\s*[\(\[]\s*sic\s*,([^)\]]+)[\)\]]`,
/// no flags. `[^)\]]` is a NEGATED custom class -> must stay OUTSIDE any `(?-u:…)` (a
/// negated class in byte/ASCII mode could match a stray continuation byte of a multi-byte
/// UTF-8 sequence, rejected by `regex-syntax` as "pattern can match invalid UTF-8" — the
/// `SEROVAR_PAREN` precedent from batch 1) -> atom-only `\s` scoping, not the whole-wrap
/// this port's rule would otherwise prefer. No backreference, no lookaround -> plain
/// `regex` crate.
static SIC_WITH_COMMENT: LazyLock<Regex> =
    LazyLock::new(|| Regex::new(r"(?-u:\s*)[(\[](?-u:\s*)sic(?-u:\s*),([^)\]]+)[)\]]").unwrap());

/// Java SIC (StripAndStash.java:29-30): `\s*[\(\[]\s*sic\s*!?\s*[)\]]`, no flags. Has `\s`
/// (x4), no `\p{...}`, no unescaped wildcard, and the custom classes `[(\[]`/`[)\]]` are
/// POSITIVE (list specific ASCII literals, not negated) so they're safe inside a
/// `(?-u:…)` group (unlike `SIC_WITH_COMMENT`'s negated class above) -> whole-pattern
/// ASCII-scope.
static SIC: LazyLock<Regex> =
    LazyLock::new(|| Regex::new(r"(?-u:\s*[(\[]\s*sic\s*!?\s*[)\]])").unwrap());

/// Java CORRIG (StripAndStash.java:35-36):
/// `\s*[\(\[]\s*corrig\.?\s*[\)\]]|(?<=\s)corrig\.?(?=\s|$)`, no flags. The bracketed
/// alternative alone needs no lookaround, but it's OR'd with a bare alternative using
/// BOTH a lookbehind and a lookahead -> the whole pattern needs `fancy_regex`. No ASCII
/// mode in `fancy_regex` -> `\s` spelled out as the literal ASCII whitespace set. Same
/// pattern text as the Phase 0 spike (`regexes::CORRIG_FANCY`) that first identified the
/// call-site harness below — re-defined here (rather than imported) to stay
/// self-contained like every other pattern in this file, and because `regexes::SIC`/
/// `CORRIG` are NOT ASCII-scoped per this port's flag rule (they predate it), so reusing
/// them directly would introduce a `\s`-scope divergence from Java.
static CORRIG: LazyLock<FancyRegex> = LazyLock::new(|| {
    FancyRegex::new(
        r"[ \t\n\x0B\f\r]*[(\[][ \t\n\x0B\f\r]*corrig\.?[ \t\n\x0B\f\r]*[)\]]|(?<=[ \t\n\x0B\f\r])corrig\.?(?=[ \t\n\x0B\f\r]|$)",
    )
    .unwrap()
});

/// Java `StripAndStash.stripSicAndCorrig` (StripAndStash.java:1101-1124). Three
/// SEQUENTIAL checks (not else-if — each runs against the possibly-already-updated `s`,
/// and a later one can overwrite an earlier one's flag if the input somehow carries both):
///   1. `[sic, comment]` / `(sic, comment)` -> `originalSpelling = true`; the inner
///      comment (trimmed, then had ALL internal whitespace removed — not just collapsed —
///      matching Java's `WHITESPACE.replaceAll("")`, replacement `""` not `" "`) is
///      parked in `ctx.pending_unparsed` as `"(sic,<comment>)"`.
///   2. Plain `[sic]` / `(sic)` / `[sic!]` (no inner comma) -> `originalSpelling = true`.
///   3. `corrig.` / `(corrig.)` / `[corrig.]` -> `originalSpelling = false`. Applied with
///      the Java call-site harness (StripAndStash.java:1117-1121, and its twin
///      `stripAuthorshipMarkers` call at line 432): a LEADING-SPACE PAD before matching
///      (so a leading/standalone "corrig." is stripped too — `CORRIG`'s bare alternative
///      needs an actual preceding whitespace char, which the pad supplies at position 0),
///      then a whitespace-collapse + trim after removing every match — the exact lesson
///      `regexes::strip_corrig_fancy` documents at length (Phase 0).
fn strip_sic_and_corrig(ctx: &mut ParseContext, mut s: String) -> String {
    if let Some(caps) = SIC_WITH_COMMENT.captures(&s) {
        ctx.name.original_spelling = Some(true);
        let inner = java_trim(caps.get(1).unwrap().as_str()).to_string();
        let squished = WHITESPACE.replace_all(&inner, "").into_owned();
        ctx.set_pending_unparsed(&format!("(sic,{squished})"));
        let whole = caps.get(0).unwrap();
        let (start, end) = (whole.start(), whole.end());
        s = format!("{}{}", &s[..start], &s[end..]);
    }
    if let Some(m) = SIC.find(&s) {
        ctx.name.original_spelling = Some(true);
        let (start, end) = (m.start(), m.end());
        s = format!("{}{}", &s[..start], &s[end..]);
    }
    let padded = format!(" {s}");
    if let Ok(Some(_)) = CORRIG.find(&padded) {
        ctx.name.original_spelling = Some(false);
        let stripped = fancy_replace_all(&CORRIG, &padded, |_| String::new());
        s = collapse_whitespace(&stripped);
    }
    s
}

// ---- Step 28: stashSynonymBracket ----

/// Java SYNONYM_BRACKET (StripAndStash.java:117-118): `\s*\[\s*=\s*[^\]]+\]\s*\.?\s*$`, no
/// flags. `[^\]]` is a negated custom class -> must stay outside `(?-u:…)` (same reasoning
/// as `SIC_WITH_COMMENT`) -> atom-only `\s` scoping.
static SYNONYM_BRACKET: LazyLock<Regex> = LazyLock::new(|| {
    Regex::new(r"(?-u:\s*)\[(?-u:\s*)=(?-u:\s*)[^\]]+\](?-u:\s*)\.?(?-u:\s*)$").unwrap()
});

/// Java `StripAndStash.stashSynonymBracket` (StripAndStash.java:1126-1138). A trailing
/// synonymy reference in square brackets ("[= Grislea L. 1753]") is parked verbatim (with
/// surrounding whitespace trimmed) as `ctx.pending_unparsed` — first-writer-wins, so an
/// earlier strip step's stash (e.g. a trailing OTU code) takes precedence — flags
/// doubtful, and strips both the bracket AND any now-trailing comma(s) left dangling
/// before it (a `while` loop: Java strips one comma, re-trims, and repeats, UNLIKE
/// `strip_bracketed_nom_note`'s single `if`).
fn stash_synonym_bracket(ctx: &mut ParseContext, s: String) -> String {
    if let Some(m) = SYNONYM_BRACKET.find(&s) {
        let tail = java_trim(&s[m.start()..]).to_string();
        ctx.set_pending_unparsed(&tail);
        ctx.name.doubtful = true;
        let mut kept = java_trim(&s[..m.start()]).to_string();
        while kept.ends_with(',') {
            kept.pop();
            kept = java_trim(&kept).to_string();
        }
        return kept;
    }
    s
}

// ---- Shared helper: normaliseNomNote (used by steps 29 and 30) ----

/// Java ET_WORD (StripAndStash.java:290): `\bet\b`, no flags. Whole-wrap (has `\b`, no
/// `\p{...}`, no unescaped wildcard).
static ET_WORD: LazyLock<Regex> = LazyLock::new(|| Regex::new(r"(?-u:\bet\b)").unwrap());

/// Java AND_WORD (StripAndStash.java:291): `\band\b`, no flags. Whole-wrap.
static AND_WORD: LazyLock<Regex> = LazyLock::new(|| Regex::new(r"(?-u:\band\b)").unwrap());

/// Java SPACE_AROUND_DOT (StripAndStash.java:292): `\s*\.\s*`, no flags. Whole-wrap (the
/// `\.` is an escaped literal, not an unescaped wildcard).
static SPACE_AROUND_DOT: LazyLock<Regex> = LazyLock::new(|| Regex::new(r"(?-u:\s*\.\s*)").unwrap());

/// Java DOT_BEFORE_ALNUM (StripAndStash.java:293): `\.(?=[\p{L}\d])`, no flags. Trailing
/// lookahead (not consumed, so the letter/digit that follows the period survives
/// untouched, allowing a following period elsewhere to independently reuse the same
/// adjacency reasoning as `GREEK_MARKER` in batch 1) -> `fancy_regex`. `\d` is ASCII-only
/// in Java here (no `UNICODE_CHARACTER_CLASS`) -> spelled out as `[0-9]` (`fancy_regex`
/// has no ASCII mode); `\p{L}` always Unicode.
static DOT_BEFORE_ALNUM: LazyLock<FancyRegex> =
    LazyLock::new(|| FancyRegex::new(r"\.(?=[\p{L}0-9])").unwrap());

/// Java SPACE_AROUND_AMP (StripAndStash.java:294): `\s*&\s*`, no flags. Whole-wrap.
static SPACE_AROUND_AMP: LazyLock<Regex> = LazyLock::new(|| Regex::new(r"(?-u:\s*&\s*)").unwrap());

/// Java `FULL_WORD_NOM_NOTES` (StripAndStash.java:406-407): `Set.of("correct", "error")`
/// — suffix words that are complete English/Latin forms; a nomenclatural note ending in
/// one of these (lower-cased) does NOT get a trailing dot appended.
const FULL_WORD_NOM_NOTES: &[&str] = &["correct", "error"];

/// Java `StripAndStash.normaliseNomNote` (StripAndStash.java:373-402). Canonical form for
/// nomenclatural notes, shared by `strip_bracketed_nom_note` (step 29) and
/// `strip_nom_note` (step 30): collapse whitespace, normalise "et"/"and" connectives to
/// "&", ensure a single space follows every interior period, add spaces around a bare
/// "&". Abbreviated notes ("nom. nud.", "Spec nov") get a closing dot if missing;
/// spelled-out "nomen …" forms have any trailing dot(s) stripped instead (sentence
/// punctuation, not part of the abbreviation); a note ending in a complete word
/// (`FULL_WORD_NOM_NOTES`) is left without an added dot either way.
fn normalise_nom_note(raw: &str) -> String {
    let mut s = collapse_whitespace(raw);
    let et_replaced = ET_WORD.replace_all(&s, "&");
    s = AND_WORD.replace_all(&et_replaced, "&").into_owned();
    s = SPACE_AROUND_DOT.replace_all(&s, ".").into_owned();
    s = fancy_replace_all(&DOT_BEFORE_ALNUM, &s, |_| ". ".to_string());
    s = SPACE_AROUND_AMP.replace_all(&s, " & ").into_owned();
    s = java_trim(&MULTI_SPACE.replace_all(&s, " ")).to_string();
    if s.len() >= 5 && s.as_bytes()[..5].eq_ignore_ascii_case(b"nomen") {
        while s.ends_with('.') {
            s.pop();
        }
        return java_trim(&s).to_string();
    }
    if !s.is_empty() && !s.ends_with('.') {
        let last_word = match s.rfind(' ') {
            Some(idx) => &s[idx + 1..],
            None => s.as_str(),
        };
        if !FULL_WORD_NOM_NOTES.contains(&last_word.to_lowercase().as_str()) {
            s.push('.');
        }
    }
    s
}

// ---- Step 29: stripBracketedNomNote ----

/// A bracketed, quoted lower-case word ending the name after its epithet or author: the spelling
/// the name was published or also cited in (`Heterosperma depressa Griseb. ("depressum")`,
/// `Xerochlorella olmiae ('olmae')`). Group 1 = the name before it, group 2 = the quoted word.
static QUOTED_SPELLING_VARIANT: LazyLock<FancyRegex> = LazyLock::new(|| {
    FancyRegex::new(
        r#"^(\S+\s+.*?(?:\p{Ll}{2}|\.|\p{Lu}\p{Ll}*))\s*\(\s*((['"])\p{Ll}[\p{Ll}-]+\3)\s*\)\s*$"#,
    )
    .unwrap()
});

/// [`QUOTED_SPELLING_VARIANT`] in a separately supplied authorship, behind its author or alone
/// (`Griseb. ("depressum")`, `('olmae')`).
static AUTHORSHIP_QUOTED_SPELLING: LazyLock<FancyRegex> = LazyLock::new(|| {
    FancyRegex::new(r#"^(.*?)\s*\(\s*((['"])\p{Ll}[\p{Ll}-]+\3)\s*\)\s*$"#).unwrap()
});

/// Moves a [`QUOTED_SPELLING_VARIANT`] into the nomenclatural note, quotes kept; Java read it as
/// part of the author ("Griseb.depressum"). Not after an indet marker ("Peltigera sp.
/// ('boreorufescens')"), which makes it the provisional name's phrase.
fn strip_quoted_spelling_variant(ctx: &mut ParseContext, s: String) -> String {
    let Ok(Some(caps)) = QUOTED_SPELLING_VARIANT.captures(&s) else {
        return s;
    };
    let before = caps.get(1).unwrap().as_str();
    let last = before.split_whitespace().last().unwrap_or_default();
    if matches!(last, "sp." | "spp." | "sp" | "spp" | "cf." | "aff.") {
        return s;
    }
    ctx.name
        .add_nomenclatural_note(caps.get(2).unwrap().as_str());
    java_trim(before).to_string()
}

/// Java BRACKETED_NOM_NOTE (StripAndStash.java:61-63):
/// `\s*[\[\(]\s*((?:nom|comb|orth|typ)\b[^\]\)]*)[\]\)]\s*$`, `Pattern.CASE_INSENSITIVE`, plus the
/// spelled-out "nomen" (`SCHLEGEL 1826 (nomen nudum)`, which Java read as an author).
/// `[^\]\)]` is a negated custom class -> stays outside `(?-u:…)` -> atom-only `\s`/`\b`
/// scoping (not whole-wrap).
static BRACKETED_NOM_NOTE: LazyLock<Regex> = LazyLock::new(|| {
    Regex::new(
        r"(?i)(?-u:\s*)[\[\(](?-u:\s*)((?:nom|nomen|comb|orth|typ|ined|in(?-u:\s+)sched)(?-u:\b)[^\]\)]*)[\]\)](?-u:\s*)$",
    )
    .unwrap()
});

/// Java `StripAndStash.stripBracketedNomNote` (StripAndStash.java:1140-1150). A trailing
/// bracketed/parenthesised nom-note ("[nom. et typ. cons.]", "(nom. nud.)",
/// "[orth. error]") OVERWRITES `nomenclaturalNote` — Java calls the plain setter here
/// (`ctx.name.setNomenclaturalNote(...)`, no null-check/append), UNLIKE `strip_nom_note`
/// (step 30, later in run-order) which appends. Also strips at most ONE trailing comma
/// left dangling before the bracket — a single `if`, not the `while` loop
/// `stash_synonym_bracket` uses.
fn strip_bracketed_nom_note(ctx: &mut ParseContext, s: String) -> String {
    if let Some(caps) = BRACKETED_NOM_NOTE.captures(&s) {
        let raw = java_trim(caps.get(1).unwrap().as_str()).to_string();
        // "U. Braun (ined.)": unpublished, as the unbracketed "ined." is
        if MANUSCRIPT_KEYWORD.is_match(&raw) {
            ctx.name.manuscript = true;
        }
        ctx.name.nomenclatural_note = Some(normalise_nom_note(&raw));
        let match_start = caps.get(0).unwrap().start();
        let mut kept = java_trim(&s[..match_start]).to_string();
        if kept.ends_with(',') {
            kept = java_trim(&kept[..kept.len() - 1]).to_string();
        }
        return kept;
    }
    s
}

// ---- Step 30: stripNomNote ----

// RULE: patterns on fancy_regex (backtracking) MUST keep Java's possessive/atomic
// quantifiers — only DROP possessives for patterns on the linear `regex` crate.
/// Java NOM_NOTE (StripAndStash.java:45-57), `Pattern.UNICODE_CHARACTER_CLASS` -> keep
/// default Unicode `\s`/`\b`/`\p{...}` throughout, ported near-verbatim. Internal
/// NEGATIVE LOOKAHEAD (`(?!\s+in\s+\p{Lu})`) in the first alternative AND a trailing
/// LOOKAHEAD boundary (`(?=$|,\s*non…|…)`) -> needs `fancy_regex` (the `regex` crate has
/// no lookaround at all). The one POSSESSIVE quantifier (`*+` on the first alternative's
/// inner repetition) is KEPT here as `*+` — UNLIKE every other possessive quantifier in
/// this port (see the RULE above, and `regexes.rs`'s module doc: those are all on the
/// linear `regex` crate, a linear-time automaton with no backtracking, where
/// possessive-vs-greedy can never change whether an overall match exists). `fancy_regex`
/// IS a backtracking engine, so on THIS pattern the possessive is load-bearing: without
/// it, an input with a long run of dotted lowercase words after "nomen"/"nom"/"comb"/
/// "orth" and no valid terminator (e.g. `" nomen " + "a.".repeat(20) + "#"`) makes the
/// greedy `*` re-partition the run exponentially before giving up, hitting
/// `fancy_regex`'s backtrack limit (proven: ~11ms and a `BacktrackLimitExceeded` no-match
/// with plain `*`, microseconds with `*+`). `fancy_regex` 0.14 parses `*+` natively
/// (compiling it to an atomic group), so restoring it is a straight verbatim port of
/// Java's own quantifier, not a restructuring. Java's own comment (StripAndStash.java:
/// 47-51) explains the captured run only ever consumes lowercase abbreviation words that
/// the trailing lookahead's own required content (whitespace/uppercase/comma) never
/// overlaps with, so the possessive changes nothing about WHICH strings match (the same
/// reasoning that lets Java itself use `*+` safely there) — it only forbids the
/// backtracking search that would otherwise explore every equivalent partition of the
/// run. Built via `concat!` (compile-time string concatenation) mirroring the Java
/// source's own `"..." + "..."` layout, one alternative per line, so it stays directly
/// diffable against StripAndStash.java line-by-line. Rust-only first alternative: "nomen" and its
/// Latin status word in any case, "Akeratidae Nomen Nudum", whose capital the general alternative
/// stops at — Java read "Nudum" as an author. Rust-only too: the "n." spelling of nova, "sp. n.",
/// "n. sp.", "n.sp." ("Anomia atacamensis n.sp. HERM 1969", where Java read an epithet "n" and an
/// author "sp.Herm").
static NOM_NOTE: LazyLock<FancyRegex> = LazyLock::new(|| {
    FancyRegex::new(concat!(
        r"\s+(",
        r"(?i:nomen\s+(?:nudum|novum|dubium|oblitum|illegitimum|invalidum|conservandum|rejiciendum|protectum|inquirendum)\b\.?)",
        r"|(?i:nom|comb|orth|nomen)\b\.?(?:(?!\s+in\s+\p{Lu})[\s.&]*[a-z][a-z.]*)*+",
        r"|(?i:sp|spec|gen|fam|var|form)\b\.?\s*(?i:nov)\b\.?(?:\s+ined\b\.?)?(?:\s+(?i:sp|spec|gen|fam|var|form)\b\.?\s*(?i:nov)\b\.?(?:\s+ined\b\.?)?)*",
        r"|(?i:nov)\b\.?\s+(?i:sp|spec|gen|fam|var|form)\b\.?",
        r"|(?:sp|gen|subsp|ssp)\.\s*n\b\.?|n\.\s*(?:sp|gen|subsp|ssp)\b\.?",
        r"|(?:in\s+obs\b\.?,?\s*)?pro\s+syn\b\.?",
        r")\s*(?=$|,\s*non(?:n\.?)?\b|,\s*nec\b|,\s*emend\b|,\s*sensu\b|,\s*auctt?\b|,\s*fide\b|\s+in\s+\p{Lu}|\s+\(.*\)\s*\.?\s*$|\s+\p{Lu})",
    ))
    .unwrap()
});

/// Java SP_NOV_PREFIX (StripAndStash.java:338-339): `(?i)^(?:sp|spec)\b\.?\s+nov.*`, no
/// `UNICODE_CHARACTER_CLASS`. Has `\b`/`\s` and an unescaped wildcard `.*` -> atom-only
/// scoping (not whole-wrap). Called via `.matches()` -> trailing `$` added.
static SP_NOV_PREFIX: LazyLock<Regex> =
    LazyLock::new(|| Regex::new(r"(?i)^(?:sp|spec)(?-u:\b)\.?(?-u:\s+)nov.*$").unwrap());

/// The "n." spelling of a nova note, "sp. n." or "n. sp.", matched by [`NOM_NOTE`].
static NOVA_ABBREVIATED: LazyLock<Regex> = LazyLock::new(|| {
    Regex::new(r"^(?:(?:sp|gen|subsp|ssp)\.\s*n\b\.?|n\.\s*(?:sp|gen|subsp|ssp)\b\.?)$").unwrap()
});

/// Java SINGLE_TITLE_WORD (StripAndStash.java:340): `^[\p{Lu}][\p{Ll}]+$`, no flags.
/// `\p{Lu}`/`\p{Ll}` always Unicode, no ASCII atoms at all -> nothing to scope. Its own
/// `^…$` anchors make `.is_match()` here equivalent to Java's `.matches()`.
static SINGLE_TITLE_WORD: LazyLock<Regex> =
    LazyLock::new(|| Regex::new(r"^[\p{Lu}][\p{Ll}]+$").unwrap());

/// Java MANUSCRIPT_KEYWORD (StripAndStash.java:312-313):
/// `(?i).*\b(?:ined|ms|msc|unpublished)\b.*`, no `UNICODE_CHARACTER_CLASS`. RESTRUCTURED:
/// called via `.matches()` on a `.*CORE.*` shape -> equivalent to an unanchored `is_match`
/// on CORE alone (same restructuring as `GREEK_MARKER_TEST`/`SEROVAR_TEST` in batch 1).
/// `\b` (x2) ASCII-scoped. Shared with `stripAuthorshipMarkers` (ported below as
/// `strip_authorship_markers`) and `stripManuscriptMarker` (batch 4) — defined once here,
/// reusable file-wide.
static MANUSCRIPT_KEYWORD: LazyLock<Regex> =
    LazyLock::new(|| Regex::new(r"(?i)(?-u:\b)(?:ined|ms|msc|unpublished)(?-u:\b)").unwrap());

/// Java NOM_NOTE_RANK_HINT (StripAndStash.java:223-225): `^(gen|fam|var|form|sp|spec)\b\.?`,
/// `Pattern.CASE_INSENSITIVE`. Has `\b`, no `\p{...}`, no unescaped wildcard -> whole
/// pattern ASCII-scoped (leading `^` left outside the wrap).
static NOM_NOTE_RANK_HINT: LazyLock<Regex> =
    LazyLock::new(|| Regex::new(r"(?i)^(?-u:(gen|fam|var|form|sp|spec)\b\.?)").unwrap());

/// Java `StripAndStash.stripNomNote` (StripAndStash.java:1152-1195). The general
/// nom/comb/orth/nomen/sp.nov./pro-syn. keyword tail — the LAST-resort, most general
/// nomenclatural-note anchor (everything more specific was already peeled off by earlier
/// steps, e.g. `strip_bracketed_nom_note`). Unlike step 29, this APPENDS to
/// `nomenclaturalNote` (`ctx.name.add_nomenclatural_note`, matching Java's inline
/// `existing == null ? norm : existing + " " + norm`). Three further side effects, all
/// conditioned on the SAME captured `raw` (group 1, trimmed) and/or `before` (the
/// pre-match text, trimmed) — independent `if`s, not else-if:
///   - a bare "sp. nov."/"spec. nov." tail on an otherwise-single-Title-Word monomial
///     REPLACES the reconstructed working string with "`before` sp." (re-adding a bare
///     rank marker so the downstream indet/INFORMAL handling still recognises a
///     species-indet name, rather than leaving a bare uninomial with the marker fully
///     gone);
///   - a captured note containing "ined"/"ms"/"msc"/"unpublished" sets `manuscript = true`
///     (the note text itself already consumed the keyword, so the separate standalone
///     manuscript-marker step, batch 4, won't see it there anymore);
///   - when the name doesn't already carry a rank (`Rank::Unranked`), a gen/fam/var/form
///     prefix on `raw` pins the rank accordingly ("sp"/"spec" is left alone — SPECIES is
///     assigned later, by Assemble, for binomials).
fn strip_nom_note(ctx: &mut ParseContext, s: String) -> String {
    let caps = match NOM_NOTE.captures(&s) {
        Ok(Some(c)) => c,
        _ => return s,
    };
    let match_start = caps.get(0).unwrap().start();
    let match_end = caps.get(0).unwrap().end();
    let raw = java_trim(caps.get(1).unwrap().as_str()).to_string();
    // A "sp. n." / "n. sp." before a specimen code, or after a bare genus with anything behind it,
    // is a provisional name's designation, kept whole for its phrase ("Heteropriapulus sp. n.
    // AAA-2017", "Amrasca (Amrasca) sp. n. VN1", "Aphonopelma sp. n. Guatemala"), and so is a new
    // subspecies not yet named ("Heliconius timareta ssp. n. CPD-2012", "Lasiophila alkaios ssp.
    // n.").
    if NOVA_ABBREVIATED.is_match(&raw) {
        let after = java_trim(&s[match_end..]);
        let code_follows = after
            .split_whitespace()
            .next()
            .is_some_and(|w| w.chars().any(|c| c.is_ascii_digit() || c == '_'));
        // a trailing code may already be stashed ("Anaka sp. n. RWW_2025")
        let stashed = ctx.name.phrase.is_some() || ctx.pending_unparsed.is_some();
        let after_bare_genus = SINGLE_TITLE_WORD.is_match(java_trim(&s[..match_start]))
            && (!after.is_empty() || stashed);
        let subspecies = raw.contains("ssp") || raw.contains("subsp");
        if code_follows || after_bare_genus || subspecies {
            return s;
        }
    }
    let norm = normalise_nom_note(&raw);
    ctx.name.add_nomenclatural_note(&norm);

    let before = java_trim(&s[..match_start]).to_string();
    let after = java_trim(&s[match_end..]).to_string();
    let mut result = if after.is_empty() {
        before.clone()
    } else {
        format!("{before} {after}")
    };
    result = java_trim(&result).to_string();
    while result.ends_with(',') {
        result.pop();
        result = java_trim(&result).to_string();
    }

    if (SP_NOV_PREFIX.is_match(&raw) || NOVA_ABBREVIATED.is_match(&raw))
        && SINGLE_TITLE_WORD.is_match(&before)
    {
        result = format!("{before} sp.");
    }
    if MANUSCRIPT_KEYWORD.is_match(&raw) {
        ctx.name.manuscript = true;
    }
    if ctx.name.rank == Rank::Unranked {
        if let Some(hint) = NOM_NOTE_RANK_HINT.captures(&raw) {
            match hint.get(1).unwrap().as_str().to_lowercase().as_str() {
                "gen" => ctx.name.rank = Rank::Genus,
                "fam" => ctx.name.rank = Rank::Family,
                "var" => ctx.name.rank = Rank::Variety,
                "form" => ctx.name.rank = Rank::Form,
                _ => {}
            }
        }
    }
    result
}

// ---------------------------------------------------------------------------------
// Batch 3 (steps 31-44): authorship placeholders, trailing-species, pro parte / pro
// sp. / approved-lists, mihi, anon, the taxonomic-note family, aggregate suffix.
// Ported (Phase 1 Slice 2, batch 2c). This batch closes `taxonomicNote` — steps 38-42
// APPEND to it (`ParsedName::add_taxonomic_note`, the Java inline `existing == null ?
// note : existing + " " + note` idiom); step 43 (`stripTaxNote`, the LAST of the six
// taxonomic-note steps to run) PREPENDS to it, since its note stands in front of what the
// steps above it peeled off the end (Java's plain `setTaxonomicNote(norm)` overwrote it).
// All worked examples below were spot-checked against the real Java CLI oracle
// (`name-parser-cli-4.2.0-SNAPSHOT-shaded.jar`), same convention as batches 1-2b.
// ---------------------------------------------------------------------------------

// ---- Step 31: stripAuthorshipPlaceholders ----

/// Java AUTHORSHIP_PLACEHOLDER (StripAndStash.java:226-228):
/// `\s+Not\s+(?:applicable|given|known|recorded|found)\s*$`, `Pattern.CASE_INSENSITIVE`.
/// Extended beyond Java with the placeholders ChecklistBank sources actually use — "Missing"
/// (22k rows, all in the separate authorship), "Not specified" (19k), "Unknown", "NONE", "NA",
/// "author unknown", "Author" — after an optional comma ("Semenov, Unknown") and with an
/// optional trailing dot. The bare single words are matched case-sensitively, Title or upper case
/// only. A lone particle is one too: [`LONE_PARTICLE`]. Has `\s`, no `\p{...}`, no unescaped
/// wildcard -> ASCII-scoped. No lookaround/backreference -> plain `regex` crate.
static AUTHORSHIP_PLACEHOLDER: LazyLock<Regex> = LazyLock::new(|| {
    Regex::new(concat!(
        r"(?-u:[\s,]*\s)(?:",
        r"(?i:not(?-u:\s+)(?:applicable|given|known|recorded|found|specified|available|provided|stated))",
        r"|(?i:author(?-u:\s+)unknown|unknown(?-u:\s+)author)",
        r"|Unknown|UNKNOWN|Missing|MISSING|None|NONE|NA|N/A|Author\??(?:,(?-u:\s*)\[0000\])?",
        r")(?-u:\s*)\.?(?-u:\s*)$",
    ))
    .unwrap()
});

/// Java `StripAndStash.stripAuthorshipPlaceholders` (StripAndStash.java:1197-1208). A
/// trailing "Not applicable"/"Not given"/"Not known"/"Not recorded"/"Not found"
/// authorship placeholder (any case) is dropped silently, flagging `AUTHORSHIP_REMOVED`
/// so the bare name (with whatever real author text preceded the placeholder, if any)
/// still parses — spot-checked: "Aus bus Smith Not given" -> authors=["Smith"],
/// warnings=["authorship placeholder removed"]; "Aus bus Not applicable" -> no author,
/// same warning.
fn strip_authorship_placeholders(ctx: &mut ParseContext, s: String) -> String {
    match find_placeholder(&s) {
        Some(start) => {
            ctx.name.add_warning(warnings::AUTHORSHIP_REMOVED);
            java_trim(&s[..start]).to_string()
        }
        None => s,
    }
}

/// The name string without a trailing authorship placeholder, for Preflight's placeholder-name
/// check: "Ascidia zara author unknown" is a species whose author is unknown, not an "unknown"
/// placeholder taxon. A placeholder that is the whole string stays.
pub(crate) fn without_authorship_placeholder(s: &str) -> &str {
    find_placeholder(s).map_or(s, |start| &s[..start])
}

/// A lone lower-case particle after the name, an author's name cut short ("de", 28 ChecklistBank
/// authorships; "Del." and "Ten." are Delile and Tenore).
static LONE_PARTICLE: LazyLock<Regex> =
    LazyLock::new(|| Regex::new(r"(?-u:[\s,]*\s)(?:de|del|da|du|van|von)(?-u:\s*)$").unwrap());

/// Where an [`AUTHORSHIP_PLACEHOLDER`] starts — unless it answers a label ("Type: Unknown."),
/// which says nothing about the authorship. A [`LONE_PARTICLE`] counts only after an epithet: right
/// after the genus or a rank marker it is the epithet (`Eresus da` under a species rank hint).
fn find_placeholder(s: &str) -> Option<usize> {
    AUTHORSHIP_PLACEHOLDER
        .find(s)
        .map(|m| m.start())
        .filter(|&start| !s[..start].ends_with(':'))
        .or_else(|| {
            let start = LONE_PARTICLE.find(s)?.start();
            let words: Vec<&str> = s[..start].split_whitespace().collect();
            match words.as_slice() {
                [] => Some(start),
                [_genus] => None,
                [.., last] => rank_of_marker(last.trim_end_matches('.'))
                    .is_none()
                    .then_some(start),
            }
        })
}

/// [`strip_authorship_placeholders`] for a separately supplied authorship, where the placeholder
/// usually IS the whole string ("Missing", "Not specified") — so it is matched against a
/// space-padded copy. (On the name string a placeholder must follow the name: "None" alone is a
/// name.)
pub(crate) fn strip_authorship_placeholder(authorship: &str, name: &mut ParsedName) -> String {
    let padded = format!(" {authorship}");
    if let Some(start) = find_placeholder(&padded) {
        name.add_warning(warnings::AUTHORSHIP_REMOVED);
        return java_trim(&padded[..start]).to_string();
    }
    authorship.to_string()
}

/// "not validly publ." / "not validly published" / "not effectively published" after the
/// authorship: a nomenclatural status (nom. inval.), not an author — 3.7k ChecklistBank names, e.g.
/// `Bridelia scleroneuroides var. typica Gehrm., not validly publ.`. Rust-only: Java read it as a
/// second author.
static NOT_VALIDLY_PUBLISHED: LazyLock<Regex> = LazyLock::new(|| {
    Regex::new(
        r"(?i)(?-u:[\s,]*\s)(not(?-u:\s+)(?:validly|effectively)(?-u:\s+)publ(?:ished|\.)?)(?-u:\s*)$",
    )
    .unwrap()
});

fn strip_not_validly_published(ctx: &mut ParseContext, s: String) -> String {
    strip_not_validly_published_note(&s, &mut ctx.name)
}

/// Moves a trailing [`NOT_VALIDLY_PUBLISHED`] status into the nomenclatural note, verbatim — once:
/// sources repeat it in the separate authorship. The status always follows an author or a name,
/// so no padding is needed.
pub(crate) fn strip_not_validly_published_note(s: &str, name: &mut ParsedName) -> String {
    if let Some(caps) = NOT_VALIDLY_PUBLISHED.captures(s) {
        let note = caps.get(1).unwrap().as_str();
        if !name
            .nomenclatural_note
            .as_deref()
            .is_some_and(|existing| contains_words(existing, note))
        {
            name.add_nomenclatural_note(note);
        }
        return java_trim(&s[..caps.get(0).unwrap().start()]).to_string();
    }
    s.to_string()
}

// ---- Step 32: stripTrailingSpeciesWord ----

/// Java TRAILING_SPECIES_WORD_TEST (StripAndStash.java:354-355):
/// `^[\p{Lu}][\p{Ll}]+\s+species\s*\.?$`, no flags. Has `\p{Lu}`/`\p{Ll}` (always
/// Unicode) and `\s` (x2) -> only `\s` ASCII-scoped (atom-only, not whole-wrap). Called
/// via `.matches()`, but the pattern already opens with `^` and closes with `$` -> no
/// change needed. Gates the strip to a bare "Title word" + " species[.]" shape only, so a
/// real binomial ("Genus species alba") is never mistaken for this placeholder form.
static TRAILING_SPECIES_WORD_TEST: LazyLock<Regex> =
    LazyLock::new(|| Regex::new(r"^[\p{Lu}][\p{Ll}]+(?-u:\s+)species(?-u:\s*)\.?$").unwrap());

/// Java TRAILING_SPECIES_WORD (StripAndStash.java:356): `\s+species\s*\.?$`, no flags.
/// Has `\s` (x2), no `\p{...}`, no unescaped wildcard (the `\.` is an escaped literal) ->
/// whole-wrap ASCII scope. No lookaround/backreference -> plain `regex` crate.
static TRAILING_SPECIES_WORD: LazyLock<Regex> =
    LazyLock::new(|| Regex::new(r"(?-u:\s+species\s*)\.?$").unwrap());

/// Java `StripAndStash.stripTrailingSpeciesWord` (StripAndStash.java:1210-1218). A
/// trailing " species"/" species." on an otherwise-bare Title-cased uninomial ("Abies
/// species", "Abies species.") drops the word, producing a plain monomial — spot-checked:
/// both forms -> `uninomial="Abies"` (no rank/INFORMAL marker stashed here; that
/// classification happens in the tokenizer/Assemble).
fn strip_trailing_species_word(_ctx: &mut ParseContext, s: String) -> String {
    if TRAILING_SPECIES_WORD_TEST.is_match(&s) {
        if let Some(m) = TRAILING_SPECIES_WORD.find(&s) {
            return java_trim(&s[..m.start()]).to_string();
        }
    }
    s
}

// ---- Step 33: stripProParte ----

/// Java PRO_PARTE (StripAndStash.java:229-231): `\s*,\s*(?:pro\s+parte|p\.\s*p\.[A-Z]?)\s*$`,
/// `Pattern.CASE_INSENSITIVE`. Has `\s` (x5), no `\p{...}`, no unescaped wildcard (dots
/// escaped) -> whole-wrap ASCII scope; the positive class `[A-Z]` sits inside the wrap
/// too, so under `(?i)` it folds ASCII-only (matching Java's default CASE_INSENSITIVE,
/// which is ASCII-only unless UNICODE_CASE is also set — it isn't here). No
/// lookaround/backreference -> plain `regex` crate. Rust-only: without the comma too ("Aconitum
/// gracile Rchb. pro parte", "Rchb. p.p.") and as "pro max./maj./min. parte".
static PRO_PARTE: LazyLock<Regex> = LazyLock::new(|| {
    Regex::new(
        r"(?i)(?-u:(?:\s*,\s*|\s+)(?:pro(?:\s+(?:max|maj|min)\.?)?\s+parte|p\.\s*p\.[A-Z]?)\s*)$",
    )
    .unwrap()
});

/// Java `StripAndStash.stripProParte` (StripAndStash.java:1220-1229). A trailing ",
/// pro parte" / ", p.p." (optionally suffixed by a single capital letter, e.g. "p.p.A")
/// "in part" taxonomic-concept qualifier is stripped silently, flagging doubtful —
/// spot-checked: "Aus bus Smith, pro parte" -> authors=["Smith"], doubtful=true, no note
/// text added (this step never touches `taxonomicNote`).
/// A sensu / auct. / sec. note keyword, which a trailing "p.p." then qualifies.
static NOTE_KEYWORD: LazyLock<Regex> =
    LazyLock::new(|| Regex::new(r"(?i)(?-u:\b(?:sensu|auctt?|auctorum|sec)\b)").unwrap());

fn strip_pro_parte(ctx: &mut ParseContext, s: String) -> String {
    if let Some(m) = PRO_PARTE.find(&s) {
        // "sensu Turcz., p.p.": the note's own "in part", kept in it, as in a separate authorship
        if NOTE_KEYWORD.is_match(&s[..m.start()]) {
            return s;
        }
        ctx.name.doubtful = true;
        return java_trim(&s[..m.start()]).to_string();
    }
    s
}

// ---- Step 34: stripProSpAnnotation ----

/// Java PRO_SP_ANNOTATION (StripAndStash.java:232-234):
/// `\s+\(\s*pro\s+(?:sp|spec|syn|hyb)\b\.?\s*\)\s*\.?\s*$`, `Pattern.CASE_INSENSITIVE`.
/// Has `\s` (x5) and `\b`, no `\p{...}`, no unescaped wildcard (parens/dots escaped) ->
/// whole-wrap ASCII scope. No lookaround/backreference -> plain `regex` crate.
static PRO_SP_ANNOTATION: LazyLock<Regex> = LazyLock::new(|| {
    Regex::new(r"(?i)(?-u:\s+\(\s*pro\s+(?:sp|spec|syn|hyb)\b\.?\s*\)\s*\.?\s*)$").unwrap()
});

/// Java `StripAndStash.stripProSpAnnotation` (StripAndStash.java:1231-1239). A trailing
/// " (pro sp.)" / " (pro spec.)" / " (pro syn.)" / " (pro hyb.)" botanical "given as"
/// annotation is stripped silently, working-string only — spot-checked: "Aus bus (pro
/// sp.)" -> `specificEpithet="bus"`, no doubtful flag, no warning, no note.
fn strip_pro_sp_annotation(_ctx: &mut ParseContext, s: String) -> String {
    if let Some(m) = PRO_SP_ANNOTATION.find(&s) {
        return java_trim(&s[..m.start()]).to_string();
    }
    s
}

// ---- Step 35: stripApprovedLists ----

/// Java APPROVED_LISTS (StripAndStash.java:235-237):
/// `\s*\(\s*Approved\s+Lists\s+\d{4}\s*\)\s*\.?\s*$`, `Pattern.CASE_INSENSITIVE`. Has `\s`
/// (x6) and `\d`, no `\p{...}`, no unescaped wildcard -> whole-wrap ASCII scope. No
/// lookaround/backreference -> plain `regex` crate. Rust-only: a comma before the year
/// (`(Approved Lists, 1980)`, 273 ChecklistBank rows), and an emendation after it (`Lee et al. 1979
/// (Approved Lists 1980) emend. Kim 2000`, 301 rows), which Java left for the authors.
static APPROVED_LISTS: LazyLock<Regex> = LazyLock::new(|| {
    Regex::new(r"(?i)(?-u:\s*\(\s*Approved\s+Lists,?\s+\d{4}\s*\)\s*\.?\s*)(?:,?(?-u:\s*)(emend(?-u:\b).*))?$")
        .unwrap()
});

/// Java `StripAndStash.stripApprovedLists` (StripAndStash.java:1241-1249). A trailing "
/// (Approved Lists YYYY)" bacterial-code annotation is stripped silently, working-string
/// only — spot-checked: "Aus bus Smith (Approved Lists 1980)" -> authors=["Smith"], no
/// other side effect.
fn strip_approved_lists(ctx: &mut ParseContext, s: String) -> String {
    if let Some(caps) = APPROVED_LISTS.captures(&s) {
        ctx.approved_lists = true;
        let before = java_trim(&s[..caps.get(0).unwrap().start()]);
        // the emendation that follows is left to the taxonomic-note step
        return match caps.get(1) {
            Some(emend) => format!("{before} {}", emend.as_str()),
            None => before.to_string(),
        };
    }
    s
}

// ---- Step 36: stripMihi ----

/// Java MIHI_TEST (StripAndStash.java:345): `(?i).*\bmihi\b.*`, no
/// `UNICODE_CHARACTER_CLASS`. RESTRUCTURED: called via `.matches()` on a `.*CORE.*` shape
/// -> equivalent to an unanchored `is_match` on CORE alone (same restructuring as
/// `MANUSCRIPT_KEYWORD` in batch 2). `\b` (x2) ASCII-scoped.
static MIHI_TEST: LazyLock<Regex> = LazyLock::new(|| Regex::new(r"(?i)(?-u:\bmihi\b)").unwrap());

/// Java MIHI (StripAndStash.java:346): `(?i)\s+mihi\.?(?=\s|$)`, no
/// `UNICODE_CHARACTER_CLASS`. Trailing lookahead (boundary not consumed, so e.g. "Genus
/// species mihi var. epithet mihi" strips BOTH occurrences — the separator before "var."
/// survives the first match to bound the next one) -> `fancy_regex`. `fancy_regex` has no
/// ASCII mode -> `\s` spelled out as the literal ASCII whitespace set. No possessive
/// quantifier in this pattern.
static MIHI: LazyLock<FancyRegex> =
    LazyLock::new(|| FancyRegex::new(r"(?i)[ \t\n\x0B\f\r]+mihi\.?(?=[ \t\n\x0B\f\r]|$)").unwrap());

/// Java `StripAndStash.stripMihi` (StripAndStash.java:1251-1266). Latin "mihi" ("by me"),
/// a self-attribution placeholder some authors used in place of a real authorship, is
/// stripped wherever it occurs (trailing OR mid-string, per `MIHI`'s non-consuming
/// lookahead) with an `AUTHORSHIP_REMOVED` warning — but ONLY when something actually
/// changed: Java's `if (!s.equals(before))` structural-equality guard (mirrored here via
/// `after != before`) means a "mihi" that satisfies `MIHI_TEST`'s loose `\bmihi\b` gate
/// but doesn't sit in `MIHI`'s required `<whitespace>mihi<whitespace-or-EOS>` position
/// (e.g. as the very first word, with no leading separator to match `\s+`) leaves the
/// string untouched and fires no warning — spot-checked: "Aus bus mihi" ->
/// warnings=["authorship placeholder removed"], "Aus bus mihi. Smith" -> same warning,
/// authors=["Smith"] (mid-string strip splices the surrounding text back together).
fn strip_mihi(ctx: &mut ParseContext, s: String) -> String {
    if MIHI_TEST.is_match(&s) {
        let before = s.clone();
        let after = java_trim(&fancy_replace_all(&MIHI, &s, |_| String::new())).to_string();
        if after != before {
            ctx.name.add_warning(warnings::AUTHORSHIP_REMOVED);
        }
        return after;
    }
    s
}

// ---- Step 37: normaliseAnon ----

/// Java ANON_UPPER (StripAndStash.java:347): `(?<=\s)Anon\b\.?`, no flags (case-sensitive
/// literal "Anon", not `(?i)`). LOOKBEHIND -> `fancy_regex`. `\s` spelled out ASCII
/// (`fancy_regex` has no ASCII mode); `\b` stays `fancy_regex`'s Unicode-default word
/// boundary (the same forced, vanishingly-rare divergence documented at `STRAIN_DESIGNATION`
/// in batch 1 — Java's own `\b` here is ASCII-only, `fancy_regex` has no ASCII `\b`
/// option). No possessive quantifier.
static ANON_UPPER: LazyLock<FancyRegex> =
    LazyLock::new(|| FancyRegex::new(r"(?<=[ \t\n\x0B\f\r])Anon\b\.?").unwrap());

/// Java ANON_LOWER (StripAndStash.java:348): `(?<=\s)anon\b(?!\.)`, no flags
/// (case-sensitive literal "anon"). LOOKBEHIND + trailing NEGATIVE LOOKAHEAD (excludes an
/// "anon." that's already dotted, so `ANON_UPPER`/this step never double-append a second
/// dot) -> `fancy_regex`, same ASCII-`\s`-spelled-out / default-`\b` reasoning as
/// `ANON_UPPER`. No possessive quantifier.
static ANON_LOWER: LazyLock<FancyRegex> =
    LazyLock::new(|| FancyRegex::new(r"(?<=[ \t\n\x0B\f\r])anon\b(?!\.)").unwrap());

/// Java `StripAndStash.normaliseAnon` (StripAndStash.java:1268-1274). Working-string-only
/// (no `ctx.name` mutation, no warnings): TWO sequential, UNCONDITIONAL replacements —
/// title-case "Anon"/"Anon." and lower-case "anon" (not already followed by a dot) both
/// normalise to the canonical lower-case "anon." so the authorship
/// parser captures it as a real anonymous-author token. Alone in an author slot the authorship
/// parser turns any spelling of it into `Authorship::anonymous` (no author string, rendered per
/// code); this spelling survives where it stays a string — an ex author ("Anon. ex Schltdl."),
/// a team member, or the anonymous work an in-citation names ("Swainson in Anon. 1837" ->
/// publishedIn "anon. 1837").
fn normalise_anon(_ctx: &mut ParseContext, s: String) -> String {
    normalise_anon_str(&s)
}

/// [`normalise_anon`] for any string — also run on a separately supplied authorship, which Java
/// left as written, so the same author came out as "Anon." or "anon." depending on the column.
fn normalise_anon_str(s: &str) -> String {
    let s = fancy_replace_all(&ANON_UPPER, s, |_| "anon.".to_string());
    fancy_replace_all(&ANON_LOWER, &s, |_| "anon.".to_string())
}

// ---- Step 38: stripColonConceptReference ----

/// Java COLON_CONCEPT_REFERENCE (StripAndStash.java:238-240):
/// `\s*:\s+(\p{Lu}[^:]*,\s*\d{3,4})\s*\.?\s*$`, `Pattern.UNICODE_CHARACTER_CLASS` -> keep
/// default Unicode `\s`/`\d`, ported verbatim. `[^:]` is a negated custom class, but
/// UNICODE_CHARACTER_CLASS means the whole pattern stays at the crate's Unicode default
/// anyway (no `(?-u:…)` anywhere), so the "invalid UTF-8 in byte mode" restriction that
/// forces atom-only scoping elsewhere in this file never comes up here. No
/// lookaround/backreference -> plain `regex` crate.
static COLON_CONCEPT_REFERENCE: LazyLock<Regex> =
    LazyLock::new(|| Regex::new(r"\s*:\s+(\p{Lu}[^:]*,\s*\d{3,4})\s*\.?\s*$").unwrap());

/// "in:" for "in" before a publication — `Henderson & Hodgson in: Hodgson & Henderson, 2000`,
/// `Mercado-Salas, 2013 In: Gutiérrez-Aguirre …`, `Young {in}: Young & Lu, 1988` — so the in-citation
/// step reads it, not [`COLON_CONCEPT_REFERENCE`] (~400 ChecklistBank authorships). Rust-only.
static IN_COLON: LazyLock<Regex> =
    LazyLock::new(|| Regex::new(r"(\s)(?:[Ii]n|\{in\}):(\s)").unwrap());

/// The two sanctioning authors (ICN Art. 15): Fries and Persoon.
static SANCTIONING_AUTHOR: LazyLock<Regex> =
    LazyLock::new(|| Regex::new(r"^(?:Fr\.|Fries\b|Pers\.|Persoon\b)").unwrap());

/// A year closing the text before a colon: "Linnaeus, 1758: Fabricius, 1793".
static ENDS_IN_YEAR: LazyLock<Regex> = LazyLock::new(|| Regex::new(r"\d{4}[a-z]?\)?$").unwrap());

/// Java `StripAndStash.stripColonConceptReference` (StripAndStash.java:1276-1290). A
/// trailing ": Author, YYYY" botanical taxonomic-concept citation (e.g. "Vespa
/// emarginata Linnaeus, 1758: Fabricius, 1793" — the Linnaeus year is the original
/// publication, Fabricius is the sensu author) APPENDS the captured text to
/// `taxonomicNote`. The explicit ", YYYY" requirement keeps the simpler
/// ": SanctioningAuthor" form (e.g. "Boletus versicolor L. : Fr.", no year) out of this
/// strip — spot-checked: the Linnaeus/Fabricius example ->
/// `taxonomicNote="Fabricius, 1793"`, working string reduces to "Vespa emarginata
/// Linnaeus, 1758". Rust-only: "in:" is first read as "in" ([`IN_COLON`]), and a sanctioning
/// author after a colon with no year before it ("Bull. : Fr., 1821") is left for the authorship
/// parser — Java made "Fr., 1821" the taxonomic note.
fn strip_colon_concept_reference(ctx: &mut ParseContext, s: String) -> String {
    let s = IN_COLON.replace_all(&s, "${1}in${2}").into_owned();
    if let Some(caps) = COLON_CONCEPT_REFERENCE.captures(&s) {
        let note = java_trim(caps.get(1).unwrap().as_str()).to_string();
        let before = java_trim(&s[..caps.get(0).unwrap().start()]);
        // "Bull. : Fr., 1821" is Fries' sanctioning, for the authorship parser
        if SANCTIONING_AUTHOR.is_match(&note) && !ENDS_IN_YEAR.is_match(before) {
            return s;
        }
        ctx.name.add_taxonomic_note(&note);
        let whole = caps.get(0).unwrap();
        return java_trim(&s[..whole.start()]).to_string();
    }
    s
}

// ---- Shared helper: normaliseLeadingAuct (used by steps 39 and 43) ----

/// Java LEADING_AUCT (StripAndStash.java:310): `^(Auct)`, no flags — literal, case-
/// sensitive "Auct" prefix. No shorthand atoms (`\s`/`\d`/`\w`/`\b`/`\p{...}`) at all ->
/// nothing to scope, ported verbatim (same as `DAGGER`/`HTML_TAG` in batch 2). No
/// lookaround/backreference -> plain `regex` crate.
static LEADING_AUCT: LazyLock<Regex> = LazyLock::new(|| Regex::new(r"^(Auct)").unwrap());

/// Java LEADING_AUCTT (StripAndStash.java:311): `^(Auctt)`, no flags. Same reasoning as
/// `LEADING_AUCT` -> ported verbatim, plain `regex` crate.
static LEADING_AUCTT: LazyLock<Regex> = LazyLock::new(|| Regex::new(r"^(Auctt)").unwrap());

/// Java's repeated `LEADING_AUCTT.matcher(LEADING_AUCT.matcher(x).replaceAll("auct"))
/// .replaceAll("auctt")` idiom (StripAndStash.java:1298, 1360): lower-cases a leading
/// title-case "Auct"/"Auctt" keyword to the canonical lower-case "auct."/"auctt."
/// convention (the trailing dot, if any, is untouched — already part of the input text).
/// Both `LEADING_AUCT`/`LEADING_AUCTT` are case-SENSITIVE, so this only fires on the
/// EXACT casing "Auct"/"Auctt" (capital A, the rest lower) — an all-lowercase note is
/// already correct and left alone, an ALL-CAPS note ("AUCTT.") is left untouched too
/// (neither pattern matches it) — spot-checked against the Java CLI oracle: "Aus bus
/// Auct." -> `taxonomicNote="auct."`, "Aus bus Auctt." -> `taxonomicNote="auctt."`.
/// Because the FIRST replacement already consumes (and lower-cases) any "Auct" prefix,
/// the second regex — which requires a literal capital "Auctt" — can only ever fire on
/// input that did NOT start with "Auct" in the first place, i.e. effectively never after
/// the first step runs; both steps are ported verbatim rather than collapsed into one,
/// since Java itself chains them this way at both call sites (`stripBracketedTaxNote`,
/// `stripTaxNote`) and a faithful port doesn't get to assume away a redundancy the
/// oracle itself carries.
fn normalise_leading_auct(note: &str) -> String {
    let step1 = LEADING_AUCT.replace(note, "auct");
    LEADING_AUCTT.replace(&step1, "auctt").into_owned()
}

// ---- Step 39: stripBracketedTaxNote ----

/// Java BRACKETED_TAX_NOTE (StripAndStash.java:123-125):
/// `\s*\[\s*((?:auctt?|sensu|sec|non|nec|misspelling|misapplied|misident)\b[^\]]*)\]\s*\.?\s*$`,
/// `Pattern.CASE_INSENSITIVE`, plus "auctorum" ("[auctorum]", see [`TAX_NOTE`]) and "not"
/// ("[not used as valid]", "[not Amphisbetia pulchella Vannucci-Mendes 1954]"), which Java
/// lacks and so read as authors. `[^\]]` is a negated custom class -> stays OUTSIDE any
/// `(?-u:…)` (`SIC_WITH_COMMENT`/`BRACKETED_NOM_NOTE` precedent from batches 1-2) ->
/// atom-only `\s`/`\b` scoping, not whole-wrap. No lookaround/backreference -> plain
/// `regex` crate.
static BRACKETED_TAX_NOTE: LazyLock<Regex> = LazyLock::new(|| {
    Regex::new(
        r"(?i)(?-u:\s*)\[(?-u:\s*)((?:auctt?|auctorum|sensu|sec|non|nec|not|misspelling|misapplied|misident)(?-u:\b)[^\]]*)\](?-u:\s*)\.?(?-u:\s*)$",
    )
    .unwrap()
});

/// Java `StripAndStash.stripBracketedTaxNote` (StripAndStash.java:1292-1304). A trailing
/// "[auctt. misspelling for Eunoe]"-style bracket introduced by a taxonomic-concept
/// keyword — the ENTIRE bracket content becomes the taxonomic note (whitespace-collapsed,
/// leading/trailing-trimmed, then leading "Auct"/"Auctt" lower-cased via
/// `normalise_leading_auct`) and APPENDS to `taxonomicNote` — spot-checked: "Eunoa bus
/// Smith [auctt. misspelling for Eunoe]" -> `taxonomicNote="auctt. misspelling for
/// Eunoe"`, authors=["Smith"].
fn strip_bracketed_tax_note(ctx: &mut ParseContext, s: String) -> String {
    if let Some(caps) = BRACKETED_TAX_NOTE.captures(&s) {
        let trimmed = java_trim(caps.get(1).unwrap().as_str());
        let collapsed = WHITESPACE.replace_all(trimmed, " ");
        let note = normalise_leading_auct(&collapsed);
        ctx.name.add_taxonomic_note(&note);
        let whole = caps.get(0).unwrap();
        return java_trim(&s[..whole.start()]).to_string();
    }
    s
}

// ---- Step 40: stripParenTaxNote ----

/// A bracketed "sensu stricto" or "sensu lato" wherever it stands: after the authors
/// ("(Wollaston,1860) (s.str.)"), before them, or between two epithets ("Ammodramus caudacutus
/// (s.s.) diversus"). Rust-only: Java read it as an author, or the epithet after it as one. The
/// lower-case "s." keeps an author's initials ("(S. L. Schultes)") out.
static PAREN_SENSU_STRICTO: LazyLock<Regex> = LazyLock::new(|| {
    Regex::new(r"(?-u:\s*)\((?-u:\s*)(s\.(?-u:\s*)(?:str|s|l|lat|ampl)\.?)(?-u:\s*)\)").unwrap()
});

/// Java PAREN_TAX_NOTE (StripAndStash.java:101-103):
/// `\s*\(\s*((?:nec|non|not)\s+[^)]+)\)\s*\.?\s*$`, `Pattern.CASE_INSENSITIVE` — extended
/// beyond Java with the concept keywords `auct`/`auctt`/`auctorum`/`sensu`/`sec` (the set the separate
/// authorship's `PAREN_NOTE` already strips), so WoRMS' `Gregariella splendida (sensu Reeve,
/// 1858)` keeps its note instead of reading `sensu Reeve` as the basionym author; and with "vide"
/// (`Örsted (vide Koren & Danielssen, 1876)`) and a "(synonym)" remark. `[^)]` is
/// a negated custom class -> atom-only `\s` scoping (same precedent as
/// `BRACKETED_TAX_NOTE` above). No lookaround/backreference -> plain `regex` crate.
static PAREN_TAX_NOTE: LazyLock<Regex> = LazyLock::new(|| {
    Regex::new(
        r"(?i)(?-u:\s*)\((?-u:\s*)((?:nec|non|not)(?-u:\s+)[^)]+|(?:auctt?|auctorum|sensu|sec|vide|synonym)(?-u:\b)[^)]*)\)(?-u:\s*)\.?(?-u:\s*)$",
    )
    .unwrap()
});

/// The Rust-only concept-keyword branch of [`PAREN_TAX_NOTE`] (`auct`/`auctt`/`auctorum`/`sensu`/
/// `sec`/`vide`/`synonym`).
static PAREN_CONCEPT_NOTE: LazyLock<Regex> = LazyLock::new(|| {
    Regex::new(r"(?i)^(?:auctt?|auctorum|sensu|sec|vide|synonym)(?-u:\b)").unwrap()
});
/// A standalone indeterminate rank-marker word (`sp.`, `spp.`, `spec.`, `species`, `indet.`).
static INDET_MARKER_WORD: LazyLock<Regex> =
    LazyLock::new(|| Regex::new(r"(?i)(?-u:\b)(?:spp?|spec|species|indet)(?-u:\b)").unwrap());

/// Java `StripAndStash.stripParenTaxNote` (StripAndStash.java:1334-1344). A trailing
/// "(nec/non/not …, YYYY)" parenthesised homonym citation — the WHOLE bracket wraps the
/// note (unlike step 40's sibling `PAREN_NOTE`/`LEADING_HOMONYM_PAREN`, ported further down
/// this file as part of `strip_authorship_markers` — those handle a homonym citation
/// embedded inside an authorship span, not this end-anchored standalone form) — APPENDS the
/// captured text (verbatim, trimmed) to `taxonomicNote` — spot-checked: "Aus bus Smith (non
/// Foo, 1850)" -> `taxonomicNote="non Foo, 1850"`, authors=["Smith"].
/// A parenthesised taxonomic note before the author on the name string — "… var. nelsonii (auct.)
/// Baker", "… (sensu Mereschkowsky, 1878) Jankowski, 1992": group 1 the note, group 2 the first
/// letter of the author it is followed by. The keyword alone is case-insensitive.
static PAREN_NOTE_BEFORE_AUTHOR: LazyLock<Regex> = LazyLock::new(|| {
    Regex::new(r"\s\(\s*((?i:auctt?|auctorum|sensu|sec)\b[^)]*)\)\s*(\p{Lu})").unwrap()
});

/// A parenthesised homonym note followed by a sensu note, "(non Scacchi, 1836) sensu Zibrowius,
/// 1968": together the taxonomic note, verbatim, as in a separate authorship.
static PAREN_HOMONYM_THEN_NOTE: LazyLock<Regex> = LazyLock::new(|| {
    Regex::new(r"\s(\(\s*(?i:non|nec|not)\s[^)]+\)\s*(?i:sensu|auct|sec)\b.*)$").unwrap()
});

/// "(auct.) auct.": the bracketed note only repeats the one that follows.
static PAREN_AUCT_REPEATED: LazyLock<Regex> =
    LazyLock::new(|| Regex::new(r"\s\(\s*(?i:auctt?\.?|auctorum)\s*\)\s*((?i:auct))").unwrap());

fn strip_paren_tax_note(ctx: &mut ParseContext, s: String) -> String {
    if let Some(caps) = PAREN_SENSU_STRICTO.captures(&s) {
        ctx.name
            .add_taxonomic_note(&WHITESPACE.replace_all(caps.get(1).unwrap().as_str(), " "));
        let whole = caps.get(0).unwrap();
        let s = format!("{} {}", java_trim(&s[..whole.start()]), &s[whole.end()..]);
        return strip_paren_tax_note(ctx, java_trim(&s).to_string());
    }
    if let Some(caps) = PAREN_AUCT_REPEATED.captures(&s) {
        let (whole, next) = (caps.get(0).unwrap(), caps.get(1).unwrap());
        let s = format!("{} {}", java_trim(&s[..whole.start()]), &s[next.start()..]);
        return strip_paren_tax_note(ctx, s);
    }
    // the two shapes a separate authorship already reads as notes, alike on the name string
    if let Some(caps) = PAREN_HOMONYM_THEN_NOTE.captures(&s) {
        let note = collapse_whitespace(java_trim(caps.get(1).unwrap().as_str()));
        ctx.name.add_taxonomic_note(&note);
        return java_trim(&s[..caps.get(0).unwrap().start()]).to_string();
    }
    if let Some(caps) = PAREN_NOTE_BEFORE_AUTHOR.captures(&s) {
        let note = WHITESPACE.replace_all(java_trim(caps.get(1).unwrap().as_str()), " ");
        ctx.name.add_taxonomic_note(&normalise_leading_auct(&note));
        let whole = caps.get(0).unwrap();
        let author = caps.get(2).unwrap().start();
        return format!("{} {}", java_trim(&s[..whole.start()]), &s[author..]);
    }
    if let Some(caps) = PAREN_TAX_NOTE.captures(&s) {
        let whole = caps.get(0).unwrap();
        // A provisional `Genus sp. a (sensu Eagle)` keeps its concept citation in the phrase: the
        // flat Informal result has no note slot, so stripping it here would silently drop it.
        if PAREN_CONCEPT_NOTE.is_match(caps.get(1).unwrap().as_str())
            && INDET_MARKER_WORD.is_match(&s[..whole.start()])
        {
            return s;
        }
        let note = normalise_leading_auct(java_trim(caps.get(1).unwrap().as_str()));
        ctx.name.add_taxonomic_note(&note);
        return java_trim(&s[..whole.start()]).to_string();
    }
    s
}

// ---- Step 41: stripSensuLatoRemainder ----

/// Java SENSU_LATO_REMAINDER (StripAndStash.java:91-92):
/// `\s+(s\.\s*l\.?|s\.\s*lat\.?|s\.\s*str\.?|s\.\s*ampl\.?)\s+(\S.*?)\s*$`, no flags
/// (deliberately case-sensitive — the Java comment: the marker is lower-case "s", so
/// uppercase author initials like "S. L. Schultes" are never mistaken for it). Has `\s`
/// (many) AND an unescaped wildcard `.` (inside the lazy `.*?`) -> atom-only ASCII
/// scoping (never whole-wrap, matching `MISSING_GENUS_NOTE_KEYWORD`'s precedent: whole-
/// wrapping would also flip `.`'s Unicode-scalar-vs-byte meaning). `\S` (negated
/// shorthand) CANNOT be ASCII-scoped at all — `(?-u:\S)` is rejected by `regex-syntax` with
/// the identical "pattern can match invalid UTF-8" error as a negated custom class (
/// confirmed empirically; same restriction as `[^…]`, just for the shorthand spelling) ->
/// `\S` stays at the crate's Unicode default, unscoped, like every other
/// can't-be-ASCII-scoped atom in this file. The lazy `.*?` needs no `fancy_regex`: the
/// plain `regex` crate is a Pike's-VM/Thompson-NFA linear-time automaton that natively
/// supports non-greedy quantifiers (laziness is a match-preference rule the automaton
/// applies directly, not a backtracking construct) — no lookaround/backreference at all
/// here -> plain `regex` crate.
static SENSU_LATO_REMAINDER: LazyLock<Regex> = LazyLock::new(|| {
    Regex::new(
        r"(?-u:\s+)(s\.(?-u:\s*)l\.?|s\.(?-u:\s*)lat\.?|s\.(?-u:\s*)str\.?|s\.(?-u:\s*)ampl\.?)(?-u:\s+)(\S.*?)(?-u:\s*)$",
    )
    .unwrap()
});

/// Java `StripAndStash.stripSensuLatoRemainder` (StripAndStash.java:1306-1318). A
/// mid-string "s.l."/"s.lat."/"s.str."/"s.ampl." marker followed by trailing junk that
/// isn't part of the name (e.g. a truncated re-citation after a dash) — the marker
/// (whitespace-removed, lower-cased) APPENDS to `taxonomicNote` and the trailing junk
/// (trimmed) is parked in `ctx.pending_unparsed` (first-writer-wins), populated faithfully
/// for the downstream stages that consume it — spot-checked:
/// "Asplenium trichomanes L. s.lat. - Asplen trich" -> `taxonomicNote="s.lat."`,
/// `unparsed="- Asplen trich"` (the `unparsed` JSON field itself, like `state=PARTIAL`, is
/// assembled by Pipeline/Assemble from `pending_unparsed` — this step
/// only needs to stash the pending value).
fn strip_sensu_lato_remainder(ctx: &mut ParseContext, s: String) -> String {
    if let Some(caps) = SENSU_LATO_REMAINDER.captures(&s) {
        let marker = caps.get(1).unwrap().as_str();
        let note = WHITESPACE.replace_all(marker, "").to_lowercase();
        let remainder = java_trim(caps.get(2).unwrap().as_str()).to_string();
        ctx.name.add_taxonomic_note(&note);
        let whole = caps.get(0).unwrap();
        let name = java_trim(&s[..whole.start()]);
        // Rust-only: the authorship after a marker straight behind the epithet (or genus) stays for the
        // authorship parser ("Acantholimon ulicinum s.l. (Schultes) Boiss."); Java left it unparsed.
        // After an author it is the concept's ("Inocybe tarda Kühner s. str. Stangl").
        let after_epithet = !name.contains(' ')
            || name
                .split_whitespace()
                .last()
                .is_some_and(|w| w.chars().all(char::is_lowercase));
        if after_epithet && AUTHORSHIP_START.is_match(&remainder) {
            return format!("{name} {remainder}");
        }
        ctx.set_pending_unparsed(&remainder);
        return name.to_string();
    }
    s
}

/// The start of an authorship: a capitalised author, or a basionym bracket of capitalised authors
/// and a year — not a phrase like "(Kulnura form)".
static AUTHORSHIP_START: LazyLock<Regex> = LazyLock::new(|| {
    Regex::new(
        r"^(?:\p{Lu}\p{Ll}*\.?(?:\s|,|$)|\(\p{Lu}[\p{L}.'\-]*(?:(?:\s+|\s*&\s*|\s+(?:et|ex|in)\s+)\p{Lu}[\p{L}.'\-]*)*(?:,?\s*\d{4})?\))",
    )
    .unwrap()
});

// ---- Step 42: stripSensuStrictoSS ----

/// Java SENSU_STRICTO_SS (StripAndStash.java:96-97): `\s+s\.\s*s\.?(\s+\S.*?)?\s*$`, no
/// flags (case-sensitive, same reasoning as `SENSU_LATO_REMAINDER`). Has `\s` (several)
/// and `\S` plus an unescaped wildcard `.` -> same atom-only scoping as
/// `SENSU_LATO_REMAINDER` (`\S`/`.` left unscoped, `\s` atoms individually ASCII-scoped).
/// No lookaround/backreference -> plain `regex` crate.
static SENSU_STRICTO_SS: LazyLock<Regex> =
    LazyLock::new(|| Regex::new(r"(?-u:\s+)s\.(?-u:\s*)s\.?((?-u:\s+)\S.*?)?(?-u:\s*)$").unwrap());

/// Java `StripAndStash.stripSensuStrictoSS` (StripAndStash.java:1320-1332). A trailing
/// "s.s." ("s. s." also matches — `\s*` between the two "s."s) sensu-stricto marker
/// APPENDS the FIXED literal "s.s." (not the captured text, which may have had internal
/// spacing) to `taxonomicNote` — matching Java's `existing == null ? "s.s." : existing +
/// " s.s."` inline literal, not a call through `add_taxonomic_note` with a variable.
/// When followed by trailing junk (group 1 present), that junk (trimmed) is parked in
/// `ctx.pending_unparsed`, conditionally — Java's `if (m.group(1) != null)` guard, unlike
/// step 41's sibling where the remainder is unconditionally captured (there, group 2 is
/// required by the pattern itself; here group 1 is optional) — spot-checked: "Aus bus
/// s.s." -> `taxonomicNote="s.s."`, no unparsed; "Aus bus s.s. extra text here" ->
/// `taxonomicNote="s.s."`, `unparsed="extra text here"`.
fn strip_sensu_stricto_ss(ctx: &mut ParseContext, s: String) -> String {
    if let Some(caps) = SENSU_STRICTO_SS.captures(&s) {
        ctx.name.add_taxonomic_note("s.s.");
        if let Some(junk) = caps.get(1) {
            ctx.set_pending_unparsed(java_trim(junk.as_str()));
        }
        let whole = caps.get(0).unwrap();
        return java_trim(&s[..whole.start()]).to_string();
    }
    s
}

// ---- Step 43: stripTaxNote ----

// RULE: patterns on fancy_regex (backtracking) MUST keep Java's possessive/atomic
// quantifiers — only DROP possessives for patterns on the linear `regex` crate. TAX_NOTE
// has no possessive quantifier and no lookaround/backreference at all -> plain `regex`
// crate, nothing to preserve here.
/// Java TAX_NOTE (StripAndStash.java:68-84), `Pattern.CASE_INSENSITIVE` overall, WITH an
/// inline `(?-i:…)` case-SENSITIVE carve-out for the trailing s.l./s.str./s.lat./s.ampl.
/// alternative (lower-case "s", so uppercase author initials "S.L." aren't eaten —
/// mirrors the sibling `SENSU_LATO_REMAINDER`/`SENSU_STRICTO_SS` patterns' own
/// case-sensitivity). Has `\s`/`\b` AND `\p{Lu}` AND unescaped wildcards (`.*`, several)
/// -> atom-only ASCII scoping throughout (never whole-wrap) — `\s`/`\b` individually
/// `(?-u:…)`-scoped, `\p{Lu}` always Unicode, `.` left at default. The inline `(?-i:…)`
/// nests independently of the `(?-u:…)` atom scoping (both toggle unrelated flags, freely
/// combinable). No lookaround/backreference anywhere -> plain `regex` crate. Built via
/// `concat!` (one alternative per line, matching Java's own `"..." + "..."` source
/// layout) so it stays directly diffable against StripAndStash.java line-by-line, same
/// convention as `NOM_NOTE` in batch 2. One Rust-only alternative: the spelled-out "auctorum"
/// ("of authors", i.e. auct.) — `Astacilla bonnieri Auctorum`, `auctorum non Westwood, 1847` —
/// which Java read as an author or an infraspecific epithet. Also Rust-only: "not" shaped like
/// "non" (`Ashmead 1887 not Motschulsky 1863`), which Java read as an author — but only before
/// something shaped like an author (`Kirby`, `L.`, `DC.`, matched case-sensitively via `(?-i:…)`:
/// under `(?i)` `\p{Lu}` matches any letter), so "species not specified", "Not applicable" and
/// "[GENUS NOT SPECIFIED]" stay put. Both are real
/// epithets too, so `strip_tax_note` keeps them in that slot (see [`note_keyword_is_epithet`]).
/// Rust-only as well, each read by Java as authors: "Em."/"em." between two authors, the
/// foraminifera catalogues' abbreviated emend. (`Sigal Em. Moullade, 1966`); "vide" (see:
/// `Meneghini in De Amicis, 1885 vide Neviani (1900)`); and "of" before the authors whose concept
/// is meant, as WoRMS writes it (`Olsson of Looss, 1899`, `of authors`). [`find_tax_note`] guards
/// the last two shapes against an author's initials and plain English. Rust-only too: "sens. str." and
/// "sens. lat." spelled out further than "s. str." (`Rubus fruticosus L. sens.str.`), and "ampl.",
/// the amplified circumscription of `Cerastium octandrum Hochst. ex A.Rich. ampl. Möschl`.
static TAX_NOTE: LazyLock<Regex> = LazyLock::new(|| {
    Regex::new(concat!(
        r"(?i)(?-u:\s+),?(?-u:\s*)(",
        r"auctt?(?-u:\b)\.?(?:[,.]?(?-u:\s).*)?",
        r"|auctorum(?-u:\b)(?:[,.]?(?-u:\s).*)?",
        r"|sensu\.?(?:(?-u:\s).*)?",
        r"|sec\.?(?:(?-u:\s).*)?",
        r"|nec(?-u:\b)(?:(?-u:\s).*)?",
        r"|nonn?\.?(?-u:\s+)\(?\p{Lu}.*",
        r"|not(?-u:\s+)\(?(?-i:\p{Lu}(?:\p{Ll}|\.|\p{Lu}\.)).*",
        r"|emend(?-u:\b)\.?(?-u:\s+)\(?\p{Lu}.*",
        r"|(?-i:[Ee]m\.)(?-u:\s+)\(?(?-i:\p{Lu}).*",
        r"|fide(?-u:\b)\.?(?-u:\s+)\(?\p{Lu}.*",
        r"|(?-i:[Vv]ide)(?-u:\s+)\(?(?-i:\p{Lu}).*",
        r"|(?-i:[Oo]f)(?-u:\s+)(?:authors(?-u:\b)|(?-i:\p{Lu})|d'|(?-i:de|van|von|la|le|du)(?-u:\s)).*",
        r"|according(?-u:\s+)to(?-u:\s+)\p{Lu}.*",
        r"|excl\.(?-u:\s+).*",
        r"|ss(?-u:\b)\.?(?-u:\s+).*",
        r"|(?-i:s\.(?-u:\s*)l\.?|s\.(?-u:\s*)str\.?|s\.(?-u:\s*)lat\.?|s\.(?-u:\s*)ampl\.?)",
        r"|(?-i:sens\.(?-u:\s*)(?:str|lat|l|ampl)\.?)",
        r"|(?-i:ampl\.)(?-u:\s+)\(?(?-i:\p{Lu}).*",
        r")$",
    ))
    .unwrap()
});

/// Java INITIAL_DOT_SPACE (StripAndStash.java:314-315):
/// `\b(\p{Lu})\.\s+([\p{Ll}][\p{Ll}]{3,})`, no flags. Has `\b`/`\s` and `\p{Lu}`/`\p{Ll}`
/// -> atom-only ASCII scoping for `\b`/`\s`. No lookaround/backreference -> plain `regex`
/// crate; the replacement pulls both captures back via `$1.$2`, the SAME `$N` syntax Java
/// and the `regex` crate happen to share. IMPORTANT (verified against the real Java CLI
/// oracle, NOT just the Java source's own paraphrasing comment — see
/// `strip_tax_note`'s doc below): group 2 requires an ALL-LOWERCASE run of >= 4 letters,
/// so this only collapses "Initial. word" when the word is a bare lowercase token (e.g. a
/// species-epithet-shaped word) — a capitalised surname like "F. Schmidt" is NOT
/// collapsed (`\p{Ll}` rejects the leading capital "S"); "non F. europaeus" -> "non
/// F.europaeus" IS collapsed.
static INITIAL_DOT_SPACE: LazyLock<Regex> =
    LazyLock::new(|| Regex::new(r"(?-u:\b)(\p{Lu})\.(?-u:\s+)([\p{Ll}][\p{Ll}]{3,})").unwrap());

/// A note keyword alone in brackets, followed by its author: "[sensu] Schmidt, 1878". Rust-only.
static KEYWORD_ONLY_BRACKET: LazyLock<Regex> = LazyLock::new(|| {
    Regex::new(r"(?i)\[(?-u:\s*)(sensu|sec\.?|non|nec|not|auctt?\.?|auctorum)(?-u:\s*)\](?-u:\s+)")
        .unwrap()
});

/// Drops the brackets around a lone note keyword ("[sensu] Schmidt, 1878" -> "sensu Schmidt,
/// 1878") so [`TAX_NOTE`] takes the whole note. Java left the bracket in place, so TAX_NOTE (which
/// needs whitespace before the keyword) missed it and "sensu Schmidt" became the author.
fn unwrap_keyword_only_bracket(s: &str) -> String {
    KEYWORD_ONLY_BRACKET.replace_all(s, "$1 ").into_owned()
}

/// An emendation inside the basionym's brackets, after its year: "(Sakagami, 1956 Em. Chisaka,
/// 1960)". Lifted out behind the bracket, where [`TAX_NOTE`] takes it as the note it is. Rust-only:
/// Java read "Em." as Chisaka's initials and 1960 as an imprint year.
static BRACKETED_EMENDATION: LazyLock<Regex> = LazyLock::new(|| {
    Regex::new(
        r"\(([^()]*?(?-u:\d{4}))(?-u:\s*),?(?-u:\s+)((?:[Ee]m\.|emend\.?)(?-u:\s+)\p{Lu}[^()]*)\)",
    )
    .unwrap()
});

fn lift_bracketed_emendation(s: &str) -> String {
    BRACKETED_EMENDATION.replace(s, "($1) $2").into_owned()
}

/// A concept note inside the basionym's brackets, after its author: "(Mag of Dollfus 1952)", "(Hall
/// of Johnson 1965)" — Mag's species in the sense of Dollfus. Group 1 is the author(s), group 2 the
/// note.
static BRACKETED_OF: LazyLock<Regex> = LazyLock::new(|| {
    let name = r"\p{Lu}[\p{L}'’.\-]*";
    Regex::new(&format!(
        r"\(({name}(?:\s+(?:&|and|et)\s+{name})*)\s+(of\s+\p{{Lu}}[^()]*)\)"
    ))
    .unwrap()
});

/// Moves an "of" note out of the basionym's bracket to the end ("(Mag of Dollfus 1952)" -> "(Mag)
/// of Dollfus 1952", "(Schellwien of Grozdylova & Lebedeva 1961) Smith" -> "(Schellwien) Smith of
/// Grozdylova & Lebedeva 1961"), where [`TAX_NOTE`] takes it like an "of" note after the bracket.
/// Only a basionym's bracket — first in the authorship or straight after an epithet, never after an
/// author ("Dennis (Fungi of South East England)") or a genus ("Copelatus (Ivohibe and North of
/// Toamasina)") — and only when the note names authors ([`OF_AUTHORS`]) and the "of" is no part of
/// a corporate author ("(Research Group of Orthoptera, 1983)"), a "not of" ("(Not of Linnaeus,
/// 1758)") or a direction ("(E of Wollogorang …)"). Rust-only: Java read "Mag of Dollfus" as the
/// basionym author.
fn lift_bracketed_of(s: &str) -> String {
    let Some(caps) = BRACKETED_OF.captures(s) else {
        return s.to_string();
    };
    let (whole, authors, note) = (caps.get(0).unwrap(), &caps[1], &caps[2]);
    let before = java_trim(&s[..whole.start()]);
    let basionym_place = before.is_empty()
        || before
            .rsplit(char::is_whitespace)
            .next()
            .is_some_and(|w| w.chars().all(|c| c.is_lowercase() || c == '-'));
    let last = authors.rsplit(char::is_whitespace).next().unwrap_or("");
    let no_author = last.chars().count() < 2
        || ["not", "non", "north", "south", "east", "west"]
            .iter()
            .any(|w| last.eq_ignore_ascii_case(w));
    if !basionym_place || no_author || CORPORATE_WORD.is_match(last) || !OF_AUTHORS.is_match(note) {
        return s.to_string();
    }
    let rest = java_trim(&s[whole.end()..]);
    let mut out = format!("{}({authors})", &s[..whole.start()]);
    if !rest.is_empty() {
        out.push(' ');
        out.push_str(rest);
    }
    out.push(' ');
    out.push_str(java_trim(note));
    out
}

/// The notes inside a basionym's brackets that belong behind them: an emendation and a concept.
fn lift_bracketed_notes(s: &str) -> String {
    lift_bracketed_of(&lift_bracketed_emendation(s))
}

/// The authors a concept "of …" names: up to the first year, comma or bracket — never a lower-case
/// word, so "endosymbiont of Drosophila simulans" stays.
static OF_AUTHORS: LazyLock<Regex> = LazyLock::new(|| {
    let particle = r"(?:de|da|du|van|von|der|den|la|le|d')";
    let name = format!(r"(?:{particle}\s*)*\p{{Lu}}[\p{{L}}'’.\-]*");
    Regex::new(&format!(
        r"^of\s+(?:(?:\p{{Lu}}\p{{Ll}}+\s+)?authors\b.*|{name}(?:\s+(?:{name}|{particle}|&|and|et))*(?:\s+et\s+al\.?)?(?:[,(\[].*|\s+[\[(]?\d{{4}}.*)?)$"
    ))
    .unwrap()
});

/// A word that makes "of" part of a corporate author: "Research Group of Orthoptera, 1983", "Sichuan
/// Institute of Biology Herpetology Department, 1977".
static CORPORATE_WORD: LazyLock<Regex> = LazyLock::new(|| {
    Regex::new(concat!(
        r"(?i)^(?:institute|institution|department|dept\.?|group|society|museum|university|academy|",
        r"college|survey|committee|commission|board|ministry|school|faculty|laboratory|garden|",
        r"gardens|herbarium|office|bureau|service|association|union|team|station|cent(?:er|re)|",
        r"council|division|section|unit|members|staff|students|project|consortium|network)$",
    ))
    .unwrap()
});

/// An "in" citation before the match: "Ye in Sichuan Institute of Biology Herpetology Department,
/// 1977" is a publication, not a concept.
static IN_CITATION_START: LazyLock<Regex> = LazyLock::new(|| Regex::new(r"\sin\s+\p{Lu}").unwrap());

/// The first [`TAX_NOTE`] match in `s` that is a note: `(start of the whole match, start of the
/// note)`. "Em." is a note only after an author — on its own (`Em. Schmid`) it is Emil's initials,
/// and on the name string the word before it must be an author's, not the genus or an epithet. An
/// "of" note must name authors, and never follows an "in" citation it belongs to, a corporate
/// author's word, nor an indeterminate marker, whose phrase it is. None of the three starts inside
/// a bracket. `authorship_only` tells a separately supplied authorship from the name string.
fn find_tax_note(s: &str, authorship_only: bool) -> Option<(usize, usize)> {
    let mut from = 0;
    while let Some(caps) = TAX_NOTE.captures_at(s, from) {
        let (whole, note) = (caps.get(0).unwrap(), caps.get(1).unwrap());
        let raw = note.as_str();
        let prefix = java_trim(&s[..whole.start()]);
        let last_word = prefix.rsplit(char::is_whitespace).next().unwrap_or("");
        // inside an open bracket the note would take the bracket's author with it: "(Nardo of
        // Dollfus 1935)", "(Sakagami, 1956 Em. Chisaka, 1960)"
        let closed = prefix.matches('(').count() == prefix.matches(')').count();
        let keep = if raw.starts_with("Em.") || raw.starts_with("em.") {
            closed && follows_author(prefix, authorship_only)
        } else if raw.starts_with("vide") || raw.starts_with("Vide") {
            closed
        } else if raw.starts_with("of ") || raw.starts_with("Of ") {
            // "?Archaeopharetra sp. of Zhuravlev & Gravestock 1994" names their species: the phrase
            closed
                && OF_AUTHORS.is_match(raw)
                && !IN_CITATION_START.is_match(&s[..whole.start()])
                && !INDET_MARKER_WORD.is_match(last_word)
                && !CORPORATE_WORD.is_match(last_word)
        } else {
            true
        };
        if keep {
            return Some((whole.start(), note.start()));
        }
        from = whole.start() + s[whole.start()..].chars().next().map_or(1, char::len_utf8);
    }
    None
}

/// `prefix` ends in an author: a word starting upper case, a year or a closing bracket. On the name
/// string the genus comes first, so it needs a word before that one.
fn follows_author(prefix: &str, authorship_only: bool) -> bool {
    let words: Vec<&str> = prefix.split_whitespace().collect();
    let Some(last) = words.last() else {
        return false;
    };
    let author_like = last.ends_with(')')
        || last.ends_with(',')
            && last
                .trim_end_matches(',')
                .chars()
                .all(|c| c.is_ascii_digit())
        || last.chars().all(|c| c.is_ascii_digit())
        || last.chars().next().is_some_and(char::is_uppercase);
    author_like && (authorship_only || words.len() >= 2)
}

/// Java `StripAndStash.stripTaxNote` (StripAndStash.java:1346-1367). The general,
/// end-anchored taxonomic-note anchor (auct./auctt./sensu/sec./nec/non/nonn./emend./
/// fide/according to/excl./ss/s.l./s.str./s.lat./s.ampl.) — the LAST of the six
/// taxonomic-note steps to run, so anything more specific was already peeled off by
/// `strip_colon_concept_reference`/`strip_bracketed_tax_note`/`strip_paren_tax_note`/
/// `strip_sensu_lato_remainder`/`strip_sensu_stricto_ss` above it. Applies
/// `INITIAL_DOT_SPACE` (collapses a bare-initial-plus-lowercase-word gap) then
/// `normalise_leading_auct` (lower-cases a leading title-case "Auct"/"Auctt") to the
/// captured text, then PREPENDS it to any `taxonomicNote` steps 38-43 already peeled off the
/// end of the string, since this note stands in front of theirs — a deliberate divergence
/// from Java's plain `setTaxonomicNote(norm)`, which overwrote and so silently dropped
/// "[non (L.) Nees]" from "Fossombronia pusilla auct. amer. [non (L.) Nees]" (now "auct.
/// amer. non (L.) Nees"). A guard skips entirely when the captured,
/// trimmed group is empty (Java: `if (!raw.isEmpty())`) — the outer match can still have
/// fired on pure separator text with nothing captured after trimming, in which case
/// neither the working string nor `taxonomicNote` should change. After stripping, any
/// now-trailing comma(s) left dangling are removed in a loop (re-trimming each time,
/// same idiom as `strip_nom_note` in batch 2) — spot-checked against the Java CLI oracle:
/// "Chlorobium phaeobacteroides Pfennig, 1968 emend. Imhoff, 2003" ->
/// `taxonomicNote="emend. Imhoff, 2003"`; "... emend Imhoff, 2003" (no dot) -> `"emend
/// Imhoff, 2003"`; "Eulima excellens Verkrüzen fide Paetel, 1887" -> `"fide Paetel,
/// 1887"`; "Procamallanus (Spirocamallanus) soodi Lakshmi & Kumari, 2001 nec (Gupta &
/// Masood, 1988)" -> `"nec (Gupta & Masood, 1988)"`; "Membranipora minuscula Canu, 1911
/// non Hincks, 1882" -> `"non Hincks, 1882"`; "Aus bus auct." -> `"auct."`; "Aus bus
/// Auct."/"Aus bus Auctt." -> `"auct."`/`"auctt."` (title-case lower-cased via
/// `normalise_leading_auct`); "Aus bus s.l." -> `"s.l."` (case-sensitive `(?-i:…)`
/// branch); uppercase "Aus bus Mill. S.L." does NOT match at all (author initials, not a
/// sensu-lato marker).
fn strip_tax_note(ctx: &mut ParseContext, s: String) -> String {
    let s = lift_bracketed_notes(&unwrap_keyword_only_bracket(&s));
    let Some((match_start, note_start)) = find_tax_note(&s, false) else {
        return s;
    };
    let raw = java_trim(&s[note_start..]).to_string();
    if raw.is_empty() {
        return s;
    }
    if (raw.starts_with("auctorum") || raw.starts_with("not "))
        && note_keyword_is_epithet(&s[..match_start], ctx.requested_rank)
    {
        return s;
    }
    let with_dots = INITIAL_DOT_SPACE.replace_all(&raw, "$1.$2");
    let norm = normalise_leading_auct(&with_dots);
    ctx.name.taxonomic_note = Some(match ctx.name.taxonomic_note.take() {
        None => norm,
        Some(later) => format!("{norm} {later}"),
    });
    let mut result = java_trim(&s[..match_start]).to_string();
    while result.ends_with(',') {
        result.pop();
        result = java_trim(&result).to_string();
    }
    result
}

// ---- Step 44: stripAggregateSuffix ----

/// Java AGGREGATE (StripAndStash.java:138-141):
/// `(?:\s+(?:agg\.?|aggregate|species\s+group|species\s+complex|group|complex)|\s*-\s*group|\s*-\s*aggregate)\s*$`,
/// `Pattern.CASE_INSENSITIVE`. Has `\s` (many), no `\p{...}`, no unescaped wildcard ->
/// whole-wrap ASCII scope. No lookaround/backreference -> plain `regex` crate. NOTE:
/// `regexes::AGGREGATE` (the Phase 0 spike file) already has a same-named pattern, but it
/// predates this port's per-pattern flag rule and is NOT ASCII-scoped (default Unicode
/// `\s` throughout) — reusing it here would introduce a `\s`-scope divergence from Java,
/// so this is a fresh, correctly-scoped definition local to this module, same precedent
/// as `SIC`/`CORRIG` in batch 2 (`strip_sic_and_corrig`'s doc comment).
static AGGREGATE: LazyLock<Regex> = LazyLock::new(|| {
    Regex::new(
        r"(?i)(?-u:(?:\s+(?:agg\.?|aggregate|species\s+group|species\s+complex|group|complex)|\s*-\s*group|\s*-\s*aggregate)\s*)$",
    )
    .unwrap()
});

/// Java `StripAndStash.stripAggregateSuffix` (StripAndStash.java:1369-1377). A trailing
/// " agg."/"aggregate"/"species group"/"species complex"/"group"/"complex"/"-group"/
/// "-aggregate" suffix marks a species aggregate: sets `ctx.aggregate = true` (a direct
/// field write, matching Java's package-private `ctx.aggregate = true;` — NOT one of the
/// 10 downstream-independent gate fields; consumed by Assemble to
/// promote `rank` to `SPECIES_AGGREGATE`) and strips the suffix — spot-checked against
/// the Java CLI oracle (rank promotion itself is Assemble's job, so this only confirms
/// the working-string strip leaves a clean binomial in all three shapes):
/// "Achillea millefolium agg." / "... species group" / "...-group" all reduce the working
/// string to "Achillea millefolium".
fn strip_aggregate_suffix(ctx: &mut ParseContext, s: String) -> String {
    if let Some(m) = AGGREGATE.find(&s) {
        ctx.aggregate = true;
        return java_trim(&s[..m.start()]).to_string();
    }
    s
}

// ---------------------------------------------------------------------------------
// Batch 4 (steps 45-52): published-in family (page, in-press, in-author variants,
// IPNI, period-/comma-separated references) + manuscript marker. Ported (Phase 1
// Slice 2, batch 2d). This batch closes `publishedIn`/`publishedInPage`/
// `publishedInYear`/`manuscript` and (jointly with batch 2b's already-ported
// `stripNomNote`/`stripBracketedNomNote`, steps 29/30) `nomenclaturalNote`. Steps 47/
// 48 (`stripInAuthorInParens`/`stripInAuthorCitation`) APPEND to `publishedIn` via the
// new `ParsedName::add_published_in` — Java's inline `existing == null ? ref :
// existing + " " + ref` immediately followed by `setPublishedIn(combined)`; appending
// and re-deriving `publishedInYear` from the COMBINED string are the SAME Java call,
// not two. Steps 49/50/51 (`stripIpniCitation`/`stripPeriodSeparatedReference`/
// `stripCommaPrefixedReference`) OVERWRITE it directly via `set_published_in` (Java's
// plain `setPublishedIn(ref)`, no null-check — nothing upstream of any of them can
// have already populated a reference). Steps 46/49/52 APPEND to `nomenclaturalNote`
// via `add_nomenclatural_note`. New `ParseContext::set_pending_publication_year`
// (first-writer-wins, mirrors `set_pending_imprint_year`) is threaded through from
// steps 48/49/50 and consumed downstream by Pipeline (applied onto the combination
// authorship's year — see `pipeline::mod`'s own doc comment), same
// port-the-producer-and-consumer-together pattern already used for
// `pending_generic_author`/`pending_specific_author`. All worked examples below were
// spot-checked against the real Java CLI oracle, same convention as batches 1-2c.
// ---------------------------------------------------------------------------------

// ---- Step 45: stripPublishedPage ----

/// Java PUBLISHED_PAGE (StripAndStash.java:157-158): `\s*:\s*(\d+(?:[-–]\d+)?)\s*$`, no
/// flags. Has `\s`/`\d`, no `\p{...}`, no unescaped wildcard — but embeds a non-ASCII literal
/// (the en dash, `–`) inside the custom class `[-–]` -> same `IMPRINT_YEAR_QUOTED`/
/// `IMPRINT_YEAR_KEYWORD` precedent from batch 1: only the individual `\s`/`\d` atoms are
/// ASCII-scoped, `[-\x{2013}]` left outside any `(?-u:…)` group (`regex-syntax` rejects a
/// non-ASCII literal inside one — "Unicode not allowed here"). No lookaround/backreference ->
/// plain `regex` crate.
static PUBLISHED_PAGE: LazyLock<Regex> = LazyLock::new(|| {
    Regex::new(r"(?-u:\s*):(?-u:\s*)((?-u:\d+)(?:[-\x{2013}](?-u:\d+))?)(?-u:\s*)$").unwrap()
});

/// Java `StripAndStash.stripPublishedPage` (StripAndStash.java:1379-1388). A trailing page
/// reference (": 377", ": 12-18", or with the colon glued/spaced either side, e.g. ":29" /
/// " : 29") is pulled directly into `publishedInPage` (a plain field write —
/// `ParsedAuthorship.setPublishedInPage` has no side effect, unlike `setPublishedIn`) and
/// stripped — spot-checked against the Java CLI oracle: "Anolis marmoratus girafus LAZELL
/// 1964: 377" -> `publishedInPage="377"`, working string "Anolis marmoratus girafus LAZELL
/// 1964"; "Recilia truncatus Dash & Viraktamath, 1998a: 29" (and its glued/extra-spaced
/// variants ":29" / " : 29") all -> `publishedInPage="29"`. Runs BEFORE
/// `strip_in_author_citation` (step 48) so a "Smith, 1900: 12 in Editor" tail strips both
/// cleanly (Java's own comment).
fn strip_published_page(ctx: &mut ParseContext, s: String) -> String {
    if let Some(caps) = PUBLISHED_PAGE.captures(&s) {
        let whole = caps.get(0).unwrap();
        // 5.0.0 divergence: a page reference is the tail of a PUBLICATION citation, so it must
        // follow a year — `Linnaeus, 1758: 228`, `LAZELL 1964: 377`, `Thor 1933:54`,
        // `(Stephens, 1829) : 151`. Strain and catalogue identifiers wear the same shape but carry
        // no year, and Java stripped those too: `Bacteroides caccae CAG:21` (a co-abundance-gene-
        // group MAG bin) was split into the bogus author "CAG" AND the bogus page 21, and
        // `irmng:1017387` into page 1017387. Requiring the year keeps every genuine citation --
        // including the tight `1933:54`, which no spacing rule could separate from `CAG:21` -- and
        // leaves the identifiers intact for the phrase/tag machinery downstream.
        if !ends_with_year_citation(&s[..whole.start()]) {
            return s;
        }
        ctx.name.published_in_page = Some(caps[1].to_string());
        // Keep the removed text verbatim (separator and spacing included). A museum or culture
        // catalogue number wears the same shape as a page citation — `Trachipterus sp.
        // HUMZ:220860` vs `Anolis marmoratus girafus LAZELL 1964: 377` — and the two cannot be
        // told apart here: the genuine `Raphitydeus Thor 1933:54` is just as tight as
        // `Prevotella sp. CAG:1031`. Assemble decides on the FINAL parse instead, restoring this
        // onto the phrase when the name turns out to be an indet informal.
        ctx.page_strip_verbatim = Some(whole.as_str().to_string());
        return java_trim(&s[..whole.start()]).to_string();
    }
    s
}

/// Java PUBLISHED_PAGE has no lookbehind, so [`strip_published_page`]'s "must follow a year" test
/// is done in code: does `prefix` end with a 4-digit year? A bibliographic letter suffix
/// (`"… Dash & Viraktamath, 1998a: 29"`) and a closing bracket with trailing space
/// (`"… (Stephens, 1829) : 151"`) are both allowed after it. Deliberately only 4 digits —
/// `Podperaea krylovii Accepted name, 55` ends in a number but not a year, and its "page" was
/// never trustworthy.
static TRAILING_YEAR_CITATION: LazyLock<Regex> =
    LazyLock::new(|| Regex::new(r"(?-u:\d{4})(?-u:[a-z])?[)\]]?(?-u:\s*)$").unwrap());

fn ends_with_year_citation(prefix: &str) -> bool {
    TRAILING_YEAR_CITATION.is_match(prefix)
}

// ---- Step 46: stripInPress ----

/// Java IN_PRESS (StripAndStash.java:144-145): `\s+in\s+press\b\.?`,
/// `Pattern.CASE_INSENSITIVE`. Has `\s` (x2) and `\b`, no `\p{...}`, no unescaped wildcard ->
/// whole pattern ASCII-scoped. No lookaround/backreference -> plain `regex` crate. NOT
/// end-anchored in Java (no trailing `$`), so this can in principle match anywhere in the
/// string, not just at the very end — ported as-is (see the function doc below for why that
/// matters to how the strip is applied).
static IN_PRESS: LazyLock<Regex> =
    LazyLock::new(|| Regex::new(r"(?i)(?-u:\s+in\s+press\b\.?)").unwrap());

/// Java `StripAndStash.stripInPress` (StripAndStash.java:1390-1400). A bare " in press"
/// marker sets `manuscript = true` and APPENDS the literal "in press" to `nomenclaturalNote`
/// (`ParsedName::add_nomenclatural_note`, Java's inline `existing == null ? "in press" :
/// existing + " in press"`) — spot-checked against the Java CLI oracle: "Abies alba Mill. in
/// press" -> `manuscript=true`, `nomenclaturalNote="in press"`, working string "Abies alba
/// Mill.". Java's `Matcher.replaceFirst("")` splices out exactly the matched span (which
/// already includes the leading whitespace via the pattern's own `\s+`) with NO subsequent
/// `.trim()` — ported as a direct mid-string splice rather than a truncate-to-match-start, to
/// stay faithful to that (the pattern isn't `$`-anchored, so it need not sit at the very end).
fn strip_in_press(ctx: &mut ParseContext, s: String) -> String {
    if let Some(m) = IN_PRESS.find(&s) {
        ctx.name.manuscript = true;
        ctx.name.add_nomenclatural_note("in press");
        return format!("{}{}", &s[..m.start()], &s[m.end()..]);
    }
    s
}

// ---- Steps 47 + 48: `in` / `apud` citations ----

/// Steps 47 and 48 together: split an `in` / `apud` citation off its author, first inside the
/// basionym parentheses, then at the tail. Shared by `run` and by the separately supplied
/// authorship in `pipeline::run`, so `Grunow in Van Heurck, 1883` gives the author `Grunow` and
/// `publishedIn="Van Heurck, 1883"` whichever way it arrives. Java only ran these steps on the
/// name string, so a separately supplied authorship kept the host inside the author (#20).
pub(crate) fn strip_in_author_citations(ctx: &mut ParseContext, s: String) -> String {
    let s = BRACKETED_IN_AUTHOR.replace_all(&s, "$1 in ").into_owned();
    let s = DANGLING_IN.replace(&s, "").into_owned();
    let before = ctx.name.published_in.clone();
    let s = strip_in_author_in_parens(ctx, s);
    let from_basionym = ctx.name.published_in != before;
    let published_in = ctx.name.published_in.clone();
    let s = strip_in_author_citation(ctx, s);
    // "(Grunow in Van Heurck) P. B. Ham. in Hamilton, …": the name was published where its
    // combination was, so that reference replaces the basionym's rather than joining it
    if from_basionym && ctx.name.published_in != published_in {
        let own = ctx.name.published_in.as_deref().and_then(|p| {
            published_in
                .as_deref()
                .and_then(|b| p.strip_prefix(b))
                .map(|rest| java_trim(rest).to_string())
        });
        if let Some(own) = own {
            ctx.name
                .set_published_in(&before.map_or(own.clone(), |b| format!("{b} {own}")));
        }
    }
    s
}

/// "[Péron in] Lamarck, 1819", "[Dryander in] Aiton": an in-citation whose author is set in
/// square brackets, the way catalogues mark an author taken from the work's text. Rust-only:
/// Java kept "Péron in Lamarck" as one author. Something must follow the bracket ("(L.) [Web.
/// in]" names no work).
static BRACKETED_IN_AUTHOR: LazyLock<Regex> =
    LazyLock::new(|| Regex::new(r"\[(\p{Lu}[^\[\]]*?)(?-u:\s+)(?:in|In)\](?-u:\s+)").unwrap());

/// A citation cut off after its "In" ("Asterocheres unicus Johnsson, In"): nothing to cite, and no
/// author either. Rust-only: Java read "In" as a second author.
static DANGLING_IN: LazyLock<Regex> =
    LazyLock::new(|| Regex::new(r"(?-u:,?\s+)(?:in|In)(?-u:\s*)$").unwrap());

// ---- Step 47: stripInAuthorInParens ----

/// Java IN_AUTHOR_IN_PARENS (StripAndStash.java:152-154):
/// `\(([^()]*?)\s+(?:in|apud)\s+(\p{Lu}[^()]*?)\)`, `Pattern.UNICODE_CHARACTER_CLASS` -> keep
/// default Unicode `\s`, ported verbatim. Both capture groups are LAZY (`[^()]*?`) — NO
/// lookaround, NO backreference -> the plain `regex` crate suffices (its leftmost-first match
/// semantics reproduce Java's backtracking result exactly for this lookaround-free,
/// backreference-free shape; confirmed empirically in an isolated scratch-crate spike against
/// the exact worked example below, not just assumed). group(1) = basionym author span,
/// group(2) = publication reference. Rust-only: the reference may also start with the anonymous
/// author "anon." (step 37 has already lower-cased "Anon."), as in "(Swainson in Anon. 1837)",
/// and the "in" may be capitalised, as in [`IN_AUTHOR`].
static IN_AUTHOR_IN_PARENS: LazyLock<Regex> = LazyLock::new(|| {
    Regex::new(r"\(([^()]*?)\s+(?:in|In|apud)\s+((?:\p{Lu}|anon\.)[^()]*?)\)").unwrap()
});

/// Java IN_AUTHOR_YEAR (StripAndStash.java:241-242): `,?\s*(\d{3,4})\s*\.?\s*$`, no flags. Has
/// `\s`/`\d`, no `\p{...}`, no unescaped wildcard -> whole pattern ASCII-scoped. Shared between
/// `strip_in_author_in_parens` (this step) and `strip_in_author_citation` (step 48, below),
/// same as Java's own single static field.
static IN_AUTHOR_YEAR: LazyLock<Regex> =
    LazyLock::new(|| Regex::new(r"(?-u:,?\s*(\d{3,4})\s*\.?\s*)$").unwrap());

/// Java `StripAndStash.stripInAuthorInParens` (StripAndStash.java:1402-1428). An "in
/// <publication>" citation INSIDE a parenthesised basionym ("Hypsicera femoralis (Geoffroy in
/// Fourcroy, 1785)") is rewritten to just the basionym author, MOVING the publication's own
/// year onto the basionym when the basionym didn't already carry one — so it survives as a
/// normal "(Author, year)" basionym for the authorship parser and code
/// inference — and the publication text APPENDS to `publishedIn` (`add_published_in`, same
/// append-is-setPublishedIn-on-the-combined-string semantics described on that method). Spot-
/// checked against the Java CLI oracle: -> "Hypsicera femoralis (Geoffroy, 1785)" with
/// `publishedIn="Fourcroy, 1785"`, `publishedInYear=1785`. When the basionym ALREADY has its
/// own year ("(Smith, 1780 in Jones, 1900)"), that year is left alone — no double year is
/// appended, matching the `!YEAR_4DIGIT.matcher(basPart).find()` guard (`YEAR_4DIGIT`, batch
/// 1). A MID-STRING SPLICE (`s[..start] + newParens + s[end..]`), NOT a truncation — this can
/// fire on a basionym that isn't at the very end of the input, unlike most other steps in this
/// file. Guarded on a non-empty basionym author AND a reference at least 2 chars long (Java
/// `String.length()`, ported as `.chars().count()` — no astral characters expected in
/// bibliographic reference text).
fn strip_in_author_in_parens(ctx: &mut ParseContext, s: String) -> String {
    if let Some(caps) = IN_AUTHOR_IN_PARENS.captures(&s) {
        let whole = caps.get(0).unwrap();
        let bas_part = java_trim(&caps[1]).to_string();
        let reference = java_trim(&caps[2]).to_string();
        if !bas_part.is_empty() && reference.chars().count() >= 2 {
            ctx.name.add_published_in(&reference);
            let new_parens = match IN_AUTHOR_YEAR.captures(&reference) {
                Some(ym) if !YEAR_4DIGIT.is_match(&bas_part) => {
                    format!("({bas_part}, {})", &ym[1])
                }
                _ => format!("({bas_part})"),
            };
            return format!("{}{}{}", &s[..whole.start()], new_parens, &s[whole.end()..]);
        }
    }
    s
}

// ---- Step 48: stripInAuthorCitation ----

/// Java IN_AUTHOR (StripAndStash.java:148-149): `\s+(?:in|apud)\s+([\p{Lu}][^\s].*)$`, no
/// flags. `\s` (x2) ASCII-only (no `UNICODE_CHARACTER_CLASS`); `\p{Lu}` always Unicode;
/// `[^\s]` is a negated PREDEFINED shorthand class (same as a bare `\S`) — under Java's default
/// (non-Unicode) flags this means "not one of the 6 ASCII whitespace chars", spelled out here
/// as the literal negated ASCII whitespace class `[^\t\n\x0B\f\r ]` at the crate's
/// Unicode-default scope (same `SEROVAR_BARE` precedent from batch 1 — `(?-u:[^\s])`/
/// `(?-u:\S)` are both rejected by `regex-syntax` as "pattern can match invalid UTF-8"); `.*`
/// unescaped wildcard, Unicode default. No lookaround/backreference -> plain `regex` crate.
/// Rust-only: the reference may also be the anonymous author "anon." (step 37 has already
/// lower-cased "Anon."): "Swainson in Anon. 1837" -> author Swainson, publishedIn "anon. 1837".
/// Rust-only as well: a capitalised "In" ("Leach In Bowdich, 1819"), as 1,251 ChecklistBank rows
/// write it, every one of them a citation; Java read it as an author.
static IN_AUTHOR: LazyLock<Regex> = LazyLock::new(|| {
    Regex::new(r"(?-u:\s+)(?:in|In|apud)(?-u:\s+)((?:\p{Lu}[^\t\n\x0B\f\r ]|anon\.).*)$").unwrap()
});

/// Java IN_AUTHOR_PAREN_YEAR (StripAndStash.java:243): `\((\d{4})\)`, no flags. Has `\d`, no
/// `\p{...}`, no unescaped wildcard (the parens are literal, escaped) -> whole pattern
/// ASCII-scoped.
static IN_AUTHOR_PAREN_YEAR: LazyLock<Regex> =
    LazyLock::new(|| Regex::new(r"(?-u:\((\d{4})\))").unwrap());

/// Java `StripAndStash.stripInAuthorCitation` (StripAndStash.java:1430-1462). A trailing " in
/// <Author>" / " apud <Author>" tail ("Cantharus lineolatus Valenciennes in Cuvier &
/// Valenciennes, 1830", "Busk in Chimonides, 1987", "Small apud Britton & Wilson") is the
/// publication reference for the name — APPENDS to `publishedIn` (`add_published_in`) and
/// records a code-neutral `ctx.pending_year`/`pending_year_from_publication` via
/// `ParseContext::set_pending_publication_year` (first-writer-wins; a PARENTHESISED year is
/// tried FIRST so it takes precedence over a bare trailing year when both are present in the
/// same reference, e.g. "Kirchner (1988), Taxon 37: 5" pins 1988, not 5). Runs BEFORE the IPNI
/// / period-/comma-separated-reference patterns (steps 49-51) so an "Author in Source, Title
/// (Year)" tail is fully consumed here rather than partially matched by one of those. A
/// trailing sentence-final period after a closing paren is dropped (`ref.endsWith(").")`); a
/// period after anything else (an author abbreviation like "Fleisch.") is kept. Guarded on the
/// reference being at least 2 chars (Java `String.length()` -> `.chars().count()`, same as
/// step 47). All example refs above spot-checked against the Java CLI oracle, including the
/// "de"-particle author-list negative case ("Yin, Z.W. de Beer & Wingf." must NOT itself be
/// swallowed here — it isn't, since `IN_AUTHOR` requires a literal " in "/" apud " word, which
/// "de Beer" doesn't contain).
fn strip_in_author_citation(ctx: &mut ParseContext, s: String) -> String {
    if let Some(caps) = IN_AUTHOR.captures(&s) {
        let whole = caps.get(0).unwrap();
        let mut reference = java_trim(&caps[1]).to_string();
        if reference.ends_with(").") {
            reference.pop();
            reference = java_trim(&reference).to_string();
        }
        if reference.chars().count() >= 2 {
            ctx.name.add_published_in(&reference);
            if let Some(pyear) = IN_AUTHOR_PAREN_YEAR.captures(&reference) {
                ctx.set_pending_publication_year(&pyear[1]);
            }
            if let Some(ym) = IN_AUTHOR_YEAR.captures(&reference) {
                ctx.set_pending_publication_year(&ym[1]);
            }
            return java_trim(&s[..whole.start()]).to_string();
        }
    }
    s
}

// ---- Step 49: stripIpniCitation ----

/// Java IPNI_CITATION (StripAndStash.java:244-246):
/// `(?<=\s)[\p{Lu}][\p{L}.]+,\s+(.+\(\d{4}\))\.?\s*$`, `Pattern.UNICODE_CHARACTER_CLASS` -> keep
/// default Unicode `\s`, no ASCII scoping needed. LOOKBEHIND `(?<=\s)` (the author span must be
/// preceded by whitespace, checked but not consumed) -> needs `fancy_regex` (the `regex` crate
/// has no lookaround at all). Ported verbatim; IPNI's other form is [`strip_page_year_citation`]'s.
static IPNI_CITATION: LazyLock<FancyRegex> =
    LazyLock::new(|| FancyRegex::new(r"(?<=\s)[\p{Lu}][\p{L}.]+,\s+(.+\(\d{4}\))\.?\s*$").unwrap());

/// Java IPNI_EMBEDDED_NOM_NOTE (StripAndStash.java:247-251), `Pattern.CASE_INSENSITIVE` (no
/// `UNICODE_CHARACTER_CLASS`, so Java's own `\s`/`\b`/`\d` here are ASCII-only). Trailing
/// LOOKAHEAD `(?=\(\d{4}\))` (the year parens are checked but not consumed) -> needs
/// `fancy_regex`. `fancy_regex` has no ASCII mode at all (`(?-u:…)` is a hard parse error,
/// unconditionally — see `GREEK_MARKER`'s doc comment in batch 1) -> `\s` spelled out as the
/// literal ASCII whitespace set `[ \t\n\x0B\f\r]`; `\d` spelled out as `[0-9]`
/// (`DOT_BEFORE_ALNUM` precedent, batch 2b — a literal class is unaffected by Unicode mode
/// either way, unlike a shorthand); `\b` left as `fancy_regex`'s only option (Unicode
/// word-boundary), the same rare, forced (not faithfulness-lapse) divergence as
/// `STRAIN_DESIGNATION` (batch 1). Built via `concat!` mirroring Java's own `"..." + "..."`
/// layout, one alternative per line, so it stays directly diffable against StripAndStash.java.
static IPNI_EMBEDDED_NOM_NOTE: LazyLock<FancyRegex> = LazyLock::new(|| {
    FancyRegex::new(concat!(
        r"(?i)[ \t\n\x0B\f\r]+((?:in[ \t\n\x0B\f\r]+obs\b\.?,?[ \t\n\x0B\f\r]*)?pro[ \t\n\x0B\f\r]+syn\b\.?",
        r"|nom\b\.?(?:[ \t\n\x0B\f\r]+[a-zA-Z][a-zA-Z.]*)*",
        r"|comb\b\.?(?:[ \t\n\x0B\f\r]+[a-zA-Z][a-zA-Z.]*)*",
        r"|orth\b\.?(?:[ \t\n\x0B\f\r]+[a-zA-Z][a-zA-Z.]*)*)[ \t\n\x0B\f\r]*(?=\([0-9]{4}\))",
    ))
    .unwrap()
});

/// Java IPNI_YEAR (StripAndStash.java:252): `\((\d{4})\)\s*\.?\s*$`, no flags -> whole pattern
/// ASCII-scoped.
static IPNI_YEAR: LazyLock<Regex> =
    LazyLock::new(|| Regex::new(r"(?-u:\((\d{4})\)\s*\.?\s*)$").unwrap());

/// Java `StripAndStash.stripIpniCitation` (StripAndStash.java:1464-1490). An IPNI-style
/// citation ("Kirchn., Annals and Magazine of Natural History (1988).") — an author span,
/// comma, then a publication title ending in a parenthesised year — OVERWRITES `publishedIn`
/// (`set_published_in`, Java's plain `setPublishedIn(ref)` with no null-check, since nothing
/// upstream can have already populated a reference by the time this step's pattern can match)
/// and records the pending publication year. Before overwriting, any nom-note keyword EMBEDDED
/// in the reference text just before the year parens ("Taxon nom. illeg. (1988)", "Taxon pro
/// syn. (1988)", "Taxon in obs., pro syn. (1988)", "Taxon comb. nov. (1988)") is spliced out
/// into `nomenclaturalNote` (APPEND, `add_nomenclatural_note`) and the reference is
/// re-squished (collapse the resulting double space via `MULTI_SPACE`, batch 1, then
/// `java_trim`) — all four spot-checked against the Java CLI oracle. Truncates the working
/// string to `pm.start(1)` (the START OF GROUP 1, NOT the whole match — the lookbehind makes
/// group 0 start at the author's own first letter, so truncating there would drop the author
/// too) then a dangling comma left over from "Author., " is explicitly stripped.
fn strip_ipni_citation(ctx: &mut ParseContext, s: String) -> String {
    let caps = match IPNI_CITATION.captures(&s) {
        Ok(Some(c)) => c,
        _ => return strip_page_year_citation(ctx, s),
    };
    let group1 = caps.get(1).unwrap();
    let mut reference = java_trim(group1.as_str()).to_string();
    if let Ok(Some(nm)) = IPNI_EMBEDDED_NOM_NOTE.captures(&reference) {
        let note_match = nm.get(1).unwrap();
        ctx.name
            .add_nomenclatural_note(java_trim(note_match.as_str()));
        let spliced = format!(
            "{} {}",
            &reference[..note_match.start()],
            &reference[note_match.end()..]
        );
        reference = java_trim(&MULTI_SPACE.replace_all(&spliced, " ")).to_string();
    }
    ctx.name.set_published_in(&reference);
    if let Some(ym) = IPNI_YEAR.captures(&reference) {
        ctx.set_pending_publication_year(&ym[1]);
    }
    let mut result = java_trim(&s[..group1.start()]).to_string();
    if result.ends_with(',') {
        result.pop();
        result = java_trim(&result).to_string();
    }
    result
}

/// The end of IPNI's other citation form: volume, page and a bare year, "1: 563. 1865." (or after
/// a bracketed year, "8: 349 (2017). 2017"). Group 1 is the year.
static PAGE_YEAR_TAIL: LazyLock<Regex> =
    LazyLock::new(|| Regex::new(r"\d\s*:\s*[^:]*?\.\s+(\d{4})\.?\s*$").unwrap());

/// A volume and page: "21: 409".
static VOLUME_PAGE: LazyLock<Regex> = LazyLock::new(|| Regex::new(r"\d\s*:\s*\d").unwrap());

/// An author-team connector, after which the title's comma comes.
static TEAM_CONNECTOR: LazyLock<Regex> = LazyLock::new(|| Regex::new(r"\s(?:&|and|et)\s").unwrap());

/// IPNI's citation with volume, page and a bare year after the authors — `Spruce ex Benth., Gen.
/// Pl. 1: 563. 1865.`, 1.3k ChecklistBank authorships — whose title Java read as an author and the
/// page as the year. The title starts after the first comma that follows the last author: past
/// the team's last "&"/"and"/"et" (`B. B. Liu & J. Wen, Front. Plant Sci. 10 - 1731: 10. 2020`)
/// and outside any bracket (`(… W. B. Liao, Q. Fan & M. Y. Ding) …`), unless the "&" is the
/// title's own (`Kerr, Trans. & Proc. Bot. Soc. Edinburgh 30: 12. 1930`). Rust-only.
fn strip_page_year_citation(ctx: &mut ParseContext, s: String) -> String {
    let Some(tail) = PAGE_YEAR_TAIL.captures(&s) else {
        return s;
    };
    let volume_end = tail.get(0).unwrap().start() + 1;
    let head = &s[..volume_end];
    let title_comma = |from: usize| {
        let mut depth = 0i32;
        for (i, c) in head.char_indices() {
            match c {
                '(' | '[' => depth += 1,
                ')' | ']' => depth -= 1,
                ',' if i >= from && depth == 0 => {
                    let title = &head[i + 1..];
                    if title.trim_start().starts_with(char::is_uppercase)
                        && !title.contains(['(', ')', '[', ']'])
                        && !java_trim(&head[..i]).is_empty()
                    {
                        return Some(i);
                    }
                }
                _ => {}
            }
        }
        None
    };
    let after_team = TEAM_CONNECTOR.find_iter(head).last().map_or(0, |m| m.end());
    let Some(comma) = title_comma(after_team).or_else(|| title_comma(0)) else {
        return s;
    };
    // a list of several citations ("K. Koch, Linnaea 21: 409. 1848. Poa polygama (K. Koch) Steud.,
    // Syn. Pl. Glumac. 1: 255. 1854") is beyond telling authors from titles
    if PAGE_YEAR_TAIL.is_match(&s[..comma]) || VOLUME_PAGE.is_match(&s[..comma]) {
        return s;
    }
    let reference = java_trim(&s[comma + 1..]).trim_end_matches('.');
    ctx.name.set_published_in(java_trim(reference));
    ctx.set_pending_publication_year(&tail[1]);
    java_trim(&s[..comma]).to_string()
}

// ---- Step 50: stripPeriodSeparatedReference ----

// RULE: patterns on fancy_regex (backtracking) MUST keep Java's possessive/atomic
// quantifiers — only DROP possessives for patterns on the linear `regex` crate.
/// Java PERIOD_SEPARATED_REFERENCE (StripAndStash.java:253-266),
/// `Pattern.UNICODE_CHARACTER_CLASS` -> keep default Unicode `\s`/`\p{...}` throughout, no
/// ASCII scoping needed. Internal NEGATIVE LOOKAHEAD (`(?!(?:of|in|de|et|the|und|für)\b)`,
/// excluding the connector words from the filler run) -> needs `fancy_regex` (the `regex`
/// crate has no lookaround at all). The POSSESSIVE quantifier (`*+`) wrapping that same
/// lookahead-guarded group is KEPT here as `*+` (see the RULE above): `fancy_regex` IS a
/// backtracking engine, and Java's own comment (StripAndStash.java:255-257) says the
/// possessive exists so "this can't blow up on a long connector-free run", so keeping it is
/// the faithful port of Java's own quantifier plus defence-in-depth. `fancy_regex` 0.14
/// parses `*+` natively (compiling it to an atomic group), so restoring it is a straight
/// verbatim port, not a restructuring.
///
/// NOTE — unlike `NOM_NOTE` (batch 2b), the possessive here is NOT strictly load-bearing:
/// this pattern's filler group is `\s+ <word>` (each iteration must consume one or more
/// whitespace chars THEN a letter-led word, and the following mandatory tail also opens
/// with `\s+`), so every partition of a whitespace-delimited run is unambiguous and plain
/// greedy `*` cannot backtrack exponentially. Measured directly (isolated scratch-crate
/// spike): `*+` and plain `*` are BOTH linear and near-identical here — ~735µs each on a
/// 640-word connector-free run, growing linearly, no cliff. Contrast `NOM_NOTE`, whose
/// inner `[\s.&]*[a-z][a-z.]*` genuinely allows ambiguous partitions: there greedy `*`
/// explodes to ~18ms (backtrack-limit no-match) while `*+` stays microseconds — THAT is a
/// load-bearing possessive. So `*+` is retained here for faithfulness + defence-in-depth,
/// not because dropping it would ReDoS; the regression test below is a linearity guard, not
/// proof of an averted cliff. Built via `concat!` mirroring Java's own `"..." + "..."`
/// layout.
static PERIOD_SEPARATED_REFERENCE: LazyLock<FancyRegex> = LazyLock::new(|| {
    FancyRegex::new(concat!(
        r"\s+[\p{Lu}][\p{L}]{2,}\.\s+",
        r"([\p{Lu}][\p{Ll}]{2,}[\p{L}.]*(?:\s+(?!(?:of|in|de|et|the|und|f\x{fc}r)\b)(?:[\p{Lu}][\p{L}.]+|[\p{Ll}][\p{L}]+))*+",
        r"\s+(?:of|in|de|et|the|und|f\x{fc}r)\s+.*)$",
    ))
    .unwrap()
});

/// Java PAGE_RANGE_TEST (StripAndStash.java:351): `.*\b\d{3,}-\d{3,}\b.*`, no flags. Has `\b`/
/// `\d` (x2 each), unescaped wildcard `.*` bookends -> only `\b`/`\d` ASCII-scoped. Called via
/// `.matches()` on a `.*CORE.*` shape -> RESTRUCTURED to an unanchored `is_match` on the core
/// alone (same precedent as `GREEK_MARKER_TEST`/`MANUSCRIPT_KEYWORD`/… — no name string embeds
/// a newline, so `.` matching "any non-newline char" makes the `.*` bookends a no-op either
/// way).
static PAGE_RANGE_TEST: LazyLock<Regex> =
    LazyLock::new(|| Regex::new(r"(?-u:\b\d{3,}-\d{3,}\b)").unwrap());

/// Java PERIOD_REF_YEAR (StripAndStash.java:267): `\b(\d{4})\b`, no flags -> whole pattern
/// ASCII-scoped. `.find()` takes the FIRST (leftmost) match. Distinct from `ParsedName::
/// set_published_in`'s OWN separate year derivation (which takes the LAST year-shaped match in
/// the full `publishedIn` string) — this extraction only ever feeds `ctx.pending_year`, not
/// `publishedInYear` directly.
static PERIOD_REF_YEAR: LazyLock<Regex> =
    LazyLock::new(|| Regex::new(r"(?-u:\b(\d{4})\b)").unwrap());

/// Java `StripAndStash.stripPeriodSeparatedReference` (StripAndStash.java:1492-1521). A
/// "Surname. <Reference Title> ... <year> ..." citation — recognised by an English/Latin
/// preposition ("of"/"in"/"de"/"et"/"the"/"und"/"für") inside the title, rare inside author
/// names — OVERWRITES `publishedIn` (`set_published_in`, Java's plain `setPublishedIn(ref)`,
/// no null-check). A reference containing a numeric PAGE RANGE ("1658-1662") is a full
/// bibliographic citation whose trailing number is ambiguous with pagination, so the year is
/// NOT propagated and the strip is flagged `NOMENCLATURAL_REFERENCE` instead; a reference
/// without a page range propagates the first 4-digit year it contains as the pending
/// publication year, no warning. Truncates the working string to `pm.start(1)` (group 1's
/// start, keeping the leading "Surname." span — mirrors `strip_ipni_citation`'s identical
/// group(1)-not-group(0) truncation), then strips a trailing period LEFT OVER from the
/// surname's own abbreviation dot (`if (s.endsWith(".")) … .trim()` — WITH a re-trim here,
/// unlike the earlier `ref`-side period strip below, which has none: Java's own
/// `ref.substring(0, ref.length() - 1)` with no following `.trim()`). All three shapes
/// (page-range / clean-year / author-particle false-positive) spot-checked against the Java
/// CLI oracle.
fn strip_period_separated_reference(ctx: &mut ParseContext, s: String) -> String {
    let caps = match PERIOD_SEPARATED_REFERENCE.captures(&s) {
        Ok(Some(c)) => c,
        _ => return s,
    };
    let group1 = caps.get(1).unwrap();
    let mut reference = java_trim(group1.as_str()).to_string();
    if reference.ends_with('.') {
        reference.pop();
    }
    ctx.name.set_published_in(&reference);
    if PAGE_RANGE_TEST.is_match(&reference) {
        ctx.name.add_warning(warnings::NOMENCLATURAL_REFERENCE);
    } else if let Some(ym) = PERIOD_REF_YEAR.captures(&reference) {
        ctx.set_pending_publication_year(&ym[1]);
    }
    let mut result = java_trim(&s[..group1.start()]).to_string();
    if result.ends_with('.') {
        result.pop();
        result = java_trim(&result).to_string();
    }
    result
}

// ---- Step 51: stripCommaPrefixedReference ----

/// Java COMMA_PREFIXED_REFERENCE (StripAndStash.java:268-276),
/// `Pattern.UNICODE_CHARACTER_CLASS` -> keep default Unicode `\s`/`\p{...}` throughout, no
/// ASCII scoping needed. NO lookaround, NO backreference anywhere (unlike its
/// `PERIOD_SEPARATED_REFERENCE` sibling above: the connector words are excluded from the
/// filler via an explicit alternation branch — `on|and|for` are allowed lowercase filler
/// words, `of|in|de|et|the|und|für` are not — rather than a negative lookahead) -> the plain
/// `regex` crate suffices. Java's possessive quantifier (`*+`) is DROPPED here (ported as
/// plain `*`) per this port's RULE (see `strip_period_separated_reference`'s doc comment
/// above): the `regex` crate is an automaton (Thompson NFA/DFA simulation) with NO
/// backtracking at all, so it is always linear-time in the input length regardless of
/// possessive-or-not — there is categorically no catastrophic-backtracking failure mode
/// possible on this engine, so the possessive carries no meaning and dropping it is a
/// provably-safe restructuring (whereas `PERIOD_SEPARATED_REFERENCE`, on the backtracking
/// `fancy_regex` engine, keeps its `*+` for faithfulness even though — as that static's own
/// NOTE measures — its particular shape also happens to stay linear). (Confirmed empirically
/// during this step's TDD spike that the `regex` crate does not even reject a literal `*+` —
/// it silently reinterprets it as nested repetition `(X*)+`, which happens to match the same
/// language as plain `X*` for this shape but is a confusing way to spell "no possessive
/// semantics exist on this engine"; writing plain `*` is the honest, idiomatic port. A
/// 200-word connector-free run completes in well under 1ms either way — there was never a
/// ReDoS risk to begin with on this engine.) Built via `concat!` mirroring Java's own
/// `"..." + "..."` layout.
static COMMA_PREFIXED_REFERENCE: LazyLock<Regex> = LazyLock::new(|| {
    Regex::new(concat!(
        r"\s+[\p{Lu}][\p{L}.]+,\s+",
        r"([\p{Lu}][\p{Ll}]{2,}[\p{L}.]*(?:\s+(?:[\p{Lu}][\p{L}.]+|on|and|for))*",
        r"\s+(?:of|in|de|et|the|und|f\x{fc}r)\s+.*)$",
    ))
    .unwrap()
});

/// Java `StripAndStash.stripCommaPrefixedReference` (StripAndStash.java:1523-1540). An
/// "Author(s), <Reference Title> …" citation with NO period after the author span (unlike step
/// 50's `PERIOD_SEPARATED_REFERENCE`) — the title must contain a recognisable connector
/// ("of"/"in"/"de"/"et"/"the"/"und"/"für") so a comma-separated co-author list isn't mistaken
/// for a reference — OVERWRITES `publishedIn` (`set_published_in`) and ALWAYS flags
/// `NOMENCLATURAL_REFERENCE` (unlike step 50, the year is never propagated onto the
/// combination authorship for this form — Java's own comment: the title's year is the
/// publication year of the article, not a zoological/botanical author-year citation).
/// Truncates to `pm.start(1)` (group 1's start, same "keep the author prefix" reasoning as
/// steps 49/50) then strips a dangling trailing comma.
/// The end of an author team, not a reference: capitalised names (with particles) joined by
/// et / and / &, perhaps with a year — "Zhang et Yang, 1995", "Dubost and Heim de Balsac 1965",
/// "Ortiz Jaureguizar et al. 1992". A reference has lower-case words and numbers of its own
/// ("Journal of the Botanical Research Institute of Texas 4(2): 611").
static AUTHOR_TEAM_TAIL: LazyLock<Regex> = LazyLock::new(|| {
    let particle = r"(?:de|da|do|dos|van|von|der|den|du|le|la|di|del)";
    let name = format!(
        r"(?:{particle}\s+)*\p{{Lu}}[\p{{L}}'.\-]*(?:\s+(?:\p{{Lu}}[\p{{L}}'.\-]*|{particle}))*"
    );
    Regex::new(&format!(
        r"^{name}(?:,\s+{name})*\s+(?:et|and|&)\s+(?:al\.?|{name})(?:(?:,\s*|\s+)\d{{4}}[a-z]?)?\.?$"
    ))
    .unwrap()
});

fn strip_comma_prefixed_reference(ctx: &mut ParseContext, s: String) -> String {
    if let Some(caps) = COMMA_PREFIXED_REFERENCE.captures(&s) {
        let group1 = caps.get(1).unwrap();
        let reference = java_trim(group1.as_str()).to_string();
        if AUTHOR_TEAM_TAIL.is_match(&reference) {
            return s;
        }
        ctx.name.set_published_in(&reference);
        let mut result = java_trim(&s[..group1.start()]).to_string();
        if result.ends_with(',') {
            result.pop();
            result = java_trim(&result).to_string();
        }
        ctx.name.add_warning(warnings::NOMENCLATURAL_REFERENCE);
        return result;
    }
    s
}

// ---- Step 52: stripManuscriptMarker ----

/// Java MANUSCRIPT_MARKER (StripAndStash.java:277-279):
/// `\s*,?\s+(ined\.?|ms\.?|msc\.?|unpublished)\s*$`, `Pattern.CASE_INSENSITIVE` (no
/// `UNICODE_CHARACTER_CLASS`) -> `\s` ASCII-only. No `\p{...}`, no unescaped wildcard -> whole
/// pattern ASCII-scoped. No lookaround/backreference -> plain `regex` crate.
/// Rust-only, the markers of a name found in a letter or on a herbarium label rather than in print:
/// "in litt."/"in lit."/"in litteris", "i.l." (lower case only: "I.L." are initials), "in sched."/
/// "in schedis" — 640 ChecklistBank authorships, all read as authors by Java. Also before a year
/// (`Schwager ms., 1866`): [`MANUSCRIPT_MARKER_BEFORE_YEAR`].
static MANUSCRIPT_MARKER: LazyLock<Regex> =
    LazyLock::new(|| Regex::new(&format!(r"(?i)(?-u:\s*,?\s+({MS_MARKERS})\s*)$")).unwrap());

/// The alternatives of [`MANUSCRIPT_MARKER`] and [`STANDALONE_MS`].
const MS_MARKERS: &str = r"ined\.?|ms\.?|msc\.?|unpublished|in\s+litt(?:\.|eris)?|in\s+lit\.|in\s+sched(?:\.|is)|(?-i:i\.\s?l\.)";

/// A manuscript marker before the year: "Schwager ms., 1866", "Grunow in litteris, 1863".
static MANUSCRIPT_MARKER_BEFORE_YEAR: LazyLock<Regex> = LazyLock::new(|| {
    Regex::new(&format!(
        r"(?i)(?-u:\s*,?\s+({MS_MARKERS})\s*,?\s*(\d{{4}}[a-z]?)\s*)$"
    ))
    .unwrap()
});

/// Java `StripAndStash.stripManuscriptMarker` (StripAndStash.java:1542-1555). A trailing
/// manuscript marker ("ined."/"ms."/"msc."/"unpublished", any case, with an optional leading
/// comma) sets `manuscript = true` and APPENDS the LOWER-CASED tag to `nomenclaturalNote`
/// (`add_nomenclatural_note`) — spot-checked against the Java CLI oracle: "Acacia bicolor
/// Bojer ms." -> `manuscript=true`, `nomenclaturalNote="ms."`, working string "Acacia bicolor
/// Bojer". Runs AFTER `strip_in_author_citation` (step 48) so a trailing "Busk ms in
/// Chimonides, 1987" cleanly strips both (the in-author tail first, leaving "Busk ms" for this
/// step to finish).
fn strip_manuscript_marker(ctx: &mut ParseContext, s: String) -> String {
    strip_trailing_manuscript_marker(&s, &mut ctx.name)
}

/// [`strip_manuscript_marker`] for any authorship string — also run on a separately supplied
/// authorship, where Java only knew a marker that is the whole string ([`STANDALONE_MS`]), so
/// "Mill. ined." / "(Fr.) anon. ined." came out as the author "Mill.ined." / "anon.ined.", with no
/// manuscript flag.
pub(crate) fn strip_trailing_manuscript_marker(s: &str, name: &mut ParsedName) -> String {
    if let Some(caps) = MANUSCRIPT_MARKER_BEFORE_YEAR.captures(s) {
        let (marker, year) = (caps.get(1).unwrap(), caps.get(2).unwrap());
        let rest = strip_trailing_manuscript_marker(&s[..marker.end()], name);
        // the comma, or its absence, is evidence of the code
        let sep = if s[marker.end()..year.start()].contains(',') {
            ", "
        } else {
            " "
        };
        return format!("{rest}{sep}{}", year.as_str());
    }
    if let Some(caps) = MANUSCRIPT_MARKER.captures(s) {
        let whole = caps.get(0).unwrap();
        let tag = collapse_whitespace(&caps[1].to_lowercase());
        name.manuscript = true;
        // once: sources repeat it in the separate authorship
        if !name
            .nomenclatural_note
            .as_deref()
            .is_some_and(|existing| contains_words(existing, &tag))
        {
            name.add_nomenclatural_note(&tag);
        }
        // "F.C.How ex ined." — the unpublished name is How's; a dangling "ex" would drop him
        let rest = java_trim(&s[..whole.start()]);
        return java_trim(DANGLING_EX.replace(rest, "").as_ref()).to_string();
    }
    s.to_string()
}

/// A trailing "ex" left without its author once a manuscript marker is removed. Rust-only.
static DANGLING_EX: LazyLock<Regex> = LazyLock::new(|| Regex::new(r"(?i)(?-u:\s+ex\.?)$").unwrap());

// ---------------------------------------------------------------------------------
// Batch 5 / 2e (steps 53-55, THE FINAL StripAndStash batch): suprarank prefix, leading
// infrageneric marker, phrase name. Landing this batch flips the golden-harness gate
// (`tests/parse_golden.rs`) from a deferred baseline print to a real `assert_eq!(…, 0)`
// over the 10 downstream-independent fields — see that file's own module doc.
//
// NOTE: Java's separate `stripAuthorshipMarkers` auxiliary-authorship reimplementation is
// NOT part of this ordered `run()` dispatch at all (see the investigation §4) — it is only
// ever invoked on the caller-supplied `authorship` string, from `pipeline::mod`'s
// aux-authorship path. It is NOT ported here (alongside these three steps); it's ported
// later in this same file, as its own separate, shorter, ordered step list — see
// `strip_authorship_markers` and the section doc comment above it (Phase 1 Slice 4 Task 4).
//
// This batch also extends `model::enums::Rank` with 18 new variants these three steps
// reference — the suprageneric family-group ranks for step 53, plus SUBGENUS and the
// botanical/zoological section/series pairs for step 54's `RANK_MARKER_MAP_INFRAGENERIC`
// subset + `BOT_TO_ZOOL` remap (see `Rank`'s own doc comment for the itemised list and
// exact Java source line references). Step 55 needs no new variants: SPECIES/SUBSPECIES/
// VARIETY/FORM already exist from earlier batches.
// ---------------------------------------------------------------------------------

// ---- Step 53: stripSupraRankPrefix ----

/// Java `SUPRA_RANK_MARKERS` (StripAndStash.java:1693-1701): the suprageneric
/// family-group rank markers `SUPRA_RANK_PREFIX` (below) can capture as its group 1,
/// mapped to the `Rank` they pin. MINIMAL port covering exactly the 8 distinct words the
/// regex's own alternation (`subfam(?:ily)?|subtrib(?:e)?|supertrib|infratrib|trib(?:e)?`)
/// can produce — a case-folded `match`, not a `HashMap`, following
/// `is_known_infraspecific_marker`'s (batch 1) precedent for a small fixed
/// string-to-value lookup. `word` must already be lower-cased by the caller (mirrors
/// Java's own `pm.group(1).toLowerCase()` immediately before the map lookup).
fn supra_rank_marker(word: &str) -> Option<Rank> {
    match word {
        "subfam" | "subfamily" => Some(Rank::Subfamily),
        "trib" | "tribe" => Some(Rank::Tribe),
        "subtrib" | "subtribe" => Some(Rank::Subtribe),
        "supertrib" => Some(Rank::Supertribe),
        "infratrib" => Some(Rank::Infratribe),
        _ => None,
    }
}

/// Java SUPRA_RANK_PREFIX (StripAndStash.java:1725-1729):
/// `^(?:[\p{Lu}][\p{L}]{2,}\s+)?(subfam(?:ily)?|subtrib(?:e)?|supertrib|infratrib|trib(?:e)?)\.?\s+(?=[\p{Lu}])`,
/// `Pattern.UNICODE_CHARACTER_CLASS | Pattern.CASE_INSENSITIVE` -> keep default Unicode
/// `\s`, add `(?i)`. Trailing LOOKAHEAD `(?=[\p{Lu}])` (the following capitalised name is
/// checked but not consumed, so it stays in the returned remainder) -> needs `fancy_regex`
/// (the `regex` crate has no lookaround at all). No nested/ambiguous quantifiers anywhere
/// in this pattern (the leading family-group is merely optional, not repeated) — no ReDoS
/// exposure to weigh, unlike some of the batch 2d fancy_regex patterns.
static SUPRA_RANK_PREFIX: LazyLock<FancyRegex> = LazyLock::new(|| {
    FancyRegex::new(
        r"(?i)^(?:[\p{Lu}][\p{L}]{2,}\s+)?(subfam(?:ily)?|subtrib(?:e)?|supertrib|infratrib|trib(?:e)?)\.?\s+(?=[\p{Lu}])",
    )
    .unwrap()
});

/// Java `StripAndStash.stripSupraRankPrefix` (StripAndStash.java:1557-1570). A leading
/// "<Family> <suprageneric-rank-marker> <Name> [Author …]" ("Poaceae subtrib.
/// Scolochloinae Soreng") — or a bare marker with no family prefix ("subtrib.
/// Scolochloinae Soreng") — pins `ctx.name.rank` from the marker and strips BOTH the
/// optional family prefix and the marker itself (`s[whole.end()..]`, not just past the
/// marker), leaving the inner uninomial (plus any trailing author) for the rest of the
/// pipeline to parse. Unconditional overwrite: Java's `ctx.name.setRank(r)` here carries
/// no "only if unset" guard, unlike step 54's `code` handling below. Both the bare-marker
/// and family-prefixed forms spot-checked against the Java CLI oracle: "subtrib.
/// Scolochloinae Soreng" and "Poaceae subtrib. Scolochloinae Soreng" both come back
/// `rank=SUBTRIBE`, `uninomial=Scolochloinae` (the family prefix, when present, is
/// discarded entirely, not preserved anywhere in the parsed output).
fn strip_supra_rank_prefix(ctx: &mut ParseContext, s: String) -> String {
    if let Ok(Some(caps)) = SUPRA_RANK_PREFIX.captures(&s) {
        let marker = caps.get(1).unwrap().as_str().to_lowercase();
        if let Some(r) = supra_rank_marker(&marker) {
            ctx.name.rank = r;
            let whole = caps.get(0).unwrap();
            return java_trim(&s[whole.end()..]).to_string();
        }
    }
    s
}

// ---- Step 54: stripLeadingInfragenericMarker ----

/// Java `RankUtils.RANK_MARKER_MAP_INFRAGENERIC` (RankUtils.java:90-106) — MINIMAL subset
/// port covering exactly the 13 distinct words `LEADING_INFRAGEN_MARKER` (below) can
/// capture as its group 1. The full Java map also auto-derives an entry for every
/// non-GENUS `Rank::isGenusGroup()` constant's own marker text
/// (`RankUtils.buildRankMarkerMap`) plus a handful of unrelated explicit aliases
/// (`supraser`, …) that this regex's own alternation can never produce — out of scope
/// here per this port's "add only what these steps need" brief. Case-folded `match`, same
/// style as `supra_rank_marker` above; `word` must already be lower-cased by the caller.
fn infrageneric_marker_rank(word: &str) -> Option<Rank> {
    match word {
        "subg" | "subgen" | "subgenus" => Some(Rank::Subgenus),
        "sect" | "section" => Some(Rank::SectionBotany),
        "subsect" | "subsection" => Some(Rank::SubsectionBotany),
        "supersect" | "suprasect" => Some(Rank::SupersectionBotany),
        "ser" | "series" => Some(Rank::SeriesBotany),
        "subser" | "subseries" => Some(Rank::SubseriesBotany),
        _ => None,
    }
}

/// Java `BOT_TO_ZOOL` (StripAndStash.java:1706-1712): botanical-flavoured infrageneric
/// ranks that have a same-NAMED zoological counterpart at a DIFFERENT nominal level
/// (zoological "section"/"series" sit between order and family, not inside a genus — see
/// `Rank.java`'s own placement of `SECTION_ZOOLOGY`/`SERIES_ZOOLOGY` right after
/// suborder, versus `SECTION_BOTANY`/`SERIES_BOTANY` down in the genus-group block).
/// Applied when a leading rank marker is parsed under a caller-supplied ZOOLOGICAL code.
/// Ported as the COMPLETE 6-pair `match`, faithful to the Java literal even though
/// `SuperseriesBotany` (only reachable via a "supraser"/"superser" word — neither is one
/// of `LEADING_INFRAGEN_MARKER`'s 13 alternatives) can never actually be produced by THIS
/// step's own regex — same "port the whole literal, not a call-site-trimmed-down version"
/// precedent as `is_known_infraspecific_marker` (batch 1) and `DIGITS_ONLY` in
/// `stash_trailing_strain_code` (batch 1). The wildcard fallback is exact here, not a
/// faithfulness compromise: Java's own `Map.get()` likewise returns `null` for any `Rank`
/// key it doesn't list (i.e. `Subgenus`, which has no zoological counterpart at all).
fn bot_to_zool(rank: Rank) -> Option<Rank> {
    match rank {
        Rank::SectionBotany => Some(Rank::SectionZoology),
        Rank::SubsectionBotany => Some(Rank::SubsectionZoology),
        Rank::SupersectionBotany => Some(Rank::SupersectionZoology),
        Rank::SeriesBotany => Some(Rank::SeriesZoology),
        Rank::SubseriesBotany => Some(Rank::SubseriesZoology),
        Rank::SuperseriesBotany => Some(Rank::SuperseriesZoology),
        _ => None,
    }
}

/// Java LEADING_INFRAGEN_MARKER (StripAndStash.java:1716-1719):
/// `^(subg|subgen|subgenus|sect|section|subsect|subsection|supersect|suprasect|ser|series|subser|subseries)\.?\s+(?=[\p{Lu}])`,
/// `Pattern.UNICODE_CHARACTER_CLASS | Pattern.CASE_INSENSITIVE` -> keep default Unicode
/// `\s`, add `(?i)`. Trailing LOOKAHEAD (same reasoning as `SUPRA_RANK_PREFIX` above) ->
/// needs `fancy_regex`. No nested/ambiguous quantifiers -> no ReDoS exposure.
static LEADING_INFRAGEN_MARKER: LazyLock<FancyRegex> = LazyLock::new(|| {
    FancyRegex::new(
        r"(?i)^(subg|subgen|subgenus|sect|section|subsect|subsection|supersect|suprasect|ser|series|subser|subseries)\.?\s+(?=[\p{Lu}])",
    )
    .unwrap()
});

/// Java `StripAndStash.stripLeadingInfragenericMarker` (StripAndStash.java:1572-1593). A
/// leading infrageneric rank marker with NO genus prefix ("subgen. Trematostoma Sacc.",
/// "sect. Taeda") pins `ctx.name.rank` — remapped to its zoological counterpart via
/// `bot_to_zool` when `ctx.requested_code == ZOOLOGICAL` — and backfills `ctx.name.code`
/// from the (possibly-remapped) rank's own `Rank::code()` ONLY when no code was already
/// set: unlike step 53's unconditional rank overwrite just above, this mirrors Java's own
/// `if (r.getCode() != null && ctx.name.getCode() == null)` guard exactly. All three
/// shapes spot-checked against the Java CLI oracle: "subgen. Trematostoma Sacc." (no
/// caller code) -> `rank=SUBGENUS`, no `code` key at all (Subgenus carries none); "sect.
/// Foo Bar" (no caller code) -> `rank=SECTION_BOTANY`, `code=BOTANICAL` (backfilled from
/// `Rank::code()`); "sect. Taeda" WITH a caller-supplied ZOOLOGICAL code -> `rank=
/// SECTION_ZOOLOGY` (remapped, not SECTION_BOTANY).
fn strip_leading_infrageneric_marker(ctx: &mut ParseContext, s: String) -> String {
    if let Ok(Some(caps)) = LEADING_INFRAGEN_MARKER.captures(&s) {
        let marker = caps.get(1).unwrap().as_str().to_lowercase();
        if let Some(mut r) = infrageneric_marker_rank(&marker) {
            if ctx.requested_code == Some(NomCode::Zoological) {
                if let Some(zool) = bot_to_zool(r) {
                    r = zool;
                }
            }
            ctx.name.rank = r;
            if let Some(code) = r.code() {
                if ctx.name.code.is_none() {
                    ctx.name.code = Some(code);
                }
            }
            let whole = caps.get(0).unwrap();
            return java_trim(&s[whole.end()..]).to_string();
        }
    }
    s
}

// ---- Step 55: stashPhraseName ----

/// Java `PHRASE_RANK_MARKERS` (StripAndStash.java:1661-1668): recognised infraspecific
/// markers that introduce a phrase name, mapped to the `Rank` they pin. Complete port —
/// unlike its two siblings above, every key this (small, `Map.of`-literal) map lists is
/// directly reachable, no call-site-unreachable subset to trim. Case-folded `match`;
/// `word` must already be lower-cased by the caller.
fn phrase_rank_marker(word: &str) -> Option<Rank> {
    match word {
        "sp" | "spec" => Some(Rank::Species),
        "subsp" | "ssp" => Some(Rank::Subspecies),
        "var" => Some(Rank::Variety),
        "form" | "f" => Some(Rank::Form),
        _ => None,
    }
}

/// Java GENUS_SUBGENUS_TEST (StripAndStash.java:352-353):
/// `^[\p{Lu}][\p{Ll}]+\s+\([\p{Lu}][\p{Ll}]+\)$`, NO flags (so Java's own `\s` here is
/// ASCII-only, unlike its Unicode-flagged `PHRASE_GENUS_SUBGENUS` sibling right below).
/// Has `\p{Lu}`/`\p{Ll}` -> only the `\s` atom is ASCII-scoped (not the whole pattern).
static GENUS_SUBGENUS_TEST: LazyLock<Regex> =
    LazyLock::new(|| Regex::new(r"^[\p{Lu}][\p{Ll}]+(?-u:\s+)\([\p{Lu}][\p{Ll}]+\)$").unwrap());

/// Java PHRASE_GENUS_SUBGENUS (StripAndStash.java:280-282):
/// `^([\p{Lu}][\p{Ll}]+)\s+\(([\p{Lu}][\p{Ll}]+)\)$`, `Pattern.UNICODE_CHARACTER_CLASS` ->
/// keep default Unicode `\s`, ported verbatim.
static PHRASE_GENUS_SUBGENUS: LazyLock<Regex> =
    LazyLock::new(|| Regex::new(r"^([\p{Lu}][\p{Ll}]+)\s+\(([\p{Lu}][\p{Ll}]+)\)$").unwrap());

// `AUTHOR_START`/`find_author_start` (Java StripAndStash.java:283-285 / 1650-1657) are
// NOT redeclared here: Java's own `findAuthorStart` is already SHARED between an earlier
// step (`stripQuotedCultivar`, StripAndStash.java:1035, batch 2b) and this step
// (StripAndStash.java:1609) — both call the exact same method — so batch 2b's port of
// both already lives earlier in this file and is reused verbatim below.

/// Java PHRASE_NAME (StripAndStash.java:1677-1689), `Pattern.UNICODE_CHARACTER_CLASS` ->
/// keep default Unicode `\s`/`\d` throughout, no ASCII scoping needed anywhere in this
/// pattern.
///
/// **THE LAST remaining Java possessive quantifier in `StripAndStash`** (`[^(]*+`, meant
/// to lock the phrase's leading non-paren run so a greedy `[^(]*` can't backtrack past the
/// first '(' looking for a balanced-parens match that isn't there). Determination: this
/// pattern has NO lookaround and NO backreference anywhere — unlike every other
/// possessive-bearing pattern ported so far (`STRAIN_DESIGNATION`,
/// `PERIOD_SEPARATED_REFERENCE`, …), which all needed `fancy_regex` for an unrelated
/// reason (a backreference or lookaround elsewhere in the same pattern) and so kept their
/// possessive/atomic quantifiers verbatim on that backtracking engine — so this pattern
/// needs only the plain `regex` crate. Per this port's rule (see
/// `strip_comma_prefixed_reference`'s doc comment, batch 2d): possessive quantifiers are
/// DROPPED on patterns that live on the linear `regex` crate, since that engine has no
/// backtracking at all and so cannot exhibit the catastrophic-backtracking failure mode a
/// possessive quantifier guards against — **the possessive is DROPPED here too** (`[^(]*+`
/// ported as plain `[^(]*`). This is not merely "safe because this engine doesn't
/// backtrack": the quantified class itself (`[^(]`, "any char but a literal '('") has
/// exactly ONE possible stopping point for greedy OR possessive alike — right before the
/// first literal '(' remaining in the string, since the class can never itself consume
/// that '(' — so there is no ambiguous partition here for ANY engine, even a backtracking
/// one, to waste time re-trying. Dropping `*+` to `*` is a provably meaning- AND
/// performance-preserving restructuring, stronger than "merely safe on this engine".
/// Built via `concat!` mirroring Java's own `"..." + "..."` layout, one alternative per
/// line, so it stays directly diffable against `StripAndStash.java`.
static PHRASE_NAME: LazyLock<Regex> = LazyLock::new(|| {
    Regex::new(concat!(
        r"^([\p{Lu}][\p{Ll}]+(?:\s+\([\p{Lu}][\p{Ll}]+\))?(?:\s+[\p{Ll}]+)?(?:\s+[\p{Lu}][\p{L}.]+)*)",
        r"\s+(sp|spec|subsp|ssp|var|form|f)\.?",
        r"\s+(",
        r#"[\p{Lu}A-Z\d'"][^(]*\(.+\)[^$]*?"#,
        r#"|['"][^'"]+['"]"#,
        r")\s*$",
    ))
    .unwrap()
});

/// Java `StripAndStash.stashPhraseName` (StripAndStash.java:1595-1644). BOLD/specimen-style
/// "phrase names" name an unidentified/undescribed taxon by a genus (optionally a species)
/// plus a rank marker plus a free-text "phrase" distinguishing the specimen/population,
/// e.g. "Prostanthera sp. Somersbey (B.J.Conn 4024)" — the phrase is stashed on
/// `ctx.name.phrase` once a recognised rank marker is found. For a bare-genus SPECIES-level
/// shape (the `Informal`-bound case) the verbatim rank marker is kept ON the phrase ("sp.
/// Somersbey (B.J.Conn 4024)", per the 5.0.0 Informal-phrase contract, so the formatter
/// round-trips it without re-synthesising "sp."); every other shape (a "Genus species"
/// binomial, a non-species marker, a subgenus/author prefix) keeps the bare marker-stripped
/// phrase as the Java oracle did. The working string is rewritten into one of four shapes
/// depending on the Latin prefix, so NameTokens sees a clean indet
/// name. All four shapes spot-checked against the Java CLI oracle:
///   - a trailing author span after the epithet(s) ("Baeckea Benth. sp. Bygalorie (ABC
///     123)" -> working "Baeckea sp. Benth.") -> the marker is spliced BEFORE that author
///     span so the author still trails as the species author for AuthorshipParser;
///     rank is NOT pinned here — oracle confirms the eventual `rank=SPECIES`
///     comes from downstream re-reading the reinserted "sp." marker, not from this step.
///   - a bare genus (no species) with a marker OTHER than "sp."/"spec." ("Grevillea
///     subsp. 'Short Leaf'" -> `rank=SUBSPECIES`, working "Grevillea") -> rank pinned
///     directly, marker dropped entirely.
///   - a "Genus (Subgenus)" prefix ("Acacia (Botrycephalae) sp. Bygalorie (P.G.Wilson
///     2585)" -> `rank=SPECIES`, `infragenericEpithet=Botrycephalae`, working "Acacia")
///     -> rank pinned, the subgenus extracted directly onto
///     `ctx.name.infrageneric_epithet` and dropped from the working string, leaving the
///     bare genus for AuthorshipSplit's own subgenus-defaulting.
///   - anything else, i.e. a bare genus with a "sp."/"spec." marker, or a full "Genus
///     species" prefix ("Prostanthera sp. Somersbey (B.J.Conn 4024)" -> working
///     "Prostanthera sp.", rank left untouched by this step) -> the marker is appended
///     back verbatim ("Genus[ species] marker.").
fn stash_phrase_name(ctx: &mut ParseContext, s: String) -> String {
    let Some(caps) = PHRASE_NAME.captures(&s) else {
        return s;
    };
    let prefix = collapse_whitespace(caps.get(1).unwrap().as_str());
    let marker = caps.get(2).unwrap().as_str();
    let phrase = collapse_whitespace(caps.get(3).unwrap().as_str());
    let Some(rank) = phrase_rank_marker(&marker.to_lowercase()) else {
        return s;
    };

    // Java re-trims `prefix` via `.trim()` at each of the three call sites below
    // (`.contains(" ")`, `GENUS_SUBGENUS_TEST`, `PHRASE_GENUS_SUBGENUS`) even though
    // `prefix` was already fully collapsed-and-trimmed by `collapse_whitespace` above — a
    // defensive no-op given that, so it is not repeated at each site here.
    let author_start = find_author_start(&prefix);
    let prefix_is_genus_only = !prefix.contains(' ');

    // 5.0.0 Informal-phrase contract: a bare-genus species-level provisional
    // ("Prostanthera sp. Somersbey (B.J.Conn 4024)") is an `Informal` result, and its phrase
    // must carry the verbatim rank marker just like NameTokens' indet capture — so the
    // formatter renders it back ("Genus sp. <phrase>") without re-synthesising a marker.
    // Gated to the genus-only SPECIES shape: a "Genus species" prefix is a Parsed binomial
    // (out of scope — keeps the bare voucher phrase), and a non-species marker (subsp./var./
    // f.) is NOT recognised by the formatter's species-only phrase guard, so keeping it in the
    // phrase would double it; those keep the marker-stripped phrase and the synthesised rank.
    ctx.name.phrase = Some(if prefix_is_genus_only && rank == Rank::Species {
        format!("{marker}. {phrase}")
    } else {
        phrase
    });
    let prefix_is_genus_plus_subgenus = GENUS_SUBGENUS_TEST.is_match(&prefix);

    if let Some(author_start) = author_start {
        // Splice the marker BEFORE the author span so it trails as the species author for
        // AuthorshipParser to pick up; rank is intentionally left
        // untouched here — the reinserted "marker." drives the rank downstream instead.
        format!(
            "{} {marker}. {}",
            java_trim(&prefix[..author_start]),
            java_trim(&prefix[author_start..]),
        )
    } else if prefix_is_genus_only && rank != Rank::Species {
        ctx.name.rank = rank;
        prefix
    } else if prefix_is_genus_plus_subgenus {
        ctx.name.rank = rank;
        match PHRASE_GENUS_SUBGENUS.captures(&prefix) {
            Some(gm) => {
                ctx.name.infrageneric_epithet = Some(gm.get(2).unwrap().as_str().to_string());
                gm.get(1).unwrap().as_str().to_string()
            }
            None => prefix,
        }
    } else {
        format!("{prefix} {marker}.")
    }
}

// ===================================================================================
// stripAuthorshipMarkers (Phase 1 Slice 4 Task 4): the auxiliary-authorship-path
// reimplementation. Strips a SUBSET of the annotations `run()` above strips from the
// embedded scientific name — reusing several of the SAME pattern constants — from a
// separately-supplied authorship string (the `authorship` parameter of
// `nameparser::parse`/`Pipeline::run`), applying their flags/notes directly onto a
// `ParsedName`. Called only from `pipeline::mod`'s aux-authorship path, on the
// caller-supplied authorship string, before it is tokenised and handed to
// `AuthorshipParser::parse`.
//
// Unlike `run()` above, this path has no `ParseContext` (no working string of its own to
// thread `pending_unparsed`/`pending_year` state through) — its only output is the
// cleaned string, plus side effects applied directly onto `name`. It is therefore NOT
// part of the `run()` dispatcher above and has its own, shorter, ordered list of steps
// (Java `StripAndStash.stripAuthorshipMarkers`, StripAndStash.java:409-525): standalone
// manuscript marker (early return) -> sic-with-comment / sic / corrig -> question-mark
// repair -> win-1252 repair -> hort./hortus ex-placeholder normalisation (CV_EX and the
// bare "ht." marker are DELIBERATELY omitted — Java's aux version calls only HORT_EX/
// HORTUS_EX, not the full 4-step `normaliseHortExPlaceholder` chain) -> leading
// homonym-citation parens (early return) -> parenthesised taxonomic note -> bracketed
// nom-note -> bare nom-note -> taxonomic-note tail.
// ===================================================================================

/// Java STANDALONE_MS (StripAndStash.java:39-40): `(?i)^(?:ined|ms|msc|unpublished)\.?$`,
/// no `UNICODE_CHARACTER_CLASS`. Already fully anchored (`^…$`) so Java's `.matches()`
/// call is identical to `.find()`/`is_match` here. No `\s`/`\d`/`\w`/`\b`/`\p{...}` atoms
/// at all -> nothing to scope, ported verbatim. Only used by `strip_authorship_markers`
/// (a manuscript marker supplied as the WHOLE separate authorship, e.g. authorship="ined."
/// — a marker glued onto an embedded author, "Monterosato ms.", is a different case,
/// handled by `strip_manuscript_marker`/`MANUSCRIPT_MARKER` in the main `run()` dispatch).
static STANDALONE_MS: LazyLock<Regex> =
    LazyLock::new(|| Regex::new(&format!(r"(?i)^(?:{MS_MARKERS})$")).unwrap());

/// Java LEADING_HOMONYM_PAREN (StripAndStash.java:113-114): `^\(\s*(?:non|nec|not)\b`,
/// `Pattern.CASE_INSENSITIVE`. Has `\s`/`\b`, no `\p{...}`, no unescaped wildcard -> whole
/// pattern ASCII-scoped (leading `^` left outside the wrap, per convention — same as
/// `CANDIDATUS_PREFIX`). No lookaround/backreference -> plain `regex` crate.
static LEADING_HOMONYM_PAREN: LazyLock<Regex> =
    LazyLock::new(|| Regex::new(r"(?i)^(?-u:\(\s*(?:non|nec|not)\b)").unwrap());

/// Java PAREN_NOTE (StripAndStash.java:108-109):
/// `\(\s*((?:auctt?|sensu|sec)\b[^)]*)\)\s*`, `Pattern.CASE_INSENSITIVE`, plus "auctorum" (see
/// [`TAX_NOTE`]). `[^)]` is a
/// NEGATED custom class -> stays OUTSIDE any `(?-u:…)` (`BRACKETED_TAX_NOTE`/
/// `SIC_WITH_COMMENT` precedent) -> atom-only `\s`/`\b` scoping. UNANCHORED (no leading/
/// trailing `^`/`$`) — unlike its `BRACKETED_TAX_NOTE`/`PAREN_TAX_NOTE` siblings in the
/// main `run()` dispatch, this note can sit ANYWHERE in the aux authorship string (e.g.
/// "(auct.) Rolfe" — a leading note with a trailing real author), not just at the end. No
/// lookaround/backreference -> plain `regex` crate.
static PAREN_NOTE: LazyLock<Regex> = LazyLock::new(|| {
    Regex::new(
        r"(?i)\((?-u:\s*)((?:auctt?|auctorum|sensu|sec|vide|synonym)(?-u:\b)[^)]*|(?-i:s\.(?-u:\s*)(?:str|s|l|lat|ampl)\.?))(?-u:\s*)\)(?-u:\s*)",
    )
    .unwrap()
});

/// One of [`run`]'s steps applied to a separately supplied authorship: on a copy padded with a
/// leading space, since several patterns expect whitespace before the annotation they strip (on
/// the name string the name itself precedes it).
fn on_authorship(
    ctx: &mut ParseContext,
    s: String,
    step: fn(&mut ParseContext, String) -> String,
) -> String {
    java_trim(&step(ctx, format!(" {s}"))).to_string()
}

/// [`run`]'s steps that apply to a separately supplied authorship as much as to an authorship on
/// the name string, and that come before [`strip_authorship_markers`]'s: coded diacritics
/// (`Mu:2ller`), uncertain authors (`?`,
/// `or`, `/`), imprint years, hyphens and homoglyphs, angle-bracketed placeholders, HTML, `hort.`,
/// the extinct dagger and a bracketed synonym (`[= Grislea L. 1753]`). In `run`'s order.
pub(crate) fn strip_authorship_leading_steps(ctx: &mut ParseContext, s: String) -> String {
    let steps: [fn(&mut ParseContext, String) -> String; 10] = [
        repair_colon_diacritics,
        flag_uncertain_authorship,
        strip_imprint_years,
        normalise_hyphens,
        replace_homoglyphs,
        strip_angle_bracket_authorship,
        strip_html,
        normalise_hort_ex_placeholder,
        strip_extinct_dagger,
        stash_synonym_bracket,
    ];
    steps
        .into_iter()
        .fold(s, |s, step| on_authorship(ctx, s, step))
}

/// [`run`]'s steps for a separately supplied authorship that come after
/// [`strip_authorship_markers`]'s and before the in-citation split: `pro parte`, `pro sp.`, the
/// Approved Lists, `mihi`, colon concept references, `s.lat.`/`s.s.`, aggregate suffixes, the page
/// and `in press`. In `run`'s order.
pub(crate) fn strip_authorship_trailing_steps(ctx: &mut ParseContext, s: String) -> String {
    let steps: [fn(&mut ParseContext, String) -> String; 10] = [
        strip_pro_parte,
        strip_pro_sp_annotation,
        strip_approved_lists,
        strip_mihi,
        strip_colon_concept_reference,
        strip_sensu_lato_remainder,
        strip_sensu_stricto_ss,
        strip_aggregate_suffix,
        strip_published_page,
        strip_in_press,
    ];
    steps
        .into_iter()
        .fold(s, |s, step| on_authorship(ctx, s, step))
}

/// [`run`]'s publication-reference steps for a separately supplied authorship, after the
/// in-citation split: IPNI-style, period-separated and comma-prefixed references.
pub(crate) fn strip_authorship_reference_steps(ctx: &mut ParseContext, s: String) -> String {
    let steps: [fn(&mut ParseContext, String) -> String; 3] = [
        strip_ipni_citation,
        strip_period_separated_reference,
        strip_comma_prefixed_reference,
    ];
    steps
        .into_iter()
        .fold(s, |s, step| on_authorship(ctx, s, step))
}

/// Java `StripAndStash.stripAuthorshipMarkers(String authorship, ParsedName name)`
/// (StripAndStash.java:409-525). See the section doc comment above for the step order.
/// Strips inline annotations from an externally-supplied authorship string and applies
/// any flags they imply directly onto `name`. Returns the cleaned authorship, ready for
/// `Tokenizer::tokenize` (`crate::token::tokenize`).
pub(crate) fn strip_authorship_markers(authorship: &str, name: &mut ParsedName) -> String {
    let mut s = java_trim(authorship).to_string();
    if s.is_empty() {
        return s;
    }
    // A standalone manuscript marker as the WHOLE authorship is a manuscript flag and note, not
    // an author — as the same marker after a name: "Eucnidoideae ined.".
    if STANDALONE_MS.is_match(&s) {
        return strip_trailing_manuscript_marker(&format!(" {s}"), name);
    }
    if let Some(m) = SIC_WITH_COMMENT.find(&s) {
        name.original_spelling = Some(true);
        s = format!("{}{}", &s[..m.start()], &s[m.end()..]);
    }
    if let Some(m) = SIC.find(&s) {
        name.original_spelling = Some(true);
        s = format!("{}{}", &s[..m.start()], &s[m.end()..]);
    }
    {
        let padded = format!(" {s}");
        if let Ok(Some(_)) = CORRIG.find(&padded) {
            name.original_spelling = Some(false);
            let stripped = fancy_replace_all(&CORRIG, &padded, |_| String::new());
            s = collapse_whitespace(&stripped);
        }
    }
    // "?" inside a word — transcription artefact for a missing letter ("Istv?nffi"). Strip
    // the ? and glue the surrounding word parts; flag doubtful + warning.
    s = remove_replacement_characters(name, s);
    if s.contains('?') && LETTER_QMARK_LETTER.is_match(&s) {
        s = remove_qmarks_between_letters(s);
        name.doubtful = true;
        name.add_warning(warnings::QUESTION_MARKS_REMOVED);
    }
    s = repair_win1252_artefacts_name(name, s);
    // "Hort."/"hortus(a)" horticultural placeholder, lower-cased to the canonical "hort.".
    // Deliberately omits `CV_EX`/`HT_MARKER` (see the section doc comment).
    s = fancy_replace_all(&HORT_EX, &s, |_| "hort.".to_string());
    s = fancy_replace_all(&HORTUS_EX, &s, |_| "hort.".to_string());
    // "Anon"/"anon" -> "anon.", as on the name string (step 37). Padded: its patterns need
    // whitespace before the word, and here it often starts the string ("Anon. 1837").
    s = java_trim(&normalise_anon_str(&format!(" {s}"))).to_string();

    // The notes this authorship carries are collected in source order and added once, at the
    // end, so the whole of it can be checked against the note the name string already gave:
    // sources often repeat the note in both columns, not always identically
    // ("Hemicycla gaudryi auctt. (non d'Orbigny, 1839)" + "auctt. (non d'Orbigny, 1839)").
    let mut notes: Vec<String> = Vec::new();
    let mut tail_notes: Vec<String> = Vec::new();

    // Trailing bracketed notes, peeled off right to left: "[non Vierh.]", "[auct. misspelling]"
    // (the name string's step 39) and "(non Salisb.)" (step 40). Without this the tokenizer
    // dropped the brackets and "non Vierh." was read as an author. Any author in front is kept
    // ("Focke [non Salisb.]"). A lone bracketed keyword is first unwrapped ("[sensu] Schmidt,
    // 1878").
    s = unwrap_keyword_only_bracket(&s);
    loop {
        let caps = match BRACKETED_TAX_NOTE.captures(&s) {
            Some(c) => c,
            None => match PAREN_TAX_NOTE.captures(&s) {
                Some(c) => c,
                None => break,
            },
        };
        let collapsed = WHITESPACE.replace_all(java_trim(caps.get(1).unwrap().as_str()), " ");
        tail_notes.push(normalise_leading_auct(&collapsed));
        s = java_trim(&s[..caps.get(0).unwrap().start()]).to_string();
        while s.ends_with(',') {
            s.pop();
            s = java_trim(&s).to_string();
        }
    }

    // A leading parenthesised homonym citation "(non/nec/not ...)" followed by more text makes
    // the whole authorship a misapplied/taxonomic note rather than a basionym — capture it
    // verbatim, no author left.
    if LEADING_HOMONYM_PAREN.is_match(&s) {
        notes.push(collapse_whitespace(&s));
        s.clear();
    }

    // Parenthesised taxonomic note "(auct.)"/"(sensu ...)"/"(sec ...)" — the parens mark a
    // note, not a basionym. Capture the inner text as the taxonomic note, drop the parens,
    // and keep any real author beside them: "(auct.) Rolfe" -> author Rolfe + note "auct.";
    // "(sensu X, 1878) Y, 1992" -> author "Y, 1992" + note "sensu X, 1878".
    if let Some(caps) = PAREN_NOTE.captures(&s) {
        let inner = java_trim(caps.get(1).unwrap().as_str());
        let norm = WHITESPACE.replace_all(inner, " ").into_owned();
        notes.push(normalise_leading_auct(&norm));
        let whole = caps.get(0).unwrap();
        let (start, end) = (whole.start(), whole.end());
        s = java_trim(&format!("{}{}", &s[..start], &s[end..])).to_string();
    }

    // A quoted attributed author leading it, as on the name string.
    if let Some(caps) = AUTHORSHIP_QUOTED_ATTRIBUTED.captures(&s) {
        s = format!("{} MS, {}", &caps[1], &caps[2]);
    }

    // A bracketed quoted spelling after the author, as on the name string.
    if let Ok(Some(caps)) = AUTHORSHIP_QUOTED_SPELLING.captures(&s) {
        name.add_nomenclatural_note(caps.get(2).unwrap().as_str());
        s = java_trim(caps.get(1).unwrap().as_str()).to_string();
    }

    // Bracketed nom-notes "(nom. nud.)"/"[nom. cons.]" in the auxiliary authorship —
    // extract into nomenclaturalNote and drop from the string before tokenisation.
    if let Some(caps) = BRACKETED_NOM_NOTE.captures(&s) {
        let raw = java_trim(caps.get(1).unwrap().as_str()).to_string();
        if MANUSCRIPT_KEYWORD.is_match(&raw) {
            name.manuscript = true;
        }
        let norm = normalise_nom_note(&raw);
        name.add_nomenclatural_note(&norm);
        let match_start = caps.get(0).unwrap().start();
        s = java_trim(&s[..match_start]).to_string();
    }

    // Bare nomenclatural notes ("nom. illeg.", "comb. nov.", "sp. nov.", …) in the
    // auxiliary authorship — same extraction as `run()`'s `strip_nom_note`, so a
    // separately-supplied authorship behaves like the equivalent tail on a full name.
    // Matched against a space-padded copy so a note anchored at the very START of the
    // string ("nom. illeg.") is caught too — NOM_NOTE requires a leading whitespace.
    let padded_nom = format!(" {s}");
    if let Ok(Some(caps)) = NOM_NOTE.captures(&padded_nom) {
        let raw = java_trim(caps.get(1).unwrap().as_str()).to_string();
        if !raw.is_empty() {
            let norm = normalise_nom_note(&raw);
            name.add_nomenclatural_note(&norm);
            let whole = caps.get(0).unwrap();
            let before = java_trim(&padded_nom[..whole.start()]).to_string();
            let after = java_trim(&padded_nom[whole.end()..]).to_string();
            s = if after.is_empty() {
                before
            } else {
                format!("{before} {after}")
            };
            s = java_trim(&s).to_string();
            while s.ends_with(',') {
                s.pop();
                s = java_trim(&s).to_string();
            }
            if MANUSCRIPT_KEYWORD.is_match(&raw) {
                name.manuscript = true;
            }
        }
    }

    s = strip_not_validly_published_note(&s, name);

    // Strip taxonomic-note tails (sensu, emend., auct., etc.) from the auxiliary
    // authorship string — same patterns `run()`'s `strip_tax_note` applies to the main
    // working string. Matched against a space-padded copy (same reasoning as NOM_NOTE
    // above).
    let padded_tax = format!(" {}", lift_bracketed_notes(&s));
    if let Some((_, group1_start)) = find_tax_note(&padded_tax, true) {
        let raw = java_trim(&padded_tax[group1_start..]).to_string();
        if !raw.is_empty() {
            let with_dots = INITIAL_DOT_SPACE.replace_all(&raw, "$1.$2");
            notes.push(normalise_leading_auct(&with_dots));
            // Cut `s` right before group(1)'s content. Group(1) is a suffix of
            // `padded_tax` (TAX_NOTE's trailing `)$` anchors it to end-of-padded-string),
            // and `padded_tax` is `s` with exactly one ASCII-space byte prepended, so
            // slicing `padded_tax[..group1_start]` (which still carries that one leading
            // pad byte) and `java_trim`-ing it away yields exactly the same content as
            // Java's `s.substring(0, s.length() - m.group(1).length()).trim()` — without
            // needing any UTF-16-vs-UTF-8 length arithmetic or a same-string byte-offset
            // subtraction that could underflow.
            s = java_trim(&padded_tax[..group1_start]).to_string();
            while s.ends_with(',') {
                s.pop();
                s = java_trim(&s).to_string();
            }
        }
    }
    notes.extend(tail_notes.into_iter().rev());
    // Within the authorship only an exact repeat is dropped ("(auct.) auct."): "sensu Pers. [non
    // sensu Pers.]" holds two different statements.
    notes.dedup();
    if let Some(note) = notes.into_iter().reduce(|a, b| format!("{a} {b}")) {
        name.taxonomic_note = Some(match name.taxonomic_note.take() {
            Some(existing) => merge_notes(existing, note),
            None => note,
        });
    }
    java_trim(&s).to_string()
}

/// Lower-case "auctorum" and "not" are real epithets too (`Lobotes auctorum Günther, 1859`,
/// `Harnischia viridula subsp. auctorum`, Erwin's `Agra not Erwin, 2002`): right after the genus
/// (and any infrageneric) or after a rank marker they stay one — unless a genus-or-above rank hint
/// says the name is a monomial (`Colobodus auctorum`). After a species epithet or an author they
/// are the note (`Cucullia ledereri auctorum`, `Apseudes minutus Brown, 1956 not Claus, 1888`).
fn note_keyword_is_epithet(prefix: &str, rank: Option<Rank>) -> bool {
    let words: Vec<&str> = prefix
        .split_whitespace()
        .filter(|w| !w.starts_with('('))
        .collect();
    match words.as_slice() {
        [_genus] => !rank.is_some_and(|r| r.higher_than(Rank::SpeciesAggregate)),
        [.., last] => rank_of_marker(last.trim_end_matches('.')).is_some(),
        [] => false,
    }
}

/// Joins two taxonomic notes, unless one already holds the other word for word: the name's
/// "sensu Blackburn, 1900 not Spinola, 1844" already says the authorship's "sensu Blackburn", and
/// the authorship's "auct. non Vahl" says more than the name's "auct.". Java appended any note that
/// was not identical.
fn merge_notes(existing: String, note: String) -> String {
    if contains_words(&existing, &note) {
        existing
    } else if contains_words(&note, &existing) {
        note
    } else {
        format!("{existing} {note}")
    }
}

/// Does `haystack` contain `needle` as whole words — starting at a word start and ending before a
/// space, comma or semicolon (so "non L." is not found in "non L.f.")?
fn contains_words(haystack: &str, needle: &str) -> bool {
    haystack.match_indices(needle).any(|(i, _)| {
        let after = &haystack[i + needle.len()..];
        (i == 0 || haystack[..i].ends_with(' '))
            && (after.is_empty() || after.starts_with([' ', ',', ';']))
    })
}

#[cfg(test)]
mod tests {
    use super::*;
    use crate::model::NameType;

    fn ctx(s: &str) -> ParseContext {
        ParseContext::new(s.to_string(), None, None, None)
    }

    /// Phase 1 Slice 2 Task 2 locked the dispatcher order down with every one of the 55
    /// steps a pure passthrough. Batches 1, 2b, 2c, 2d and 2e (steps 1-55, ALL of them as
    /// of this batch) now carry a faithful port, but a clean, unremarkable binomial should
    /// still round-trip untouched: none of steps 1-19's guard conditions (a trailing/glued
    /// "?", a quoted leading monomial, a "Missing "/lowercase-epithet prefix, Greek/star
    /// markers, a letter-subdivision marker, "str"/"strain", imprint-year brackets, "null"
    /// between epithets, Unicode hyphen/Win-1252/double-underscore artefacts, a trailing
    /// OTU code, serovar/serotype, an angle bracket, or HTML), steps 20-30's (a
    /// "Candidatus"/"Ca." prefix, a horticultural "ex" placeholder, a cultivar
    /// Group/grex/quoted epithet, an extinction dagger, a "t.infr." marker, a bracketed
    /// genus, "sic"/"corrig.", a synonymy bracket, or a nom/comb/orth/nomen/sp.nov./
    /// pro-syn. keyword), steps 31-44's (an authorship placeholder, a trailing " species",
    /// "pro parte"/"p.p.", a "(pro sp.)" annotation, "(Approved Lists YYYY)", "mihi",
    /// "Anon"/"anon", or any of the six taxonomic-note/aggregate-suffix keywords), steps
    /// 45-52's (a trailing page reference, "in press", a parenthesised or trailing
    /// "in"/"apud" citation, an IPNI/period-/comma-separated reference, or a manuscript
    /// marker), nor steps 53-55's (a suprarank/leading-infrageneric-rank prefix, or a
    /// phrase-name shape) fire on "Abies alba Mill.". This still locks the same invariant
    /// Task 2 established — a batch landing later can't silently leave a step half-wired —
    /// just now over the complete, fully-ported 55-step dispatcher rather than 55 no-ops.
    #[test]
    fn run_leaves_a_clean_binomial_untouched() {
        let mut c = ParseContext::new("Abies alba Mill.".to_string(), None, None, None);
        let before_working = c.working.clone();
        let before_name = c.name.clone();
        run(&mut c);
        assert_eq!(c.working, before_working);
        assert_eq!(c.name, before_name);
    }

    // ---- Step 1: flagUncertainAuthorship ----

    #[test]
    fn trailing_qmark_is_stripped_and_flags_doubtful() {
        let mut c = ctx("x");
        let out = flag_uncertain_authorship(&mut c, "Aus bus Smith ?".to_string());
        assert_eq!(out, "Aus bus Smith");
        assert!(c.name.doubtful);
        assert!(c
            .name
            .warnings
            .contains(&warnings::QUESTION_MARKS_REMOVED.to_string()));
    }

    #[test]
    fn qmark_glued_to_author_word_flags_uncertain_without_stripping() {
        // Spot-checked against the Java CLI oracle: "Aus bus Sess?" keeps the literal
        // "Sess?" through StripAndStash — the "?" is dropped later by the tokenizer,
        // not here.
        let mut c = ctx("x");
        let out = flag_uncertain_authorship(&mut c, "Aus bus Sess?".to_string());
        assert_eq!(out, "Aus bus Sess?");
        assert!(c.name.doubtful);
        assert!(c
            .name
            .warnings
            .contains(&warnings::UNCERTAIN_AUTHORSHIP.to_string()));
    }

    #[test]
    fn or_joined_alternative_authors_flag_uncertain_without_stripping() {
        let mut c = ctx("x");
        let out = flag_uncertain_authorship(&mut c, "Aus bus Jarocki or Schinz, 1900".to_string());
        assert_eq!(out, "Aus bus Jarocki or Schinz, 1900");
        assert!(c.name.doubtful);
        assert!(c
            .name
            .warnings
            .contains(&warnings::UNCERTAIN_AUTHORSHIP.to_string()));
    }

    #[test]
    fn slash_joined_alternative_authors_flag_uncertain_without_stripping() {
        let mut c = ctx("x");
        let out = flag_uncertain_authorship(&mut c, "Aus bus Smith/Jones, 1900".to_string());
        assert_eq!(out, "Aus bus Smith/Jones, 1900");
        assert!(c.name.doubtful);
    }

    #[test]
    fn clean_name_is_not_flagged() {
        let mut c = ctx("x");
        let out = flag_uncertain_authorship(&mut c, "Abies alba Mill.".to_string());
        assert_eq!(out, "Abies alba Mill.");
        assert!(!c.name.doubtful);
        assert!(c.name.warnings.is_empty());
    }

    // ---- Step 2: extractGenericAuthor ----

    #[test]
    fn infrageneric_author_before_marker_is_extracted() {
        let mut c = ctx("x");
        let out =
            extract_generic_author(&mut c, "Cordia (Adans.) Kuntze sect. Salimori".to_string());
        assert_eq!(out, "Cordia sect. Salimori");
        assert_eq!(
            c.pending_generic_author,
            Some("(Adans.) Kuntze".to_string())
        );
    }

    #[test]
    fn no_infrageneric_marker_leaves_string_untouched() {
        let mut c = ctx("x");
        let out = extract_generic_author(&mut c, "Abies alba Mill.".to_string());
        assert_eq!(out, "Abies alba Mill.");
        assert_eq!(c.pending_generic_author, None);
    }

    // ---- Step 3: stripQuotedMonomial ----

    #[test]
    fn single_quoted_leading_monomial_is_unquoted_and_flagged_doubtful() {
        let mut c = ctx("x");
        let out = strip_quoted_monomial(&mut c, "'Prosthète' Hesse, 1861".to_string());
        assert_eq!(out, "Prosthète Hesse, 1861");
        assert_eq!(c.quoted_monomial, Some("'".to_string()));
        assert!(c.name.doubtful);
    }

    #[test]
    fn double_quoted_monomial_with_no_trailing_text() {
        let mut c = ctx("x");
        let out = strip_quoted_monomial(&mut c, "\"Foo\"".to_string());
        assert_eq!(out, "Foo");
        assert_eq!(c.quoted_monomial, Some("\"".to_string()));
    }

    #[test]
    fn unquoted_name_is_untouched() {
        let mut c = ctx("x");
        let out = strip_quoted_monomial(&mut c, "Abies alba".to_string());
        assert_eq!(out, "Abies alba");
        assert_eq!(c.quoted_monomial, None);
    }

    // ---- Step 4: applyMissingGenusPlaceholder ----

    #[test]
    fn inferred_missing_genus_gets_placeholder_type_and_warning() {
        let mut c = ctx("x");
        let out =
            apply_missing_genus_placeholder(&mut c, "denheyeri Eghbalian, Path, 2017".to_string());
        assert_eq!(out, "? denheyeri Eghbalian, Path, 2017");
        assert_eq!(c.name.type_, NameType::Placeholder);
        assert!(c
            .name
            .warnings
            .contains(&warnings::MISSING_GENUS.to_string()));
    }

    #[test]
    fn explicit_missing_prefix_gets_placeholder_type_but_no_warning() {
        let mut c = ctx("x");
        let out = apply_missing_genus_placeholder(
            &mut c,
            "Missing penchinati Bourguignat, 1870".to_string(),
        );
        assert_eq!(out, "? penchinati Bourguignat, 1870");
        assert_eq!(c.name.type_, NameType::Placeholder);
        assert!(c.name.warnings.is_empty());
    }

    #[test]
    fn quoted_question_prefix_gets_placeholder_type_but_no_warning() {
        let mut c = ctx("x");
        let out = apply_missing_genus_placeholder(&mut c, "\"? gryphoidis".to_string());
        assert_eq!(out, "? gryphoidis");
        assert_eq!(c.name.type_, NameType::Placeholder);
        assert!(c.name.warnings.is_empty());
    }

    #[test]
    fn particle_led_epithet_shape_is_not_treated_as_missing_genus() {
        // "van" is a surname particle (AuthorParticles) — a particle-led input is an
        // author name, not an epithet whose genus went missing, even though it matches
        // MISSING_GENUS_EPITHET's shape (lowercase word + capitalised word).
        let mut c = ctx("x");
        let out = apply_missing_genus_placeholder(&mut c, "van Berg".to_string());
        assert_eq!(out, "van Berg");
        assert_eq!(c.name.type_, NameType::Scientific);
    }

    #[test]
    fn note_keyword_led_epithet_shape_is_not_treated_as_missing_genus() {
        let mut c = ctx("x");
        let out = apply_missing_genus_placeholder(&mut c, "sensu Author".to_string());
        assert_eq!(out, "sensu Author");
        assert_eq!(c.name.type_, NameType::Scientific);
    }

    #[test]
    fn clean_capitalised_name_is_untouched() {
        let mut c = ctx("x");
        let out = apply_missing_genus_placeholder(&mut c, "Abies alba Mill.".to_string());
        assert_eq!(out, "Abies alba Mill.");
        assert_eq!(c.name.type_, NameType::Scientific);
    }

    // ---- Step 5: stripInfraRankLetters ----

    #[test]
    fn greek_letter_marker_between_epithets_is_collapsed_to_a_space() {
        let mut c = ctx("x");
        let out = strip_infra_rank_letters(&mut c, "Foo bar \u{03B1} baz".to_string());
        assert_eq!(out, "Foo bar baz");
    }

    #[test]
    fn apl_alpha_lookalike_marker_is_also_collapsed() {
        let mut c = ctx("x");
        let out = strip_infra_rank_letters(&mut c, "Foo bar \u{237A} baz".to_string());
        assert_eq!(out, "Foo bar baz");
    }

    #[test]
    fn star_marker_between_epithets_is_collapsed_to_a_space() {
        let mut c = ctx("x");
        let out = strip_infra_rank_letters(&mut c, "Foo bar *** baz".to_string());
        assert_eq!(out, "Foo bar baz");
    }

    #[test]
    fn no_infra_rank_letter_marker_is_untouched() {
        let mut c = ctx("x");
        let out = strip_infra_rank_letters(&mut c, "Abies alba Mill.".to_string());
        assert_eq!(out, "Abies alba Mill.");
    }

    // ---- Step 6: normaliseLetterSubdivisionMarker ----

    #[test]
    fn letter_subdivision_marker_is_rewritten_to_the_synthetic_token() {
        let mut c = ctx("x");
        let out = normalise_letter_subdivision_marker(
            &mut c,
            "Graphis scripta L. a.b pulverulenta".to_string(),
        );
        assert_eq!(out, "Graphis scripta L. infrasubdivision pulverulenta");
    }

    #[test]
    fn real_rank_marker_shaped_like_a_single_letter_is_left_alone() {
        // "f." is itself a real rank marker (forma) — must be left for the normal
        // rank-marker path, not rewritten to the synthetic subdivision token (confirmed
        // against the Java CLI oracle: this input parses with rank=FORM, not OTHER).
        let mut c = ctx("x");
        let out = normalise_letter_subdivision_marker(
            &mut c,
            "Graphis scripta L. f. pulverulenta".to_string(),
        );
        assert_eq!(out, "Graphis scripta L. f. pulverulenta");
    }

    #[test]
    fn non_matching_shape_is_untouched() {
        let mut c = ctx("x");
        let out = normalise_letter_subdivision_marker(&mut c, "Abies alba Mill.".to_string());
        assert_eq!(out, "Abies alba Mill.");
    }

    // ---- Step 7: repairQuestionMarkInWord ----

    #[test]
    fn qmark_inside_a_word_is_removed_and_flags_doubtful() {
        let mut c = ctx("x");
        let out = repair_question_mark_in_word(&mut c, "Aus bus Istv?nffi".to_string());
        assert_eq!(out, "Aus bus Istvnffi");
        assert!(c.name.doubtful);
        assert!(c
            .name
            .warnings
            .contains(&warnings::QUESTION_MARKS_REMOVED.to_string()));
    }

    #[test]
    fn no_internal_qmark_is_untouched() {
        let mut c = ctx("x");
        let out = repair_question_mark_in_word(&mut c, "Abies alba Mill.".to_string());
        assert_eq!(out, "Abies alba Mill.");
        assert!(!c.name.doubtful);
    }

    // ---- Step 8: stripStrainDesignation ----

    #[test]
    fn quoted_strain_designation_becomes_a_phrase() {
        let mut c = ctx("x");
        let out =
            strip_strain_designation(&mut c, "Aphanizomenon flos-aquae str .'Aph K2'".to_string());
        assert_eq!(out, "Aphanizomenon flos-aquae str.");
        assert_eq!(c.name.phrase, Some("Aph K2".to_string()));
        assert_eq!(c.name.type_, NameType::Informal);
    }

    #[test]
    fn strain_designation_with_lowercase_prefix_is_untouched() {
        // The prefix before the marker must start with an uppercase letter (a plausible
        // genus); a lowercase-led prefix is junk, never touched.
        let mut c = ctx("x");
        let out = strip_strain_designation(&mut c, "foo str .'Aph K2'".to_string());
        assert_eq!(out, "foo str .'Aph K2'");
        assert_eq!(c.name.phrase, None);
    }

    #[test]
    fn no_strain_marker_is_untouched() {
        let mut c = ctx("x");
        let out = strip_strain_designation(&mut c, "Abies alba Mill.".to_string());
        assert_eq!(out, "Abies alba Mill.");
    }

    // ---- Step 9: stashTrailingStrainCode ----

    #[test]
    fn trailing_rna_code_becomes_a_phrase() {
        let mut c = ctx("x");
        let out = stash_trailing_strain_code(&mut c, "Candida albicans RNA_CTR0-3".to_string());
        assert_eq!(out, "Candida albicans");
        assert_eq!(c.name.phrase, Some("RNA_CTR0-3".to_string()));
        assert_eq!(c.name.type_, NameType::Informal);
    }

    #[test]
    fn trailing_short_rna_code_becomes_a_phrase() {
        let mut c = ctx("x");
        let out = stash_trailing_strain_code(&mut c, "Armillaria ostoyae RNA1".to_string());
        assert_eq!(out, "Armillaria ostoyae");
        assert_eq!(c.name.phrase, Some("RNA1".to_string()));
    }

    #[test]
    fn clean_binomial_with_no_trailing_code_is_untouched() {
        let mut c = ctx("x");
        let out = stash_trailing_strain_code(&mut c, "Abies alba".to_string());
        assert_eq!(out, "Abies alba");
        assert_eq!(c.name.phrase, None);
    }

    // gbif/name-parser-rust#16 — the digit-leading code alternative and its three guards.

    #[test]
    fn trailing_digit_leading_code_becomes_a_phrase() {
        for (input, head, code) in [
            ("Prunus domestica 6", "Prunus domestica", "6"),
            ("Prunus domestica 5a", "Prunus domestica", "5a"),
            ("Prunus domestica 6/12", "Prunus domestica", "6/12"),
            ("Abies alba 12", "Abies alba", "12"),
            ("Escherichia coli 18-41", "Escherichia coli", "18-41"),
            (
                "Acinetobacter baumannii 1237893",
                "Acinetobacter baumannii",
                "1237893",
            ),
            (
                "Actinomycetota bacterium 4327",
                "Actinomycetota bacterium",
                "4327",
            ),
            (
                "Lachnospiraceae bacterium 47-T17",
                "Lachnospiraceae bacterium",
                "47-T17",
            ),
            ("Trachelomonas strain T101", "Trachelomonas strain", "T101"),
        ] {
            let mut c = ctx("x");
            let out = stash_trailing_strain_code(&mut c, input.to_string());
            assert_eq!(out, head, "head for {input:?}");
            assert_eq!(
                c.name.phrase,
                Some(code.to_string()),
                "phrase for {input:?}"
            );
            assert_eq!(c.name.type_, NameType::Informal, "type for {input:?}");
        }
    }

    #[test]
    fn trailing_bare_year_is_left_for_the_authorship_parser() {
        // TRAILING_YEAR: a bare 1xxx/2xxx keeps its pre-#16 reading as a publication year.
        for input in ["Prunus domestica 1888", "Xanthomonas eucalypti 1974"] {
            let mut c = ctx("x");
            let out = stash_trailing_strain_code(&mut c, input.to_string());
            assert_eq!(out, input);
            assert_eq!(c.name.phrase, None);
        }
    }

    #[test]
    fn trailing_numeral_epithet_is_not_a_strain_code() {
        // TRAILING_NUMERAL_EPITHET: "7-maculatus" is an epithet the tokenizer glues into a
        // single WORD and NameTokens accepts; stashing it would lose the infraspecific name.
        let mut c = ctx("x");
        let out = stash_trailing_strain_code(&mut c, "Episyron rufipes 7-maculatus".to_string());
        assert_eq!(out, "Episyron rufipes 7-maculatus");
        assert_eq!(c.name.phrase, None);
    }

    #[test]
    fn indet_species_marker_head_is_left_to_name_tokens() {
        // is_indet_species_marker: "Allium species 1" is an indeterminate Allium, and
        // NameTokens keeps the marker in the phrase ("species 1"). Stripping the "1" here
        // would drop the marker and render "Allium 1".
        for input in ["Allium species 1", "Anopheles sp TIP1", "Allium spec 1"] {
            let mut c = ctx("x");
            let out = stash_trailing_strain_code(&mut c, input.to_string());
            assert_eq!(out, input, "for {input:?}");
            assert_eq!(c.name.phrase, None, "for {input:?}");
        }
    }

    #[test]
    fn a_full_stop_closing_the_string_is_not_part_of_the_code() {
        // The `\.?` tail: one trailing full stop is sentence punctuation, consumed but kept out
        // of the phrase. Without it `Prunus domestica 6.` stayed on the truncation path.
        for (input, head, code) in [
            ("Prunus domestica 6.", "Prunus domestica", "6"),
            ("Bacteroides caccae CAG21.", "Bacteroides caccae", "CAG21"),
        ] {
            let mut c = ctx("x");
            let out = stash_trailing_strain_code(&mut c, input.to_string());
            assert_eq!(out, head, "head for {input:?}");
            assert_eq!(
                c.name.phrase,
                Some(code.to_string()),
                "phrase for {input:?}"
            );
        }
    }

    #[test]
    fn a_dotted_bare_year_is_still_left_for_the_authorship_parser() {
        let mut c = ctx("x");
        let out = stash_trailing_strain_code(&mut c, "Prunus domestica 1888.".to_string());
        assert_eq!(out, "Prunus domestica 1888.");
        assert_eq!(c.name.phrase, None);
    }

    // ---- gbif/name-parser-rust#16: indeterminate "Genus <rank marker> CODE" ----

    #[test]
    fn a_rank_marker_in_the_epithet_slot_takes_the_whole_tail_as_the_phrase() {
        for (input, genus, phrase) in [
            ("Allium sect 1", "Allium", "sect 1"),
            ("Allium sect. 1", "Allium", "sect. 1"),
            ("Allium subg. 3", "Allium", "subg. 3"),
            ("Allium var 3", "Allium", "var 3"),
            ("Trachelomonas strain T101", "Trachelomonas", "strain T101"),
        ] {
            let mut c = ctx("x");
            let out = stash_trailing_rank_marker_code(&mut c, input.to_string());
            assert_eq!(out, genus, "head for {input:?}");
            assert_eq!(
                c.name.phrase,
                Some(phrase.to_string()),
                "phrase for {input:?}"
            );
            assert_eq!(c.name.type_, NameType::Informal, "type for {input:?}");
        }
    }

    #[test]
    fn the_rank_marker_step_sets_only_an_infraspecific_rank() {
        // An infraspecific marker's rank is applied…
        let mut c = ctx("x");
        stash_trailing_rank_marker_code(&mut c, "Allium var. 3".to_string());
        assert_eq!(c.name.rank, Rank::Variety);
        // …an infrageneric one's is not: at an infrageneric rank Assemble reads the lone
        // remaining word as the infrageneric EPITHET, leaving "Allium sect 1" with no genus.
        let mut c = ctx("x");
        let out = stash_trailing_rank_marker_code(&mut c, "Allium sect. 1".to_string());
        assert_eq!(out, "Allium");
        assert_eq!(c.name.phrase, Some("sect. 1".to_string()));
        assert_eq!(c.name.rank, Rank::Unranked);
    }

    #[test]
    fn the_rank_marker_step_leaves_real_epithets_and_indet_markers_alone() {
        for input in [
            // a real binomial + strain code — stash_trailing_strain_code's job, not this one
            "Bacteroides caccae CAG21",
            "Prunus domestica 6",
            // sp/spec/species belong to NameTokens
            "Allium species 1",
            "Allium sp. 1",
        ] {
            let mut c = ctx("x");
            let out = stash_trailing_rank_marker_code(&mut c, input.to_string());
            assert_eq!(out, input, "for {input:?}");
            assert_eq!(c.name.phrase, None, "for {input:?}");
        }
    }

    // ---- Step 10: stripImprintYears ----

    #[test]
    fn quoted_bracketed_imprint_year_is_stashed() {
        let mut c = ctx("x");
        let out = strip_imprint_years(&mut c, "Aus bus Storr, 1970 [\"1969\"]".to_string());
        assert_eq!(out, "Aus bus Storr, 1970");
        assert_eq!(c.pending_imprint_year, Some("1969".to_string()));
    }

    #[test]
    fn keyword_imprint_year_is_stashed() {
        let mut c = ctx("x");
        let out = strip_imprint_years(&mut c, "Aus bus Storr, 1970 (imprint 1969)".to_string());
        assert_eq!(out, "Aus bus Storr, 1970");
        assert_eq!(c.pending_imprint_year, Some("1969".to_string()));
    }

    #[test]
    fn alt_ampersand_year_is_stashed_when_an_earlier_year_exists() {
        let mut c = ctx("x");
        let out = strip_imprint_years(&mut c, "Aus bus Wagener, 1959 & 1961".to_string());
        assert_eq!(out, "Aus bus Wagener, 1959");
        assert_eq!(c.pending_imprint_year, Some("1961".to_string()));
    }

    #[test]
    fn alt_ampersand_year_is_not_stripped_without_an_earlier_year() {
        let mut c = ctx("x");
        let out = strip_imprint_years(&mut c, "Aus bus & 1961".to_string());
        assert_eq!(out, "Aus bus & 1961");
        assert_eq!(c.pending_imprint_year, None);
    }

    #[test]
    fn no_imprint_year_annotation_is_untouched() {
        let mut c = ctx("x");
        let out = strip_imprint_years(&mut c, "Abies alba Mill.".to_string());
        assert_eq!(out, "Abies alba Mill.");
        assert_eq!(c.pending_imprint_year, None);
    }

    // ---- Step 11: stripNullBetweenEpithets ----

    #[test]
    fn bare_null_between_epithets_is_dropped_and_flags_doubtful() {
        let mut c = ctx("x");
        let out = strip_null_between_epithets(
            &mut c,
            "Austrorhynchus pectatus null pectatus".to_string(),
        );
        assert_eq!(out, "Austrorhynchus pectatus pectatus");
        assert!(c.name.doubtful);
        assert!(c
            .name
            .warnings
            .contains(&warnings::NULL_EPITHET.to_string()));
    }

    #[test]
    fn no_null_epithet_is_untouched() {
        let mut c = ctx("x");
        let out = strip_null_between_epithets(&mut c, "Abies alba Mill.".to_string());
        assert_eq!(out, "Abies alba Mill.");
        assert!(!c.name.doubtful);
    }

    // ---- Step 12: normaliseHyphens ----

    #[test]
    fn en_dash_is_normalised_to_ascii_hyphen_and_flags_homoglyphs() {
        let mut c = ctx("x");
        let out = normalise_hyphens(&mut c, "Aus bus\u{2013}fer Mill.".to_string());
        assert_eq!(out, "Aus bus-fer Mill.");
        assert!(c.name.warnings.contains(&warnings::HOMOGLYHPS.to_string()));
    }

    #[test]
    fn all_five_unicode_hyphen_variants_are_normalised() {
        let mut c = ctx("x");
        let input = "a\u{2010}b\u{2011}c\u{2012}d\u{2013}e\u{2014}f";
        let out = normalise_hyphens(&mut c, input.to_string());
        assert_eq!(out, "a-b-c-d-e-f");
    }

    #[test]
    fn ascii_hyphen_alone_is_untouched_with_no_warning() {
        let mut c = ctx("x");
        let out = normalise_hyphens(&mut c, "Aus bus-fer Mill.".to_string());
        assert_eq!(out, "Aus bus-fer Mill.");
        assert!(c.name.warnings.is_empty());
    }

    // ---- Step 13: replaceHomoglyphs ----

    #[test]
    fn cyrillic_lookalike_is_folded_to_latin_and_flags_homoglyphs() {
        let mut c = ctx("x");
        let out = replace_homoglyphs(&mut c, "Aus \u{0430}bus".to_string()); // Cyrillic 'а'
        assert_eq!(out, "Aus abus");
        assert!(c.name.warnings.contains(&warnings::HOMOGLYHPS.to_string()));
    }

    /// The exact corpus shape this step used to leave untouched (see
    /// `tests/parse_golden.rs`'s now-empty `ALLOWLIST`): a specific epithet carrying U+017F
    /// LATIN SMALL LETTER LONG S folds to plain "s".
    #[test]
    fn long_s_in_specific_epithet_is_folded_and_flags_homoglyphs() {
        let mut c = ctx("x");
        let out = replace_homoglyphs(&mut c, "Musca dome\u{017F}tica Linnaeus 1758".to_string());
        assert_eq!(out, "Musca domestica Linnaeus 1758");
        assert!(c.name.warnings.contains(&warnings::HOMOGLYHPS.to_string()));
    }

    #[test]
    fn hybrid_marker_and_ae_ligature_are_not_homoglyphs_here_either() {
        let mut c = ctx("x");
        let out = replace_homoglyphs(&mut c, "Abies \u{00D7} Picea".to_string());
        assert_eq!(out, "Abies \u{00D7} Picea");
        assert!(c.name.warnings.is_empty());

        let mut c2 = ctx("x");
        let out2 = replace_homoglyphs(&mut c2, "Amphisb\u{00E6}na".to_string());
        assert_eq!(out2, "Amphisb\u{00E6}na");
        assert!(c2.name.warnings.is_empty());
    }

    #[test]
    fn plain_name_is_untouched_with_no_warning() {
        let mut c = ctx("x");
        let out = replace_homoglyphs(&mut c, "Abies alba Mill.".to_string());
        assert_eq!(out, "Abies alba Mill.");
        assert!(c.name.warnings.is_empty());
    }

    // ---- Step 14: repairWin1252Artefacts ----

    #[test]
    fn inverted_exclamation_artefact_is_repaired_and_flags_homoglyphs() {
        let mut c = ctx("x");
        let out = repair_win1252_artefacts(&mut c, "Aus bus Plesn\u{00A1}k, 1900".to_string());
        assert_eq!(out, "Aus bus Plesnik, 1900");
        assert!(c.name.warnings.contains(&warnings::HOMOGLYHPS.to_string()));
    }

    #[test]
    fn all_six_win1252_artefacts_are_repaired() {
        let mut c = ctx("x");
        let input = "\u{00A1}\u{00A2}\u{00A3}\u{201A}\u{201E}\u{2030}";
        let out = repair_win1252_artefacts(&mut c, input.to_string());
        assert_eq!(out, "icLeae");
    }

    #[test]
    fn no_win1252_artefact_is_untouched_with_no_warning() {
        let mut c = ctx("x");
        let out = repair_win1252_artefacts(&mut c, "Abies alba Mill.".to_string());
        assert_eq!(out, "Abies alba Mill.");
        assert!(c.name.warnings.is_empty());
    }

    #[test]
    fn colon_coded_diacritics_are_restored() {
        let mut c = ctx("x");
        let out = repair_colon_diacritics(&mut c, "A:1ngstro:2m, Vondra:4c:3ek".to_string());
        assert_eq!(out, "Ångström, Vondráček");
        assert!(c.coded_diacritics);
        assert!(c.name.warnings.contains(&warnings::HOMOGLYHPS.to_string()));
    }

    #[test]
    fn a_colon_before_several_digits_or_no_letter_is_no_diacritic() {
        let mut c = ctx("x");
        let input = "Smith DOI:10.1234, names:864424, Mus:9";
        let out = repair_colon_diacritics(&mut c, input.to_string());
        assert_eq!(out, input);
        assert!(!c.coded_diacritics);
        assert!(c.name.warnings.is_empty());
    }

    // ---- Step 15: normaliseDoubleUnderscores ----

    #[test]
    fn double_underscore_collapses_to_a_single_space() {
        let mut c = ctx("x");
        let out = normalise_double_underscores(&mut c, "Pseudocercospora__dendrobii".to_string());
        assert_eq!(out, "Pseudocercospora dendrobii");
    }

    #[test]
    fn triple_underscore_also_collapses_to_a_single_space() {
        let mut c = ctx("x");
        let out = normalise_double_underscores(&mut c, "Foo___bar".to_string());
        assert_eq!(out, "Foo bar");
    }

    #[test]
    fn single_underscore_is_untouched() {
        let mut c = ctx("x");
        let out = normalise_double_underscores(&mut c, "Foo_bar".to_string());
        assert_eq!(out, "Foo_bar");
    }

    // ---- Step 16: stashTrailingOtuCode ----

    #[test]
    fn trailing_otu_code_is_stashed_as_pending_unparsed() {
        let mut c = ctx("x");
        let out = stash_trailing_otu_code(&mut c, "Oxalis barrelieri XXZ_21243".to_string());
        assert_eq!(out, "Oxalis barrelieri");
        assert_eq!(c.pending_unparsed, Some("XXZ_21243".to_string()));
    }

    #[test]
    fn otu_code_extraction_is_skipped_when_pending_unparsed_already_set() {
        let mut c = ctx("x");
        c.pending_unparsed = Some("existing".to_string());
        let out = stash_trailing_otu_code(&mut c, "Oxalis barrelieri XXZ_21243".to_string());
        assert_eq!(out, "Oxalis barrelieri XXZ_21243");
        assert_eq!(c.pending_unparsed, Some("existing".to_string()));
    }

    #[test]
    fn single_word_input_is_untouched() {
        let mut c = ctx("x");
        let out = stash_trailing_otu_code(&mut c, "Abies".to_string());
        assert_eq!(out, "Abies");
        assert_eq!(c.pending_unparsed, None);
    }

    // ---- Step 17: stripSerovarSerotype ----

    #[test]
    fn bare_serovar_annotation_is_stripped_silently() {
        let mut c = ctx("x");
        let out =
            strip_serovar_serotype(&mut c, "Leptospira interrogans serovar Fugis".to_string());
        assert_eq!(out, "Leptospira interrogans");
        assert!(c.name.warnings.is_empty());
    }

    #[test]
    fn serotype_with_trailing_strain_suffix_is_stripped() {
        let mut c = ctx("x");
        let out = strip_serovar_serotype(
            &mut c,
            "Aggregatibacter actinomycetemcomitans serotype d str. SA508".to_string(),
        );
        assert_eq!(out, "Aggregatibacter actinomycetemcomitans");
    }

    #[test]
    fn parenthesised_serotype_annotation_is_stripped() {
        let mut c = ctx("x");
        let out =
            strip_serovar_serotype(&mut c, "Streptococcus pyogenes (serotype M18)".to_string());
        assert_eq!(out, "Streptococcus pyogenes");
    }

    #[test]
    fn no_serovar_annotation_is_untouched() {
        let mut c = ctx("x");
        let out = strip_serovar_serotype(&mut c, "Abies alba Mill.".to_string());
        assert_eq!(out, "Abies alba Mill.");
    }

    // ---- Step 18: stripAngleBracketAuthorship ----

    #[test]
    fn angle_bracketed_authorship_placeholder_is_stripped() {
        let mut c = ctx("x");
        let out =
            strip_angle_bracket_authorship(&mut c, "Doradidae <Unspecified Agent>".to_string());
        assert_eq!(out, "Doradidae");
        assert!(c.name.doubtful);
        assert!(c
            .name
            .warnings
            .contains(&warnings::AUTHORSHIP_REMOVED.to_string()));
        assert!(c
            .name
            .warnings
            .contains(&warnings::UNUSUAL_CHARACTERS.to_string()));
    }

    #[test]
    fn no_angle_bracket_is_untouched() {
        let mut c = ctx("x");
        let out = strip_angle_bracket_authorship(&mut c, "Abies alba Mill.".to_string());
        assert_eq!(out, "Abies alba Mill.");
        assert!(!c.name.doubtful);
    }

    // ---- Step 19: stripHtml ----

    #[test]
    fn html_tags_are_stripped_keeping_text_content() {
        let mut c = ctx("x");
        let out = strip_html(&mut c, "<i>Aus bus</i> Smith".to_string());
        assert_eq!(out, "Aus bus Smith");
        assert!(c.name.warnings.contains(&warnings::XML_TAGS.to_string()));
    }

    #[test]
    fn html_entities_are_decoded() {
        let mut c = ctx("x");
        let out = strip_html(&mut c, "Aus &amp; bus".to_string());
        assert_eq!(out, "Aus & bus");
        assert!(c
            .name
            .warnings
            .contains(&warnings::HTML_ENTITIES.to_string()));
    }

    #[test]
    fn whitespace_left_by_tag_removal_is_collapsed() {
        let mut c = ctx("x");
        let out = strip_html(&mut c, "Aus <br/> bus".to_string());
        assert_eq!(out, "Aus bus");
    }

    #[test]
    fn no_html_markup_is_untouched() {
        let mut c = ctx("x");
        let out = strip_html(&mut c, "Abies alba Mill.".to_string());
        assert_eq!(out, "Abies alba Mill.");
        assert!(c.name.warnings.is_empty());
    }

    // ---- Step 20: stripCandidatus ----
    // All step-20/21/22/23/24/25/26/27/28/29/30 examples below spot-checked against the
    // Java CLI oracle (`name-parser-cli-4.2.0-SNAPSHOT-shaded.jar`), not just traced by
    // hand — same rigor batch 1's module doc describes.

    #[test]
    fn candidatus_prefix_is_stripped_and_flags_bacterial() {
        let mut c = ctx("x");
        let out = strip_candidatus(&mut c, "Candidatus Amesbacteria bacterium".to_string());
        assert_eq!(out, "Amesbacteria bacterium");
        assert!(c.name.candidatus);
        assert_eq!(c.name.code, Some(NomCode::Bacterial));
    }

    #[test]
    fn ca_abbreviation_prefix_is_stripped() {
        let mut c = ctx("x");
        let out = strip_candidatus(&mut c, "Ca. Halobonum".to_string());
        assert_eq!(out, "Halobonum");
        assert!(c.name.candidatus);
        assert_eq!(c.name.code, Some(NomCode::Bacterial));
    }

    #[test]
    fn quoted_candidatus_prefix_strips_leading_and_trailing_quote() {
        let mut c = ctx("x");
        let out = strip_candidatus(&mut c, "\"Candidatus Foo bar\"".to_string());
        assert_eq!(out, "Foo bar");
        assert!(c.name.candidatus);
    }

    #[test]
    fn no_candidatus_prefix_is_untouched() {
        let mut c = ctx("x");
        let out = strip_candidatus(&mut c, "Abies alba Mill.".to_string());
        assert_eq!(out, "Abies alba Mill.");
        assert!(!c.name.candidatus);
        assert_eq!(c.name.code, None);
    }

    // ---- Step 21: normaliseHortExPlaceholder ----

    #[test]
    fn cv_ex_placeholder_is_normalised() {
        let mut c = ctx("x");
        let out = normalise_hort_ex_placeholder(&mut c, "Rosa foo cv. ex Smith".to_string());
        assert_eq!(out, "Rosa foo hort. ex Smith");
    }

    #[test]
    fn hort_ex_placeholder_is_normalised() {
        let mut c = ctx("x");
        let out = normalise_hort_ex_placeholder(&mut c, "Rosa foo Hort. ex Smith".to_string());
        assert_eq!(out, "Rosa foo hort. ex Smith");
    }

    #[test]
    fn hortus_ex_placeholder_is_normalised() {
        let mut c = ctx("x");
        let out = normalise_hort_ex_placeholder(&mut c, "Rosa foo hortus ex Smith".to_string());
        assert_eq!(out, "Rosa foo hort. ex Smith");
    }

    #[test]
    fn ht_marker_is_normalised() {
        let mut c = ctx("x");
        let out =
            normalise_hort_ex_placeholder(&mut c, "Gymnogramma alstoni ht.Birkenh.".to_string());
        assert_eq!(out, "Gymnogramma alstoni hort.Birkenh.");
    }

    #[test]
    fn no_hort_ex_placeholder_is_untouched() {
        let mut c = ctx("x");
        let out = normalise_hort_ex_placeholder(&mut c, "Abies alba Mill.".to_string());
        assert_eq!(out, "Abies alba Mill.");
    }

    // ---- Step 22: stripCultivarGroupGrex ----

    #[test]
    fn trailing_group_marker_sets_cultivar_group_rank() {
        let mut c = ctx("x");
        let out = strip_cultivar_group_grex(&mut c, "Brassica oleracea Capitata Group".to_string());
        assert_eq!(out, "Brassica oleracea");
        assert_eq!(c.name.cultivar_epithet, Some("Capitata".to_string()));
        assert_eq!(c.name.code, Some(NomCode::Cultivars));
        assert_eq!(c.name.rank, Rank::CultivarGroup);
    }

    #[test]
    fn trailing_grex_marker_sets_grex_rank() {
        let mut c = ctx("x");
        let out = strip_cultivar_group_grex(&mut c, "Paphiopedilum Maudiae grex".to_string());
        assert_eq!(out, "Paphiopedilum");
        assert_eq!(c.name.cultivar_epithet, Some("Maudiae".to_string()));
        assert_eq!(c.name.code, Some(NomCode::Cultivars));
        assert_eq!(c.name.rank, Rank::Grex);
    }

    #[test]
    fn trailing_gx_marker_also_sets_grex_rank() {
        let mut c = ctx("x");
        let out = strip_cultivar_group_grex(&mut c, "Paphiopedilum Maudiae gx".to_string());
        assert_eq!(out, "Paphiopedilum");
        assert_eq!(c.name.rank, Rank::Grex);
    }

    #[test]
    fn no_group_grex_marker_is_untouched() {
        let mut c = ctx("x");
        let out = strip_cultivar_group_grex(&mut c, "Abies alba Mill.".to_string());
        assert_eq!(out, "Abies alba Mill.");
        assert_eq!(c.name.cultivar_epithet, None);
    }

    // ---- Step 23: stripQuotedCultivar ----

    #[test]
    fn quoted_cultivar_at_end_with_explicit_cv_marker_is_captured() {
        let mut c = ctx("x");
        let out = strip_quoted_cultivar(&mut c, "Acer campestre L. cv. 'nanum'".to_string());
        assert_eq!(out, "Acer campestre L.");
        assert_eq!(c.name.cultivar_epithet, Some("nanum".to_string()));
        assert_eq!(c.name.code, Some(NomCode::Cultivars));
        assert_eq!(c.name.rank, Rank::Cultivar);
        // Shape 1 never splits off a specific author (only shape 2/MID does) — the
        // Java oracle keeps "L." in the main combinationAuthorship for this shape.
        assert_eq!(c.pending_specific_author, None);
    }

    #[test]
    fn quoted_cultivar_at_end_without_cv_marker_is_captured() {
        let mut c = ctx("x");
        let out = strip_quoted_cultivar(&mut c, "Acer pseudoplatanus L. 'Negenia'".to_string());
        assert_eq!(out, "Acer pseudoplatanus L.");
        assert_eq!(c.name.cultivar_epithet, Some("Negenia".to_string()));
    }

    #[test]
    fn quoted_cultivar_mid_string_splits_off_preceding_specific_author() {
        let mut c = ctx("x");
        let out = strip_quoted_cultivar(
            &mut c,
            "Acer campestre L. cv. 'Elsrijk' Broerse".to_string(),
        );
        // Spot-checked against the Java CLI oracle: genus=Acer, specificEpithet=campestre,
        // specificAuthorship.combinationAuthorship=["L."], cultivarEpithet=Elsrijk,
        // combinationAuthorship=["Broerse"] — i.e. the reduced working string must read as
        // "Genus species CombinationAuthor" with "L." split off separately.
        assert_eq!(out, "Acer campestre Broerse");
        assert_eq!(c.name.cultivar_epithet, Some("Elsrijk".to_string()));
        assert_eq!(c.name.code, Some(NomCode::Cultivars));
        assert_eq!(c.name.rank, Rank::Cultivar);
        assert_eq!(c.pending_specific_author, Some("L.".to_string()));
    }

    #[test]
    fn quoted_cultivar_mid_string_without_cv_marker_and_without_preceding_author() {
        // No "cv." marker required for shape 2 — MID's own prefix is optional. No author
        // precedes the epithet here (just "Genus species"), so `find_author_start` finds
        // nothing to split off. Spot-checked: combinationAuthorship=["Pils."], no
        // specificAuthorship.
        let mut c = ctx("x");
        let out = strip_quoted_cultivar(&mut c, "Verpericola megasoma \"Dall\" Pils.".to_string());
        assert_eq!(out, "Verpericola megasoma Pils.");
        assert_eq!(c.name.cultivar_epithet, Some("Dall".to_string()));
        assert_eq!(c.pending_specific_author, None);
    }

    #[test]
    fn unclosed_trailing_cultivar_quote_is_captured() {
        let mut c = ctx("x");
        let out = strip_quoted_cultivar(&mut c, "Genus species 'albino".to_string());
        assert_eq!(out, "Genus species");
        assert_eq!(c.name.cultivar_epithet, Some("albino".to_string()));
        assert_eq!(c.name.code, Some(NomCode::Cultivars));
        assert_eq!(c.name.rank, Rank::Cultivar);
    }

    #[test]
    fn quote_preceded_by_bare_rank_marker_is_not_a_cultivar() {
        // "var." right before the quote with no explicit "cv." is a phrase-name shape,
        // not a cultivar — RANK_MARKER_SUFFIX guard must suppress the strip.
        let mut c = ctx("x");
        let out = strip_quoted_cultivar(&mut c, "Genus species var. 'foo'".to_string());
        assert_eq!(out, "Genus species var. 'foo'");
        assert_eq!(c.name.cultivar_epithet, None);
    }

    #[test]
    fn no_quoted_cultivar_is_untouched() {
        let mut c = ctx("x");
        let out = strip_quoted_cultivar(&mut c, "Abies alba Mill.".to_string());
        assert_eq!(out, "Abies alba Mill.");
        assert_eq!(c.name.cultivar_epithet, None);
    }

    // ---- Step 24: stripExtinctDagger ----

    #[test]
    fn dagger_glued_to_genus_is_stripped_and_flags_extinct() {
        let mut c = ctx("x");
        let out = strip_extinct_dagger(
            &mut c,
            "Henriksenopterix\u{2020} paucistriata (Henriksen, 1922)".to_string(),
        );
        assert_eq!(out, "Henriksenopterix paucistriata (Henriksen, 1922)");
        assert!(c.name.extinct);
    }

    #[test]
    fn alternate_dagger_glyph_is_also_stripped() {
        let mut c = ctx("x");
        let out = strip_extinct_dagger(&mut c, "Foo \u{271D}bar".to_string());
        assert_eq!(out, "Foo bar");
        assert!(c.name.extinct);
    }

    #[test]
    fn no_dagger_is_untouched() {
        let mut c = ctx("x");
        let out = strip_extinct_dagger(&mut c, "Abies alba Mill.".to_string());
        assert_eq!(out, "Abies alba Mill.");
        assert!(!c.name.extinct);
    }

    // ---- Step 25: stripTinfrMarker ----

    #[test]
    fn tinfr_marker_between_species_and_infraspecific_epithet_is_stripped() {
        let mut c = ctx("x");
        let out = strip_tinfr_marker(&mut c, "Hieracium alpinum t.infr. foobarum".to_string());
        assert_eq!(out, "Hieracium alpinum foobarum");
    }

    #[test]
    fn tinfr_marker_directly_after_a_bare_genus_is_also_stripped() {
        let mut c = ctx("x");
        let out = strip_tinfr_marker(&mut c, "Hieracium t.infr. foobarum".to_string());
        assert_eq!(out, "Hieracium foobarum");
    }

    #[test]
    fn no_tinfr_marker_is_untouched() {
        let mut c = ctx("x");
        let out = strip_tinfr_marker(&mut c, "Abies alba Mill.".to_string());
        assert_eq!(out, "Abies alba Mill.");
    }

    // ---- Step 26: stripDoubtfulGenusBrackets ----

    #[test]
    fn bracketed_genus_followed_by_epithet_is_unbracketed_and_flags_doubtful() {
        let mut c = ctx("x");
        let out = strip_doubtful_genus_brackets(&mut c, "[Acontia] chia".to_string());
        assert_eq!(out, "Acontia chia");
        assert!(c.name.doubtful);
        assert!(c
            .name
            .warnings
            .contains(&warnings::DOUBTFUL_GENUS.to_string()));
    }

    #[test]
    fn bracketed_genus_alone_is_unbracketed() {
        let mut c = ctx("x");
        let out = strip_doubtful_genus_brackets(&mut c, "[Dexia]".to_string());
        assert_eq!(out, "Dexia");
        assert!(c.name.doubtful);
    }

    #[test]
    fn no_leading_bracket_is_untouched() {
        let mut c = ctx("x");
        let out = strip_doubtful_genus_brackets(&mut c, "Abies alba Mill.".to_string());
        assert_eq!(out, "Abies alba Mill.");
        assert!(!c.name.doubtful);
    }

    // ---- Step 27: stripSicAndCorrig ----

    #[test]
    fn bracketed_sic_with_comment_flags_true_and_stashes_squished_comment() {
        let mut c = ctx("x");
        let out = strip_sic_and_corrig(&mut c, "Aus bus Storr [sic, porphyria]".to_string());
        assert_eq!(out, "Aus bus Storr");
        assert_eq!(c.name.original_spelling, Some(true));
        assert_eq!(c.pending_unparsed, Some("(sic,porphyria)".to_string()));
    }

    #[test]
    fn multi_word_sic_comment_has_all_internal_whitespace_removed_not_just_collapsed() {
        // Spot-checked against the Java CLI oracle: "multiple words here" squishes to
        // "multiplewordshere" — Java's WHITESPACE.replaceAll("") here, replacement "",
        // NOT collapsed to single spaces.
        let mut c = ctx("x");
        let out = strip_sic_and_corrig(&mut c, "Foo bar [sic, multiple words here]".to_string());
        assert_eq!(out, "Foo bar");
        assert_eq!(
            c.pending_unparsed,
            Some("(sic,multiplewordshere)".to_string())
        );
    }

    #[test]
    fn plain_sic_without_comment_flags_true() {
        let mut c = ctx("x");
        let out = strip_sic_and_corrig(
            &mut c,
            "Ameiva plei (sic) Duméril & Bibron, 1839".to_string(),
        );
        assert_eq!(out, "Ameiva plei Duméril & Bibron, 1839");
        assert_eq!(c.name.original_spelling, Some(true));
        assert_eq!(c.pending_unparsed, None);
    }

    #[test]
    fn bare_corrig_marker_flags_false() {
        let mut c = ctx("x");
        let out = strip_sic_and_corrig(&mut c, "Aus bus corrig. Peters, 1878".to_string());
        assert_eq!(out, "Aus bus Peters, 1878");
        assert_eq!(c.name.original_spelling, Some(false));
    }

    #[test]
    fn bracketed_corrig_marker_flags_false() {
        let mut c = ctx("x");
        let out = strip_sic_and_corrig(&mut c, "Aus bus (corrig.) Smith".to_string());
        assert_eq!(out, "Aus bus Smith");
        assert_eq!(c.name.original_spelling, Some(false));
    }

    #[test]
    fn leading_standalone_corrig_is_stripped_via_the_pad_harness() {
        // The exact Phase 0 lesson: CORRIG's bare alternative needs an actual preceding
        // whitespace char, supplied by the call site's leading-space pad — a leading
        // "corrig." with nothing before it must still strip.
        let mut c = ctx("x");
        let out = strip_sic_and_corrig(&mut c, "corrig. Peters, 1878".to_string());
        assert_eq!(out, "Peters, 1878");
        assert_eq!(c.name.original_spelling, Some(false));
    }

    #[test]
    fn no_sic_or_corrig_marker_is_untouched() {
        let mut c = ctx("x");
        let out = strip_sic_and_corrig(&mut c, "Abies alba Mill.".to_string());
        assert_eq!(out, "Abies alba Mill.");
        assert_eq!(c.name.original_spelling, None);
    }

    // ---- Step 28: stashSynonymBracket ----

    #[test]
    fn trailing_synonym_bracket_is_stashed_verbatim_with_brackets() {
        let mut c = ctx("x");
        let out = stash_synonym_bracket(&mut c, "Aus bus [= Grislea L. 1753]".to_string());
        assert_eq!(out, "Aus bus");
        assert_eq!(c.pending_unparsed, Some("[= Grislea L. 1753]".to_string()));
        assert!(c.name.doubtful);
    }

    #[test]
    fn dangling_commas_before_the_bracket_are_all_stripped() {
        let mut c = ctx("x");
        let out = stash_synonym_bracket(&mut c, "Aus bus,, [= Grislea L. 1753]".to_string());
        assert_eq!(out, "Aus bus");
    }

    #[test]
    fn no_synonym_bracket_is_untouched() {
        let mut c = ctx("x");
        let out = stash_synonym_bracket(&mut c, "Abies alba Mill.".to_string());
        assert_eq!(out, "Abies alba Mill.");
        assert_eq!(c.pending_unparsed, None);
        assert!(!c.name.doubtful);
    }

    // ---- Shared helper: normaliseNomNote ----

    #[test]
    fn normalise_nom_note_adds_a_closing_dot_to_an_abbreviated_note() {
        assert_eq!(normalise_nom_note("nom nud"), "nom nud.");
    }

    #[test]
    fn normalise_nom_note_leaves_a_full_word_suffix_without_an_added_dot() {
        assert_eq!(normalise_nom_note("orth error"), "orth error");
    }

    #[test]
    fn normalise_nom_note_strips_trailing_dots_from_spelled_out_nomen_forms() {
        assert_eq!(normalise_nom_note("nomen nudum..."), "nomen nudum");
    }

    #[test]
    fn normalise_nom_note_normalises_et_and_and_to_ampersand() {
        assert_eq!(
            normalise_nom_note("nom. cons. et typ. cons"),
            "nom. cons. & typ. cons."
        );
    }

    // ---- Step 29: stripBracketedNomNote ----

    #[test]
    fn bracketed_nom_nud_note_overwrites_nomenclatural_note() {
        let mut c = ctx("x");
        let out = strip_bracketed_nom_note(
            &mut c,
            "Baccharis microphylla var. rhomboidea (nom. nud.)".to_string(),
        );
        assert_eq!(out, "Baccharis microphylla var. rhomboidea");
        assert_eq!(c.name.nomenclatural_note, Some("nom. nud.".to_string()));
    }

    #[test]
    fn bracketed_nom_illeg_note_overwrites_nomenclatural_note() {
        let mut c = ctx("x");
        let out =
            strip_bracketed_nom_note(&mut c, "Barbula obscura Sull. (nom. illeg.)".to_string());
        assert_eq!(out, "Barbula obscura Sull.");
        assert_eq!(c.name.nomenclatural_note, Some("nom. illeg.".to_string()));
    }

    #[test]
    fn preexisting_note_is_overwritten_not_appended() {
        // Java calls the plain setter here (no null-check) — an already-populated note
        // (as could happen via a directly-constructed ParsedName, or a future reordering)
        // must be REPLACED, not appended to, unlike `strip_nom_note` (step 30).
        let mut c = ctx("x");
        c.name.nomenclatural_note = Some("existing".to_string());
        let out = strip_bracketed_nom_note(&mut c, "Foo bar (nom. nud.)".to_string());
        assert_eq!(out, "Foo bar");
        assert_eq!(c.name.nomenclatural_note, Some("nom. nud.".to_string()));
    }

    #[test]
    fn no_bracketed_nom_note_is_untouched() {
        let mut c = ctx("x");
        let out = strip_bracketed_nom_note(&mut c, "Abies alba Mill.".to_string());
        assert_eq!(out, "Abies alba Mill.");
        assert_eq!(c.name.nomenclatural_note, None);
    }

    // ---- Step 30: stripNomNote ----

    #[test]
    fn sp_nov_on_a_bare_monomial_appends_note_and_keeps_a_bare_sp_marker() {
        // Spot-checked against the Java CLI oracle: genus=Abies (no specificEpithet),
        // type=INFORMAL, nomenclaturalNote="sp. nov." — the SP_NOV_PREFIX +
        // SINGLE_TITLE_WORD override reduces the working string to "Abies sp." so the
        // indet-species handling still recognises it downstream.
        let mut c = ctx("x");
        let out = strip_nom_note(&mut c, "Abies sp. nov.".to_string());
        assert_eq!(out, "Abies sp.");
        assert_eq!(c.name.nomenclatural_note, Some("sp. nov.".to_string()));
        assert!(!c.name.manuscript);
    }

    #[test]
    fn sp_nov_ined_also_sets_manuscript_true() {
        let mut c = ctx("x");
        let out = strip_nom_note(&mut c, "Abies sp. nov. ined.".to_string());
        assert_eq!(out, "Abies sp.");
        assert_eq!(
            c.name.nomenclatural_note,
            Some("sp. nov. ined.".to_string())
        );
        assert!(c.name.manuscript);
    }

    #[test]
    fn sp_nov_on_a_full_binomial_does_not_trigger_the_bare_sp_override() {
        // `before` is "Abies alba" (two words) — SINGLE_TITLE_WORD must fail, so the
        // override does not fire; the note is still appended normally.
        let mut c = ctx("x");
        let out = strip_nom_note(&mut c, "Abies alba Sp. nov.".to_string());
        assert_eq!(out, "Abies alba");
        assert_eq!(c.name.nomenclatural_note, Some("Sp. nov.".to_string()));
    }

    #[test]
    fn gen_nov_pins_genus_rank_when_unranked() {
        let mut c = ctx("x");
        let out = strip_nom_note(&mut c, "Fooxus gen. nov.".to_string());
        assert_eq!(out, "Fooxus");
        assert_eq!(c.name.nomenclatural_note, Some("gen. nov.".to_string()));
        assert_eq!(c.name.rank, Rank::Genus);
    }

    #[test]
    fn var_nov_pins_variety_rank() {
        let mut c = ctx("x");
        let out = strip_nom_note(&mut c, "Foovar var. nov.".to_string());
        assert_eq!(out, "Foovar");
        assert_eq!(c.name.rank, Rank::Variety);
    }

    #[test]
    fn fam_nov_pins_family_rank() {
        let mut c = ctx("x");
        let out = strip_nom_note(&mut c, "Foofam fam. nov.".to_string());
        assert_eq!(out, "Foofam");
        assert_eq!(c.name.rank, Rank::Family);
    }

    #[test]
    fn form_nov_pins_form_rank() {
        let mut c = ctx("x");
        let out = strip_nom_note(&mut c, "Fooform form. nov.".to_string());
        assert_eq!(out, "Fooform");
        assert_eq!(c.name.rank, Rank::Form);
    }

    #[test]
    fn rank_hint_does_not_override_an_already_set_rank() {
        let mut c = ctx("x");
        c.name.rank = Rank::Species;
        let out = strip_nom_note(&mut c, "Fooxus gen. nov.".to_string());
        assert_eq!(out, "Fooxus");
        assert_eq!(
            c.name.rank,
            Rank::Species,
            "an already-set rank must not be clobbered by the hint"
        );
    }

    #[test]
    fn nom_note_appends_to_an_existing_nomenclatural_note() {
        let mut c = ctx("x");
        c.name.nomenclatural_note = Some("existing".to_string());
        let out = strip_nom_note(&mut c, "Foo bar comb. nov.".to_string());
        assert_eq!(out, "Foo bar");
        assert_eq!(
            c.name.nomenclatural_note,
            Some("existing comb. nov.".to_string())
        );
    }

    #[test]
    fn no_nom_note_keyword_is_untouched() {
        let mut c = ctx("x");
        let out = strip_nom_note(&mut c, "Abies alba Mill.".to_string());
        assert_eq!(out, "Abies alba Mill.");
        assert_eq!(c.name.nomenclatural_note, None);
        assert!(!c.name.manuscript);
    }

    #[test]
    fn nom_note_requires_a_leading_whitespace_and_does_not_fire_at_string_start() {
        // NOM_NOTE's leading `\s+` means a marker glued to the very start of the string
        // (no preceding name text at all) can never match — spot-checked: "Gen. nov.
        // Foobarus" parses "Gen." as an abbreviated genus, "nov" as a specific epithet,
        // NOT as a nom-note (rank stays SPECIES, not GENUS, on the Java oracle).
        let mut c = ctx("x");
        let out = strip_nom_note(&mut c, "Gen. nov. Foobarus".to_string());
        assert_eq!(out, "Gen. nov. Foobarus");
        assert_eq!(c.name.nomenclatural_note, None);
        assert_eq!(c.name.rank, Rank::Unranked);
    }

    #[test]
    fn nom_note_does_not_redos_on_dotted_abbrev_run() {
        // NOM_NOTE runs on fancy_regex (backtracking), so Java's possessive quantifier
        // (restored above, see the RULE comment) is load-bearing. A long run of dotted
        // lowercase "words" after "nomen" with no valid terminator in sight (no comma, no
        // uppercase, no closing paren, no end-of-string right after) used to force the
        // greedy `*` to re-partition the run exponentially before finally giving up —
        // reintroducing the exact catastrophic-backtracking shape Java's own `*+` exists
        // to prevent (proven: ~11ms and a backtrack-limit no-match with plain `*` on just
        // 20 repeats; microseconds with `*+` restored). This must complete promptly
        // regardless of how long the dotted run is.
        let mut c = ctx("x");
        let input = "Aus bus nomen ".to_string() + &"a.".repeat(30) + "#";
        let start = std::time::Instant::now();
        let out = strip_nom_note(&mut c, input.clone());
        let elapsed = start.elapsed();
        assert!(
            elapsed.as_millis() < 200,
            "strip_nom_note took {elapsed:?} on a dotted-abbrev run — possessive quantifier regressed"
        );
        // The trailing "#" satisfies none of NOM_NOTE's terminator lookaheads, so the
        // whole pattern never matches here (same as any other non-matching input) — the
        // string comes back untouched, no note stashed.
        assert_eq!(out, input);
        assert_eq!(c.name.nomenclatural_note, None);
    }

    // ---- Step 31: stripAuthorshipPlaceholders ----

    #[test]
    fn trailing_not_given_is_stripped_and_flags_authorship_removed() {
        let mut c = ctx("x");
        let out = strip_authorship_placeholders(&mut c, "Aus bus Smith Not given".to_string());
        assert_eq!(out, "Aus bus Smith");
        assert!(c
            .name
            .warnings
            .contains(&warnings::AUTHORSHIP_REMOVED.to_string()));
    }

    #[test]
    fn not_applicable_is_case_insensitive() {
        let mut c = ctx("x");
        let out = strip_authorship_placeholders(&mut c, "Aus bus not applicable".to_string());
        assert_eq!(out, "Aus bus");
        assert!(c
            .name
            .warnings
            .contains(&warnings::AUTHORSHIP_REMOVED.to_string()));
    }

    #[test]
    fn no_placeholder_keyword_is_untouched() {
        let mut c = ctx("x");
        let out = strip_authorship_placeholders(&mut c, "Abies alba Mill.".to_string());
        assert_eq!(out, "Abies alba Mill.");
        assert!(c.name.warnings.is_empty());
    }

    // ---- Step 32: stripTrailingSpeciesWord ----

    #[test]
    fn trailing_species_word_is_dropped() {
        let mut c = ctx("x");
        let out = strip_trailing_species_word(&mut c, "Abies species".to_string());
        assert_eq!(out, "Abies");
    }

    #[test]
    fn trailing_species_word_with_dot_is_dropped() {
        let mut c = ctx("x");
        let out = strip_trailing_species_word(&mut c, "Abies species.".to_string());
        assert_eq!(out, "Abies");
    }

    #[test]
    fn real_binomial_ending_in_an_epithet_is_not_mistaken_for_the_placeholder() {
        // TRAILING_SPECIES_WORD_TEST only fires on a bare "Title word" + " species[.]"
        // shape — a genuine binomial like "Genus species alba" must be left alone.
        let mut c = ctx("x");
        let out = strip_trailing_species_word(&mut c, "Genus species alba".to_string());
        assert_eq!(out, "Genus species alba");
    }

    #[test]
    fn no_trailing_species_word_is_untouched() {
        let mut c = ctx("x");
        let out = strip_trailing_species_word(&mut c, "Abies alba Mill.".to_string());
        assert_eq!(out, "Abies alba Mill.");
    }

    // ---- Step 33: stripProParte ----

    #[test]
    fn trailing_pro_parte_is_stripped_and_flags_doubtful() {
        let mut c = ctx("x");
        let out = strip_pro_parte(&mut c, "Aus bus Smith, pro parte".to_string());
        assert_eq!(out, "Aus bus Smith");
        assert!(c.name.doubtful);
    }

    #[test]
    fn abbreviated_p_p_form_is_also_stripped() {
        let mut c = ctx("x");
        let out = strip_pro_parte(&mut c, "Aus bus Smith, p.p.".to_string());
        assert_eq!(out, "Aus bus Smith");
        assert!(c.name.doubtful);
    }

    #[test]
    fn no_pro_parte_marker_is_untouched() {
        let mut c = ctx("x");
        let out = strip_pro_parte(&mut c, "Abies alba Mill.".to_string());
        assert_eq!(out, "Abies alba Mill.");
        assert!(!c.name.doubtful);
    }

    // ---- Step 34: stripProSpAnnotation ----

    #[test]
    fn pro_sp_annotation_is_stripped_silently() {
        let mut c = ctx("x");
        let out = strip_pro_sp_annotation(&mut c, "Aus bus (pro sp.)".to_string());
        assert_eq!(out, "Aus bus");
        assert!(!c.name.doubtful);
        assert!(c.name.warnings.is_empty());
    }

    #[test]
    fn pro_hyb_variant_without_a_dot_is_also_stripped() {
        let mut c = ctx("x");
        let out = strip_pro_sp_annotation(&mut c, "Aus bus (pro hyb)".to_string());
        assert_eq!(out, "Aus bus");
    }

    #[test]
    fn no_pro_sp_annotation_is_untouched() {
        let mut c = ctx("x");
        let out = strip_pro_sp_annotation(&mut c, "Abies alba Mill.".to_string());
        assert_eq!(out, "Abies alba Mill.");
    }

    // ---- Step 35: stripApprovedLists ----

    #[test]
    fn approved_lists_annotation_is_stripped_silently() {
        let mut c = ctx("x");
        let out = strip_approved_lists(&mut c, "Aus bus Smith (Approved Lists 1980)".to_string());
        assert_eq!(out, "Aus bus Smith");
    }

    #[test]
    fn no_approved_lists_annotation_is_untouched() {
        let mut c = ctx("x");
        let out = strip_approved_lists(&mut c, "Abies alba Mill.".to_string());
        assert_eq!(out, "Abies alba Mill.");
    }

    // ---- Step 36: stripMihi ----

    #[test]
    fn trailing_mihi_is_stripped_and_flags_authorship_removed() {
        let mut c = ctx("x");
        let out = strip_mihi(&mut c, "Aus bus mihi".to_string());
        assert_eq!(out, "Aus bus");
        assert!(c
            .name
            .warnings
            .contains(&warnings::AUTHORSHIP_REMOVED.to_string()));
    }

    #[test]
    fn mid_string_mihi_is_stripped_and_the_surrounding_text_splices_together() {
        let mut c = ctx("x");
        let out = strip_mihi(&mut c, "Aus bus mihi. Smith".to_string());
        assert_eq!(out, "Aus bus Smith");
        assert!(c
            .name
            .warnings
            .contains(&warnings::AUTHORSHIP_REMOVED.to_string()));
    }

    #[test]
    fn both_occurrences_of_mihi_are_stripped() {
        let mut c = ctx("x");
        let out = strip_mihi(&mut c, "Genus species mihi var. epithet mihi".to_string());
        assert_eq!(out, "Genus species var. epithet");
    }

    #[test]
    fn mihi_glued_to_a_preceding_word_is_not_a_false_positive() {
        // "mihilaris" contains "mihi" as a substring but MIHI_TEST's `\bmihi\b` requires
        // a word boundary on both sides — a boundary fails mid-word ("mihi"+"laris"), so
        // this must never be touched, matching the Java CLI oracle's parse of "Aus
        // mihilaris bus" (specificEpithet="mihilaris", untouched, no warning).
        let mut c = ctx("x");
        let out = strip_mihi(&mut c, "Aus mihilaris bus".to_string());
        assert_eq!(out, "Aus mihilaris bus");
        assert!(c.name.warnings.is_empty());
    }

    #[test]
    fn leading_mihi_with_no_preceding_whitespace_is_not_stripped_by_this_step_in_isolation() {
        // MIHI_TEST's loose `\bmihi\b` gate matches "mihi Aus bus" (mihi is present as a
        // whole word), but MIHI itself additionally requires a LEADING `\s+` before
        // "mihi" — at absolute string-start there is no preceding character at all, so
        // MIHI never matches here and the structural-equality guard (`after != before`)
        // correctly suppresses the warning. (In the FULL run() pipeline this exact input
        // is rewritten by the earlier-running `apply_missing_genus_placeholder`, step 4,
        // into "? mihi Aus bus" first — which DOES have leading whitespace before "mihi"
        // and so IS stripped, confirmed against the Java CLI oracle; this test isolates
        // step 36's own boundary requirement independent of that upstream interaction.)
        let mut c = ctx("x");
        let out = strip_mihi(&mut c, "mihi Aus bus".to_string());
        assert_eq!(out, "mihi Aus bus");
        assert!(c.name.warnings.is_empty());
    }

    #[test]
    fn no_mihi_is_untouched() {
        let mut c = ctx("x");
        let out = strip_mihi(&mut c, "Abies alba Mill.".to_string());
        assert_eq!(out, "Abies alba Mill.");
        assert!(c.name.warnings.is_empty());
    }

    // ---- Step 37: normaliseAnon ----

    #[test]
    fn title_case_anon_is_normalised_to_lower_case_with_a_dot() {
        let mut c = ctx("x");
        let out = normalise_anon(&mut c, "Aus bus Anon.".to_string());
        assert_eq!(out, "Aus bus anon.");
    }

    #[test]
    fn bare_lower_case_anon_is_also_normalised() {
        let mut c = ctx("x");
        let out = normalise_anon(&mut c, "Aus bus anon".to_string());
        assert_eq!(out, "Aus bus anon.");
    }

    #[test]
    fn already_normalised_anon_is_left_alone() {
        // ANON_LOWER's negative lookahead `(?!\.)` excludes an "anon" already followed
        // by a dot, and ANON_UPPER requires the literal capital "Anon" — neither fires,
        // so this is idempotent.
        let mut c = ctx("x");
        let out = normalise_anon(&mut c, "Aus bus anon.".to_string());
        assert_eq!(out, "Aus bus anon.");
    }

    #[test]
    fn no_anon_keyword_is_untouched() {
        let mut c = ctx("x");
        let out = normalise_anon(&mut c, "Abies alba Mill.".to_string());
        assert_eq!(out, "Abies alba Mill.");
    }

    // ---- Step 38: stripColonConceptReference ----

    #[test]
    fn colon_concept_reference_appends_to_taxonomic_note() {
        let mut c = ctx("x");
        let out = strip_colon_concept_reference(
            &mut c,
            "Vespa emarginata Linnaeus, 1758: Fabricius, 1793".to_string(),
        );
        assert_eq!(out, "Vespa emarginata Linnaeus, 1758");
        assert_eq!(c.name.taxonomic_note, Some("Fabricius, 1793".to_string()));
    }

    #[test]
    fn colon_concept_reference_appends_to_an_existing_note() {
        let mut c = ctx("x");
        c.name.taxonomic_note = Some("existing".to_string());
        let out = strip_colon_concept_reference(&mut c, "Aus bus: Fabricius, 1793".to_string());
        assert_eq!(out, "Aus bus");
        assert_eq!(
            c.name.taxonomic_note,
            Some("existing Fabricius, 1793".to_string())
        );
    }

    #[test]
    fn sanctioning_author_colon_form_without_a_year_is_not_a_concept_reference() {
        // No ", YYYY" after the colon (a sanctioning-author citation, e.g. "Boletus
        // versicolor L. : Fr.") must NOT be captured here — spot-checked against the
        // Java CLI oracle: this form surfaces as `sanctioningAuthor`, a wholly different
        // mechanism, and StripAndStash leaves it untouched.
        let mut c = ctx("x");
        let out = strip_colon_concept_reference(
            &mut c,
            "Vespa emarginata Linnaeus, 1758 : Fr.".to_string(),
        );
        assert_eq!(out, "Vespa emarginata Linnaeus, 1758 : Fr.");
        assert_eq!(c.name.taxonomic_note, None);
    }

    #[test]
    fn no_colon_is_untouched() {
        let mut c = ctx("x");
        let out = strip_colon_concept_reference(&mut c, "Abies alba Mill.".to_string());
        assert_eq!(out, "Abies alba Mill.");
        assert_eq!(c.name.taxonomic_note, None);
    }

    // ---- Shared helper: normaliseLeadingAuct ----

    #[test]
    fn normalise_leading_auct_lowercases_single_t_form() {
        assert_eq!(normalise_leading_auct("Auct. europ."), "auct. europ.");
    }

    #[test]
    fn normalise_leading_auct_lowercases_double_t_form() {
        assert_eq!(normalise_leading_auct("Auctt. europ."), "auctt. europ.");
    }

    #[test]
    fn normalise_leading_auct_leaves_all_caps_form_untouched() {
        // Both LEADING_AUCT/LEADING_AUCTT are case-sensitive against the EXACT literal
        // "Auct"/"Auctt" (capital A, lower rest) — an all-caps "AUCTT." matches neither.
        assert_eq!(normalise_leading_auct("AUCTT. europ."), "AUCTT. europ.");
    }

    #[test]
    fn normalise_leading_auct_leaves_already_lower_case_form_untouched() {
        assert_eq!(normalise_leading_auct("auctt. europ."), "auctt. europ.");
    }

    // ---- Step 39: stripBracketedTaxNote ----

    #[test]
    fn bracketed_auctt_note_appends_to_taxonomic_note() {
        let mut c = ctx("x");
        let out = strip_bracketed_tax_note(
            &mut c,
            "Eunoa bus Smith [auctt. misspelling for Eunoe]".to_string(),
        );
        assert_eq!(out, "Eunoa bus Smith");
        assert_eq!(
            c.name.taxonomic_note,
            Some("auctt. misspelling for Eunoe".to_string())
        );
    }

    #[test]
    fn bracketed_tax_note_lowercases_a_leading_title_case_auct() {
        let mut c = ctx("x");
        let out = strip_bracketed_tax_note(&mut c, "Aus bus [Auct. europ.]".to_string());
        assert_eq!(out, "Aus bus");
        assert_eq!(c.name.taxonomic_note, Some("auct. europ.".to_string()));
    }

    #[test]
    fn bracketed_tax_note_collapses_internal_whitespace_runs() {
        let mut c = ctx("x");
        let out = strip_bracketed_tax_note(&mut c, "Aus bus [sensu   Miller   1990]".to_string());
        assert_eq!(out, "Aus bus");
        assert_eq!(c.name.taxonomic_note, Some("sensu Miller 1990".to_string()));
    }

    #[test]
    fn bracketed_tax_note_appends_to_an_existing_note() {
        let mut c = ctx("x");
        c.name.taxonomic_note = Some("existing".to_string());
        let out = strip_bracketed_tax_note(&mut c, "Aus bus [non Foo]".to_string());
        assert_eq!(out, "Aus bus");
        assert_eq!(c.name.taxonomic_note, Some("existing non Foo".to_string()));
    }

    #[test]
    fn no_bracketed_tax_note_is_untouched() {
        let mut c = ctx("x");
        let out = strip_bracketed_tax_note(&mut c, "Abies alba Mill.".to_string());
        assert_eq!(out, "Abies alba Mill.");
        assert_eq!(c.name.taxonomic_note, None);
    }

    // ---- Step 40: stripParenTaxNote ----

    #[test]
    fn paren_non_homonym_citation_appends_to_taxonomic_note() {
        let mut c = ctx("x");
        let out = strip_paren_tax_note(&mut c, "Aus bus Smith (non Foo, 1850)".to_string());
        assert_eq!(out, "Aus bus Smith");
        assert_eq!(c.name.taxonomic_note, Some("non Foo, 1850".to_string()));
    }

    #[test]
    fn paren_nec_and_not_variants_are_also_captured() {
        let mut c = ctx("x");
        let out = strip_paren_tax_note(&mut c, "Aus bus (nec Jones, 1900)".to_string());
        assert_eq!(out, "Aus bus");
        assert_eq!(c.name.taxonomic_note, Some("nec Jones, 1900".to_string()));
    }

    #[test]
    fn paren_tax_note_appends_to_an_existing_note() {
        let mut c = ctx("x");
        c.name.taxonomic_note = Some("existing".to_string());
        let out = strip_paren_tax_note(&mut c, "Aus bus (non Foo, 1850)".to_string());
        assert_eq!(out, "Aus bus");
        assert_eq!(
            c.name.taxonomic_note,
            Some("existing non Foo, 1850".to_string())
        );
    }

    #[test]
    fn no_paren_tax_note_is_untouched() {
        let mut c = ctx("x");
        let out = strip_paren_tax_note(&mut c, "Abies alba Mill.".to_string());
        assert_eq!(out, "Abies alba Mill.");
        assert_eq!(c.name.taxonomic_note, None);
    }

    // ---- Step 41: stripSensuLatoRemainder ----

    #[test]
    fn sensu_lato_marker_with_trailing_junk_appends_note_and_stashes_unparsed() {
        let mut c = ctx("x");
        let out = strip_sensu_lato_remainder(
            &mut c,
            "Asplenium trichomanes L. s.lat. - Asplen trich".to_string(),
        );
        assert_eq!(out, "Asplenium trichomanes L.");
        assert_eq!(c.name.taxonomic_note, Some("s.lat.".to_string()));
        assert_eq!(c.pending_unparsed, Some("- Asplen trich".to_string()));
    }

    #[test]
    fn sensu_lato_remainder_appends_to_an_existing_note() {
        let mut c = ctx("x");
        c.name.taxonomic_note = Some("existing".to_string());
        let out = strip_sensu_lato_remainder(&mut c, "Aus bus s.str. junk here".to_string());
        assert_eq!(out, "Aus bus");
        assert_eq!(c.name.taxonomic_note, Some("existing s.str.".to_string()));
    }

    #[test]
    fn uppercase_author_initials_are_not_mistaken_for_a_sensu_lato_marker() {
        let mut c = ctx("x");
        let out = strip_sensu_lato_remainder(&mut c, "Aus bus Mill. S.L. Schultes".to_string());
        assert_eq!(out, "Aus bus Mill. S.L. Schultes");
        assert_eq!(c.name.taxonomic_note, None);
    }

    #[test]
    fn bare_trailing_sensu_lato_with_no_junk_is_not_matched_here() {
        // SENSU_LATO_REMAINDER requires a MANDATORY non-empty trailing remainder after
        // the marker — a bare trailing "s.l." with nothing following is left for
        // `strip_tax_note` (step 43) instead.
        let mut c = ctx("x");
        let out = strip_sensu_lato_remainder(&mut c, "Aus bus s.l.".to_string());
        assert_eq!(out, "Aus bus s.l.");
        assert_eq!(c.name.taxonomic_note, None);
    }

    // ---- Step 42: stripSensuStrictoSS ----

    #[test]
    fn trailing_ss_with_no_junk_appends_literal_note_and_stashes_nothing() {
        let mut c = ctx("x");
        let out = strip_sensu_stricto_ss(&mut c, "Aus bus s.s.".to_string());
        assert_eq!(out, "Aus bus");
        assert_eq!(c.name.taxonomic_note, Some("s.s.".to_string()));
        assert_eq!(c.pending_unparsed, None);
    }

    #[test]
    fn trailing_ss_with_junk_appends_note_and_stashes_the_trimmed_junk() {
        let mut c = ctx("x");
        let out = strip_sensu_stricto_ss(&mut c, "Aus bus s.s. extra text here".to_string());
        assert_eq!(out, "Aus bus");
        assert_eq!(c.name.taxonomic_note, Some("s.s.".to_string()));
        assert_eq!(c.pending_unparsed, Some("extra text here".to_string()));
    }

    #[test]
    fn sensu_stricto_ss_appends_to_an_existing_note() {
        let mut c = ctx("x");
        c.name.taxonomic_note = Some("existing".to_string());
        let out = strip_sensu_stricto_ss(&mut c, "Aus bus s.s.".to_string());
        assert_eq!(out, "Aus bus");
        assert_eq!(c.name.taxonomic_note, Some("existing s.s.".to_string()));
    }

    #[test]
    fn no_sensu_stricto_marker_is_untouched() {
        let mut c = ctx("x");
        let out = strip_sensu_stricto_ss(&mut c, "Abies alba Mill.".to_string());
        assert_eq!(out, "Abies alba Mill.");
        assert_eq!(c.name.taxonomic_note, None);
        assert_eq!(c.pending_unparsed, None);
    }

    // ---- Step 43: stripTaxNote ----

    #[test]
    fn emend_with_a_dot_overwrites_taxonomic_note() {
        let mut c = ctx("x");
        let out = strip_tax_note(
            &mut c,
            "Chlorobium phaeobacteroides Pfennig, 1968 emend. Imhoff, 2003".to_string(),
        );
        assert_eq!(out, "Chlorobium phaeobacteroides Pfennig, 1968");
        assert_eq!(
            c.name.taxonomic_note,
            Some("emend. Imhoff, 2003".to_string())
        );
    }

    #[test]
    fn emend_without_a_dot_is_also_matched() {
        let mut c = ctx("x");
        let out = strip_tax_note(
            &mut c,
            "Chlorobium phaeobacteroides Pfennig, 1968 emend Imhoff, 2003".to_string(),
        );
        assert_eq!(out, "Chlorobium phaeobacteroides Pfennig, 1968");
        assert_eq!(
            c.name.taxonomic_note,
            Some("emend Imhoff, 2003".to_string())
        );
    }

    #[test]
    fn fide_keyword_is_captured() {
        let mut c = ctx("x");
        let out = strip_tax_note(
            &mut c,
            "Eulima excellens Verkrüzen fide Paetel, 1887".to_string(),
        );
        assert_eq!(out, "Eulima excellens Verkrüzen");
        assert_eq!(c.name.taxonomic_note, Some("fide Paetel, 1887".to_string()));
    }

    #[test]
    fn nec_keyword_captures_a_trailing_parenthesised_citation() {
        let mut c = ctx("x");
        let out = strip_tax_note(
            &mut c,
            "Procamallanus (Spirocamallanus) soodi Lakshmi & Kumari, 2001 nec (Gupta & Masood, 1988)"
                .to_string(),
        );
        assert_eq!(
            out,
            "Procamallanus (Spirocamallanus) soodi Lakshmi & Kumari, 2001"
        );
        assert_eq!(
            c.name.taxonomic_note,
            Some("nec (Gupta & Masood, 1988)".to_string())
        );
    }

    #[test]
    fn non_keyword_is_captured() {
        let mut c = ctx("x");
        let out = strip_tax_note(
            &mut c,
            "Membranipora minuscula Canu, 1911 non Hincks, 1882".to_string(),
        );
        assert_eq!(out, "Membranipora minuscula Canu, 1911");
        assert_eq!(c.name.taxonomic_note, Some("non Hincks, 1882".to_string()));
    }

    #[test]
    fn bare_trailing_auct_is_captured_and_lower_cased() {
        let mut c = ctx("x");
        let out = strip_tax_note(&mut c, "Aus bus auct.".to_string());
        assert_eq!(out, "Aus bus");
        assert_eq!(c.name.taxonomic_note, Some("auct.".to_string()));
    }

    #[test]
    fn title_case_auct_and_auctt_are_lower_cased() {
        let mut c = ctx("x");
        let out = strip_tax_note(&mut c, "Aus bus Auct.".to_string());
        assert_eq!(out, "Aus bus");
        assert_eq!(c.name.taxonomic_note, Some("auct.".to_string()));

        let mut c2 = ctx("x");
        let out2 = strip_tax_note(&mut c2, "Aus bus Auctt.".to_string());
        assert_eq!(out2, "Aus bus");
        assert_eq!(c2.name.taxonomic_note, Some("auctt.".to_string()));
    }

    #[test]
    fn lower_case_sensu_lato_marker_is_matched_case_sensitively() {
        let mut c = ctx("x");
        let out = strip_tax_note(&mut c, "Aus bus s.l.".to_string());
        assert_eq!(out, "Aus bus");
        assert_eq!(c.name.taxonomic_note, Some("s.l.".to_string()));
    }

    #[test]
    fn uppercase_author_initials_do_not_match_the_sensu_lato_branch() {
        // The inline `(?-i:…)` case-sensitive carve-out means "S.L." (capital, author
        // initials) is never mistaken for the lower-case sensu-lato marker — spot-checked
        // against the Java CLI oracle: "Aus bus Mill. S.L." ends up with the initials
        // folded into the author string (authors=["Mill.S.L."]), no taxonomicNote at all.
        let mut c = ctx("x");
        let out = strip_tax_note(&mut c, "Aus bus Mill. S.L.".to_string());
        assert_eq!(out, "Aus bus Mill. S.L.");
        assert_eq!(c.name.taxonomic_note, None);
    }

    #[test]
    fn initial_dot_space_collapses_a_bare_initial_before_a_lowercase_word() {
        // group 2 of INITIAL_DOT_SPACE requires an ALL-LOWERCASE word (>= 4 letters) —
        // spot-checked against the Java CLI oracle: "non F. europaeus" collapses the gap
        // ("F. europaeus" -> "F.europaeus") because "europaeus" is all lower-case.
        let mut c = ctx("x");
        let out = strip_tax_note(&mut c, "Aus bus non F. europaeus".to_string());
        assert_eq!(out, "Aus bus");
        assert_eq!(c.name.taxonomic_note, Some("non F.europaeus".to_string()));
    }

    #[test]
    fn initial_dot_space_does_not_collapse_before_a_capitalised_surname() {
        // Conversely a capitalised surname like "Schmidt" does NOT satisfy `[\p{Ll}]`
        // (lower-case only) as the word after the dot, so the space survives — spot-
        // checked against the Java CLI oracle: "sensu F. Schmidt" keeps its space.
        let mut c = ctx("x");
        let out = strip_tax_note(&mut c, "Aus bus sensu F. Schmidt".to_string());
        assert_eq!(out, "Aus bus");
        assert_eq!(c.name.taxonomic_note, Some("sensu F. Schmidt".to_string()));
    }

    #[test]
    fn multi_letter_abbreviations_keep_their_space() {
        // INITIAL_DOT_SPACE only collapses a SINGLE capital letter before the dot (a
        // genuine author initial) — "ss." (two letters) must keep its trailing space so
        // abbreviated taxonomic keywords render verbatim, per the Java source's own
        // comment on `stripTaxNote`.
        let mut c = ctx("x");
        let out = strip_tax_note(&mut c, "Aus bus ss. auct. europ.".to_string());
        assert_eq!(out, "Aus bus");
        assert_eq!(c.name.taxonomic_note, Some("ss. auct. europ.".to_string()));
    }

    #[test]
    fn sec_according_to_and_excl_alternatives_are_all_matched() {
        let mut c1 = ctx("x");
        assert_eq!(
            strip_tax_note(&mut c1, "Aus bus sec. Smith 1990".to_string()),
            "Aus bus"
        );
        assert_eq!(c1.name.taxonomic_note, Some("sec. Smith 1990".to_string()));

        let mut c2 = ctx("x");
        assert_eq!(
            strip_tax_note(&mut c2, "Aus bus according to Smith".to_string()),
            "Aus bus"
        );
        assert_eq!(
            c2.name.taxonomic_note,
            Some("according to Smith".to_string())
        );

        let mut c3 = ctx("x");
        assert_eq!(
            strip_tax_note(&mut c3, "Aus bus excl. var. minor".to_string()),
            "Aus bus"
        );
        assert_eq!(c3.name.taxonomic_note, Some("excl. var. minor".to_string()));
    }

    #[test]
    fn prepends_to_an_existing_note() {
        // The LAST of the six taxonomic-note steps: a note steps 38-43 already took came from
        // further right, so this one goes in front of it. Java overwrote it instead.
        let mut c = ctx("x");
        c.name.taxonomic_note = Some("existing".to_string());
        let out = strip_tax_note(&mut c, "Aus bus sensu Miller".to_string());
        assert_eq!(out, "Aus bus");
        assert_eq!(
            c.name.taxonomic_note,
            Some("sensu Miller existing".to_string())
        );
    }

    #[test]
    fn multiple_dangling_commas_before_the_match_are_all_stripped() {
        // A single dangling comma right before the keyword is consumed by TAX_NOTE's own
        // leading `,?`; a SECOND comma (e.g. a doubled ",,") is left over and must be
        // peeled off by the trailing `while (s.endsWith(","))` loop — spot-checked
        // against the Java CLI oracle: "Aus bus,, sensu Miller" -> taxonomicNote "sensu
        // Miller" with a clean "Aus bus" genus/species (no comma artefacts survive).
        let mut c = ctx("x");
        let out = strip_tax_note(&mut c, "Aus bus,, sensu Miller".to_string());
        assert_eq!(out, "Aus bus");
        assert_eq!(c.name.taxonomic_note, Some("sensu Miller".to_string()));
    }

    #[test]
    fn captured_text_case_is_preserved_verbatim_except_for_the_auct_normalisation() {
        // TAX_NOTE's `(?i)` only affects MATCHING, not the captured text itself — spot-
        // checked against the Java CLI oracle: "Aus bus SENSU Smith" keeps "SENSU"
        // upper-case in the note (only a leading "Auct"/"Auctt" gets normalised).
        let mut c = ctx("x");
        let out = strip_tax_note(&mut c, "Aus bus SENSU Smith".to_string());
        assert_eq!(out, "Aus bus");
        assert_eq!(c.name.taxonomic_note, Some("SENSU Smith".to_string()));
    }

    #[test]
    fn no_tax_note_keyword_is_untouched() {
        let mut c = ctx("x");
        let out = strip_tax_note(&mut c, "Abies alba Mill.".to_string());
        assert_eq!(out, "Abies alba Mill.");
        assert_eq!(c.name.taxonomic_note, None);
    }

    // ---- Step 44: stripAggregateSuffix ----

    #[test]
    fn agg_suffix_sets_aggregate_and_strips_the_marker() {
        let mut c = ctx("x");
        let out = strip_aggregate_suffix(&mut c, "Achillea millefolium agg.".to_string());
        assert_eq!(out, "Achillea millefolium");
        assert!(c.aggregate);
    }

    #[test]
    fn species_group_suffix_is_also_recognised() {
        let mut c = ctx("x");
        let out = strip_aggregate_suffix(&mut c, "Achillea millefolium species group".to_string());
        assert_eq!(out, "Achillea millefolium");
        assert!(c.aggregate);
    }

    #[test]
    fn hyphenated_group_suffix_is_also_recognised() {
        let mut c = ctx("x");
        let out = strip_aggregate_suffix(&mut c, "Achillea millefolium-group".to_string());
        assert_eq!(out, "Achillea millefolium");
        assert!(c.aggregate);
    }

    #[test]
    fn no_aggregate_suffix_is_untouched() {
        let mut c = ctx("x");
        let out = strip_aggregate_suffix(&mut c, "Abies alba Mill.".to_string());
        assert_eq!(out, "Abies alba Mill.");
        assert!(!c.aggregate);
    }

    // ---- Step 45: stripPublishedPage ----
    // Every case below spot-checked against the Java CLI oracle via the full parse pipeline
    // (the field values StripAndStash alone contributes match one-for-one).

    #[test]
    fn published_page_colon_space_digits_is_stashed() {
        let mut c = ctx("x");
        let out = strip_published_page(
            &mut c,
            "Anolis marmoratus girafus LAZELL 1964: 377".to_string(),
        );
        assert_eq!(out, "Anolis marmoratus girafus LAZELL 1964");
        assert_eq!(c.name.published_in_page, Some("377".to_string()));
    }

    #[test]
    fn published_page_glued_colon_is_also_recognised() {
        let mut c = ctx("x");
        let out = strip_published_page(
            &mut c,
            "Recilia truncatus Dash & Viraktamath, 1998a:29".to_string(),
        );
        assert_eq!(out, "Recilia truncatus Dash & Viraktamath, 1998a");
        assert_eq!(c.name.published_in_page, Some("29".to_string()));
    }

    #[test]
    fn published_page_extra_spaced_colon_is_also_recognised() {
        let mut c = ctx("x");
        let out = strip_published_page(
            &mut c,
            "Recilia truncatus Dash & Viraktamath, 1998a : 29".to_string(),
        );
        assert_eq!(out, "Recilia truncatus Dash & Viraktamath, 1998a");
        assert_eq!(c.name.published_in_page, Some("29".to_string()));
    }

    #[test]
    fn published_page_range_with_en_dash_is_kept_verbatim() {
        let mut c = ctx("x");
        let out = strip_published_page(&mut c, "Foo bar Author, 1900: 12\u{2013}18".to_string());
        assert_eq!(out, "Foo bar Author, 1900");
        assert_eq!(c.name.published_in_page, Some("12\u{2013}18".to_string()));
    }

    #[test]
    fn no_published_page_is_untouched() {
        let mut c = ctx("x");
        let out = strip_published_page(&mut c, "Abies alba Mill.".to_string());
        assert_eq!(out, "Abies alba Mill.");
        assert_eq!(c.name.published_in_page, None);
    }

    // ---- Step 46: stripInPress ----

    #[test]
    fn documented_example_in_press_sets_manuscript_and_appends_nomenclatural_note() {
        let mut c = ctx("x");
        let out = strip_in_press(&mut c, "Abies alba Mill. in press".to_string());
        assert_eq!(out, "Abies alba Mill.");
        assert!(c.name.manuscript);
        assert_eq!(c.name.nomenclatural_note, Some("in press".to_string()));
    }

    #[test]
    fn in_press_is_case_insensitive_and_always_stashes_the_lowercase_literal() {
        let mut c = ctx("x");
        let out = strip_in_press(&mut c, "Abies alba Mill. In Press.".to_string());
        assert_eq!(out, "Abies alba Mill.");
        assert!(c.name.manuscript);
        assert_eq!(c.name.nomenclatural_note, Some("in press".to_string()));
    }

    #[test]
    fn in_press_appends_to_an_existing_nomenclatural_note() {
        let mut c = ctx("x");
        c.name.nomenclatural_note = Some("nom. illeg.".to_string());
        let out = strip_in_press(&mut c, "Abies alba Mill. in press".to_string());
        assert_eq!(out, "Abies alba Mill.");
        assert_eq!(
            c.name.nomenclatural_note,
            Some("nom. illeg. in press".to_string())
        );
    }

    #[test]
    fn no_in_press_marker_is_untouched() {
        let mut c = ctx("x");
        let out = strip_in_press(&mut c, "Abies alba Mill.".to_string());
        assert_eq!(out, "Abies alba Mill.");
        assert!(!c.name.manuscript);
        assert_eq!(c.name.nomenclatural_note, None);
    }

    // ---- Step 47: stripInAuthorInParens ----

    #[test]
    fn in_author_in_parens_moves_the_publication_year_onto_a_yearless_basionym() {
        let mut c = ctx("x");
        let out = strip_in_author_in_parens(
            &mut c,
            "Hypsicera femoralis (Geoffroy in Fourcroy, 1785)".to_string(),
        );
        assert_eq!(out, "Hypsicera femoralis (Geoffroy, 1785)");
        assert_eq!(c.name.published_in, Some("Fourcroy, 1785".to_string()));
        assert_eq!(c.name.published_in_year, Some(1785));
    }

    #[test]
    fn in_author_in_parens_apud_variant_is_also_recognised() {
        let mut c = ctx("x");
        let out =
            strip_in_author_in_parens(&mut c, "Foo bar (Smith apud Jones, 1900) Mill.".to_string());
        assert_eq!(out, "Foo bar (Smith, 1900) Mill.");
        assert_eq!(c.name.published_in, Some("Jones, 1900".to_string()));
    }

    #[test]
    fn in_author_in_parens_does_not_double_up_a_year_the_basionym_already_has() {
        let mut c = ctx("x");
        let out =
            strip_in_author_in_parens(&mut c, "Foo bar (Smith, 1780 in Jones, 1900)".to_string());
        assert_eq!(out, "Foo bar (Smith, 1780)");
        assert_eq!(c.name.published_in, Some("Jones, 1900".to_string()));
    }

    #[test]
    fn in_author_in_parens_appends_to_an_existing_published_in() {
        let mut c = ctx("x");
        c.name.set_published_in("Earlier ref, 1700");
        let out = strip_in_author_in_parens(
            &mut c,
            "Hypsicera femoralis (Geoffroy in Fourcroy, 1785)".to_string(),
        );
        assert_eq!(out, "Hypsicera femoralis (Geoffroy, 1785)");
        assert_eq!(
            c.name.published_in,
            Some("Earlier ref, 1700 Fourcroy, 1785".to_string())
        );
        assert_eq!(
            c.name.published_in_year,
            Some(1785),
            "the year must be re-derived from the full COMBINED publishedIn string"
        );
    }

    #[test]
    fn plain_parenthesised_basionym_without_in_author_is_untouched() {
        let mut c = ctx("x");
        let out =
            strip_in_author_in_parens(&mut c, "Hypsicera femoralis (Geoffroy, 1785)".to_string());
        assert_eq!(out, "Hypsicera femoralis (Geoffroy, 1785)");
        assert_eq!(c.name.published_in, None);
    }

    // ---- Step 48: stripInAuthorCitation ----

    #[test]
    fn documented_example_busk_in_chimonides_sets_published_in_and_year() {
        let mut c = ctx("x");
        let out = strip_in_author_citation(&mut c, "Busk in Chimonides, 1987".to_string());
        assert_eq!(out, "Busk");
        assert_eq!(c.name.published_in, Some("Chimonides, 1987".to_string()));
        assert_eq!(c.name.published_in_year, Some(1987));
        assert_eq!(c.pending_year, Some("1987".to_string()));
        assert!(c.pending_year_from_publication);
    }

    #[test]
    fn apud_variant_is_also_recognised() {
        let mut c = ctx("x");
        let out = strip_in_author_citation(&mut c, "Small apud Britton & Wilson".to_string());
        assert_eq!(out, "Small");
        assert_eq!(c.name.published_in, Some("Britton & Wilson".to_string()));
    }

    #[test]
    fn trailing_sentence_period_after_closing_paren_is_dropped() {
        let mut c = ctx("x");
        let out =
            strip_in_author_citation(&mut c, "Foo bar Author in Kirchner (1988).".to_string());
        assert_eq!(out, "Foo bar Author");
        assert_eq!(c.name.published_in, Some("Kirchner (1988)".to_string()));
    }

    #[test]
    fn period_after_an_author_abbreviation_is_kept_not_dropped() {
        let mut c = ctx("x");
        let out = strip_in_author_citation(
            &mut c,
            "Papillaria  fuscescens (Hook.) Jaeg. fo. gracilis Card. in Fleisch.".to_string(),
        );
        assert_eq!(
            out,
            "Papillaria  fuscescens (Hook.) Jaeg. fo. gracilis Card."
        );
        assert_eq!(c.name.published_in, Some("Fleisch.".to_string()));
    }

    #[test]
    fn paren_year_takes_precedence_for_pending_year_while_published_in_year_takes_the_last_match() {
        // publishedInYear and pending_year are DISTINCT extractions (see IN_AUTHOR_PAREN_YEAR/
        // IN_AUTHOR_YEAR's doc comments): the former is set_published_in's own "last
        // year-shaped match in the combined string" rule, the latter is
        // set_pending_publication_year's "parenthesised year tried first" rule. Oracle-verified
        // this input yields publishedInYear=1990 but a combinationAuthorship year of 1988 (the
        // pending_year, applied by the Pipeline stage).
        let mut c = ctx("x");
        let out = strip_in_author_citation(
            &mut c,
            "Foo bar Author in Kirchner (1988), 1990".to_string(),
        );
        assert_eq!(out, "Foo bar Author");
        assert_eq!(
            c.name.published_in,
            Some("Kirchner (1988), 1990".to_string())
        );
        assert_eq!(c.name.published_in_year, Some(1990));
        assert_eq!(
            c.pending_year,
            Some("1988".to_string()),
            "the parenthesised year must win over the trailing bare year for pending_year"
        );
    }

    #[test]
    fn no_in_author_tail_is_untouched() {
        let mut c = ctx("x");
        let out = strip_in_author_citation(&mut c, "Abies alba Mill.".to_string());
        assert_eq!(out, "Abies alba Mill.");
        assert_eq!(c.name.published_in, None);
        assert_eq!(c.pending_year, None);
    }

    #[test]
    fn lowercase_word_after_in_is_not_mistaken_for_an_author() {
        // "in obscurity" — the word after "in"/"apud" must start with an uppercase letter;
        // oracle-verified this whole string survives untouched into the raw authorship text.
        let mut c = ctx("x");
        let out = strip_in_author_citation(&mut c, "Foo bar Smith in obscurity".to_string());
        assert_eq!(out, "Foo bar Smith in obscurity");
        assert_eq!(c.name.published_in, None);
    }

    // ---- Step 49: stripIpniCitation ----

    #[test]
    fn documented_ipni_example_sets_published_in_and_year() {
        let mut c = ctx("x");
        let out = strip_ipni_citation(
            &mut c,
            "Foo bar Kirchn., Annals and Magazine of Natural History (1988).".to_string(),
        );
        assert_eq!(out, "Foo bar Kirchn.");
        assert_eq!(
            c.name.published_in,
            Some("Annals and Magazine of Natural History (1988)".to_string())
        );
        assert_eq!(c.name.published_in_year, Some(1988));
        assert_eq!(c.pending_year, Some("1988".to_string()));
    }

    #[test]
    fn embedded_nom_illeg_note_is_extracted_and_the_reference_is_resquished() {
        let mut c = ctx("x");
        let out = strip_ipni_citation(
            &mut c,
            "Foo bar Kirchn., Taxon nom. illeg. (1988).".to_string(),
        );
        assert_eq!(out, "Foo bar Kirchn.");
        assert_eq!(c.name.nomenclatural_note, Some("nom. illeg.".to_string()));
        assert_eq!(c.name.published_in, Some("Taxon (1988)".to_string()));
    }

    #[test]
    fn embedded_pro_syn_note_with_in_obs_prefix_is_extracted() {
        let mut c = ctx("x");
        let out = strip_ipni_citation(
            &mut c,
            "Foo bar Kirchn., Taxon in obs., pro syn. (1988).".to_string(),
        );
        assert_eq!(out, "Foo bar Kirchn.");
        assert_eq!(
            c.name.nomenclatural_note,
            Some("in obs., pro syn.".to_string())
        );
        assert_eq!(c.name.published_in, Some("Taxon (1988)".to_string()));
    }

    #[test]
    fn embedded_comb_nov_note_is_extracted() {
        let mut c = ctx("x");
        let out = strip_ipni_citation(
            &mut c,
            "Foo bar Kirchn., Taxon comb. nov. (1988).".to_string(),
        );
        assert_eq!(out, "Foo bar Kirchn.");
        assert_eq!(c.name.nomenclatural_note, Some("comb. nov.".to_string()));
        assert_eq!(c.name.published_in, Some("Taxon (1988)".to_string()));
    }

    #[test]
    fn ipni_appends_the_embedded_note_to_an_existing_nomenclatural_note() {
        let mut c = ctx("x");
        c.name.nomenclatural_note = Some("earlier note".to_string());
        let out = strip_ipni_citation(
            &mut c,
            "Foo bar Kirchn., Taxon nom. illeg. (1988).".to_string(),
        );
        assert_eq!(out, "Foo bar Kirchn.");
        assert_eq!(
            c.name.nomenclatural_note,
            Some("earlier note nom. illeg.".to_string())
        );
    }

    #[test]
    fn ipni_overwrites_rather_than_appends_an_existing_published_in() {
        let mut c = ctx("x");
        c.name.set_published_in("Stale ref, 1700");
        let out = strip_ipni_citation(
            &mut c,
            "Foo bar Kirchn., Annals and Magazine of Natural History (1988).".to_string(),
        );
        assert_eq!(out, "Foo bar Kirchn.");
        assert_eq!(
            c.name.published_in,
            Some("Annals and Magazine of Natural History (1988)".to_string()),
            "stripIpniCitation calls the plain setPublishedIn — it must OVERWRITE, not append"
        );
    }

    #[test]
    fn no_ipni_citation_is_untouched() {
        let mut c = ctx("x");
        let out = strip_ipni_citation(&mut c, "Abies alba Mill.".to_string());
        assert_eq!(out, "Abies alba Mill.");
        assert_eq!(c.name.published_in, None);
    }

    // ---- Step 50: stripPeriodSeparatedReference ----

    #[test]
    fn clean_year_reference_overwrites_published_in_and_propagates_the_year() {
        let mut c = ctx("x");
        let out = strip_period_separated_reference(
            &mut c,
            "Foo bar Smith. Annals of Botany 1988".to_string(),
        );
        assert_eq!(out, "Foo bar Smith");
        assert_eq!(
            c.name.published_in,
            Some("Annals of Botany 1988".to_string())
        );
        assert_eq!(c.name.published_in_year, Some(1988));
        assert_eq!(c.pending_year, Some("1988".to_string()));
        assert!(!c
            .name
            .warnings
            .contains(&warnings::NOMENCLATURAL_REFERENCE.to_string()));
    }

    #[test]
    fn page_range_reference_flags_nomenclatural_reference_and_does_not_propagate_the_year() {
        // Oracle-verified: the reference must ALSO contain a connector word ("of" here) —
        // "Zootaxa 4759: 1658-1662" alone (no connector) never matches PERIOD_SEPARATED_
        // REFERENCE at all, since the pattern's trailing `\s+(?:of|in|...)#\s+.*` suffix is
        // mandatory, not optional.
        let mut c = ctx("x");
        let out = strip_period_separated_reference(
            &mut c,
            "Foo bar Smith. Annals of Zootaxa 1658-1662, 1988".to_string(),
        );
        assert_eq!(out, "Foo bar Smith");
        assert_eq!(
            c.name.published_in,
            Some("Annals of Zootaxa 1658-1662, 1988".to_string())
        );
        assert_eq!(c.name.published_in_year, Some(1988));
        assert!(c
            .name
            .warnings
            .contains(&warnings::NOMENCLATURAL_REFERENCE.to_string()));
        assert_eq!(
            c.pending_year, None,
            "a page-range reference must NOT propagate a pending year"
        );
    }

    #[test]
    fn author_particle_list_is_not_mistaken_for_a_reference() {
        // "Yin, Z.W. de Beer & Wingf." — a comma (not a period) follows "Yin", so this never
        // reaches PERIOD_SEPARATED_REFERENCE's leading `[\p{Lu}][\p{L}]{2,}\.` anchor at all;
        // oracle-verified the whole string survives into the raw (if mangled) authorship text.
        let mut c = ctx("x");
        let out = strip_period_separated_reference(
            &mut c,
            "Foo bar Yin, Z.W. de Beer & Wingf. Mycologia 2004".to_string(),
        );
        assert_eq!(out, "Foo bar Yin, Z.W. de Beer & Wingf. Mycologia 2004");
        assert_eq!(c.name.published_in, None);
    }

    #[test]
    fn no_period_separated_reference_is_untouched() {
        let mut c = ctx("x");
        let out = strip_period_separated_reference(&mut c, "Abies alba Mill.".to_string());
        assert_eq!(out, "Abies alba Mill.");
        assert_eq!(c.name.published_in, None);
    }

    #[test]
    fn period_separated_reference_stays_linear_on_a_long_connector_free_run() {
        // PERIOD_SEPARATED_REFERENCE runs on fancy_regex (backtracking). A long run of
        // capitalised "words" after "Smith. " with NO connector word anywhere (so the
        // pattern's mandatory trailing `\s+(?:of|in|...)\s+.*` suffix never matches) forces
        // the filler `*+` group to consume the whole run and then fail the suffix. This is a
        // LINEARITY guard, not proof of an averted cliff: as the static's doc NOTE explains
        // and a scratch-crate spike measured directly, this pattern's `\s+ <word>` filler
        // makes every partition unambiguous, so plain greedy `*` is ALSO linear here (~735µs
        // vs `*+`'s ~735µs on a 640-word run) — unlike NOM_NOTE, where the possessive is
        // genuinely load-bearing. The `*+` is kept for faithfulness + defence-in-depth; this
        // test simply pins that the step stays fast regardless of run length.
        let mut c = ctx("x");
        let mut input = "Foo bar Smith.".to_string();
        for i in 0..60 {
            input.push_str(&format!(" Wordxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx{i}"));
        }
        let start = std::time::Instant::now();
        let out = strip_period_separated_reference(&mut c, input.clone());
        let elapsed = start.elapsed();
        assert!(
            elapsed.as_millis() < 500,
            "strip_period_separated_reference took {elapsed:?} on a connector-free run"
        );
        // No connector word anywhere -> the pattern's mandatory suffix never matches, so the
        // string comes back untouched, same as any other non-matching input.
        assert_eq!(out, input);
        assert_eq!(c.name.published_in, None);
    }

    // ---- Step 51: stripCommaPrefixedReference ----

    #[test]
    fn documented_comma_prefixed_reference_overwrites_published_in_and_flags_the_warning() {
        let mut c = ctx("x");
        let out = strip_comma_prefixed_reference(
            &mut c,
            "Foo bar Smith, Journal of Botany 1988".to_string(),
        );
        assert_eq!(out, "Foo bar Smith");
        assert_eq!(
            c.name.published_in,
            Some("Journal of Botany 1988".to_string())
        );
        assert!(c
            .name
            .warnings
            .contains(&warnings::NOMENCLATURAL_REFERENCE.to_string()));
    }

    #[test]
    fn comma_prefixed_reference_does_not_propagate_a_pending_year() {
        let mut c = ctx("x");
        strip_comma_prefixed_reference(&mut c, "Foo bar Smith, Journal of Botany 1988".to_string());
        assert_eq!(
            c.pending_year, None,
            "a comma-prefixed reference's year must never be propagated onto the authorship"
        );
    }

    #[test]
    fn comma_prefixed_reference_overwrites_rather_than_appends_an_existing_published_in() {
        let mut c = ctx("x");
        c.name.set_published_in("Stale ref, 1700");
        let out = strip_comma_prefixed_reference(
            &mut c,
            "Foo bar Miller & Jones, Annals and Magazine of Natural History (1988)".to_string(),
        );
        assert_eq!(out, "Foo bar Miller & Jones");
        assert_eq!(
            c.name.published_in,
            Some("Annals and Magazine of Natural History (1988)".to_string())
        );
    }

    #[test]
    fn author_particle_list_is_not_mistaken_for_a_comma_prefixed_reference_either() {
        // Same negative example as step 50's sibling test — "Z.W." can't open the captured
        // reference title (fails `[\p{Lu}][\p{Ll}]{2,}`), so this is never mistaken for a ref
        // by this step either.
        let mut c = ctx("x");
        let out = strip_comma_prefixed_reference(
            &mut c,
            "Foo bar Yin, Z.W. de Beer & Wingf. Mycologia 2004".to_string(),
        );
        assert_eq!(out, "Foo bar Yin, Z.W. de Beer & Wingf. Mycologia 2004");
        assert_eq!(c.name.published_in, None);
    }

    #[test]
    fn no_comma_prefixed_reference_is_untouched() {
        let mut c = ctx("x");
        let out = strip_comma_prefixed_reference(&mut c, "Abies alba Mill.".to_string());
        assert_eq!(out, "Abies alba Mill.");
        assert_eq!(c.name.published_in, None);
        assert!(c.name.warnings.is_empty());
    }

    #[test]
    fn comma_prefixed_reference_does_not_redos_on_a_long_connector_free_run() {
        // COMMA_PREFIXED_REFERENCE runs on the plain `regex` crate (automaton-based, no
        // backtracking at all), so — unlike step 50's fancy_regex-based sibling — there is no
        // possessive quantifier to preserve and no ReDoS failure mode to guard against. Same
        // pathological input shape as step 50's regression test, so a future reader can see
        // both engines were checked, not just assumed.
        let mut c = ctx("x");
        let mut input = "Foo bar Smith,".to_string();
        for i in 0..300 {
            input.push_str(&format!(" Wordxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx{i}"));
        }
        let start = std::time::Instant::now();
        let out = strip_comma_prefixed_reference(&mut c, input.clone());
        let elapsed = start.elapsed();
        assert!(
            elapsed.as_millis() < 200,
            "strip_comma_prefixed_reference took {elapsed:?} on a connector-free run"
        );
        assert_eq!(out, input);
    }

    // ---- Step 52: stripManuscriptMarker ----

    #[test]
    fn trailing_ms_marker_sets_manuscript_and_appends_the_lowercased_tag() {
        let mut c = ctx("x");
        let out = strip_manuscript_marker(&mut c, "Acacia bicolor Bojer ms.".to_string());
        assert_eq!(out, "Acacia bicolor Bojer");
        assert!(c.name.manuscript);
        assert_eq!(c.name.nomenclatural_note, Some("ms.".to_string()));
    }

    #[test]
    fn ined_marker_with_leading_comma_is_also_recognised() {
        let mut c = ctx("x");
        let out = strip_manuscript_marker(&mut c, "Foo bar Author, ined.".to_string());
        assert_eq!(out, "Foo bar Author");
        assert!(c.name.manuscript);
        assert_eq!(c.name.nomenclatural_note, Some("ined.".to_string()));
    }

    #[test]
    fn unpublished_and_msc_markers_are_also_recognised() {
        let mut c1 = ctx("x");
        let out1 = strip_manuscript_marker(&mut c1, "Foo bar Author unpublished".to_string());
        assert_eq!(out1, "Foo bar Author");
        assert_eq!(c1.name.nomenclatural_note, Some("unpublished".to_string()));

        let mut c2 = ctx("x");
        let out2 = strip_manuscript_marker(&mut c2, "Foo bar Author msc".to_string());
        assert_eq!(out2, "Foo bar Author");
        assert_eq!(c2.name.nomenclatural_note, Some("msc".to_string()));
    }

    #[test]
    fn marker_case_is_lowercased_in_the_stashed_tag() {
        let mut c = ctx("x");
        let out = strip_manuscript_marker(&mut c, "Foo bar Author MS.".to_string());
        assert_eq!(out, "Foo bar Author");
        assert_eq!(c.name.nomenclatural_note, Some("ms.".to_string()));
    }

    #[test]
    fn manuscript_marker_appends_to_an_existing_nomenclatural_note() {
        let mut c = ctx("x");
        c.name.nomenclatural_note = Some("earlier note".to_string());
        let out = strip_manuscript_marker(&mut c, "Foo bar Author ms.".to_string());
        assert_eq!(out, "Foo bar Author");
        assert_eq!(
            c.name.nomenclatural_note,
            Some("earlier note ms.".to_string())
        );
    }

    #[test]
    fn manuscript_marker_after_in_author_strip_still_matches() {
        // "Busk ms in Chimonides, 1987" — in the real pipeline, strip_in_author_citation
        // (step 48) already consumed " in Chimonides, 1987" before this step runs, leaving
        // "Busk ms" for this step alone to finish (see the full-run test below).
        let mut c = ctx("x");
        let out = strip_manuscript_marker(&mut c, "Busk ms".to_string());
        assert_eq!(out, "Busk");
        assert!(c.name.manuscript);
        assert_eq!(c.name.nomenclatural_note, Some("ms".to_string()));
    }

    #[test]
    fn no_manuscript_marker_is_untouched() {
        let mut c = ctx("x");
        let out = strip_manuscript_marker(&mut c, "Abies alba Mill.".to_string());
        assert_eq!(out, "Abies alba Mill.");
        assert!(!c.name.manuscript);
        assert_eq!(c.name.nomenclatural_note, None);
    }

    // ---- Batch 2d cross-step interaction (full `run()`) ----

    #[test]
    fn full_run_strips_both_in_author_citation_and_manuscript_marker_in_order() {
        // Oracle-verified end-to-end (StripAndStash's own contribution): "Aus bus Busk ms in
        // Chimonides, 1987" must have the in-author tail stripped first (step 48), leaving
        // "Aus bus Busk ms" for the manuscript marker (step 52) to finish.
        let mut c = ctx("Aus bus Busk ms in Chimonides, 1987");
        run(&mut c);
        assert_eq!(c.working, "Aus bus Busk");
        assert!(c.name.manuscript);
        assert_eq!(c.name.nomenclatural_note, Some("ms".to_string()));
        assert_eq!(c.name.published_in, Some("Chimonides, 1987".to_string()));
        assert_eq!(c.name.published_in_year, Some(1987));
    }

    // ---- Step 53: stripSupraRankPrefix ----

    #[test]
    fn bare_suprageneric_marker_pins_rank_and_strips_the_marker() {
        // Oracle-verified: "subtrib. Scolochloinae Soreng" -> rank=SUBTRIBE,
        // uninomial=Scolochloinae, authors=[Soreng].
        let mut c = ctx("x");
        let out = strip_supra_rank_prefix(&mut c, "subtrib. Scolochloinae Soreng".to_string());
        assert_eq!(out, "Scolochloinae Soreng");
        assert_eq!(c.name.rank, Rank::Subtribe);
    }

    #[test]
    fn family_prefixed_suprageneric_marker_strips_both_family_and_marker() {
        // Oracle-verified: "Poaceae subtrib. Scolochloinae Soreng" -> IDENTICAL parse to
        // the bare-marker form above (rank=SUBTRIBE, uninomial=Scolochloinae) — the
        // family prefix "Poaceae" is discarded entirely, not preserved anywhere.
        let mut c = ctx("x");
        let out =
            strip_supra_rank_prefix(&mut c, "Poaceae subtrib. Scolochloinae Soreng".to_string());
        assert_eq!(out, "Scolochloinae Soreng");
        assert_eq!(c.name.rank, Rank::Subtribe);
    }

    #[test]
    fn tribe_and_subfamily_markers_are_also_recognised() {
        // Oracle-verified: "trib. Triticeae Dumort." -> rank=TRIBE; "subfam. Pooideae" ->
        // rank=SUBFAMILY.
        let mut c1 = ctx("x");
        let out1 = strip_supra_rank_prefix(&mut c1, "trib. Triticeae Dumort.".to_string());
        assert_eq!(out1, "Triticeae Dumort.");
        assert_eq!(c1.name.rank, Rank::Tribe);

        let mut c2 = ctx("x");
        let out2 = strip_supra_rank_prefix(&mut c2, "subfam. Pooideae".to_string());
        assert_eq!(out2, "Pooideae");
        assert_eq!(c2.name.rank, Rank::Subfamily);
    }

    #[test]
    fn no_supra_rank_prefix_is_untouched() {
        let mut c = ctx("x");
        let out = strip_supra_rank_prefix(&mut c, "Abies alba Mill.".to_string());
        assert_eq!(out, "Abies alba Mill.");
        assert_eq!(c.name.rank, Rank::Unranked);
    }

    // ---- Step 54: stripLeadingInfragenericMarker ----

    #[test]
    fn leading_infragen_marker_pins_rank_and_strips_the_marker() {
        // Oracle-verified: "subgen. Trematostoma Sacc." -> rank=SUBGENUS, no `code` key at
        // all in the wire output (Subgenus carries none — no backfill).
        let mut c = ctx("x");
        let out =
            strip_leading_infrageneric_marker(&mut c, "subgen. Trematostoma Sacc.".to_string());
        assert_eq!(out, "Trematostoma Sacc.");
        assert_eq!(c.name.rank, Rank::Subgenus);
        assert_eq!(c.name.code, None);
    }

    #[test]
    fn leading_infragen_marker_backfills_unset_code_from_the_ranks_own_code() {
        // Oracle-verified: "sect. Foo Bar" (no caller-supplied code) -> rank=SECTION_BOTANY,
        // code=BOTANICAL (backfilled — Subgenus above has no code, but SectionBotany does).
        let mut c = ctx("x");
        let out = strip_leading_infrageneric_marker(&mut c, "sect. Foo Bar".to_string());
        assert_eq!(out, "Foo Bar");
        assert_eq!(c.name.rank, Rank::SectionBotany);
        assert_eq!(c.name.code, Some(NomCode::Botanical));
    }

    #[test]
    fn leading_infragen_marker_no_trailing_dot_form_is_also_recognised() {
        // The marker's trailing dot is optional (`\.?`); "series" (no dot) must match too.
        let mut c = ctx("x");
        let out = strip_leading_infrageneric_marker(&mut c, "series Foo Bar".to_string());
        assert_eq!(out, "Foo Bar");
        assert_eq!(c.name.rank, Rank::SeriesBotany);
        assert_eq!(c.name.code, Some(NomCode::Botanical));
    }

    #[test]
    fn leading_infragen_marker_remaps_to_zoological_counterpart_under_zoological_code() {
        // Oracle-verified (via a ColDP TSV row with code=Zoological): "sect. Taeda" ->
        // rank=SECTION_ZOOLOGY (remapped from SECTION_BOTANY), not SECTION_BOTANY.
        let mut c = ParseContext::new("x".to_string(), None, None, Some(NomCode::Zoological));
        let out = strip_leading_infrageneric_marker(&mut c, "sect. Taeda".to_string());
        assert_eq!(out, "Taeda");
        assert_eq!(c.name.rank, Rank::SectionZoology);
        assert_eq!(c.name.code, Some(NomCode::Zoological));
    }

    #[test]
    fn leading_infragen_marker_subgenus_has_no_zoological_counterpart_to_remap_to() {
        // Oracle-verified (via a ColDP TSV row with code=Zoological): "subgen. Trematostoma
        // Sacc." -> rank stays SUBGENUS even under a caller-supplied ZOOLOGICAL code — Java's
        // BOT_TO_ZOOL map has no SUBGENUS entry, so `bot_to_zool` returns None and the rank
        // is left as-is (`r` unchanged, not remapped).
        let mut c = ParseContext::new("x".to_string(), None, None, Some(NomCode::Zoological));
        let out =
            strip_leading_infrageneric_marker(&mut c, "subgen. Trematostoma Sacc.".to_string());
        assert_eq!(out, "Trematostoma Sacc.");
        assert_eq!(c.name.rank, Rank::Subgenus);
    }

    #[test]
    fn leading_infragen_marker_does_not_overwrite_an_already_set_code() {
        // Java: `if (r.getCode() != null && ctx.name.getCode() == null)` — an existing
        // code (e.g. from an earlier step in the same run, such as strip_candidatus
        // setting BACTERIAL) must survive untouched, unlike step 53's unconditional rank
        // overwrite.
        let mut c = ctx("x");
        c.name.code = Some(NomCode::Bacterial);
        let out = strip_leading_infrageneric_marker(&mut c, "sect. Foo Bar".to_string());
        assert_eq!(out, "Foo Bar");
        assert_eq!(c.name.rank, Rank::SectionBotany, "rank is still pinned");
        assert_eq!(
            c.name.code,
            Some(NomCode::Bacterial),
            "a pre-existing code must not be overwritten"
        );
    }

    #[test]
    fn no_leading_infragen_marker_is_untouched() {
        let mut c = ctx("x");
        let out = strip_leading_infrageneric_marker(&mut c, "Abies alba Mill.".to_string());
        assert_eq!(out, "Abies alba Mill.");
        assert_eq!(c.name.rank, Rank::Unranked);
        assert_eq!(c.name.code, None);
    }

    // ---- Step 55: stashPhraseName ----

    #[test]
    fn phrase_name_bare_genus_with_species_marker_sets_phrase_but_leaves_rank_untouched() {
        // "Prostanthera sp. Somersbey (B.J.Conn 4024)" -> phrase="sp. Somersbey (B.J.Conn
        // 4024)". 5.0.0 Informal-phrase contract: a bare-genus SPECIES-level provisional keeps
        // the verbatim rank marker in the phrase (the Java oracle stashed the bare
        // "Somersbey (B.J.Conn 4024)"; here it is prefixed so the formatter round-trips it
        // without re-synthesising "sp."). The working rewrite is unchanged — the eventual
        // full-pipeline `rank=SPECIES` still comes from NameTokens re-reading the reinserted
        // "sp." marker, NOT from this step directly.
        let mut c = ctx("x");
        let out = stash_phrase_name(
            &mut c,
            "Prostanthera sp. Somersbey (B.J.Conn 4024)".to_string(),
        );
        assert_eq!(out, "Prostanthera sp.");
        assert_eq!(
            c.name.phrase,
            Some("sp. Somersbey (B.J.Conn 4024)".to_string())
        );
        assert_eq!(
            c.name.rank,
            Rank::Unranked,
            "bare genus + \"sp.\" marker must NOT pin rank directly in this step"
        );
    }

    #[test]
    fn phrase_name_bare_genus_with_non_species_marker_pins_rank_and_drops_the_marker() {
        // Oracle-verified: "Grevillea subsp. 'Short Leaf'" -> rank=SUBSPECIES,
        // phrase="'Short Leaf'" (quotes are part of the captured phrase text, not
        // stripped), uninomial reduces to the bare genus "Grevillea".
        let mut c = ctx("x");
        let out = stash_phrase_name(&mut c, "Grevillea subsp. 'Short Leaf'".to_string());
        assert_eq!(out, "Grevillea");
        assert_eq!(c.name.rank, Rank::Subspecies);
        assert_eq!(c.name.phrase, Some("'Short Leaf'".to_string()));
    }

    #[test]
    fn phrase_name_digit_leading_quoted_phrase_is_also_recognised() {
        // Oracle-verified: "Baeckea ssp. 2 (LJM 2019)" -> rank=SUBSPECIES,
        // phrase="2 (LJM 2019)" — group 3's first alternative allows a leading digit.
        let mut c = ctx("x");
        let out = stash_phrase_name(&mut c, "Baeckea ssp. 2 (LJM 2019)".to_string());
        assert_eq!(out, "Baeckea");
        assert_eq!(c.name.rank, Rank::Subspecies);
        assert_eq!(c.name.phrase, Some("2 (LJM 2019)".to_string()));
    }

    #[test]
    fn phrase_name_genus_plus_subgenus_extracts_infrageneric_epithet() {
        // Oracle-verified: "Acacia (Botrycephalae) sp. Bygalorie (P.G.Wilson 2585)" ->
        // rank=SPECIES, infragenericEpithet=Botrycephalae, uninomial reduces to "Acacia"
        // (the "(Botrycephalae)" parens are dropped from the working string entirely,
        // extracted onto a dedicated field instead).
        let mut c = ctx("x");
        let out = stash_phrase_name(
            &mut c,
            "Acacia (Botrycephalae) sp. Bygalorie (P.G.Wilson 2585)".to_string(),
        );
        assert_eq!(out, "Acacia");
        assert_eq!(c.name.rank, Rank::Species);
        assert_eq!(
            c.name.infrageneric_epithet,
            Some("Botrycephalae".to_string())
        );
        assert_eq!(
            c.name.phrase,
            Some("Bygalorie (P.G.Wilson 2585)".to_string())
        );
    }

    #[test]
    fn phrase_name_trailing_author_splices_the_marker_before_the_author() {
        // Oracle-verified: "Baeckea Benth. sp. Bygalorie (ABC 123)" -> working rewritten to
        // "Baeckea sp. Benth." (marker moved BEFORE the author span so it trails as the
        // species author for AuthorshipParser); rank untouched by this step
        // (same "downstream infers it from the reinserted marker" situation as the bare
        // "sp."-marker case above).
        let mut c = ctx("x");
        let out = stash_phrase_name(&mut c, "Baeckea Benth. sp. Bygalorie (ABC 123)".to_string());
        assert_eq!(out, "Baeckea sp. Benth.");
        assert_eq!(c.name.phrase, Some("Bygalorie (ABC 123)".to_string()));
        assert_eq!(c.name.rank, Rank::Unranked);
    }

    #[test]
    fn phrase_name_double_quoted_phrase_without_parens_is_also_recognised() {
        // "Prostanthera sp. \"Big Leaf\"" -> phrase="sp. \"Big Leaf\"" (quotes kept verbatim,
        // matching group 3's second, no-parens alternative; the 5.0.0 Informal-phrase contract
        // prefixes the "sp." marker onto this bare-genus SPECIES phrase — Java stashed just
        // "\"Big Leaf\"").
        let mut c = ctx("x");
        let out = stash_phrase_name(&mut c, "Prostanthera sp. \"Big Leaf\"".to_string());
        assert_eq!(out, "Prostanthera sp.");
        assert_eq!(c.name.phrase, Some("sp. \"Big Leaf\"".to_string()));
    }

    #[test]
    fn phrase_without_parens_or_quotes_is_not_recognised_as_a_phrase_name() {
        // Group 3 requires EITHER parens OR quotes in the phrase text; a bare trailing
        // author span with neither ("P.G.Wilson 2585 F.Muell.") must not match at all —
        // oracle-verified: this exact string parses via the ordinary (doubtful) authorship
        // path instead, with no `phrase` field set.
        let mut c = ctx("x");
        let out = stash_phrase_name(&mut c, "Baeckea sp. P.G.Wilson 2585 F.Muell.".to_string());
        assert_eq!(out, "Baeckea sp. P.G.Wilson 2585 F.Muell.");
        assert_eq!(c.name.phrase, None);
    }

    #[test]
    fn no_phrase_name_shape_is_untouched() {
        let mut c = ctx("x");
        let out = stash_phrase_name(&mut c, "Abies alba Mill.".to_string());
        assert_eq!(out, "Abies alba Mill.");
        assert_eq!(c.name.phrase, None);
        assert_eq!(c.name.rank, Rank::Unranked);
    }

    // ---- Batch 2e cross-step interaction (full `run()`) ----

    #[test]
    fn full_run_strips_a_leading_infrageneric_marker_and_backfills_the_code() {
        // Oracle-verified end-to-end: "sect. Taeda" -> rank=SECTION_BOTANY, code=BOTANICAL,
        // with none of steps 1-52 interfering before step 54 gets to it (a bare "sect."
        // prefix has a period right after it, so it doesn't trip step 4's
        // missing-genus-placeholder heuristic the way an unpunctuated word would).
        let mut c = ctx("sect. Taeda");
        run(&mut c);
        assert_eq!(c.working, "Taeda");
        assert_eq!(c.name.rank, Rank::SectionBotany);
        assert_eq!(c.name.code, Some(NomCode::Botanical));
    }

    #[test]
    fn full_run_stashes_a_phrase_name() {
        // End-to-end (StripAndStash's own contribution): "Prostanthera sp. Somersbey
        // (B.J.Conn 4024)" -> phrase="sp. Somersbey (B.J.Conn 4024)" (5.0.0 Informal-phrase
        // contract: verbatim marker kept in the phrase), working rewritten to "Prostanthera
        // sp." — none of steps 1-52 interfere on this clean, capital-letter-led input before
        // step 55 gets to it.
        let mut c = ctx("Prostanthera sp. Somersbey (B.J.Conn 4024)");
        run(&mut c);
        assert_eq!(c.working, "Prostanthera sp.");
        assert_eq!(
            c.name.phrase,
            Some("sp. Somersbey (B.J.Conn 4024)".to_string())
        );
    }

    // ===================================================================================
    // strip_authorship_markers (Phase 1 Slice 4 Task 4) — the aux-authorship-path
    // reimplementation. `name()` builds a fresh `ParsedName` since this function has no
    // `ParseContext` of its own.
    // ===================================================================================

    fn name() -> ParsedName {
        ParsedName::default()
    }

    #[test]
    fn standalone_manuscript_marker_sets_manuscript_and_returns_empty() {
        let mut n = name();
        let out = strip_authorship_markers("ined.", &mut n);
        assert_eq!(out, "");
        assert!(n.manuscript);
    }

    #[test]
    fn standalone_manuscript_marker_matches_case_insensitively_without_the_dot() {
        let mut n = name();
        let out = strip_authorship_markers("MS", &mut n);
        assert_eq!(out, "");
        assert!(n.manuscript);
    }

    #[test]
    fn blank_authorship_returns_empty_without_touching_name() {
        let mut n = name();
        let out = strip_authorship_markers("   ", &mut n);
        assert_eq!(out, "");
        assert_eq!(n, ParsedName::default());
    }

    #[test]
    fn sic_with_comment_strips_and_flags_original_spelling_true() {
        let mut n = name();
        let out = strip_authorship_markers("L. (sic, misspelling)", &mut n);
        assert_eq!(out, "L.");
        assert_eq!(n.original_spelling, Some(true));
    }

    #[test]
    fn plain_sic_flags_original_spelling_true() {
        let mut n = name();
        let out = strip_authorship_markers("L. (sic)", &mut n);
        assert_eq!(out, "L.");
        assert_eq!(n.original_spelling, Some(true));
    }

    #[test]
    fn corrig_flags_original_spelling_false() {
        let mut n = name();
        let out = strip_authorship_markers("L. corrig.", &mut n);
        assert_eq!(out, "L.");
        assert_eq!(n.original_spelling, Some(false));
    }

    #[test]
    fn question_mark_transcription_artefact_glues_and_flags_doubtful() {
        let mut n = name();
        let out = strip_authorship_markers("Istv?nffi", &mut n);
        assert_eq!(out, "Istvnffi");
        assert!(n.doubtful);
        assert!(n
            .warnings
            .contains(&warnings::QUESTION_MARKS_REMOVED.to_string()));
    }

    #[test]
    fn win1252_artefact_is_repaired_with_a_homoglyphs_warning() {
        let mut n = name();
        let out = strip_authorship_markers("Plesn\u{00A1}k", &mut n);
        assert_eq!(out, "Plesnik");
        assert!(n.warnings.contains(&warnings::HOMOGLYHPS.to_string()));
    }

    #[test]
    fn hort_ex_placeholder_is_lowercased() {
        let mut n = name();
        let out = strip_authorship_markers("Hort. ex Voss", &mut n);
        assert_eq!(out, "hort. ex Voss");
    }

    #[test]
    fn hortus_ex_placeholder_is_lowercased() {
        let mut n = name();
        let out = strip_authorship_markers("hortus ex Someone", &mut n);
        assert_eq!(out, "hort. ex Someone");
    }

    #[test]
    fn cv_ex_is_deliberately_left_untouched() {
        // Unlike the main `run()` dispatch's `normalise_hort_ex_placeholder` (which also
        // handles CV_EX/HT_MARKER), the aux path calls ONLY HORT_EX/HORTUS_EX — see the
        // section doc comment.
        let mut n = name();
        let out = strip_authorship_markers("cv. ex Someone", &mut n);
        assert_eq!(out, "cv. ex Someone");
    }

    #[test]
    fn a_parenthesised_homonym_citation_is_the_whole_note() {
        // Unlike Java, the parens are dropped, as on the name string ("Aus bus (non Smith,
        // 1900)"), so the note a source repeats in both columns is recognised as the same.
        let mut n = name();
        let out = strip_authorship_markers("(non Smith, 1900)", &mut n);
        assert_eq!(out, "");
        assert_eq!(n.taxonomic_note, Some("non Smith, 1900".to_string()));
    }

    #[test]
    fn paren_note_splits_off_a_leading_note_and_keeps_the_trailing_author() {
        let mut n = name();
        let out = strip_authorship_markers("(auct.) Rolfe", &mut n);
        assert_eq!(out, "Rolfe");
        assert_eq!(n.taxonomic_note, Some("auct.".to_string()));
    }

    #[test]
    fn paren_note_keeps_a_leading_author_case_intact() {
        // The Java doc-comment example: "(sensu X, 1878) Y, 1992" -> author "Y, 1992" +
        // note "sensu X, 1878" (unchanged — only a leading "Auct"/"Auctt" is lower-cased).
        let mut n = name();
        let out = strip_authorship_markers("(sensu X, 1878) Y, 1992", &mut n);
        assert_eq!(out, "Y, 1992");
        assert_eq!(n.taxonomic_note, Some("sensu X, 1878".to_string()));
    }

    #[test]
    fn bracketed_nom_note_is_extracted_and_stripped() {
        let mut n = name();
        let out = strip_authorship_markers("L. (nom. cons.)", &mut n);
        assert_eq!(out, "L.");
        assert_eq!(n.nomenclatural_note, Some("nom. cons.".to_string()));
    }

    #[test]
    fn bare_nom_note_is_extracted_and_stripped() {
        let mut n = name();
        let out = strip_authorship_markers("L. nom. illeg.", &mut n);
        assert_eq!(out, "L.");
        assert_eq!(n.nomenclatural_note, Some("nom. illeg.".to_string()));
    }

    #[test]
    fn bare_nom_note_anchored_at_the_very_start_is_still_caught() {
        // NOM_NOTE itself requires a leading whitespace boundary — the space-padded copy
        // ("`padded_nom`") is what lets a note anchored at position 0 of `s` match at all.
        let mut n = name();
        let out = strip_authorship_markers("nom. illeg.", &mut n);
        assert_eq!(out, "");
        assert_eq!(n.nomenclatural_note, Some("nom. illeg.".to_string()));
    }

    #[test]
    fn bare_nom_note_with_ined_keyword_flags_manuscript() {
        let mut n = name();
        let out = strip_authorship_markers("L. sp. nov. ined.", &mut n);
        assert_eq!(out, "L.");
        assert!(n.manuscript);
    }

    #[test]
    fn tax_note_sensu_is_extracted_and_stripped() {
        let mut n = name();
        let out = strip_authorship_markers("L. sensu Smith", &mut n);
        assert_eq!(out, "L.");
        assert_eq!(n.taxonomic_note, Some("sensu Smith".to_string()));
    }

    #[test]
    fn tax_note_initial_dot_space_is_collapsed() {
        // Doc-comment example on INITIAL_DOT_SPACE: "non F. europaeus" -> "non F.europaeus".
        let mut n = name();
        let out = strip_authorship_markers("L. non F. europaeus", &mut n);
        assert_eq!(out, "L.");
        assert_eq!(n.taxonomic_note, Some("non F.europaeus".to_string()));
    }

    #[test]
    fn tax_note_leading_auct_title_case_is_lowercased() {
        let mut n = name();
        let out = strip_authorship_markers("L. Auct.", &mut n);
        assert_eq!(out, "L.");
        assert_eq!(n.taxonomic_note, Some("auct.".to_string()));
    }

    #[test]
    fn tax_note_dedups_against_an_identical_existing_note() {
        // UNLIKE every other note-setter in this function, the final TAX_NOTE step dedups
        // rather than always appending — calling it twice with the same trailing note must
        // not double it up.
        let mut n = name();
        n.taxonomic_note = Some("sensu Smith".to_string());
        let out = strip_authorship_markers("L. sensu Smith", &mut n);
        assert_eq!(out, "L.");
        assert_eq!(n.taxonomic_note, Some("sensu Smith".to_string()));
    }

    #[test]
    fn tax_note_appends_a_distinct_existing_note() {
        let mut n = name();
        n.taxonomic_note = Some("auct.".to_string());
        let out = strip_authorship_markers("L. sensu Smith", &mut n);
        assert_eq!(out, "L.");
        assert_eq!(n.taxonomic_note, Some("auct. sensu Smith".to_string()));
    }

    #[test]
    fn plain_authorship_with_no_markers_is_returned_verbatim() {
        let mut n = name();
        let out = strip_authorship_markers("Mill.", &mut n);
        assert_eq!(out, "Mill.");
        assert_eq!(n, ParsedName::default());
    }
}