chematic-perception 0.4.30

SSSR ring perception and Hückel aromaticity for chematic — pure-Rust RDKit alternative
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
//! Hückel aromaticity perception with antiaromaticity detection.
//!
//! Works on kekulized molecules (no `Aromatic` bond orders) **or** on molecules
//! that retain `Aromatic` bond orders from the SMILES parser (pre-kekulization).
//! Call `kekulize` + `apply_kekule` from `chematic-core` before calling
//! `assign_aromaticity` if you need the explicit double-bond form.
//!
//! Algorithm:
//! 1. Find all SSSR rings via `find_sssr`.
//! 2. **Pass 1**: evaluate each ring independently using Hückel electron counting.
//!    Aromatic (`BondOrder::Aromatic`) bonds are treated equivalently to double bonds
//!    so that pre-kekulization input is handled correctly.
//!    A special "bridgehead N" rule covers fused-ring N atoms whose entire valence
//!    is satisfied by single σ-bonds (like indolizine's junction nitrogen).
//! 3. **Pass 2**: iterative propagation. Rings that were `NonAromatic` or
//!    indeterminate in Pass 1 are re-evaluated using the already-aromatic atom set
//!    as context: confirmed-aromatic atoms contribute 1π unconditionally, allowing
//!    fused rings to be recognised bottom-up (e.g. the 6-ring of indolizine).
//! 4. Classify rings by electron count:
//!    - 4n+2 electrons (n >= 0): aromatic (favorable)
//!    - 4n electrons (n > 0): antiaromatic (unfavorable, strongly disfavored)
//!    - Other: non-aromatic
//! 5. Record all aromatic atoms, bonds, and antiaromatic rings in an `AromaticityModel`.

// ---------------------------------------------------------------------------
// Algorithm selector
// ---------------------------------------------------------------------------

/// Algorithm used to classify ring aromaticity.
///
/// Passed to [`assign_aromaticity_ex`] and [`apply_aromaticity_ex`].
#[derive(Debug, Clone, Copy, Default, PartialEq, Eq)]
pub enum AromaticityAlgorithm {
    /// Strict Hückel 4n+2 rule (default). Supports C, N, O, S.
    #[default]
    Huckel,
    /// RDKit-compatible extension. Adds Se (34) and Te (52) as chalcogen lone-pair
    /// donors (2π), matching the RDKit DEFAULT aromaticity model for common
    /// organic and chalcogen heteroaromatics.
    ///
    /// P-containing aromatic rings are NOT supported in this mode (separate sprint).
    /// Keto-lactam aromaticity is NOT included (TautomerMode, separate sprint).
    RdkitLike,
}

use rustc_hash::{FxHashMap, FxHashSet};

use chematic_core::{AtomIdx, BondIdx, BondOrder, Molecule, implicit_hcount};

use crate::ring_family::RingFamily;
use crate::sssr::find_sssr;

// ---------------------------------------------------------------------------
// Public types
// ---------------------------------------------------------------------------

/// Ring aromaticity classification.
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum RingAromaticity {
    /// 4n+2 electrons: aromatic (favorable)
    Aromatic,
    /// 4n electrons (n > 0): antiaromatic (unfavorable)
    Antiaromatic,
    /// Any other electron count: non-aromatic
    NonAromatic,
}

/// Aromaticity assignment for a molecule.
///
/// Records which atoms and bonds belong to aromatic rings according to
/// the Hückel 4n+2 rule applied to SSSR rings (with fused-ring propagation).
/// Also tracks antiaromatic rings (4n electrons) for chemical accuracy.
#[derive(Debug, Clone)]
pub struct AromaticityModel {
    aromatic_atoms: FxHashSet<AtomIdx>,
    aromatic_bonds: FxHashSet<BondIdx>,
    antiaromatic_rings: Vec<Vec<AtomIdx>>,
    ring_classifications: Vec<(Vec<AtomIdx>, RingAromaticity, u32)>,
}

impl AromaticityModel {
    /// Whether atom `idx` is part of an aromatic ring.
    pub fn is_atom_aromatic(&self, idx: AtomIdx) -> bool {
        self.aromatic_atoms.contains(&idx)
    }

    /// Whether bond `idx` is part of an aromatic ring.
    pub fn is_bond_aromatic(&self, idx: BondIdx) -> bool {
        self.aromatic_bonds.contains(&idx)
    }

    /// Total number of atoms flagged as aromatic.
    pub fn aromatic_atom_count(&self) -> usize {
        self.aromatic_atoms.len()
    }

    /// Get all rings and their classification with electron counts.
    ///
    /// Each entry is `(ring_atoms, classification, π_electron_count)`.
    /// Rings that could not be evaluated (sp3 atoms, unsupported elements) are omitted.
    pub fn ring_classifications(&self) -> &[(Vec<AtomIdx>, RingAromaticity, u32)] {
        &self.ring_classifications
    }

    /// Get all antiaromatic rings (4n electrons, n > 0).
    pub fn antiaromatic_rings(&self) -> &[Vec<AtomIdx>] {
        &self.antiaromatic_rings
    }

    /// Check if any atom belongs to an antiaromatic ring.
    pub fn has_antiaromaticity(&self) -> bool {
        !self.antiaromatic_rings.is_empty()
    }

    /// Build a model directly from an aromatic atom/bond set, with no ring
    /// classification or antiaromaticity data.
    ///
    /// Used by engines (e.g. `rdkit_parity`'s experimental production API)
    /// that determine an aromatic atom/bond set directly rather than via
    /// this module's own per-ring Hückel passes -- `ring_classifications()`
    /// and `antiaromatic_rings()` are empty on the result.
    pub(crate) fn from_atom_bond_sets(
        aromatic_atoms: FxHashSet<AtomIdx>,
        aromatic_bonds: FxHashSet<BondIdx>,
    ) -> Self {
        AromaticityModel {
            aromatic_atoms,
            aromatic_bonds,
            antiaromatic_rings: Vec::new(),
            ring_classifications: Vec::new(),
        }
    }
}

// ---------------------------------------------------------------------------
// Main entry points
// ---------------------------------------------------------------------------

/// Classify a ring by its pi electron count using Hückel and antiaromaticity rules.
#[allow(clippy::manual_is_multiple_of)]
fn classify_ring_aromaticity(pi_electrons: u32) -> (RingAromaticity, u32) {
    if pi_electrons >= 2 && (pi_electrons - 2) % 4 == 0 {
        (RingAromaticity::Aromatic, pi_electrons)
    } else if pi_electrons > 0 && pi_electrons % 4 == 0 {
        (RingAromaticity::Antiaromatic, pi_electrons)
    } else {
        (RingAromaticity::NonAromatic, pi_electrons)
    }
}

/// Mark all atoms and bonds in `ring` as aromatic in the provided sets.
fn mark_ring_aromatic(
    mol: &Molecule,
    ring: &[AtomIdx],
    aromatic_atoms: &mut FxHashSet<AtomIdx>,
    aromatic_bonds: &mut FxHashSet<BondIdx>,
) {
    for &atom in ring {
        aromatic_atoms.insert(atom);
    }
    for i in 0..ring.len() {
        let a = ring[i];
        let b = ring[(i + 1) % ring.len()];
        if let Some((bidx, _)) = mol.bond_between(a, b) {
            aromatic_bonds.insert(bidx);
        }
    }
}

/// Assign aromaticity to a molecule using the Hückel 4n+2 rule with fused-ring
/// propagation (Pass 2) and antiaromaticity detection (4n electrons).
///
/// The molecule may be kekulized (`Single`/`Double` bonds) **or** may retain
/// `BondOrder::Aromatic` bonds from the SMILES parser.  In the latter case,
/// aromatic bonds are treated as equivalent to double bonds for electron
/// counting, allowing correct detection without an explicit kekulization step.
///
/// For kekulized input from aromatic SMILES, call `chematic_core::kekulize`
/// then `chematic_core::apply_kekule` first.
///
/// Uses [`AromaticityAlgorithm::Huckel`] (default). See [`assign_aromaticity_ex`]
/// for the RdkitLike variant.
pub fn assign_aromaticity(mol: &Molecule) -> AromaticityModel {
    assign_aromaticity_ex(mol, AromaticityAlgorithm::Huckel)
}

/// Assign aromaticity using the specified algorithm.
///
/// The default ([`assign_aromaticity`]) uses [`AromaticityAlgorithm::Huckel`].
/// Pass [`AromaticityAlgorithm::RdkitLike`] to additionally recognise Se/Te
/// as lone-pair donors in aromatic rings.
pub fn assign_aromaticity_ex(mol: &Molecule, algo: AromaticityAlgorithm) -> AromaticityModel {
    let ring_set = find_sssr(mol);
    let sssr_rings = ring_set.rings();

    // Augment SSSR rings with smaller XOR sub-rings (GF(2) differences between pairs).
    // This corrects the case where the SSSR algorithm stores a large fundamental cycle
    // instead of its smaller GF(2)-reduced equivalent (e.g. the 5-ring of indolizine).
    let rings: Vec<Vec<AtomIdx>> = augmented_ring_set(mol, sssr_rings);

    let mut aromatic_atoms: FxHashSet<AtomIdx> = FxHashSet::default();
    let mut aromatic_bonds: FxHashSet<BondIdx> = FxHashSet::default();
    let mut antiaromatic_rings: Vec<Vec<AtomIdx>> = Vec::new();

    // Per-ring classification: None means "not yet evaluated / indeterminate".
    let mut classifications: Vec<Option<(RingAromaticity, u32)>> = vec![None; rings.len()];

    // Indices of rings that are candidates for Pass 2 re-evaluation
    // (returned None or NonAromatic in Pass 1).
    let mut pass2_candidates: Vec<usize> = Vec::new();

    // ----- Pass 1: independent Hückel per ring -----
    let empty_context = FxHashSet::default();
    for (ring_idx, ring) in rings.iter().enumerate() {
        match ring_pi_electrons(mol, ring, &empty_context, algo) {
            Some(pi) => {
                let (cls, count) = classify_ring_aromaticity(pi);
                classifications[ring_idx] = Some((cls, count));
                match cls {
                    RingAromaticity::Aromatic => {
                        mark_ring_aromatic(mol, ring, &mut aromatic_atoms, &mut aromatic_bonds);
                    }
                    RingAromaticity::Antiaromatic => {
                        antiaromatic_rings.push(ring.to_vec());
                        // Antiaromatic is definitive — do not retry in Pass 2.
                    }
                    RingAromaticity::NonAromatic => {
                        pass2_candidates.push(ring_idx);
                    }
                }
            }
            None => {
                // Indeterminate (sp3 atoms, unsupported elements, etc.).
                pass2_candidates.push(ring_idx);
            }
        }
    }

    // ----- Pass 2: propagate through fused ring systems -----
    // Re-evaluate rings adjacent to already-aromatic rings.  Repeat until
    // convergence (no newly aromatic ring found in the last iteration).
    loop {
        let mut any_new = false;
        let mut still_pending: Vec<usize> = Vec::new();

        for ring_idx in pass2_candidates {
            let ring = &rings[ring_idx];
            // Only rings that share an atom with an already-aromatic ring qualify.
            if !ring.iter().any(|a| aromatic_atoms.contains(a)) {
                still_pending.push(ring_idx);
                continue;
            }
            match ring_pi_electrons(mol, ring, &aromatic_atoms, algo) {
                Some(pi) => {
                    let (cls, count) = classify_ring_aromaticity(pi);
                    classifications[ring_idx] = Some((cls, count));
                    if matches!(cls, RingAromaticity::Aromatic) {
                        mark_ring_aromatic(mol, ring, &mut aromatic_atoms, &mut aromatic_bonds);
                        any_new = true;
                    }
                    // NonAromatic even in Pass 2 context: do not retry further.
                }
                None => {
                    still_pending.push(ring_idx);
                }
            }
        }

        pass2_candidates = still_pending;
        if !any_new {
            break;
        }
    }

    // Build the public ring_classifications list (SSSR rings only, omitting augmented/indeterminate).
    let ring_classifications: Vec<(Vec<AtomIdx>, RingAromaticity, u32)> = rings
        .iter()
        .take(sssr_rings.len()) // only expose SSSR rings in the public API
        .enumerate()
        .filter_map(|(i, ring)| classifications[i].map(|(cls, count)| (ring.to_vec(), cls, count)))
        .collect();

    AromaticityModel {
        aromatic_atoms,
        aromatic_bonds,
        antiaromatic_rings,
        ring_classifications,
    }
}

/// Apply aromaticity perception to a molecule.
///
/// Returns a new [`Molecule`] where atoms in Hückel-aromatic rings have
/// `atom.aromatic = true` and their bonds carry [`BondOrder::Aromatic`].
/// Non-aromatic atoms and bonds are unchanged.
///
/// The input may be kekulized (no `Aromatic` bond orders) or may retain
/// aromatic bond orders from the SMILES parser.
///
/// Uses [`AromaticityAlgorithm::Huckel`] (default). See [`apply_aromaticity_ex`]
/// for the RdkitLike variant.
pub fn apply_aromaticity(mol: &Molecule) -> Molecule {
    apply_aromaticity_ex(mol, AromaticityAlgorithm::Huckel)
}

/// Apply aromaticity using the specified algorithm.
///
/// Returns a new [`Molecule`] with aromatic flags set according to `algo`.
pub fn apply_aromaticity_ex(mol: &Molecule, algo: AromaticityAlgorithm) -> Molecule {
    let model = assign_aromaticity_ex(mol, algo);
    build_molecule_from_model(mol, &model)
}

/// Build a new [`Molecule`] from `mol` with atom/bond aromaticity flags set
/// according to an already-computed `model`.
///
/// Shared by [`apply_aromaticity_ex`] and the `rdkit_parity` experimental
/// production API (`apply_aromaticity_rdkit_parity_experimental`) so both
/// get the same implicit-H preservation, bond-direction stashing, and
/// stereo-metadata copying -- this is the same "Kekule-then-perceive"
/// normalization either caller needs, not something specific to one
/// algorithm.
pub(crate) fn build_molecule_from_model(mol: &Molecule, model: &AromaticityModel) -> Molecule {
    use chematic_core::{BondOrder, MoleculeBuilder, implicit_hcount};

    // Implicit-H counts computed BEFORE bond orders are normalized below, for
    // organic-subset atoms without an explicit bracket H count. Needed because
    // normalizing every aromatic-model bond to `BondOrder::Aromatic` (below)
    // discards the Kekule Single/Double pattern that distinguishes a
    // lone-pair-donating "pyrrole-type" heteroatom (2 ring single bonds pre-
    // normalization, needs 1 implicit H) from a "pyridine-type" one (1 ring
    // single + 1 ring double, needs 0) -- post-normalization both look
    // identical (aromatic, 2 aromatic-order ring bonds, no substituent), so
    // `implicit_hcount`'s aromatic-path heuristic (correct for SMILES that
    // was aromatic-written from the start, per OpenSMILES convention: bare
    // aromatic `n` is pyridine-type, pyrrole-type is always `[nH]`) silently
    // returns the wrong value for atoms that reach this function via
    // Kekule-then-perceive instead. This under-counts molecular weight and
    // formula, not just fingerprints/canonical SMILES.
    let pre_h: Vec<Option<u8>> = mol
        .atoms()
        .map(|(idx, atom)| {
            if atom.hydrogen_count.is_some() {
                None // already explicit; nothing to preserve
            } else {
                Some(implicit_hcount(mol, idx))
            }
        })
        .collect();

    let mut builder = MoleculeBuilder::new();
    for (idx, atom) in mol.atoms() {
        let mut a = atom.clone();
        if model.is_atom_aromatic(idx) {
            a.aromatic = true;
        }
        builder.add_atom(a);
    }
    for (bidx, bond) in mol.bonds() {
        let order = if model.is_bond_aromatic(bidx) {
            BondOrder::Aromatic
        } else {
            bond.order
        };
        if let Ok(new_bidx) = builder.add_bond(bond.atom1, bond.atom2, order)
            && order == BondOrder::Aromatic
            && matches!(bond.order, BondOrder::Up | BondOrder::Down)
        {
            // Kekule input promoted to Aromatic here loses its E/Z direction
            // the same way the SMILES parser's aromatic-aromatic coercion
            // does — stash it so an exocyclic double bond anchored on this
            // ring bond still round-trips through the canonical writer.
            builder.set_bond_direction(new_bidx, bond.order);
        }
    }
    // Atoms/bonds above are re-added in `mol`'s own enumeration order with
    // none skipped, so indices line up 1:1 — safe to copy side-channel
    // metadata wholesale. (This rebuild previously dropped stereo_groups and
    // stereo_neighbor_order silently; closing that here too.)
    builder.copy_stereo_groups_from(mol);
    builder.copy_stereo_from(mol);
    builder.copy_bond_directions_from(mol);
    let normalized = builder.build();

    // Compare the pre-normalization implicit H against what the same
    // (already-tested, unmodified) `implicit_hcount` computes on the
    // normalized bonds; only atoms where normalization actually changed the
    // answer get an explicit H frozen in. Benzene CH and pyridine-type N
    // (heuristic already agrees) are left untouched -- no spurious bracket
    // notation for atoms that didn't need it.
    let needs_patch: Vec<(chematic_core::AtomIdx, u8)> = normalized
        .atoms()
        .filter_map(|(idx, _)| {
            let pre = pre_h[idx.0 as usize]?;
            let post = implicit_hcount(&normalized, idx);
            (pre != post).then_some((idx, pre))
        })
        .collect();
    if needs_patch.is_empty() {
        return normalized;
    }

    let mut patched = MoleculeBuilder::new();
    for (idx, atom) in normalized.atoms() {
        let mut a = atom.clone();
        if let Some(&(_, h)) = needs_patch.iter().find(|(pidx, _)| *pidx == idx) {
            a.hydrogen_count = Some(h);
        }
        patched.add_atom(a);
    }
    for (_bond_idx, bond) in normalized.bonds() {
        let _ = patched.add_bond(bond.atom1, bond.atom2, bond.order);
    }
    patched.copy_stereo_groups_from(&normalized);
    patched.copy_stereo_from(&normalized);
    patched.copy_bond_directions_from(&normalized);
    patched.build()
}

// ---------------------------------------------------------------------------
// Ring augmentation (XOR sub-rings)
// ---------------------------------------------------------------------------

/// Return the sorted set of bond indices that form `ring`.
fn ring_bond_set(mol: &Molecule, ring: &[AtomIdx]) -> Vec<BondIdx> {
    let n = ring.len();
    let mut bonds: Vec<BondIdx> = (0..n)
        .filter_map(|i| {
            let a = ring[i];
            let b = ring[(i + 1) % n];
            mol.bond_between(a, b).map(|(bidx, _)| bidx)
        })
        .collect();
    bonds.sort();
    bonds
}

/// Sorted symmetric difference of two sorted slices.
fn bond_sym_diff(a: &[BondIdx], b: &[BondIdx]) -> Vec<BondIdx> {
    let mut result: Vec<BondIdx> = Vec::new();
    let mut i = 0;
    let mut j = 0;
    while i < a.len() && j < b.len() {
        match a[i].cmp(&b[j]) {
            std::cmp::Ordering::Less => {
                result.push(a[i]);
                i += 1;
            }
            std::cmp::Ordering::Greater => {
                result.push(b[j]);
                j += 1;
            }
            std::cmp::Ordering::Equal => {
                i += 1;
                j += 1;
            }
        }
    }
    result.extend_from_slice(&a[i..]);
    result.extend_from_slice(&b[j..]);
    result
}

/// Reconstruct an ordered atom sequence from a set of bond indices forming a simple cycle.
/// Returns `None` if the bonds do not form a valid simple cycle.
fn ring_atoms_from_bond_set(mol: &Molecule, bonds: &[BondIdx]) -> Option<Vec<AtomIdx>> {
    if bonds.is_empty() {
        return None;
    }
    let mut adj: FxHashMap<AtomIdx, [Option<AtomIdx>; 2]> = FxHashMap::default();
    for &bidx in bonds {
        let bond = mol.bond(bidx);
        for (a, b) in [(bond.atom1, bond.atom2), (bond.atom2, bond.atom1)] {
            let e = adj.entry(a).or_insert([None; 2]);
            if e[0].is_none() {
                e[0] = Some(b);
            } else if e[1].is_none() {
                e[1] = Some(b);
            } else {
                return None; // degree > 2 — not a simple ring
            }
        }
    }
    // All atoms must have exactly 2 neighbours.
    if adj.values().any(|e| e[1].is_none()) {
        return None;
    }
    let start = *adj.keys().next()?;
    let mut path = vec![start];
    let mut prev = start;
    let mut current = adj[&start][0]?;
    while current != start {
        path.push(current);
        let [n0, n1] = adj[&current];
        let next = if n0 == Some(prev) { n1? } else { n0? };
        prev = current;
        current = next;
    }
    if path.len() != bonds.len() {
        return None;
    }
    Some(path)
}

/// Augment the SSSR ring list with smaller XOR sub-rings found by pairwise GF(2)
/// differences between SSSR rings that share atoms.
///
/// The standard SSSR algorithm sometimes stores a large fundamental cycle rather
/// than its smaller GF(2)-reduced equivalent (e.g. the 5-ring of indolizine is
/// the XOR of the 6-ring and the 9-ring the algorithm reports).
/// This augmentation adds such missing smaller rings so that aromaticity
/// perception works on the correct smallest rings without modifying the SSSR.
///
/// The returned `Vec` starts with all SSSR rings in their original order; any
/// additional sub-rings derived by GF(2) pairwise XOR follow.  The function
/// only adds a ring if it is strictly smaller than *both* parents, ensuring
/// that envelope rings (e.g. the 10-membered perimeter of naphthalene) are
/// never introduced.
pub fn augmented_ring_set(mol: &Molecule, sssr_rings: &[Vec<AtomIdx>]) -> Vec<Vec<AtomIdx>> {
    let mut rings: Vec<Vec<AtomIdx>> = sssr_rings.to_vec();

    // Track which atom-sets we already have (as sorted atom lists).
    let mut known: FxHashSet<Vec<AtomIdx>> = sssr_rings
        .iter()
        .map(|r| {
            let mut s = r.clone();
            s.sort();
            s
        })
        .collect();

    // Iterative pairwise XOR until convergence.
    //
    // A single pass only finds rings that are the XOR of two SSSR rings.
    // Iterating also finds rings that require XOR of 3+ SSSR rings
    // (e.g. the inner hexagon of coronene, or sub-rings in multi-step
    // fused PAHs where the SSSR chose large perimeter cycles).
    // Termination is guaranteed because each new ring is strictly smaller
    // than both of its parents, so ring size can only decrease.
    loop {
        let mut changed = false;
        let n = rings.len();
        let bond_sets: Vec<Vec<BondIdx>> = rings.iter().map(|r| ring_bond_set(mol, r)).collect();

        for i in 0..n {
            for j in (i + 1)..n {
                // Only consider pairs that share atoms (fused rings).
                let shares_atom = rings[i].iter().any(|a| rings[j].contains(a));
                if !shares_atom {
                    continue;
                }
                let xor_bonds = bond_sym_diff(&bond_sets[i], &bond_sets[j]);
                if xor_bonds.is_empty() {
                    continue;
                }
                // Only interesting if the XOR ring is not larger than the larger
                // parent.  Using max() recovers cases where SSSR chose a large
                // cycle (e.g. 10-ring macro vs 6-ring benzene twin).
                // Using `>` (not `>=`) also allows same-size XOR rings, which
                // handles bridged bicyclics (e.g. tropane or dioxolane spirocycles)
                // where both parent rings are 6-membered and the missing bridge
                // ring is also 6-membered.  Termination is still guaranteed:
                // the `known` set prevents duplicates, and a finite molecule has
                // finitely many valid cycles.
                if xor_bonds.len() > rings[i].len().max(rings[j].len()) {
                    continue;
                }
                if let Some(new_ring) = ring_atoms_from_bond_set(mol, &xor_bonds) {
                    let mut key = new_ring.clone();
                    key.sort();
                    if known.insert(key) {
                        rings.push(new_ring);
                        changed = true;
                    }
                }
            }
        }

        // 3-ring XOR: catches small rings that require XOR of 3 SSSR rings
        // when no intermediate 2-ring XOR produces a valid smaller ring.
        for i in 0..n {
            for j in (i + 1)..n {
                let shares_ij = rings[i].iter().any(|a| rings[j].contains(a));
                if !shares_ij {
                    continue;
                }
                let xor_ij = bond_sym_diff(&bond_sets[i], &bond_sets[j]);
                if xor_ij.is_empty() {
                    continue;
                }
                for k in (j + 1)..n {
                    let shares_k = rings[k]
                        .iter()
                        .any(|a| rings[i].contains(a) || rings[j].contains(a));
                    if !shares_k {
                        continue;
                    }
                    let xor_ijk = bond_sym_diff(&xor_ij, &bond_sets[k]);
                    let max_size = rings[i].len().max(rings[j].len()).max(rings[k].len());
                    if xor_ijk.is_empty() || xor_ijk.len() > max_size {
                        continue;
                    }
                    if let Some(new_ring) = ring_atoms_from_bond_set(mol, &xor_ijk) {
                        let mut key = new_ring.clone();
                        key.sort();
                        if known.insert(key) {
                            rings.push(new_ring);
                            changed = true;
                        }
                    }
                }
            }
        }

        if !changed {
            break;
        }
    }

    rings
}

/// Shared inner: SSSR → augmented_ring_set → strip_envelope_rings, no aromaticity filter.
fn all_ring_list_inner(mol: &Molecule) -> Vec<Vec<AtomIdx>> {
    let sssr = crate::sssr::find_sssr(mol);
    let aug = augmented_ring_set(mol, sssr.rings());
    if aug.len() <= 1 {
        return aug;
    }
    let bond_sets: Vec<Vec<BondIdx>> = aug.iter().map(|r| ring_bond_set(mol, r)).collect();
    let mut is_envelope = vec![false; aug.len()];
    strip_envelope_rings(&aug, &bond_sets, &mut is_envelope);
    aug.into_iter()
        .zip(is_envelope)
        .filter(|(_, e)| !e)
        .map(|(r, _)| r)
        .collect()
}

/// Return all rings after augmented-ring-set expansion and envelope stripping.
///
/// Same pipeline as [`aromatic_ring_list`] but with no aromaticity filter — useful
/// for aliphatic/saturated ring counting and bridgehead detection where SSSR
/// envelope rings cause over-counting.
pub fn all_ring_list(mol: &Molecule) -> Vec<Vec<AtomIdx>> {
    all_ring_list_inner(mol)
}

/// True when all ring bonds between ring atoms are `BondOrder::Aromatic`.
///
/// Rings written with aromatic-SMILES notation but containing an explicit single
/// bond (`c-n`, `nc-2`, etc.) are NOT truly aromatic.  RDKit canonicalises such
/// SMILES with lowercase atoms and a `-` bond, which the parser stores as
/// `BondOrder::Single` between two aromatic-flagged atoms.  Returning `false`
/// here lets callers exclude them from the aromatic ring count.
pub fn ring_bonds_all_aromatic(mol: &Molecule, ring: &[AtomIdx]) -> bool {
    let n = ring.len();
    (0..n).all(|i| {
        let a = ring[i];
        let b = ring[(i + 1) % n];
        mol.bond_between(a, b)
            .map(|(bidx, _)| mol.bond(bidx).order == BondOrder::Aromatic)
            .unwrap_or(true)
    })
}

/// Return the de-duplicated list of aromatic rings after augmented-ring-set expansion
/// and envelope stripping.  Useful for filtering (e.g. counting only aromatic heterocycles).
pub fn aromatic_ring_list(mol: &Molecule) -> Vec<Vec<AtomIdx>> {
    let mol_with_arom;
    let mol = if mol.atoms().any(|(_, a)| a.aromatic) {
        mol
    } else {
        mol_with_arom = apply_aromaticity(mol);
        &mol_with_arom
    };
    all_ring_list_inner(mol)
        .into_iter()
        .filter(|ring| {
            ring.iter().all(|&idx| mol.atom(idx).aromatic) && ring_bonds_all_aromatic(mol, ring)
        })
        .collect()
}

/// Mark which rings in `aromatic` are GF(2) sums (bond-XOR) of 2–4 smaller rings.
fn strip_envelope_rings(
    aromatic: &[Vec<AtomIdx>],
    bond_sets: &[Vec<BondIdx>],
    is_envelope: &mut [bool],
) {
    let n = aromatic.len();
    for i in 0..n {
        let si = aromatic[i].len();
        'jk: for j in 0..n {
            if j == i || aromatic[j].len() >= si {
                continue;
            }
            for k in (j + 1)..n {
                if k == i || aromatic[k].len() >= si {
                    continue;
                }
                if bond_sym_diff(&bond_sets[j], &bond_sets[k]) == bond_sets[i] {
                    is_envelope[i] = true;
                    break 'jk;
                }
            }
        }
        if !is_envelope[i] {
            'jkl: for j in 0..n {
                if j == i || aromatic[j].len() >= si {
                    continue;
                }
                for k in (j + 1)..n {
                    if k == i || aromatic[k].len() >= si {
                        continue;
                    }
                    let xor_jk = bond_sym_diff(&bond_sets[j], &bond_sets[k]);
                    for l in (k + 1)..n {
                        if l == i || aromatic[l].len() >= si {
                            continue;
                        }
                        if bond_sym_diff(&xor_jk, &bond_sets[l]) == bond_sets[i] {
                            is_envelope[i] = true;
                            break 'jkl;
                        }
                    }
                }
            }
        }
        if !is_envelope[i] {
            'jklm: for j in 0..n {
                if j == i || aromatic[j].len() >= si {
                    continue;
                }
                for k in (j + 1)..n {
                    if k == i || aromatic[k].len() >= si {
                        continue;
                    }
                    let xor_jk = bond_sym_diff(&bond_sets[j], &bond_sets[k]);
                    for l in (k + 1)..n {
                        if l == i || aromatic[l].len() >= si {
                            continue;
                        }
                        let xor_jkl = bond_sym_diff(&xor_jk, &bond_sets[l]);
                        for m in (l + 1)..n {
                            if m == i || aromatic[m].len() >= si {
                                continue;
                            }
                            if bond_sym_diff(&xor_jkl, &bond_sets[m]) == bond_sets[i] {
                                is_envelope[i] = true;
                                break 'jklm;
                            }
                        }
                    }
                }
            }
        }
    }
}

pub fn count_aromatic_rings(mol: &Molecule) -> usize {
    // For Kekulé-form input (uppercase atoms, no aromatic flags yet), run Hückel
    // perception first so ring detection works correctly (RDKit #9271).
    let mol_with_arom;
    let mol = if mol.atoms().any(|(_, a)| a.aromatic) {
        mol // aromatic SMILES — flags already set during parsing
    } else {
        mol_with_arom = apply_aromaticity(mol);
        &mol_with_arom
    };

    let sssr = crate::sssr::find_sssr(mol);
    let aug = augmented_ring_set(mol, sssr.rings());

    // Keep only rings where every atom carries the aromatic flag.
    let aromatic: Vec<Vec<AtomIdx>> = aug
        .into_iter()
        .filter(|ring| ring.iter().all(|&idx| mol.atom(idx).aromatic))
        .collect();

    if aromatic.len() <= 1 {
        return aromatic.len();
    }

    // Build sorted bond-index sets for each aromatic ring.
    let bond_sets: Vec<Vec<BondIdx>> = aromatic.iter().map(|r| ring_bond_set(mol, r)).collect();

    // Mark rings that are the GF(2) sum (bond-XOR) of 2, 3, or 4 strictly
    // smaller aromatic rings.  Such rings are "envelope" cycles introduced
    // when the SSSR chose a large fundamental cycle instead of its smaller
    // GF(2) components.
    // 2-ring XOR: handles linear/angular fused systems (naphthalene, indolizine…).
    // 3-ring XOR: handles compact PAHs like pyrene.
    // 4-ring XOR: handles coronene-class PAHs where the outer perimeter is the
    //   GF(2) sum of four inner hexagons.
    let n = aromatic.len();
    let mut is_envelope = vec![false; n];
    strip_envelope_rings(&aromatic, &bond_sets, &mut is_envelope);
    is_envelope.iter().filter(|&&e| !e).count()
}

// ---------------------------------------------------------------------------
// Per-ring pi electron count
// ---------------------------------------------------------------------------

/// Count pi electrons for a ring atom, returning `None` if the atom is
/// incompatible with aromaticity (e.g. sp3 carbon).
///
/// `aromatic_context`: atoms already confirmed aromatic (from Pass 1 or a
/// previous Pass 2 iteration).  Such atoms contribute 1π unconditionally,
/// without requiring an explicit double bond.
///
/// Rules:
/// - **C**: if already in `aromatic_context` → 1π (confirmed sp2).
///   1. No double bond anywhere: carbanion (`charge == -1`) → 2π (lone pair,
///      e.g. cyclopentadienyl anion); otherwise sp3 → None.
///   2. Has a double bond, but only exocyclic and to a more electronegative
///      atom (O/N/S) → 0π (its p-orbital electrons are in the exocyclic π
///      bond, e.g. the carbonyl carbon in tropone/pyridone/pyranone).
///   3. Otherwise (has an endocyclic Double/Aromatic bond) → 1π.
/// - **N**:
///   1. Has H → 2π (pyrrole-type lone pair).
///   2. Has an explicit `Double` bond → 1π (pyridine-type).
///   3. total_degree == 3 AND ring_degree < total_degree AND no explicit
///      double bond → 2π (lone pair in p orbital): covers both a bridgehead
///      N shared by two fused rings (indolizine) and a substituted
///      pyrrole-type N (N-methylpyrrole, N-glycosylated purine); the overall
///      4n+2 sum, not the substituent, decides ring aromaticity.
///   4. Has in-ring `Aromatic` bond → 1π (pyridine-like aromatic N).
///   5. Already in `aromatic_context` → 1π.
///   6. Otherwise → None.
/// - **O/S**: ring_degree must be 2; contributes 2π (lone pair).
/// - **Se (34) / Te (52)**: analogous to S; only in [`AromaticityAlgorithm::RdkitLike`] mode.
/// - **Other elements**: None (unsupported).
fn ring_pi_electrons(
    mol: &Molecule,
    ring: &[AtomIdx],
    aromatic_context: &FxHashSet<AtomIdx>,
    algo: AromaticityAlgorithm,
) -> Option<u32> {
    let ring_atom_set: FxHashSet<AtomIdx> = ring.iter().copied().collect();
    let mut total_pi: u32 = 0;

    for &atom_idx in ring {
        // Atoms already confirmed aromatic in an adjacent ring contribute 1π.
        if aromatic_context.contains(&atom_idx) {
            total_pi += 1;
            continue;
        }

        let atom = mol.atom(atom_idx);
        let an = atom.element.atomic_number();

        let ring_degree = mol
            .neighbors(atom_idx)
            .filter(|(nb, _)| ring_atom_set.contains(nb))
            .count();

        let total_degree = mol.degree(atom_idx);

        // Explicit Double bond anywhere (not counting Aromatic).
        let has_explicit_double = mol
            .neighbors(atom_idx)
            .any(|(_, bidx)| mol.bond(bidx).order == BondOrder::Double);

        // Double OR Aromatic bond anywhere (for C sp2 check).
        let has_double_any = has_explicit_double
            || mol
                .neighbors(atom_idx)
                .any(|(_, bidx)| mol.bond(bidx).order == BondOrder::Aromatic);

        // Aromatic bond within the ring (for pyridine-like N in aromatic SMILES).
        let has_aromatic_in_ring = mol
            .neighbors(atom_idx)
            .filter(|(nb, _)| ring_atom_set.contains(nb))
            .any(|(_, bidx)| mol.bond(bidx).order == BondOrder::Aromatic);

        let pi = match an {
            // Carbon: must be sp2 (has a double or aromatic bond somewhere).
            6 => {
                if !has_double_any {
                    // No double bond: a ring carbanion still donates its lone
                    // pair (e.g. cyclopentadienyl anion), otherwise sp3.
                    if atom.charge == -1 {
                        2
                    } else {
                        return None; // sp3 carbon — ring cannot be aromatic
                    }
                } else if has_explicit_double
                    && !has_aromatic_in_ring
                    && !mol.neighbors(atom_idx).any(|(nb, bidx)| {
                        ring_atom_set.contains(&nb) && mol.bond(bidx).order == BondOrder::Double
                    })
                    && mol.neighbors(atom_idx).any(|(nb, bidx)| {
                        !ring_atom_set.contains(&nb)
                            && mol.bond(bidx).order == BondOrder::Double
                            && matches!(mol.atom(nb).element.atomic_number(), 7 | 8 | 16)
                    })
                {
                    // Only double bond is exocyclic, to a more electronegative
                    // atom (O/N/S): p-orbital electrons sit in that exocyclic π
                    // bond, contributing 0π to the ring (e.g. carbonyl carbon
                    // in tropone/pyridone/pyranone).
                    0
                } else {
                    1
                }
            }

            // Nitrogen
            7 => {
                if implicit_hcount(mol, atom_idx) > 0 {
                    // Pyrrole-type N with H: lone pair → 2π.
                    2
                } else if has_explicit_double {
                    // Pyridine-type N with explicit double bond → 1π.
                    1
                } else if total_degree == 3 && ring_degree < total_degree {
                    // N with no H, no explicit double bond, and all three σ-bonds
                    // exactly filling its valence (3): a bridgehead N shared by two
                    // fused rings (e.g. indolizine) and a substituted pyrrole-type N
                    // (e.g. N-methylpyrrole, N-glycosylated purine/pyrimidine) have
                    // the identical local shape — the lone pair occupies the p
                    // orbital → 2π either way. Whether the ring this atom sits in is
                    // actually aromatic is decided by the overall 4n+2 sum below, not
                    // by inspecting the substituent: an imide N (phthalimide) still
                    // correctly comes out non-aromatic because its ring's carbonyl
                    // carbons contribute 0π each (exocyclic C=O rule above), giving
                    // 4π total, not 4n+2.
                    2
                } else if has_aromatic_in_ring {
                    // N in an aromatic ring (pre-kekulization input) without an
                    // explicit double bond and not a bridgehead → pyridine-like → 1π.
                    1
                } else {
                    // Cannot determine pi contribution.
                    return None;
                }
            }

            // Oxygen / sulfur: lone-pair donor, must be 2-connected in the ring.
            8 | 16 => {
                if ring_degree != 2 {
                    return None;
                }
                // Sulfoxide/sulfone: exocyclic S=O ties up the lone pair; cannot donate 2π
                if an == 16
                    && mol.neighbors(atom_idx).any(|(nb, bidx)| {
                        !ring_atom_set.contains(&nb) && mol.bond(bidx).order == BondOrder::Double
                    })
                {
                    return None;
                }
                2
            }

            // Se (34) / Te (52): chalcogen lone-pair donors (2π), analogous to S.
            // Only recognised in RdkitLike mode.
            34 | 52 => {
                if algo != AromaticityAlgorithm::RdkitLike {
                    return None;
                }
                if ring_degree != 2 {
                    return None;
                }
                // Exocyclic Se=O / Te=O ties up the lone pair.
                if mol.neighbors(atom_idx).any(|(nb, bidx)| {
                    !ring_atom_set.contains(&nb) && mol.bond(bidx).order == BondOrder::Double
                }) {
                    return None;
                }
                2
            }

            // Unsupported element.
            _ => return None,
        };

        total_pi += pi;
    }

    Some(total_pi)
}

// ---------------------------------------------------------------------------
// Diagnostic trace (Aromaticity-A1-0) — observational only, no production
// behavior change. `ring_pi_electrons` above is untouched and remains the
// single source of truth for `assign_aromaticity_ex`'s actual decisions;
// this is a parallel, read-only explanation layer for `component/atom/reason`
// tracing, used by `aromaticity_a1_0_report` and the corpus diagnostics in
// `validation/aromaticity_a1_0_corpus.jsonl`. See `docs/aromaticity_a1_rfc.md`.
// ---------------------------------------------------------------------------

/// Reason a ring atom contributes (or fails to contribute) pi electrons,
/// mirroring `ring_pi_electrons`'s branches one-to-one. Purely diagnostic.
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum ContributionReason {
    /// Already aromatic from a previous Pass 1/Pass 2 ring: contributes 1π unconditionally.
    AlreadyAromaticContext,
    /// Carbon with an endocyclic double/aromatic bond: 1π.
    CarbonEndocyclicDouble,
    /// Carbon whose only double bond is exocyclic to O/N/S: 0π (e.g. a carbonyl carbon).
    CarbonExocyclicHeteroatomDouble,
    /// Carbanion with no double bond: 2π (lone pair).
    CarbonCarbanionLonePair,
    /// sp3 carbon (no double bond, not a carbanion): ineligible.
    CarbonSp3Ineligible,
    /// Pyrrole-type N with an H: 2π.
    NitrogenPyrroleTypeH,
    /// Pyridine-type N with an explicit double bond: 1π.
    NitrogenPyridineTypeExplicitDouble,
    /// Bridgehead N (or N-substituted azole N): all-sigma valence, lone pair in p orbital: 2π.
    NitrogenBridgeheadOrSubstitutedLonePair,
    /// N with an in-ring aromatic bond, not a bridgehead: 1π.
    NitrogenAromaticInRing,
    /// N matching none of the above rules: ineligible.
    NitrogenIneligible,
    /// O/S/Se/Te lone-pair donor, ring-degree 2: 2π.
    ChalcogenLonePair,
    /// O/S/Se/Te with the wrong ring degree, an exocyclic X=O, or (Se/Te) non-RdkitLike mode: ineligible.
    ChalcogenIneligible,
    /// Element not supported by the model: ineligible.
    UnsupportedElement,
}

impl ContributionReason {
    /// Whether this reason is an eligible contribution (matches
    /// `ring_pi_electrons` returning `Some`) rather than one that disqualifies
    /// the whole ring (matches it returning `None`).
    pub fn is_eligible(self) -> bool {
        !matches!(
            self,
            ContributionReason::CarbonSp3Ineligible
                | ContributionReason::NitrogenIneligible
                | ContributionReason::ChalcogenIneligible
                | ContributionReason::UnsupportedElement
        )
    }

    /// Coarse `PiEligibility` bucket for this fine-grained reason
    /// (Aromaticity-A1-1a). `AlreadyAromaticContext` has no single fixed
    /// bucket -- it always carries exactly 1π, so it maps to `OneElectron`.
    pub fn eligibility(self) -> PiEligibility {
        use ContributionReason::*;
        match self {
            AlreadyAromaticContext
            | CarbonEndocyclicDouble
            | NitrogenPyridineTypeExplicitDouble
            | NitrogenAromaticInRing => PiEligibility::OneElectron,
            CarbonCarbanionLonePair
            | NitrogenPyrroleTypeH
            | NitrogenBridgeheadOrSubstitutedLonePair
            | ChalcogenLonePair => PiEligibility::LonePairDonor,
            CarbonExocyclicHeteroatomDouble => PiEligibility::ZeroElectron,
            CarbonSp3Ineligible | NitrogenIneligible | ChalcogenIneligible | UnsupportedElement => {
                PiEligibility::Ineligible
            }
        }
    }
}

/// Coarse per-atom pi-eligibility bucket (Aromaticity-A1-1a). A summary view
/// over [`ContributionReason`]'s finer-grained rules -- `electrons()` gives
/// the electron count implied by each bucket.
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum PiEligibility {
    /// Contributes exactly 1π (e.g. an endocyclic double/aromatic bond).
    OneElectron,
    /// Contributes 2π (a lone pair: pyrrole-type N, chalcogen, bridgehead N, carbanion).
    LonePairDonor,
    /// Contributes 0π but is still sp2 (p-orbital spent on an exocyclic multiple bond).
    ZeroElectron,
    /// Not eligible to be part of any conjugated system (e.g. sp3).
    Ineligible,
}

impl PiEligibility {
    /// Electron count implied by this bucket, or `None` for `Ineligible`.
    pub fn electrons(self) -> Option<u8> {
        match self {
            PiEligibility::OneElectron => Some(1),
            PiEligibility::LonePairDonor => Some(2),
            PiEligibility::ZeroElectron => Some(0),
            PiEligibility::Ineligible => None,
        }
    }
}

/// A candidate conjugated system: some atoms/bonds evaluated together as one
/// pi-electron-counting problem (Aromaticity-A1-1a). Two distinct uses:
/// - a single SSSR/augmented ring, reinterpreted as a trivial one-ring
///   candidate (what `trace_ring_pi_electrons` builds today);
/// - a genuine multi-ring fused envelope, built by
///   [`build_conjugated_components`] as a connected component of the
///   "conjugation graph" (double/aromatic-bonded atoms, plus lone-pair-donor
///   atoms bridging across single bonds) -- the azulene-class candidate
///   `augmented_ring_set`'s own docstring already named as future work
///   ("candidate rings = SSSR ∪ fused envelopes").
#[derive(Debug, Clone)]
pub struct ConjugatedComponent {
    pub atoms: Vec<AtomIdx>,
    pub bonds: Vec<BondIdx>,
    /// Ring indices (into whatever ring list the caller built this from) this
    /// candidate derives from -- one entry for a plain single-ring candidate,
    /// 2+ for a fused envelope spanning multiple rings.
    pub source_rings: Vec<usize>,
}

impl ConjugatedComponent {
    /// Build a trivial single-ring candidate from one ring's atom list (no
    /// bond list needed by [`evaluate_atom_pi_contribution`], which only
    /// consults `atoms` membership).
    fn from_ring(ring: &[AtomIdx], ring_idx: usize) -> Self {
        ConjugatedComponent {
            atoms: ring.to_vec(),
            bonds: Vec::new(),
            source_rings: vec![ring_idx],
        }
    }
}

/// The full per-atom decision from [`evaluate_atom_pi_contribution`]: the
/// coarse eligibility bucket plus the specific rule that produced it.
#[derive(Debug, Clone, Copy)]
pub struct ContributionDecision {
    pub eligibility: PiEligibility,
    pub reason: ContributionReason,
}

impl ContributionDecision {
    pub fn electrons(&self) -> Option<u8> {
        self.eligibility.electrons()
    }
}

/// Per-atom trace entry from [`trace_ring_pi_electrons`].
#[derive(Debug, Clone, Copy)]
pub struct AtomElectronTrace {
    pub atom_idx: AtomIdx,
    /// `None` iff `reason.is_eligible()` is false.
    pub contribution: Option<u8>,
    pub reason: ContributionReason,
}

/// Full per-atom pi-electron trace for one ring — the diagnostic twin of
/// [`ring_pi_electrons`]. Unlike `ring_pi_electrons` (which returns `None` at
/// the first ineligible atom), this always scans every atom so a caller can
/// see exactly which atom(s) disqualify a ring, not just that one did.
#[derive(Debug, Clone)]
pub struct RingElectronTrace {
    pub atoms: Vec<AtomElectronTrace>,
    /// `Some(sum)` iff every atom was eligible — must equal
    /// `ring_pi_electrons(mol, ring, aromatic_context, algo)` for the same
    /// inputs (checked by `trace_matches_ring_pi_electrons_on_corpus` below).
    pub total: Option<u32>,
}

/// Diagnostic twin of [`ring_pi_electrons`]: identical per-atom rules
/// (delegating to [`evaluate_atom_pi_contribution`], the single source of
/// truth for both this trace and any future experimental production path —
/// see `docs/aromaticity_a1_rfc.md`'s A1-1a section), but returns a full
/// trace instead of a single early-exiting `Option<u32>`. Does not call,
/// wrap, or change `ring_pi_electrons` itself — zero effect on
/// `assign_aromaticity_ex`'s behavior. `trace_matches_ring_pi_electrons_on_corpus`
/// is the anti-drift guard that keeps this and `ring_pi_electrons` in sync.
pub fn trace_ring_pi_electrons(
    mol: &Molecule,
    ring: &[AtomIdx],
    aromatic_context: &FxHashSet<AtomIdx>,
    algo: AromaticityAlgorithm,
) -> RingElectronTrace {
    let component = ConjugatedComponent::from_ring(ring, 0);
    let mut atoms = Vec::with_capacity(ring.len());
    let mut total: Option<u32> = Some(0);

    for &atom_idx in ring {
        let (contribution, reason) = if aromatic_context.contains(&atom_idx) {
            (Some(1u8), ContributionReason::AlreadyAromaticContext)
        } else {
            let decision = evaluate_atom_pi_contribution(mol, atom_idx, &component, algo);
            (decision.electrons(), decision.reason)
        };

        total = match (total, contribution) {
            (Some(t), Some(c)) => Some(t + c as u32),
            _ => None,
        };

        atoms.push(AtomElectronTrace {
            atom_idx,
            contribution,
            reason,
        });
    }

    RingElectronTrace { atoms, total }
}

/// Single source of truth for per-atom pi-electron contribution
/// (Aromaticity-A1-1a): identical rules to `ring_pi_electrons`'s match arms,
/// condition-for-condition, parameterized by an arbitrary candidate
/// [`ConjugatedComponent`] instead of one fixed SSSR ring — the same
/// function evaluates a plain single-ring candidate (via
/// `ConjugatedComponent::from_ring`) or a genuine multi-ring fused envelope
/// (via `build_conjugated_components`) identically. Currently called by
/// `trace_ring_pi_electrons` only — NOT wired into `ring_pi_electrons` or
/// `assign_aromaticity_ex` (that wiring, behind a new opt-in
/// `AromaticityAlgorithm` variant, is Aromaticity-A1-1b, not this round).
pub fn evaluate_atom_pi_contribution(
    mol: &Molecule,
    atom_idx: AtomIdx,
    component: &ConjugatedComponent,
    algo: AromaticityAlgorithm,
) -> ContributionDecision {
    let component_atoms: FxHashSet<AtomIdx> = component.atoms.iter().copied().collect();
    let (_electrons, reason) =
        evaluate_atom_pi_contribution_inner(mol, atom_idx, &component_atoms, algo);
    // `reason.eligibility().electrons()` is asserted equal to `_electrons`
    // for every branch by `contribution_decision_electrons_match_inner_on_corpus`.
    ContributionDecision {
        eligibility: reason.eligibility(),
        reason,
    }
}

/// Per-atom contribution logic, mirroring `ring_pi_electrons`'s match arms
/// condition-for-condition, but returning a reason alongside the
/// contribution instead of returning early on `None`.
fn evaluate_atom_pi_contribution_inner(
    mol: &Molecule,
    atom_idx: AtomIdx,
    ring_atom_set: &FxHashSet<AtomIdx>,
    algo: AromaticityAlgorithm,
) -> (Option<u8>, ContributionReason) {
    let atom = mol.atom(atom_idx);
    let an = atom.element.atomic_number();

    let ring_degree = mol
        .neighbors(atom_idx)
        .filter(|(nb, _)| ring_atom_set.contains(nb))
        .count();
    let total_degree = mol.degree(atom_idx);

    let has_explicit_double = mol
        .neighbors(atom_idx)
        .any(|(_, bidx)| mol.bond(bidx).order == BondOrder::Double);
    let has_double_any = has_explicit_double
        || mol
            .neighbors(atom_idx)
            .any(|(_, bidx)| mol.bond(bidx).order == BondOrder::Aromatic);
    let has_aromatic_in_ring = mol
        .neighbors(atom_idx)
        .filter(|(nb, _)| ring_atom_set.contains(nb))
        .any(|(_, bidx)| mol.bond(bidx).order == BondOrder::Aromatic);

    match an {
        6 => {
            if !has_double_any {
                if atom.charge == -1 {
                    (Some(2), ContributionReason::CarbonCarbanionLonePair)
                } else {
                    (None, ContributionReason::CarbonSp3Ineligible)
                }
            } else if has_explicit_double
                && !has_aromatic_in_ring
                && !mol.neighbors(atom_idx).any(|(nb, bidx)| {
                    ring_atom_set.contains(&nb) && mol.bond(bidx).order == BondOrder::Double
                })
                && mol.neighbors(atom_idx).any(|(nb, bidx)| {
                    !ring_atom_set.contains(&nb)
                        && mol.bond(bidx).order == BondOrder::Double
                        && matches!(mol.atom(nb).element.atomic_number(), 7 | 8 | 16)
                })
            {
                (Some(0), ContributionReason::CarbonExocyclicHeteroatomDouble)
            } else {
                (Some(1), ContributionReason::CarbonEndocyclicDouble)
            }
        }
        7 => {
            if implicit_hcount(mol, atom_idx) > 0 {
                (Some(2), ContributionReason::NitrogenPyrroleTypeH)
            } else if has_explicit_double {
                (
                    Some(1),
                    ContributionReason::NitrogenPyridineTypeExplicitDouble,
                )
            } else if total_degree == 3 && ring_degree < total_degree {
                (
                    Some(2),
                    ContributionReason::NitrogenBridgeheadOrSubstitutedLonePair,
                )
            } else if has_aromatic_in_ring {
                (Some(1), ContributionReason::NitrogenAromaticInRing)
            } else {
                (None, ContributionReason::NitrogenIneligible)
            }
        }
        8 | 16 => {
            let exocyclic_double = an == 16
                && mol.neighbors(atom_idx).any(|(nb, bidx)| {
                    !ring_atom_set.contains(&nb) && mol.bond(bidx).order == BondOrder::Double
                });
            if ring_degree != 2 || exocyclic_double {
                (None, ContributionReason::ChalcogenIneligible)
            } else {
                (Some(2), ContributionReason::ChalcogenLonePair)
            }
        }
        34 | 52 => {
            let exocyclic_double = mol.neighbors(atom_idx).any(|(nb, bidx)| {
                !ring_atom_set.contains(&nb) && mol.bond(bidx).order == BondOrder::Double
            });
            if algo != AromaticityAlgorithm::RdkitLike || ring_degree != 2 || exocyclic_double {
                (None, ContributionReason::ChalcogenIneligible)
            } else {
                (Some(2), ContributionReason::ChalcogenLonePair)
            }
        }
        _ => (None, ContributionReason::UnsupportedElement),
    }
}

/// Evaluate an atom's pi contribution using its "home ring" within a
/// (possibly multi-ring) candidate, instead of the candidate's flattened
/// atom set directly: tries each of `candidate.source_rings` that actually
/// contains the atom, evaluating against *that one ring's own* atom set, and
/// returns the first eligible result found. Falls back to evaluating
/// directly against the flattened `candidate` if `source_rings` is empty or
/// none of them contain the atom (shouldn't happen for well-formed
/// candidates, but keeps this total rather than panicking).
///
/// Needed because degree-sensitive rules (the N bridgehead/substituted-azole
/// rule, `total_degree == 3 && ring_degree < total_degree`) test "does this
/// atom have a bond that points outside THIS ring" -- a genuine multi-ring
/// bridgehead's every bond is "in-family" once the evaluation context is the
/// flattened whole envelope (every neighbor is, by construction, some other
/// family member), which silently defeats that test and makes a real
/// bridgehead N (e.g. indolizine's) look `Ineligible`. Evaluating against
/// one constituent ring at a time preserves the rule's original, correct,
/// per-ring meaning even when the candidate spans multiple rings. This does
/// **not** attempt to resolve whether a bridgehead's lone-pair credit is
/// *legitimately shared* between two rings that are both otherwise valid vs.
/// wrongly borrowed by one ring from another that's actually broken (e.g.
/// by an sp3 atom) -- that is a distinct, harder, open question, deliberately
/// left to Aromaticity-A1-1b (see `docs/aromaticity_a1_rfc.md`).
fn evaluate_atom_via_home_ring(
    mol: &Molecule,
    atom_idx: AtomIdx,
    candidate: &ConjugatedComponent,
    rings: &[Vec<AtomIdx>],
    algo: AromaticityAlgorithm,
) -> ContributionDecision {
    let mut last = None;
    for &ri in &candidate.source_rings {
        if !rings[ri].contains(&atom_idx) {
            continue;
        }
        let home = ConjugatedComponent::from_ring(&rings[ri], ri);
        let decision = evaluate_atom_pi_contribution(mol, atom_idx, &home, algo);
        if decision.electrons().is_some() {
            return decision;
        }
        last = Some(decision);
    }
    last.unwrap_or_else(|| evaluate_atom_pi_contribution(mol, atom_idx, candidate, algo))
}

/// Build genuine multi-ring conjugated-system candidates (Aromaticity-A1-1a):
/// connected components of the "conjugation graph" over each ring family's
/// atoms -- nodes are atoms whose eligibility (evaluated per-atom against its
/// own home ring, via `evaluate_atom_via_home_ring` -- not the flattened
/// family) is not `Ineligible`; edges are any bond (single, double, or
/// aromatic) between two independently-eligible family atoms: ordinary
/// carbon-carbon single-bond conjugation (butadiene's C=C-C=C middle bond,
/// styrene's vinyl-to-phenyl bond) connects just as directly as a
/// lone-pair-donor heteroatom bridging a sigma bond.
///
/// A pure candidate *generator* -- callers (currently only
/// `exhaustive_aromaticity_oracle`) still run full 4n+2 electron counting on
/// each result. Only components spanning 2+ of a family's rings are
/// returned: a single unfused ring is already covered by
/// `ConjugatedComponent::from_ring`, so this only adds the fused-envelope
/// candidates `augmented_ring_set`'s docstring named as future work
/// ("candidate rings = SSSR ∪ fused envelopes").
pub fn build_conjugated_components(
    mol: &Molecule,
    rings: &[Vec<AtomIdx>],
    ring_families: &[RingFamily],
    algo: AromaticityAlgorithm,
) -> Vec<ConjugatedComponent> {
    let mut out = Vec::new();

    for family in ring_families {
        if family.ring_indices.len() < 2 {
            continue; // single-ring families add nothing beyond from_ring.
        }
        let family_component = ConjugatedComponent {
            atoms: family.atoms.clone(),
            bonds: Vec::new(),
            source_rings: family.ring_indices.clone(),
        };

        // Eligibility per atom, evaluated against its *home* constituent
        // ring (not the flattened family) -- see `evaluate_atom_via_home_ring`'s
        // doc comment for why the flattened version breaks degree-sensitive
        // rules (bridgehead N) for any atom whose every bond happens to be
        // "in-family" once the family itself is the context.
        let eligible: FxHashMap<AtomIdx, bool> = family
            .atoms
            .iter()
            .map(|&a| {
                let decision = evaluate_atom_via_home_ring(mol, a, &family_component, rings, algo);
                (a, decision.electrons().is_some())
            })
            .collect();
        // Union-find over eligible family atoms, connected by conjugation edges.
        let atoms: Vec<AtomIdx> = family.atoms.clone();
        let index_of: FxHashMap<AtomIdx, usize> =
            atoms.iter().enumerate().map(|(i, &a)| (a, i)).collect();
        let mut parent: Vec<usize> = (0..atoms.len()).collect();
        fn find(parent: &mut [usize], x: usize) -> usize {
            if parent[x] != x {
                parent[x] = find(parent, parent[x]);
            }
            parent[x]
        }
        fn union(parent: &mut [usize], x: usize, y: usize) {
            let (px, py) = (find(parent, x), find(parent, y));
            if px != py {
                parent[px] = py;
            }
        }

        // Any bond (single, double, or aromatic) between two independently
        // eligible atoms conjugation-connects them: two sp2 atoms bridge
        // across a single bond exactly like butadiene's C=C-C=C middle bond
        // or styrene's vinyl-to-phenyl bond -- ordinary carbon-carbon
        // conjugation, not just lone-pair-donor bridging. (First version of
        // this rule only bridged single bonds via a `LonePairDonor`
        // endpoint, which is too narrow: it left azulene's all-carbon
        // alternating single/double perimeter as 5 disconnected 2-atom
        // pairs, never forming the one 10-atom fused-envelope candidate it
        // needs -- caught by `exhaustive_aromaticity_oracle` returning an
        // empty set for azulene instead of the whole ring.) The
        // `is_lone_pair_donor` check is now unused for connectivity, kept
        // only where a NON-eligible atom's neighbor still needs distinguishing
        // (none currently) -- eligibility alone (both endpoints not
        // `Ineligible`) is the connectivity condition; bond order still fully
        // determines each atom's *electron count* via
        // `evaluate_atom_pi_contribution`, just not graph connectivity.
        let family_atom_set: FxHashSet<AtomIdx> = family.atoms.iter().copied().collect();
        let mut conjugation_bonds: Vec<BondIdx> = Vec::new();
        for &a in &atoms {
            if !eligible[&a] {
                continue;
            }
            for (nb, bidx) in mol.neighbors(a) {
                if !family_atom_set.contains(&nb) || !eligible.get(&nb).copied().unwrap_or(false) {
                    continue;
                }
                // Both endpoints eligible -> connected (see comment above).
                union(&mut parent, index_of[&a], index_of[&nb]);
                conjugation_bonds.push(bidx);
            }
        }

        let mut groups: FxHashMap<usize, Vec<AtomIdx>> = FxHashMap::default();
        for &a in &atoms {
            if !eligible[&a] {
                continue;
            }
            let root = find(&mut parent, index_of[&a]);
            groups.entry(root).or_default().push(a);
        }

        for group_atoms in groups.into_values() {
            let group_set: FxHashSet<AtomIdx> = group_atoms.iter().copied().collect();
            let source_rings: Vec<usize> = family
                .ring_indices
                .iter()
                .copied()
                .filter(|&ri| rings[ri].iter().all(|a| group_set.contains(a)))
                .collect();
            if source_rings.len() < 2 {
                continue; // doesn't actually span multiple full rings.
            }
            let group_bonds: Vec<BondIdx> = conjugation_bonds
                .iter()
                .copied()
                .filter(|&bidx| {
                    let b = mol.bond(bidx);
                    group_set.contains(&b.atom1) && group_set.contains(&b.atom2)
                })
                .collect();
            out.push(ConjugatedComponent {
                atoms: group_atoms,
                bonds: group_bonds,
                source_rings,
            });
        }
    }

    out
}

/// Test/diagnostic-only exhaustive-candidate reference oracle
/// (Aromaticity-A1-1a) — **not** used by production or by
/// `trace_ring_pi_electrons`. Evaluates every SSSR/augmented ring AND every
/// multi-ring fused-envelope candidate from `build_conjugated_components`,
/// marking an atom/bond aromatic if ANY candidate containing it
/// independently satisfies 4n+2 via `evaluate_atom_pi_contribution`'s
/// per-atom rules — every candidate is evaluated from a clean slate, with NO
/// `aromatic_context` bootstrapping at all (unlike `assign_aromaticity_ex`'s
/// production Pass 1/Pass 2). Exists to cross-check hypotheses about which
/// per-atom rule needs to change, per the MANCUDE-style bounded-enumeration
/// precedent — see `docs/aromaticity_a1_rfc.md`'s A1-1a section.
/// Deliberately simple/slow: O(rings + fused envelopes) candidates, no
/// attempt at Pass-2-style iteration, memoization, or performance tuning.
pub fn exhaustive_aromaticity_oracle(
    mol: &Molecule,
    algo: AromaticityAlgorithm,
) -> (FxHashSet<AtomIdx>, FxHashSet<BondIdx>) {
    let sssr = find_sssr(mol);
    let rings = augmented_ring_set(mol, sssr.rings());
    let families = crate::ring_family::find_ring_families_over(mol, &rings);

    let mut candidates: Vec<ConjugatedComponent> = rings
        .iter()
        .enumerate()
        .map(|(i, r)| ConjugatedComponent::from_ring(r, i))
        .collect();
    candidates.extend(build_conjugated_components(mol, &rings, &families, algo));

    let mut aromatic_atoms: FxHashSet<AtomIdx> = FxHashSet::default();
    let mut aromatic_bonds: FxHashSet<BondIdx> = FxHashSet::default();

    for candidate in &candidates {
        let mut total: Option<u32> = Some(0);
        for &atom_idx in &candidate.atoms {
            // Multi-ring candidates evaluate each atom against its home ring
            // (see `evaluate_atom_via_home_ring`'s doc comment); single-ring
            // candidates fall through to the same code path with exactly one
            // source ring, unchanged from evaluating against `candidate` directly.
            let decision = evaluate_atom_via_home_ring(mol, atom_idx, candidate, &rings, algo);
            total = match (total, decision.electrons()) {
                (Some(t), Some(e)) => Some(t + e as u32),
                _ => None,
            };
        }
        let Some(pi) = total else { continue };
        let (cls, _) = classify_ring_aromaticity(pi);
        if !matches!(cls, RingAromaticity::Aromatic) {
            continue;
        }
        for &a in &candidate.atoms {
            aromatic_atoms.insert(a);
        }
        for &a in &candidate.atoms {
            for (nb, bidx) in mol.neighbors(a) {
                if candidate.atoms.contains(&nb)
                    && matches!(
                        mol.bond(bidx).order,
                        BondOrder::Double | BondOrder::Aromatic
                    )
                {
                    aromatic_bonds.insert(bidx);
                }
            }
        }
    }

    (aromatic_atoms, aromatic_bonds)
}

// ---------------------------------------------------------------------------
// Tests
// ---------------------------------------------------------------------------

#[cfg(test)]
mod tests {
    use super::*;
    use chematic_core::{Atom, BondOrder, Element, MoleculeBuilder};

    // =========================================================================
    // Molecule builder helpers (kekulized, manually constructed)
    // =========================================================================

    fn benzene_kekule() -> chematic_core::Molecule {
        let mut b = MoleculeBuilder::new();
        let atoms: Vec<_> = (0..6).map(|_| b.add_atom(Atom::new(Element::C))).collect();
        for i in 0..6 {
            let order = if i % 2 == 0 {
                BondOrder::Double
            } else {
                BondOrder::Single
            };
            b.add_bond(atoms[i], atoms[(i + 1) % 6], order).unwrap();
        }
        b.build()
    }

    fn cyclohexane() -> chematic_core::Molecule {
        let mut b = MoleculeBuilder::new();
        let atoms: Vec<_> = (0..6).map(|_| b.add_atom(Atom::new(Element::C))).collect();
        for i in 0..6 {
            b.add_bond(atoms[i], atoms[(i + 1) % 6], BondOrder::Single)
                .unwrap();
        }
        b.build()
    }

    fn pyridine_kekule() -> chematic_core::Molecule {
        let mut b = MoleculeBuilder::new();
        let n = b.add_atom(Atom::new(Element::N));
        let atoms_c: Vec<_> = (0..5).map(|_| b.add_atom(Atom::new(Element::C))).collect();
        let ring = [
            n, atoms_c[0], atoms_c[1], atoms_c[2], atoms_c[3], atoms_c[4],
        ];
        for i in 0..6 {
            let order = if i % 2 == 0 {
                BondOrder::Double
            } else {
                BondOrder::Single
            };
            b.add_bond(ring[i], ring[(i + 1) % 6], order).unwrap();
        }
        b.build()
    }

    fn furan_kekule() -> chematic_core::Molecule {
        let mut b = MoleculeBuilder::new();
        let o = b.add_atom(Atom::new(Element::O));
        let c1 = b.add_atom(Atom::new(Element::C));
        let c2 = b.add_atom(Atom::new(Element::C));
        let c3 = b.add_atom(Atom::new(Element::C));
        let c4 = b.add_atom(Atom::new(Element::C));
        let ring = [o, c1, c2, c3, c4];
        b.add_bond(ring[0], ring[1], BondOrder::Single).unwrap();
        b.add_bond(ring[1], ring[2], BondOrder::Double).unwrap();
        b.add_bond(ring[2], ring[3], BondOrder::Single).unwrap();
        b.add_bond(ring[3], ring[4], BondOrder::Double).unwrap();
        b.add_bond(ring[4], ring[0], BondOrder::Single).unwrap();
        b.build()
    }

    fn pyrrole_kekule() -> chematic_core::Molecule {
        let mut b = MoleculeBuilder::new();
        let mut n_atom = Atom::new(Element::N);
        n_atom.hydrogen_count = Some(1);
        let n = b.add_atom(n_atom);
        let c1 = b.add_atom(Atom::new(Element::C));
        let c2 = b.add_atom(Atom::new(Element::C));
        let c3 = b.add_atom(Atom::new(Element::C));
        let c4 = b.add_atom(Atom::new(Element::C));
        let ring = [n, c1, c2, c3, c4];
        b.add_bond(ring[0], ring[1], BondOrder::Single).unwrap();
        b.add_bond(ring[1], ring[2], BondOrder::Double).unwrap();
        b.add_bond(ring[2], ring[3], BondOrder::Single).unwrap();
        b.add_bond(ring[3], ring[4], BondOrder::Double).unwrap();
        b.add_bond(ring[4], ring[0], BondOrder::Single).unwrap();
        b.build()
    }

    /// Same ring as `pyrrole_kekule()`, but the N has NO explicit
    /// `hydrogen_count` — matching how the SMILES parser actually builds a
    /// bare, non-bracket `N` (e.g. from `Chem.Kekulize` + non-canonical
    /// `MolToSmiles(kekuleSmiles=True)` round-tripping an `[nH]`-written
    /// pyrrole/imidazole/purine nitrogen). `pyrrole_kekule()` above sidesteps
    /// the bug this reproduces by setting `hydrogen_count` manually.
    fn pyrrole_kekule_implicit_h() -> chematic_core::Molecule {
        let mut b = MoleculeBuilder::new();
        let n = b.add_atom(Atom::new(Element::N));
        let c1 = b.add_atom(Atom::new(Element::C));
        let c2 = b.add_atom(Atom::new(Element::C));
        let c3 = b.add_atom(Atom::new(Element::C));
        let c4 = b.add_atom(Atom::new(Element::C));
        let ring = [n, c1, c2, c3, c4];
        b.add_bond(ring[0], ring[1], BondOrder::Single).unwrap();
        b.add_bond(ring[1], ring[2], BondOrder::Double).unwrap();
        b.add_bond(ring[2], ring[3], BondOrder::Single).unwrap();
        b.add_bond(ring[3], ring[4], BondOrder::Double).unwrap();
        b.add_bond(ring[4], ring[0], BondOrder::Single).unwrap();
        b.build()
    }

    fn naphthalene_kekule() -> chematic_core::Molecule {
        let mut b = MoleculeBuilder::new();
        let atoms: Vec<_> = (0..10).map(|_| b.add_atom(Atom::new(Element::C))).collect();
        let ring1 = [0usize, 1, 2, 3, 4, 9];
        let orders1 = [
            BondOrder::Double,
            BondOrder::Single,
            BondOrder::Double,
            BondOrder::Single,
            BondOrder::Double,
            BondOrder::Single,
        ];
        for i in 0..6 {
            b.add_bond(atoms[ring1[i]], atoms[ring1[(i + 1) % 6]], orders1[i])
                .unwrap();
        }
        let ring2_extra = [(4, 5), (5, 6), (6, 7), (7, 8), (8, 9)];
        let orders2 = [
            BondOrder::Single,
            BondOrder::Double,
            BondOrder::Single,
            BondOrder::Double,
            BondOrder::Single,
        ];
        for (i, &(a, bb)) in ring2_extra.iter().enumerate() {
            b.add_bond(atoms[a], atoms[bb], orders2[i]).unwrap();
        }
        b.build()
    }

    fn cyclobutadiene_kekule() -> chematic_core::Molecule {
        let mut b = MoleculeBuilder::new();
        let atoms: Vec<_> = (0..4).map(|_| b.add_atom(Atom::new(Element::C))).collect();
        for i in 0..4 {
            let order = if i % 2 == 0 {
                BondOrder::Double
            } else {
                BondOrder::Single
            };
            b.add_bond(atoms[i], atoms[(i + 1) % 4], order).unwrap();
        }
        b.build()
    }

    fn cyclooctatetraene_kekule() -> chematic_core::Molecule {
        let mut b = MoleculeBuilder::new();
        let atoms: Vec<_> = (0..8).map(|_| b.add_atom(Atom::new(Element::C))).collect();
        for i in 0..8 {
            let order = if i % 2 == 0 {
                BondOrder::Double
            } else {
                BondOrder::Single
            };
            b.add_bond(atoms[i], atoms[(i + 1) % 8], order).unwrap();
        }
        b.build()
    }

    /// Helper: parse an aromatic SMILES and return the molecule with aromatic bonds
    /// (no kekulization).  Use for compounds where kekulization is unsupported.
    #[cfg(test)]
    fn mol_aromatic(smiles: &str) -> chematic_core::Molecule {
        chematic_smiles::parse(smiles).expect("valid SMILES")
    }

    /// Helper: parse SMILES and kekulize.  Panics if kekulization fails.
    #[cfg(test)]
    fn mol_kekulized(smiles: &str) -> chematic_core::Molecule {
        let mol = chematic_smiles::parse(smiles).expect("valid SMILES");
        let k = chematic_core::kekulize(&mol).expect("kekulizable");
        chematic_core::apply_kekule(&mol, &k)
    }

    // =========================================================================
    // Regression: kekulized single-ring aromatics (Pass 1 only, no context)
    // =========================================================================

    #[test]
    fn test_benzene_is_aromatic() {
        let mol = benzene_kekule();
        let model = assign_aromaticity(&mol);
        assert_eq!(
            model.aromatic_atom_count(),
            6,
            "all 6 benzene atoms aromatic"
        );
        for i in 0..6u32 {
            assert!(model.is_atom_aromatic(AtomIdx(i)));
        }
    }

    #[test]
    fn test_cyclohexane_not_aromatic() {
        let mol = cyclohexane();
        let model = assign_aromaticity(&mol);
        assert_eq!(model.aromatic_atom_count(), 0, "cyclohexane not aromatic");
    }

    #[test]
    fn test_pyridine_is_aromatic() {
        let mol = pyridine_kekule();
        let model = assign_aromaticity(&mol);
        assert_eq!(model.aromatic_atom_count(), 6);
    }

    #[test]
    fn test_furan_is_aromatic() {
        let mol = furan_kekule();
        let model = assign_aromaticity(&mol);
        assert_eq!(model.aromatic_atom_count(), 5);
    }

    #[test]
    fn test_pyrrole_is_aromatic() {
        let mol = pyrrole_kekule();
        let model = assign_aromaticity(&mol);
        assert_eq!(model.aromatic_atom_count(), 5);
    }

    #[test]
    fn test_apply_aromaticity_preserves_pyrrole_nh_implicit_hydrogen() {
        // Regression test: apply_aromaticity_ex() normalizes all aromatic-
        // model ring bonds to BondOrder::Aromatic, which discards the
        // Kekule Single/Double pattern that distinguishes a pyrrole-type N
        // (needs 1 implicit H) from a pyridine-type N (needs 0) once both
        // have exactly 2 aromatic-order ring bonds and no explicit bracket
        // H count. Without preserving the pre-normalization value,
        // implicit_hcount() on the perceived molecule silently returns 0
        // instead of 1 for the unsubstituted pyrrole N -- wrong molecular
        // formula/weight, and a representation-dependent divergence from
        // the same molecule parsed directly from aromatic-written SMILES
        // (where `[nH]`'s bracket H count is correct by construction).
        let mol = pyrrole_kekule_implicit_h();
        let n_idx = AtomIdx(0);
        assert_eq!(
            implicit_hcount(&mol, n_idx),
            1,
            "pre-normalization: bare N with 2 single ring bonds must show 1 implicit H"
        );

        let perceived = apply_aromaticity(&mol);
        assert!(perceived.atom(n_idx).aromatic, "ring N must be aromatic");
        assert_eq!(
            implicit_hcount(&perceived, n_idx),
            1,
            "post-apply_aromaticity: pyrrole N must still show 1 implicit H, not 0"
        );
    }

    #[test]
    fn test_apply_aromaticity_does_not_add_h_to_pyridine_type_n() {
        // Sibling check to the pyrrole regression above: a pyridine-type
        // ring N (1 ring single + 1 ring double pre-normalization, no H)
        // must NOT gain a spurious implicit H from the preservation logic --
        // its pre- and post-normalization implicit_hcount already agree
        // (both 0), so it must be left untouched.
        let mol = pyridine_kekule();
        let n_idx = AtomIdx(0);
        assert_eq!(implicit_hcount(&mol, n_idx), 0);

        let perceived = apply_aromaticity(&mol);
        assert!(perceived.atom(n_idx).aromatic);
        assert_eq!(implicit_hcount(&perceived, n_idx), 0);
        assert_eq!(
            perceived.atom(n_idx).hydrogen_count,
            None,
            "pyridine N must not gain an explicit hydrogen_count -- would force spurious bracket notation"
        );
    }

    #[test]
    fn test_naphthalene_both_rings_aromatic() {
        let mol = naphthalene_kekule();
        let model = assign_aromaticity(&mol);
        assert_eq!(
            model.aromatic_atom_count(),
            10,
            "all 10 naphthalene atoms aromatic"
        );
    }

    #[test]
    fn test_bond_aromaticity_benzene() {
        let mol = benzene_kekule();
        let model = assign_aromaticity(&mol);
        let count = mol
            .bonds()
            .filter(|(b, _)| model.is_bond_aromatic(*b))
            .count();
        assert_eq!(count, 6);
    }

    #[test]
    fn test_apply_aromaticity_benzene() {
        let mol = benzene_kekule();
        let aromatic = apply_aromaticity(&mol);
        for (_, atom) in aromatic.atoms() {
            assert!(atom.aromatic, "every benzene carbon should be aromatic");
        }
        let aromatic_bond_count = aromatic
            .bonds()
            .filter(|(_, b)| b.order == BondOrder::Aromatic)
            .count();
        assert_eq!(aromatic_bond_count, 6);
    }

    #[test]
    fn test_apply_aromaticity_cyclohexane_unchanged() {
        let mol = cyclohexane();
        let result = apply_aromaticity(&mol);
        for (_, atom) in result.atoms() {
            assert!(!atom.aromatic);
        }
        for (_, bond) in result.bonds() {
            assert_ne!(bond.order, BondOrder::Aromatic);
        }
    }

    // =========================================================================
    // Antiaromaticity
    // =========================================================================

    #[test]
    fn test_cyclobutadiene_antiaromatic() {
        let mol = cyclobutadiene_kekule();
        let model = assign_aromaticity(&mol);
        assert_eq!(
            model.aromatic_atom_count(),
            0,
            "cyclobutadiene not aromatic"
        );
        assert!(model.has_antiaromaticity(), "cyclobutadiene antiaromatic");
        assert_eq!(model.antiaromatic_rings().len(), 1);
        let classifications = model.ring_classifications();
        assert_eq!(classifications.len(), 1);
        assert_eq!(classifications[0].1, RingAromaticity::Antiaromatic);
        assert_eq!(classifications[0].2, 4);
    }

    #[test]
    fn test_cyclooctatetraene_antiaromatic() {
        let mol = cyclooctatetraene_kekule();
        let model = assign_aromaticity(&mol);
        assert_eq!(model.aromatic_atom_count(), 0, "COT not aromatic");
        assert!(model.has_antiaromaticity(), "COT antiaromatic");
        assert_eq!(model.antiaromatic_rings().len(), 1);
        let cls = &model.ring_classifications()[0];
        assert_eq!(cls.1, RingAromaticity::Antiaromatic);
        assert_eq!(cls.2, 8);
    }

    // =========================================================================
    // Ring classifications
    // =========================================================================

    #[test]
    fn test_ring_classifications_benzene() {
        let mol = benzene_kekule();
        let model = assign_aromaticity(&mol);
        let classifications = model.ring_classifications();
        assert_eq!(classifications.len(), 1);
        assert_eq!(classifications[0].1, RingAromaticity::Aromatic);
        assert_eq!(classifications[0].2, 6);
    }

    #[test]
    fn test_ring_classifications_naphthalene() {
        let mol = naphthalene_kekule();
        let model = assign_aromaticity(&mol);
        let classifications = model.ring_classifications();
        assert_eq!(classifications.len(), 2, "naphthalene has two rings");
        for (_, classification, count) in classifications {
            assert_eq!(*classification, RingAromaticity::Aromatic);
            assert_eq!(*count, 6);
        }
    }

    #[test]
    fn test_non_aromatic_cyclohexane() {
        let mol = cyclohexane();
        let model = assign_aromaticity(&mol);
        for (_, classification, _) in model.ring_classifications() {
            assert_ne!(*classification, RingAromaticity::Aromatic);
            assert_ne!(*classification, RingAromaticity::Antiaromatic);
        }
    }

    // =========================================================================
    // Electron distribution
    // =========================================================================

    #[test]
    fn test_thiophene_aromatic() {
        let mut b = MoleculeBuilder::new();
        let s = b.add_atom(Atom::new(Element::S));
        let c1 = b.add_atom(Atom::new(Element::C));
        let c2 = b.add_atom(Atom::new(Element::C));
        let c3 = b.add_atom(Atom::new(Element::C));
        let c4 = b.add_atom(Atom::new(Element::C));
        let ring = [s, c1, c2, c3, c4];
        b.add_bond(ring[0], ring[1], BondOrder::Single).unwrap();
        b.add_bond(ring[1], ring[2], BondOrder::Double).unwrap();
        b.add_bond(ring[2], ring[3], BondOrder::Single).unwrap();
        b.add_bond(ring[3], ring[4], BondOrder::Double).unwrap();
        b.add_bond(ring[4], ring[0], BondOrder::Single).unwrap();
        let mol = b.build();
        let model = assign_aromaticity(&mol);
        assert_eq!(model.aromatic_atom_count(), 5);
        assert_eq!(model.ring_classifications()[0].2, 6);
    }

    #[test]
    fn test_electron_distribution_tracking() {
        let mol = benzene_kekule();
        let model = assign_aromaticity(&mol);
        assert_eq!(model.ring_classifications()[0].2, 6, "benzene: 6 × 1π = 6");

        let mol = pyrrole_kekule();
        let model = assign_aromaticity(&mol);
        assert_eq!(
            model.ring_classifications()[0].2,
            6,
            "pyrrole: N(2π) + 4C(1π) = 6"
        );

        let mol = furan_kekule();
        let model = assign_aromaticity(&mol);
        assert_eq!(
            model.ring_classifications()[0].2,
            6,
            "furan: O(2π) + 4C(1π) = 6"
        );
    }

    // =========================================================================
    // Aromatic-SMILES input (BondOrder::Aromatic, no kekulization)
    // Verifies that assign_aromaticity works on pre-kekulization molecules.
    // =========================================================================

    #[test]
    fn test_benzene_aromatic_smiles() {
        // c1ccccc1 — parsed with BondOrder::Aromatic bonds
        let mol = mol_aromatic("c1ccccc1");
        let model = assign_aromaticity(&mol);
        assert_eq!(
            model.aromatic_atom_count(),
            6,
            "benzene from aromatic SMILES"
        );
    }

    #[test]
    fn test_naphthalene_aromatic_smiles() {
        let mol = mol_aromatic("c1ccc2ccccc2c1");
        let model = assign_aromaticity(&mol);
        assert_eq!(
            model.aromatic_atom_count(),
            10,
            "naphthalene from aromatic SMILES"
        );
    }

    #[test]
    fn test_pyridine_aromatic_smiles() {
        let mol = mol_aromatic("c1ccncc1");
        let model = assign_aromaticity(&mol);
        assert_eq!(
            model.aromatic_atom_count(),
            6,
            "pyridine from aromatic SMILES"
        );
    }

    #[test]
    fn test_furan_aromatic_smiles() {
        let mol = mol_aromatic("c1ccoc1");
        let model = assign_aromaticity(&mol);
        assert_eq!(model.aromatic_atom_count(), 5, "furan from aromatic SMILES");
    }

    #[test]
    fn test_pyrrole_aromatic_smiles() {
        // [nH] bracket atom: hydrogen_count = Some(1)
        let mol = mol_aromatic("c1cc[nH]c1");
        let model = assign_aromaticity(&mol);
        assert_eq!(
            model.aromatic_atom_count(),
            5,
            "pyrrole from aromatic SMILES"
        );
    }

    #[test]
    fn test_thiophene_aromatic_smiles() {
        let mol = mol_aromatic("c1ccsc1");
        let model = assign_aromaticity(&mol);
        assert_eq!(
            model.aromatic_atom_count(),
            5,
            "thiophene from aromatic SMILES"
        );
    }

    // =========================================================================
    // Fused-ring kekulized systems (Pass 2 propagation)
    // =========================================================================

    #[test]
    fn test_indole_aromatic() {
        // c1ccc2[nH]ccc2c1 — indole (9 atoms, 5-ring + 6-ring fused)
        let mol = mol_kekulized("c1ccc2[nH]ccc2c1");
        let model = assign_aromaticity(&mol);
        assert_eq!(
            model.aromatic_atom_count(),
            9,
            "all 9 indole atoms aromatic"
        );
    }

    #[test]
    fn test_benzimidazole_aromatic() {
        // Two N atoms in fused 5+6 ring system
        let mol = mol_kekulized("c1ccc2[nH]cnc2c1");
        let model = assign_aromaticity(&mol);
        assert_eq!(model.aromatic_atom_count(), 9, "all 9 benzimidazole atoms");
    }

    #[test]
    fn test_quinoline_aromatic() {
        let mol = mol_kekulized("c1ccc2ncccc2c1");
        let model = assign_aromaticity(&mol);
        assert_eq!(model.aromatic_atom_count(), 10, "all 10 quinoline atoms");
    }

    #[test]
    fn test_acridine_aromatic() {
        // 3 fused 6-membered rings, central N: 13 atoms
        let mol = mol_kekulized("c1ccc2nc3ccccc3cc2c1");
        let model = assign_aromaticity(&mol);
        // acridine is C13H9N → 14 heavy atoms (13 C + 1 N), all aromatic
        assert_eq!(model.aromatic_atom_count(), 14, "all 14 acridine atoms");
    }

    // =========================================================================
    // Fused-ring aromatic-SMILES input (BondOrder::Aromatic, kekulize fails)
    // =========================================================================

    #[test]
    fn test_indolizine_aromatic() {
        // c1ccn2cccc2c1 — indolizine: bridgehead N, kekulization unsupported.
        // The SSSR finds a 6-ring and a 9-ring; the 5-ring is recovered via
        // augmentation (XOR of 6- and 9-ring).
        // Pass 1: 5-ring (augmented) detected via bridgehead-N rule → 6π.
        // Pass 2: 6-ring detected using N already aromatic from 5-ring → 6π.
        // The 9-ring (SSSR artifact) is NonAromatic (9π ≠ 4n+2), but all
        // 9 atoms are correctly flagged aromatic via the 5- and 6-ring.
        let mol = mol_aromatic("c1ccn2cccc2c1");
        let model = assign_aromaticity(&mol);
        assert_eq!(
            model.aromatic_atom_count(),
            9,
            "all 9 indolizine atoms aromatic"
        );
        // At least the 6-ring should be classified as Aromatic in the SSSR set.
        let has_aromatic_ring = model
            .ring_classifications()
            .iter()
            .any(|(_, cls, _)| *cls == RingAromaticity::Aromatic);
        assert!(has_aromatic_ring, "at least one SSSR ring aromatic");
    }

    #[test]
    #[ignore = "PROVISIONAL: regressed by the Horton SSSR fix, see comment below"]
    fn test_purine_aromatic() {
        // c1cnc2[nH]cnc2n1 — purine: 9 atoms, kekulizable
        //
        // Regressed by the Horton SSSR rewrite (confirmed passing on the old
        // single-spanning-tree find_sssr, failing only after Horton; see
        // debug dump captured during diagnosis). Root cause, empirically
        // confirmed: the 6-membered ring (pyrimidine-type) passes Pass 1
        // alone (6π) and marks its atoms aromatic. The 5-membered ring
        // (imidazole-type) evaluates to 4π in isolation — its two fusion
        // carbons each have their only double bond exocyclic to a ring N,
        // which the exocyclic-to-heteroatom rule scores as 0π — and 4π trips
        // `classify_ring_aromaticity`'s "4n → Antiaromatic" branch. Pass 1
        // treats Antiaromatic as definitive and never retries it in Pass 2,
        // even though the fusion carbons would each contribute 1π (not 0π)
        // once `aromatic_context` recognizes them as already-aromatic — that
        // recount gives 6π (aromatic). The old, non-minimal SSSR never hit
        // this path because it fed a different (structurally wrong) ring set
        // into Pass 1 in the first place.
        //
        // Fix belongs in the aromatic_context-removal PR (see
        // greedy-hopping-crescent.md step 5), not here: retrying
        // Antiaromatic rings in Pass 2 is a real fix, but must not be
        // bundled into the SSSR PR per the "measure free recoveries with
        // zero aromaticity.rs changes" staging requirement.
        let mol = mol_kekulized("c1cnc2[nH]cnc2n1");
        let model = assign_aromaticity(&mol);
        assert_eq!(
            model.aromatic_atom_count(),
            9,
            "all 9 purine atoms aromatic"
        );
    }

    #[test]
    fn test_purine_aromatic_from_aromatic_smiles() {
        let mol = mol_aromatic("c1cnc2[nH]cnc2n1");
        let model = assign_aromaticity(&mol);
        assert_eq!(
            model.aromatic_atom_count(),
            9,
            "purine from aromatic SMILES"
        );
    }

    #[test]
    fn test_2_pyridinone_aromatic() {
        // O=c1ccncc1 — 2-pyridinone (aromatic SMILES, N without H, exo C=O).
        // Kekulization fails; tested on the aromatic-bond form directly.
        // The exo C=O gives the C atom has_double_any=true → 1π.
        // N has Aromatic bonds in ring → 1π (pyridine-like).
        // Total: 6 × 1π = 6π → aromatic.
        let mol = mol_aromatic("O=c1ccncc1");
        let model = assign_aromaticity(&mol);
        assert_eq!(
            model.aromatic_atom_count(),
            6,
            "all 6 ring atoms of 2-pyridinone aromatic"
        );
    }

    #[test]
    fn test_quinolone_aromatic() {
        // O=c1ccc2ncccc2c1 — quinolone: fused 6+6 with exo C=O, kekulize fails
        let mol = mol_aromatic("O=c1ccc2ncccc2c1");
        let model = assign_aromaticity(&mol);
        assert_eq!(
            model.aromatic_atom_count(),
            10,
            "all 10 quinolone ring atoms aromatic"
        );
        assert_eq!(
            model.ring_classifications().len(),
            2,
            "two rings classified"
        );
    }

    #[test]
    fn test_indole_aromatic_smiles() {
        let mol = mol_aromatic("c1ccc2[nH]ccc2c1");
        let model = assign_aromaticity(&mol);
        assert_eq!(
            model.aromatic_atom_count(),
            9,
            "indole from aromatic SMILES"
        );
    }

    // =========================================================================
    // Bridgehead N rule: specifically test that the rule fires correctly
    // =========================================================================

    #[test]
    fn test_bridgehead_n_contributes_lone_pair() {
        // Indolizine: the bridgehead N (degree 3, no H, no explicit double bond)
        // must be detected as a 2π contributor for the 5-membered ring.
        // We verify by checking the 5-ring classification (if accessible).
        let mol = mol_aromatic("c1ccn2cccc2c1");
        let model = assign_aromaticity(&mol);
        // All 9 atoms aromatic: both rings must be aromatic.
        assert_eq!(model.aromatic_atom_count(), 9);
        // The bridgehead N itself must be in the aromatic set.
        // In the SMILES c1ccn2cccc2c1, n is atom index 3.
        assert!(
            model.is_atom_aromatic(AtomIdx(3)),
            "bridgehead N must be aromatic"
        );
    }

    #[test]
    fn test_non_bridgehead_n_no_false_positive() {
        // Pyrimidine: two N atoms in a 6-membered ring, no bridgehead.
        // Both N have ring_degree == total_degree == 2.
        // Should be detected as aromatic via has_aromatic_in_ring (Aromatic bonds).
        let mol = mol_aromatic("c1ccncn1");
        let model = assign_aromaticity(&mol);
        assert_eq!(model.aromatic_atom_count(), 6, "pyrimidine is aromatic");
    }

    #[test]
    fn test_imidazole_aromatic() {
        // c1cn[nH]c1 / c1c[nH]cn1 — imidazole: one pyridine-type N, one pyrrole-type N
        let mol = mol_aromatic("c1cn[nH]c1");
        let model = assign_aromaticity(&mol);
        assert_eq!(model.aromatic_atom_count(), 5, "imidazole is aromatic");
    }

    // =========================================================================
    // Pass 2 specifically: rings that need fused-ring context
    // =========================================================================

    #[test]
    fn test_pass2_needed_for_indolizine_6ring() {
        // The augmented 5-ring (XOR of SSSR 6-ring and 9-ring) is detected aromatic in Pass 1.
        // The SSSR 6-ring is then detected aromatic in Pass 2 (N already aromatic → 1π).
        // The SSSR 9-ring (9π) remains NonAromatic per Hückel.
        // Key assertion: all 9 atoms are aromatic (correct overall perception).
        let mol = mol_aromatic("c1ccn2cccc2c1");
        let model = assign_aromaticity(&mol);
        assert_eq!(
            model.aromatic_atom_count(),
            9,
            "all 9 indolizine atoms aromatic"
        );
        // The bridgehead N must be aromatic.
        assert!(
            model.is_atom_aromatic(AtomIdx(3)),
            "bridgehead N is aromatic"
        );
        // The 6-ring (SSSR ring, improved by Pass 2) should be classified Aromatic.
        let aromatic_count = model
            .ring_classifications()
            .iter()
            .filter(|(_, cls, _)| *cls == RingAromaticity::Aromatic)
            .count();
        assert!(aromatic_count >= 1, "at least one SSSR ring is aromatic");
    }

    #[test]
    fn test_no_pass2_needed_for_naphthalene() {
        // Naphthalene: both rings pass independently in Pass 1.
        // Verifies Pass 2 doesn't break things that already work.
        let mol = naphthalene_kekule();
        let model = assign_aromaticity(&mol);
        assert_eq!(model.aromatic_atom_count(), 10);
        let classes = model.ring_classifications();
        assert_eq!(classes.len(), 2);
        for (_, cls, _) in classes {
            assert_eq!(*cls, RingAromaticity::Aromatic);
        }
    }

    #[test]
    fn test_anthracene_aromatic() {
        // c1ccc2cc3ccccc3cc2c1 — anthracene: 3 linearly fused 6-rings, 14 atoms
        let mol = mol_kekulized("c1ccc2cc3ccccc3cc2c1");
        let model = assign_aromaticity(&mol);
        assert_eq!(model.aromatic_atom_count(), 14, "all 14 anthracene atoms");
    }

    // =========================================================================
    // Regression: aromatic-bond path must not perturb kekulized correctness
    // =========================================================================

    #[test]
    fn test_kekulized_path_unaffected_by_aromatic_bond_changes() {
        // Kekulized benzene: bonds are Double/Single, not Aromatic.
        // The new Aromatic-bond branches must stay dormant.
        let mol = benzene_kekule();
        // Verify no aromatic bonds in input.
        for (_, bond) in mol.bonds() {
            assert_ne!(bond.order, BondOrder::Aromatic, "input must be kekulized");
        }
        let model = assign_aromaticity(&mol);
        assert_eq!(model.aromatic_atom_count(), 6);
        // All 6 bonds in benzene ring should be aromatic.
        let aromatic_bonds = mol
            .bonds()
            .filter(|(b, _)| model.is_bond_aromatic(*b))
            .count();
        assert_eq!(aromatic_bonds, 6);
    }

    #[test]
    fn test_keto_pyridinone_aromatic() {
        // O=C1NC=CC=C1 — 2-pyridinone keto form with N-H.
        // π count: C(=O)(0π, exocyclic-only double bond to O) + N-H(2π) +
        // 4×C in 2 ring C=C (1π each) = 6π → aromatic. Matches RDKit, which
        // marks all 6 ring atoms aromatic (exocyclic O stays non-aromatic).
        let mol = mol_kekulized("O=C1NC=CC=C1");
        let model = assign_aromaticity(&mol);
        assert_eq!(
            model.aromatic_atom_count(),
            6,
            "keto pyridinone ring is Hückel aromatic (6π = 4n+2)"
        );
    }

    #[test]
    fn test_tropone_aromatic() {
        // O=C1C=CC=CC=C1 — tropone (cycloheptatrienone), Kekulized input.
        // Carbonyl C contributes 0π (exocyclic-only double bond to O); the
        // other 6 ring carbons contribute 1π each from 3 endocyclic C=C.
        // Total 6π → aromatic, matching RDKit (all 7 ring atoms aromatic).
        let mol = mol_kekulized("O=C1C=CC=CC=C1");
        let model = assign_aromaticity(&mol);
        assert_eq!(
            model.aromatic_atom_count(),
            7,
            "all 7 tropone ring atoms aromatic"
        );
    }

    #[test]
    fn test_4_pyridone_aromatic() {
        // O=C1C=CNC=C1 — 4-pyridone, Kekulized input. Same 6π accounting as
        // 2-pyridone, just with N para to the carbonyl. Matches RDKit.
        let mol = mol_kekulized("O=C1C=CNC=C1");
        let model = assign_aromaticity(&mol);
        assert_eq!(
            model.aromatic_atom_count(),
            6,
            "all 6 4-pyridone ring atoms aromatic"
        );
    }

    #[test]
    fn test_pyranone_aromatic() {
        // O=C1C=COC=C1 — 4H-pyran-4-one, Kekulized input. Ring O contributes
        // 2π (lone pair), carbonyl C contributes 0π, remaining 4 ring carbons
        // contribute 1π each from 2 endocyclic C=C. Total 6π. Matches RDKit.
        let mol = mol_kekulized("O=C1C=COC=C1");
        let model = assign_aromaticity(&mol);
        assert_eq!(
            model.aromatic_atom_count(),
            6,
            "all 6 pyranone ring atoms aromatic"
        );
    }

    #[test]
    fn test_cyclopentadienyl_anion_aromatic() {
        // [CH-]1C=CC=C1 — cyclopentadienyl anion. The carbanion carbon has no
        // double bond but contributes 2π (lone pair); the other 4 carbons
        // contribute 1π each from 2 endocyclic C=C. Total 6π. Matches RDKit
        // (all 5 atoms aromatic).
        let mol = mol_kekulized("[CH-]1C=CC=C1");
        let model = assign_aromaticity(&mol);
        assert_eq!(
            model.aromatic_atom_count(),
            5,
            "all 5 cyclopentadienyl anion atoms aromatic"
        );
    }

    // ── N-substituted pyrrole-type N: bridgehead-branch guard removal ────────
    //
    // The bridgehead-N branch used to require the exocyclic substituent to be
    // sp2, to defensively block imide N (phthalimide). That guard also
    // blocked the much more common case of a plain alkyl/aryl/sugar
    // substituent on an otherwise-aromatic pyrrole-type N. It was removed;
    // these tests cover both the newly-fixed cases and the phthalimide
    // regression it was guarding against (which stays correct via the
    // overall 4n+2 sum, not the substituent).

    #[test]
    fn test_n_methylpyrrole_aromatic() {
        let mol = mol_kekulized("CN1C=CC=C1");
        let model = assign_aromaticity(&mol);
        assert_eq!(
            model.aromatic_atom_count(),
            5,
            "all 5 N-methylpyrrole ring atoms aromatic"
        );
    }

    #[test]
    fn test_n_methylimidazole_aromatic() {
        let mol = mol_kekulized("CN1C=CN=C1");
        let model = assign_aromaticity(&mol);
        assert_eq!(
            model.aromatic_atom_count(),
            5,
            "all 5 N-methylimidazole ring atoms aromatic"
        );
    }

    #[test]
    fn test_n_methylindole_aromatic() {
        let mol = mol_kekulized("CN1C=CC2=CC=CC=C21");
        let model = assign_aromaticity(&mol);
        assert_eq!(
            model.aromatic_atom_count(),
            9,
            "all 9 N-methylindole ring atoms aromatic"
        );
    }

    #[test]
    fn test_9_methylpurine_aromatic() {
        let mol = mol_kekulized("CN1C=NC2=NC=NC=C21");
        let model = assign_aromaticity(&mol);
        assert_eq!(
            model.aromatic_atom_count(),
            9,
            "all 9 9-methylpurine ring atoms aromatic"
        );
    }

    #[test]
    fn test_phthalimide_5ring_not_aromatic() {
        // O=C1NC(=O)c2ccccc21 — only the fused benzo ring is aromatic (6
        // atoms); the imide 5-ring (2 carbonyl C + N) is not: carbonyl
        // carbons contribute 0π each (exocyclic C=O rule), N contributes 2π,
        // the two ring-fusion carbons contribute 1π each — 4π total, not
        // 4n+2. Regression guard for the bridgehead-N guard removal above.
        let mol = mol_kekulized("O=C1NC(=O)c2ccccc21");
        let model = assign_aromaticity(&mol);
        assert_eq!(
            model.aromatic_atom_count(),
            6,
            "only the 6 benzo atoms of phthalimide are aromatic"
        );
    }

    #[test]
    fn test_n_methylphthalimide_5ring_not_aromatic() {
        // O=C1N(C)C(=O)c2ccccc21 — same as phthalimide but N-methylated;
        // same accounting applies (N still contributes 2π regardless of
        // substituent), 5-ring still non-aromatic.
        let mol = mol_kekulized("O=C1N(C)C(=O)c2ccccc21");
        let model = assign_aromaticity(&mol);
        assert_eq!(
            model.aromatic_atom_count(),
            6,
            "only the 6 benzo atoms of N-methylphthalimide are aromatic"
        );
    }

    #[test]
    #[ignore = "PROVISIONAL: regressed by the Horton SSSR fix, see comment below"]
    fn test_azulene_kekulized_aromatic() {
        // C1=CC2=CC=CC=CC2=C1 — non-alternant fused bicyclic, all 10 atoms
        // aromatic per RDKit. Regression coverage: this was previously
        // (incorrectly) believed to need a ring-system rewrite, based on a
        // test that never called apply_aromaticity() on Kekulized input.
        //
        // Regressed by the Horton SSSR rewrite (confirmed passing on the old
        // single-spanning-tree find_sssr, failing only after Horton). Root
        // cause, empirically confirmed via debug dump: Horton's correct,
        // minimal SSSR is exactly the 5-ring + 7-ring (matches RDKit). Each
        // evaluated standalone has an ODD pi-electron count (5-ring: 5pi,
        // 7-ring: 7pi — every ring atom contributes 1pi via a double bond,
        // whether the double bond is endo- or exocyclic-to-a-carbon), so
        // neither passes Pass 1 and neither can seed Pass 2's
        // aromatic_context bootstrap. Azulene's aromaticity is a genuinely
        // non-alternant, whole-perimeter (10-atom, 10pi) delocalized system
        // — it needs the full-ring-system envelope as a Hückel candidate,
        // which `augmented_ring_set` deliberately excludes (its docstring
        // names naphthalene's spurious 10-ring as the exact case to avoid).
        // The old, non-minimal SSSR happened to hand a large fundamental
        // cycle straight to Pass 1 that included the whole perimeter,
        // papering over this gap by coincidence.
        //
        // Fix belongs in the aromatic_context-removal PR (see
        // greedy-hopping-crescent.md step 5: "candidate rings = SSSR ∪ fused
        // envelopes"), not here — adding an envelope-candidate fallback in
        // this PR would be compensating code that step 5's fixed-point
        // ring-system evaluation subsumes and would need to delete anyway.
        let mol = mol_kekulized("C1=CC2=CC=CC=CC2=C1");
        let model = assign_aromaticity(&mol);
        assert_eq!(
            model.aromatic_atom_count(),
            10,
            "all 10 azulene atoms aromatic"
        );
    }

    // ── RDKit #9271: charged / zwitterionic aromatic systems ─────────────────

    #[test]
    fn test_fluorescein_dianion_aromatic() {
        // Fluorescein dianion: RDKit #9271 incorrectly marked xanthene bonds as
        // single instead of aromatic. Verify chematic parses and identifies
        // aromatic atoms correctly (two benzene rings + xanthene O-bridge ring).
        // Kekulé-form SMILES: all atoms uppercase.
        let smi = "C1=CC=C(C(=C1)C2=C3C=CC(=O)C=C3OC4=C2C=CC(=C4)[O-])C(=O)[O-]";
        let mol = chematic_smiles::parse(smi).expect("fluorescein dianion should parse");
        // The molecule should parse without panic. Verify aromatic ring count:
        // fluorescein has 3 aromatic rings (2 benzene + xanthene core).
        let arc = count_aromatic_rings(&mol);
        assert!(
            arc >= 2,
            "fluorescein dianion: expected ≥2 aromatic rings, got {arc} \
             (RDKit #9271: charged aromatics may be misclassified)"
        );
    }

    #[test]
    fn test_rhodamine_zwitterion_parses() {
        // Rhodamine-type zwitterion with N+ and bridging O (RDKit #9271).
        // Must parse cleanly and produce a valid aromatic ring count.
        let smi = "CCN(CC)c1ccc2c(-c3ccccc3C(=O)O)c3ccc(=[N+](CC)CC)cc-3oc2c1";
        let mol = chematic_smiles::parse(smi).expect("rhodamine zwitterion should parse");
        let arc = count_aromatic_rings(&mol);
        assert!(arc >= 3, "rhodamine: expected ≥3 aromatic rings, got {arc}");
    }

    #[test]
    fn test_cyclopentadienyl_not_aromatic_kekulized() {
        // C1=CC=CC1 — cyclopentadiene (4 C with doubles + 1 sp3 CH2): not aromatic.
        let mut b = MoleculeBuilder::new();
        let c0 = b.add_atom(Atom::new(Element::C)); // sp3
        let c1 = b.add_atom(Atom::new(Element::C));
        let c2 = b.add_atom(Atom::new(Element::C));
        let c3 = b.add_atom(Atom::new(Element::C));
        let c4 = b.add_atom(Atom::new(Element::C));
        b.add_bond(c0, c1, BondOrder::Single).unwrap();
        b.add_bond(c1, c2, BondOrder::Double).unwrap();
        b.add_bond(c2, c3, BondOrder::Single).unwrap();
        b.add_bond(c3, c4, BondOrder::Double).unwrap();
        b.add_bond(c4, c0, BondOrder::Single).unwrap();
        let mol = b.build();
        let model = assign_aromaticity(&mol);
        assert_eq!(
            model.aromatic_atom_count(),
            0,
            "cyclopentadiene not aromatic"
        );
    }

    // =========================================================================
    // RdkitLike mode: Se/Te chalcogen heteroaromatics
    // =========================================================================

    #[test]
    fn test_selenophene_huckel_not_aromatic() {
        // c1cc[se]c1 — in strict Hückel mode, Se is unsupported → 0 aromatic atoms
        // (assign_aromaticity_ex re-derives from scratch, ignoring parser's aromatic flags)
        let mol = mol_aromatic("c1cc[se]c1");
        let m = assign_aromaticity(&mol); // default Hückel
        assert_eq!(
            m.aromatic_atom_count(),
            0,
            "selenophene: Se not aromatic in Hückel mode"
        );
    }

    #[test]
    fn test_selenophene_rdkit_aromatic() {
        // c1cc[se]c1 — in RdkitLike mode, Se donates 2π → 6π total → aromatic
        let mol = mol_aromatic("c1cc[se]c1");
        let m = assign_aromaticity_ex(&mol, AromaticityAlgorithm::RdkitLike);
        assert_eq!(
            m.aromatic_atom_count(),
            5,
            "selenophene: all 5 atoms aromatic in RdkitLike"
        );
    }

    #[test]
    fn test_tellurophene_rdkit_aromatic() {
        // c1cc[te]c1 — Te analogous to Se (2π donor)
        let mol = mol_aromatic("c1cc[te]c1");
        let m = assign_aromaticity_ex(&mol, AromaticityAlgorithm::RdkitLike);
        assert_eq!(
            m.aromatic_atom_count(),
            5,
            "tellurophene: all 5 atoms aromatic in RdkitLike"
        );
    }

    #[test]
    fn test_benzoselenophene_rdkit() {
        // Fused benzene + selenophene
        let mol = mol_aromatic("c1ccc2[se]ccc2c1");
        let m = assign_aromaticity_ex(&mol, AromaticityAlgorithm::RdkitLike);
        assert_eq!(
            m.aromatic_atom_count(),
            9,
            "benzoselenophene: 9 atoms aromatic"
        );
    }

    #[test]
    fn test_rdkit_mode_does_not_break_benzene() {
        // Benzene must give same result in both modes
        let mol = mol_aromatic("c1ccccc1");
        let m_h = assign_aromaticity(&mol);
        let m_r = assign_aromaticity_ex(&mol, AromaticityAlgorithm::RdkitLike);
        assert_eq!(m_h.aromatic_atom_count(), m_r.aromatic_atom_count());
    }

    #[test]
    fn test_rdkit_mode_does_not_break_thiophene() {
        let mol = mol_aromatic("c1ccsc1");
        let m_h = assign_aromaticity(&mol);
        let m_r = assign_aromaticity_ex(&mol, AromaticityAlgorithm::RdkitLike);
        assert_eq!(
            m_h.aromatic_atom_count(),
            m_r.aromatic_atom_count(),
            "thiophene same in both modes"
        );
    }

    // ── Known regressions from fix #2 (bridgehead-N guard removal) ──────────
    //
    // Re-measured after the Horton SSSR rewrite landed (find_sssr is now
    // minimal and deterministic, 0% self-instability on the 5000-molecule
    // corpus): all 32 counts below are UNCHANGED. Zero free recoveries.
    // This confirms these regressions are caused entirely by the
    // `aromatic_context` bypass, independent of SSSR ring selection -- the
    // two bugs don't interact for this molecule class.
    //
    // These 32 molecules share one root cause: a "fake bridgehead" N (same
    // local shape as a genuine bridgehead or N-substituted azole) feeds a
    // central ring that only closes via the `aromatic_context` bypass reusing
    // an unrelated ring's atoms. Fixing this requires removing the bypass in
    // favor of proper ring-system candidate enumeration (see project plan/
    // issue tracker). Pinned here as *known-wrong* so the eventual fix is
    // measurable by how many of these flip from this assertion to correct,
    // not just by an aggregate corpus percentage.
    // (kekulized SMILES, current chematic aromatic_atom_count(), RDKit's correct count).
    // Named at module level (not a local in the test below) so
    // Aromaticity-A1-0's corpus tests, further down this module, can reuse
    // the identical pinned data instead of re-deriving a copy that could
    // silently drift out of sync with it.
    const KNOWN_BRIDGEHEAD_N_FALSE_POSITIVES: &[(&str, usize, usize)] = &[
        ("C[Si](C)(C)C1=CC=C(C2=CC3=CC=CC=C3C3=NCCCN23)C=C1", 16, 12),
        (
            "C1=C(C2=CC=C(CCC3=CC=CC=C3)C=C2)N2CCCN=C2C2=CC=CC=C12",
            22,
            18,
        ),
        ("ClC1=CC=C(OCC2=CC3=CC=CC=C3C3=NCCCN23)C=C1", 16, 12),
        ("N[C@@H](CC1=CC=CC=C1)C1=CC2=CC=CC=C2C2=NCCCN12", 16, 12),
        (
            "CC(C)(C)C1=CC=C(C2=C(CC3=CC=CC=C3)C3=CC=CC=C3C3=NCCCN32)C=C1",
            22,
            18,
        ),
        (
            "C[Si](C)(C)C1=CC=C(C2=C(CC3=CC=CC=C3)C3=CC=CC=C3C3=NCCCN32)C=C1",
            22,
            18,
        ),
        (
            "C1=C(C2=CC=C(C3=CC=CC=C3)C=C2)N2CCCN=C2C2=CC=CC=C12",
            22,
            18,
        ),
        (
            "C1=C(C2=CC=C(OCC3=CC=CC=C3)C=C2)N2CCCN=C2C2=CC=CC=C12",
            22,
            18,
        ),
        ("COC1=C(OC)C(OC)=CC(C2=CC3=CC=CC=C3C3=NCCCN23)=C1", 16, 12),
        ("CC1=CC2=CC=CC=C2C2=NCCCN12", 10, 6),
        (
            "CC(C)(C)C1=CC=C(C2=CC3=C(C=C(NC(=O)NC4CCCCC4)C=C3)C3=NCCCN23)C=C1",
            16,
            12,
        ),
        (
            "C1=CC=C(CCC2=CC=C(C3=C(CC4=CC=CC=C4)C4=CC=CC=C4C4=NCCCN43)C=C2)C=C1",
            28,
            24,
        ),
        (
            "CCCCC1=C(C2=CC=C(CCC3=CC=CC=C3)C=C2)N2CCCN=C2C2=CC=CC=C12",
            22,
            18,
        ),
        (
            "CCCCC1=C(C2=CC=C(C(C)(C)C)C=C2)N2CCCN=C2C2=CC=CC=C12",
            16,
            12,
        ),
        ("CCCCCCC1=CC2=CC=CC=C2C2=NCCCN12", 10, 6),
        (
            "CCOC1=CC=C(CC2=C(CCCC3=CC=CC4=CC=CC=C34)N3CCCN=C3C3=CC=CC=C23)C=C1",
            26,
            22,
        ),
        (
            "CCOC1=CC=C(CC2=C(C3=CC=C(CCC4=CC=CC=C4)C=C3)N3CCCN=C3C3=CC=CC=C23)C=C1",
            28,
            24,
        ),
        (
            "CN(C)CCC1=C(C2=CC=C(C(C)(C)C)C=C2)N2CCCN=C2C2=CC=CC=C12",
            16,
            12,
        ),
        (
            "CC(C)(C)C1=CC=C(C2=CC3=C(C=C(N/C(S)=N/C4CCCCC4)C=C3)C3=NCCCN23)C=C1",
            16,
            12,
        ),
        ("C1=C(/C=C/C2=CC=CC=C2)N2CCCN=C2C2=CC=CC=C12", 16, 12),
        ("CC(C)(C)C1=CC=C(C2=CC3=CC=CC=C3C3=NCCCN23)C=C1", 16, 12),
        (
            "CC(C)(C)C1=CC=C(C2=CC3=C(C=C(NC(=O)CC4=CC=CC=N4)C=C3)C3=NCCCN23)C=C1",
            22,
            18,
        ),
        (
            "CC(C)(C)C1=CC=C(C2=CC3=C(C=C(NC(=O)NC4=C(Cl)C=C(Cl)C=C4)C=C3)C3=NCCCN23)C=C1",
            22,
            18,
        ),
        ("C1=C(CC2=CC=CC=C2)C2=CC=CC=C2C2=NCCCN12", 16, 12),
        ("ClC1=CC=C(C2=CC3=CC=CC=C3C3=NCCCN23)C=C1", 16, 12),
        ("C1=C(C2=CC=CC=C2)N2CCCN=C2C2=CC=CC=C12", 16, 12),
        (
            "CC(C)(C)C1=CC=C(C2=CC3=C(C=C(N(CC4=CC=CC=C4)CC4=CC=CC=C4)C=C3)C3=NCCCN23)C=C1",
            28,
            24,
        ),
        (
            "CC(C)(C)C1=CC=C(C2=CC3=C(C=C(N)C=C3)C3=NCCCN23)C=C1",
            16,
            12,
        ),
        ("CC1=C2C(=NC=C1)N(C1CC1)C1=NC=CC=C1C(=O)N2C", 15, 12),
        ("CC(=O)N1C2=NC=CC=C2C(=O)N(C)C2=CC=CN=C21", 15, 12),
        ("CN1C(=O)C2=CC=CN=C2N(C(C)(C)C)C2=NC=CC=C21", 15, 12),
        ("CCCN1C2=NC=CC=C2C(=O)N(C)C2=CC=CN=C21", 15, 12),
    ];

    #[test]
    fn test_known_regressions_from_bridgehead_n_fix() {
        for (smi, expected_wrong, rdkit_correct) in KNOWN_BRIDGEHEAD_N_FALSE_POSITIVES {
            let mol = mol_kekulized(smi);
            let model = assign_aromaticity(&mol);
            assert_eq!(
                model.aromatic_atom_count(),
                *expected_wrong,
                "{smi}: expected current (wrong) count {expected_wrong} (RDKit correct: {rdkit_correct})"
            );
        }
    }

    // ── Known order-dependence: same molecule, different Kekulized traversal ─
    //
    // Originally found because these 3 molecules passed with RDKit's
    // canonical Kekulized SMILES but failed with at least one other valid
    // Kekulized ordering of the identical structure -- confirmed via
    // atom-map-number alignment (no substructure matching). Root cause was
    // NOT Pass 1/Pass 2 (verified order-invariant by construction) -- it was
    // `find_sssr` itself, non-deterministic and non-minimal.
    //
    // Re-measured after the Horton SSSR rewrite (find_sssr is now
    // deterministic and minimal, 0% self-instability on the 5000-molecule
    // corpus): the 3 pinned failing-traversal counts below are UNCHANGED.
    // The original order-dependence *mechanism* (find_sssr picking a
    // different non-minimal ring depending on traversal) is resolved -- but
    // these 3 specific SMILES still disagree with RDKit's count, so at least
    // one more bug (likely `aromatic_context`, same as the 32-molecule
    // corpus above) also affects this molecule class. Not re-diagnosed here;
    // a fresh worst-of-N run against the full corpus would confirm whether
    // order-dependence itself (canonical vs. this pinned variant disagreeing
    // with each other) is now fully gone, separate from RDKit agreement.
    // Named at module level for the same reason as
    // `KNOWN_BRIDGEHEAD_N_FALSE_POSITIVES` above -- Aromaticity-A1-0's corpus
    // tests reuse this exact pinned data instead of a second copy.
    const KNOWN_ORDER_DEPENDENT_FALSE_NEGATIVES: &[(&str, usize, usize)] = &[
        (
            "N1=C2C(N(CC(O)=O)C(=O)N=C2N(C2C=C(C(F)(F)F)C=C(C=2)C(F)(F)F)C2C1=CC=CC=2)=O",
            16,
            20,
        ),
        (
            "[C@H]12N(C([C@H](NC(=O)[C@H]([C@H](OC(=O)[C@@H](N(C)C(CN(C)C1=O)=O)C(C)C)C)NC(=O)C1C=C(OC)C(C)=C3OC4=C(C)C(=O)C(=C(C4=NC=13)C(=O)N[C@H]1C(=O)N[C@@H](C(C)C)C(N3[C@H](C(=O)N(CC(N([C@H](C(C)C)C(O[C@H]1C)=O)C)=O)C)CCC3)=O)N)C(C)C)=O)CCC2",
            6,
            14,
        ),
        ("C12N(C3C=CC=CC=3)C3=NC(=O)N(C)C(C3=NC1=CC=CC=2)=O", 16, 20),
    ];

    #[test]
    fn test_known_order_dependent_regressions() {
        for (smi, expected_wrong, rdkit_correct) in KNOWN_ORDER_DEPENDENT_FALSE_NEGATIVES {
            let mol = mol_kekulized(smi);
            let model = assign_aromaticity(&mol);
            assert_eq!(
                model.aromatic_atom_count(),
                *expected_wrong,
                "{smi}: expected current (wrong) count {expected_wrong} (RDKit correct: {rdkit_correct})"
            );
        }
    }

    // ── Aromaticity-A1-0: anti-drift guard for `trace_ring_pi_electrons` ────
    //
    // `trace_ring_pi_electrons` is a deliberately separate implementation
    // from `ring_pi_electrons` (see the doc comment above it) so it can
    // report *why* each atom scored what it did. That separateness is a
    // drift risk: nothing stops the two from silently diverging as either
    // one is edited. This test is the guard -- for every ring in every
    // molecule of the known false-positive/false-negative/negative-control
    // corpus (the same molecules `docs/aromaticity_a1_rfc.md`'s diagnostic
    // corpus uses), both functions must agree exactly, in both an empty
    // context (Pass-1-equivalent) and the model's final converged context
    // (an upper-bound Pass-2-equivalent). This does not assert anything
    // about correctness vs RDKit -- only that the trace and the real engine
    // never disagree with each other.
    #[test]
    fn trace_matches_ring_pi_electrons_on_corpus() {
        let smiles: Vec<&str> = KNOWN_BRIDGEHEAD_N_FALSE_POSITIVES
            .iter()
            .map(|(smi, _, _)| *smi)
            .chain(
                KNOWN_ORDER_DEPENDENT_FALSE_NEGATIVES
                    .iter()
                    .map(|(smi, _, _)| *smi),
            )
            .chain([
                "C1=CC2=CC=CC=CC2=C1",    // azulene (Kekulized) -- known false negative
                "c1cnc2[nH]cnc2n1",       // purine -- known false negative
                "C1=Cc2ccccc2C2=NCCCN12", // PR #86 minimal false-positive reproducer
                "C1=Cc2ccccc2C2=CCCC12",  // negative control: no bridgehead N
                "C1=Cc2ccccc2C2=CCNC12",  // negative control: N not at bridgehead
                "C1Cc2ccccc2C2=NCCCN12",  // negative control: bridgehead N, no exocyclic C=C
                "c1ccc2[nH]ccc2c1",       // indole -- must stay correct
                "c1ccc2ncccc2c1",         // quinoline -- must stay correct
                "c1ccc2ccccc2c1",         // naphthalene -- must stay correct
            ])
            .collect();

        for algo in [
            AromaticityAlgorithm::Huckel,
            AromaticityAlgorithm::RdkitLike,
        ] {
            for smi in &smiles {
                let mol = mol_kekulized(smi);
                let model = assign_aromaticity_ex(&mol, algo);
                let final_context: FxHashSet<AtomIdx> = mol
                    .atoms()
                    .map(|(idx, _)| idx)
                    .filter(|&idx| model.is_atom_aromatic(idx))
                    .collect();

                let sssr = find_sssr(&mol);
                let rings = augmented_ring_set(&mol, sssr.rings());
                let empty_context: FxHashSet<AtomIdx> = FxHashSet::default();

                for ring in &rings {
                    for ctx in [&empty_context, &final_context] {
                        let expected = ring_pi_electrons(&mol, ring, ctx, algo);
                        let traced = trace_ring_pi_electrons(&mol, ring, ctx, algo);
                        assert_eq!(
                            traced.total,
                            expected,
                            "{smi} (algo={algo:?}, ring={ring:?}, ctx_len={}): \
                             trace_ring_pi_electrons diverged from ring_pi_electrons",
                            ctx.len()
                        );
                        // Cross-check the per-atom eligibility bookkeeping too.
                        for a in &traced.atoms {
                            assert_eq!(
                                a.contribution.is_some(),
                                a.reason.is_eligible(),
                                "{smi}: atom {:?} contribution/reason eligibility mismatch",
                                a.atom_idx
                            );
                        }
                    }
                }
            }
        }
    }

    // ── Aromaticity-A1-0: false-positive/false-negative polarity sanity ────
    //
    // These are cheap, structural sanity checks that the corpus buckets are
    // labeled the direction they claim -- not a re-measurement of the full
    // corpus (that's `aromaticity_a1_0_report` + the Python RDKit join, see
    // `docs/aromaticity_a1_rfc.md`). Catches an accidental swap or a stale
    // pinned count silently going the other way.
    #[test]
    fn false_positive_corpus_over_counts_vs_rdkit() {
        for (smi, expected_wrong, rdkit_correct) in KNOWN_BRIDGEHEAD_N_FALSE_POSITIVES {
            assert!(
                expected_wrong > rdkit_correct,
                "{smi}: false-positive bucket entry should over-count \
                 (chematic={expected_wrong} should be > rdkit={rdkit_correct})"
            );
        }
    }

    #[test]
    fn false_negative_corpus_under_counts_vs_rdkit() {
        for (smi, expected_wrong, rdkit_correct) in KNOWN_ORDER_DEPENDENT_FALSE_NEGATIVES {
            assert!(
                expected_wrong < rdkit_correct,
                "{smi}: false-negative bucket entry should under-count \
                 (chematic={expected_wrong} should be < rdkit={rdkit_correct})"
            );
        }
    }

    // ── Aromaticity-A1-1a: exhaustive_aromaticity_oracle pinned cases ──────
    //
    // The oracle is a discovery tool, not a correct-answer generator: its
    // candidates are built from the SAME per-atom local rules
    // (`evaluate_atom_pi_contribution`) that are wrong for the false-positive
    // family, so it can't independently arbitrate that family. This test
    // pins what the oracle DOES get right (RDKit-atom-index-verified, not
    // guessed) after two real fixes made during this milestone:
    //
    // 1. Connectivity: `build_conjugated_components`'s conjugation graph
    //    originally only bridged single bonds via a `LonePairDonor` endpoint,
    //    leaving azulene's all-carbon alternating perimeter as 5 disconnected
    //    2-atom pairs (oracle returned an empty set). Fixed: any bond between
    //    two independently-eligible atoms connects (ordinary carbon-carbon
    //    single-bond conjugation, ordinary organic chemistry).
    // 2. Home-ring evaluation: evaluating a multi-ring candidate's electron
    //    sum against its own *flattened* atom set broke the N
    //    bridgehead/substituted-azole rule for any TRUE bridgehead (every
    //    bond looks "in-family" once the family itself is the context) --
    //    indolizine's own bridgehead N came out `Ineligible`, an oracle bug,
    //    not a chematic bug. Fixed via `evaluate_atom_via_home_ring`.
    //
    // Both fixes are confirmed correct AND confirmed NOT to silently
    // "fix" the false-positive family by accident (still wrong, on purpose,
    // pinned below) -- an oracle that quietly agreed with the bug would be
    // worse than no oracle.
    //
    // purine is a genuinely OPEN finding, not a regression to chase in this
    // round: before the home-ring fix, the (buggy, flattened) evaluation
    // happened to give all 9 atoms aromatic (matching RDKit) BY ACCIDENT --
    // the SAME flattening bug that broke indolizine happened to produce the
    // right answer for purine. After the fix, purine's 5-ring fusion carbons
    // (whose own `#[ignore]`d production test already documents an
    // antiaromatic-lock issue -- each scores 0π alone, exocyclic-to-N rule)
    // need cross-ring information neither a single home ring nor the
    // flattened family alone provides correctly. Pinning the current
    // (still-wrong) oracle answer here so a future A1-1b design has a
    // concrete regression check once it actually resolves this, rather than
    // silently inheriting whichever answer the oracle happens to produce.
    #[test]
    fn exhaustive_oracle_pinned_cases() {
        let algo = AromaticityAlgorithm::RdkitLike;

        // (name, smiles, expected oracle-aromatic atom indices, sorted)
        let matches_rdkit: &[(&str, &str, &[u32])] = &[
            (
                "azulene",
                "C1=CC2=CC=CC=CC2=C1",
                &[0, 1, 2, 3, 4, 5, 6, 7, 8, 9],
            ),
            (
                "naphthalene",
                "c1ccc2ccccc2c1",
                &[0, 1, 2, 3, 4, 5, 6, 7, 8, 9],
            ),
            (
                "anthracene",
                "c1ccc2cc3ccccc3cc2c1",
                &[0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13],
            ),
            ("indole", "c1ccc2[nH]ccc2c1", &[0, 1, 2, 3, 4, 5, 6, 7, 8]),
            (
                "quinoline",
                "c1ccc2ncccc2c1",
                &[0, 1, 2, 3, 4, 5, 6, 7, 8, 9],
            ),
            (
                "indolizine (bridgehead N, both rings valid)",
                "c1ccn2ccccc12",
                &[0, 1, 2, 3, 4, 5, 6, 7, 8],
            ),
            ("tropone", "O=c1cccccc1", &[1, 2, 3, 4, 5, 6, 7]),
            ("2-pyridone", "O=c1cccc[nH]1", &[1, 2, 3, 4, 5, 6]),
        ];
        for (name, smi, expected) in matches_rdkit {
            let mol = mol_kekulized(smi);
            let (atoms, _bonds) = exhaustive_aromaticity_oracle(&mol, algo);
            let mut got: Vec<u32> = atoms.iter().map(|a| a.0).collect();
            got.sort();
            assert_eq!(&got, expected, "{name} ({smi}): oracle should match RDKit");
        }

        // Still wrong, on purpose -- the false-positive family isn't fixable
        // by candidate generation alone (Issue B, deliberately deferred to
        // A1-1b; see docs/aromaticity_a1_rfc.md).
        let (fp_atoms, _) =
            exhaustive_aromaticity_oracle(&mol_kekulized("C1=Cc2ccccc2C2=NCCCN12"), algo);
        let mut fp_got: Vec<u32> = fp_atoms.iter().map(|a| a.0).collect();
        fp_got.sort();
        assert_eq!(
            fp_got,
            vec![0, 1, 2, 3, 4, 5, 6, 7, 8, 13],
            "false-positive reproducer: still over-aromatized by the oracle, as expected"
        );

        // Open finding, not a regression -- see this test's doc comment.
        let (purine_atoms, _) =
            exhaustive_aromaticity_oracle(&mol_kekulized("c1cnc2[nH]cnc2n1"), algo);
        let mut purine_got: Vec<u32> = purine_atoms.iter().map(|a| a.0).collect();
        purine_got.sort();
        assert_eq!(
            purine_got,
            vec![0, 1, 2, 3, 7, 8],
            "purine: oracle still under-counts (RDKit says all 9) -- open A1-1b question, not fixed here"
        );
    }
}