citum-engine 0.80.0

Citum citation and bibliography processor
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
1205
1206
1207
1208
1209
1210
1211
1212
1213
1214
1215
1216
1217
1218
1219
1220
1221
1222
1223
1224
1225
1226
1227
1228
1229
1230
1231
1232
1233
1234
1235
1236
1237
1238
1239
1240
1241
1242
1243
1244
1245
1246
1247
1248
1249
1250
1251
1252
1253
1254
1255
1256
1257
1258
1259
1260
1261
1262
1263
1264
1265
1266
1267
1268
1269
1270
1271
1272
1273
1274
1275
1276
1277
1278
1279
1280
1281
1282
1283
1284
1285
1286
1287
1288
1289
1290
1291
1292
1293
1294
1295
1296
1297
1298
1299
1300
1301
1302
1303
1304
1305
1306
1307
1308
1309
1310
1311
1312
1313
1314
1315
1316
1317
1318
1319
1320
1321
1322
1323
1324
1325
1326
1327
1328
1329
1330
1331
1332
1333
1334
1335
1336
1337
1338
1339
1340
1341
1342
1343
1344
1345
1346
1347
1348
1349
1350
1351
1352
1353
1354
1355
1356
1357
1358
1359
1360
1361
1362
1363
1364
1365
1366
1367
1368
1369
1370
1371
1372
1373
1374
1375
1376
1377
1378
1379
1380
1381
1382
1383
1384
1385
1386
1387
1388
1389
1390
1391
1392
1393
1394
1395
1396
1397
1398
1399
1400
1401
1402
1403
1404
1405
1406
1407
1408
1409
1410
1411
1412
1413
1414
1415
1416
1417
1418
1419
1420
1421
1422
1423
1424
1425
1426
1427
1428
1429
1430
1431
1432
1433
1434
1435
1436
1437
1438
1439
1440
1441
1442
1443
1444
1445
1446
1447
1448
1449
1450
1451
1452
1453
1454
1455
1456
1457
1458
1459
1460
1461
1462
1463
1464
1465
1466
1467
1468
1469
1470
1471
1472
1473
1474
1475
1476
1477
1478
1479
1480
1481
1482
1483
1484
1485
1486
1487
1488
1489
1490
1491
1492
1493
1494
1495
1496
1497
1498
1499
1500
1501
1502
1503
1504
1505
1506
1507
1508
1509
1510
1511
1512
1513
1514
1515
1516
1517
1518
1519
1520
1521
1522
1523
1524
1525
1526
1527
1528
1529
1530
1531
1532
1533
1534
1535
1536
1537
1538
1539
1540
1541
1542
1543
1544
1545
1546
1547
1548
1549
1550
1551
1552
1553
1554
1555
1556
1557
1558
1559
1560
1561
1562
1563
1564
1565
1566
1567
1568
1569
1570
1571
1572
1573
1574
1575
1576
1577
1578
1579
1580
1581
1582
1583
1584
1585
1586
1587
1588
1589
1590
1591
1592
1593
1594
1595
1596
1597
1598
1599
1600
1601
1602
1603
1604
1605
1606
1607
1608
1609
1610
1611
1612
1613
1614
1615
1616
1617
1618
1619
1620
1621
1622
1623
1624
1625
1626
1627
1628
1629
1630
1631
1632
1633
1634
1635
1636
1637
1638
1639
1640
1641
1642
1643
1644
1645
1646
1647
1648
1649
1650
1651
1652
1653
1654
1655
1656
1657
1658
1659
1660
1661
1662
1663
1664
1665
1666
1667
1668
1669
1670
1671
1672
1673
1674
1675
1676
1677
1678
1679
1680
1681
1682
1683
1684
1685
1686
1687
1688
1689
1690
1691
1692
1693
1694
1695
1696
1697
1698
1699
1700
1701
1702
1703
1704
1705
1706
1707
1708
1709
1710
1711
1712
1713
1714
1715
1716
1717
1718
1719
1720
1721
1722
1723
1724
1725
1726
1727
1728
1729
1730
1731
1732
1733
1734
1735
1736
1737
1738
1739
1740
1741
1742
1743
1744
1745
1746
1747
1748
1749
1750
1751
1752
1753
1754
1755
1756
1757
1758
1759
1760
1761
1762
1763
1764
1765
1766
1767
1768
1769
1770
1771
1772
1773
1774
1775
1776
1777
1778
1779
1780
1781
1782
1783
1784
1785
1786
1787
1788
1789
1790
1791
1792
1793
1794
1795
1796
1797
1798
1799
1800
1801
1802
1803
1804
1805
1806
1807
1808
1809
1810
1811
1812
1813
1814
1815
1816
1817
1818
1819
1820
1821
1822
1823
1824
1825
1826
1827
1828
1829
1830
1831
1832
1833
1834
1835
1836
1837
1838
1839
1840
1841
1842
1843
1844
1845
1846
1847
1848
1849
1850
1851
1852
1853
1854
1855
1856
1857
1858
1859
1860
1861
1862
1863
1864
1865
1866
1867
1868
1869
1870
1871
1872
1873
1874
1875
1876
1877
1878
1879
1880
1881
1882
1883
1884
1885
1886
1887
1888
1889
1890
1891
1892
1893
1894
1895
1896
1897
1898
1899
1900
1901
1902
1903
1904
1905
1906
1907
1908
1909
1910
1911
1912
1913
1914
1915
1916
1917
1918
1919
1920
1921
1922
1923
1924
1925
1926
1927
1928
1929
1930
1931
1932
1933
1934
1935
1936
1937
1938
1939
1940
1941
1942
1943
1944
1945
1946
1947
1948
1949
1950
1951
1952
1953
1954
1955
1956
1957
1958
1959
1960
1961
1962
1963
1964
1965
1966
1967
1968
1969
1970
1971
1972
1973
1974
1975
1976
1977
1978
1979
1980
1981
1982
1983
1984
1985
1986
1987
1988
1989
1990
1991
1992
1993
1994
1995
1996
1997
1998
1999
2000
2001
2002
2003
2004
2005
2006
2007
2008
2009
2010
2011
2012
2013
2014
2015
2016
2017
2018
2019
2020
2021
2022
2023
2024
2025
2026
2027
2028
2029
2030
2031
2032
2033
2034
2035
2036
2037
2038
2039
2040
2041
2042
2043
2044
2045
2046
2047
2048
2049
2050
2051
2052
2053
2054
2055
2056
2057
2058
2059
2060
2061
2062
2063
2064
2065
2066
2067
2068
2069
2070
2071
2072
2073
2074
2075
2076
2077
2078
2079
2080
2081
2082
2083
2084
2085
2086
2087
2088
2089
2090
2091
2092
2093
2094
2095
2096
2097
2098
2099
2100
2101
2102
2103
2104
2105
2106
2107
2108
2109
2110
2111
2112
2113
2114
2115
2116
2117
2118
2119
2120
2121
2122
2123
2124
2125
2126
2127
2128
2129
2130
2131
2132
2133
2134
2135
2136
2137
2138
2139
2140
2141
2142
2143
2144
2145
2146
2147
2148
2149
2150
2151
2152
2153
2154
2155
2156
2157
2158
2159
2160
2161
2162
2163
2164
2165
2166
2167
2168
2169
2170
2171
2172
2173
2174
2175
2176
2177
2178
2179
2180
2181
2182
2183
2184
2185
2186
2187
2188
2189
2190
2191
2192
2193
2194
2195
2196
2197
2198
2199
2200
2201
2202
2203
2204
2205
2206
2207
2208
2209
2210
2211
2212
2213
2214
2215
2216
2217
2218
2219
2220
2221
2222
2223
2224
2225
2226
2227
2228
2229
2230
2231
2232
2233
2234
2235
2236
2237
2238
2239
2240
2241
2242
2243
2244
2245
2246
2247
2248
2249
2250
2251
2252
2253
2254
2255
2256
2257
2258
2259
2260
2261
2262
2263
2264
2265
2266
2267
2268
2269
2270
2271
2272
2273
2274
2275
2276
2277
2278
2279
2280
2281
2282
2283
2284
2285
2286
2287
2288
2289
2290
2291
2292
2293
2294
2295
2296
2297
2298
2299
2300
2301
2302
2303
2304
2305
2306
2307
2308
2309
2310
2311
2312
2313
2314
2315
2316
2317
2318
2319
2320
2321
2322
2323
2324
2325
2326
2327
2328
2329
2330
2331
2332
2333
2334
2335
2336
2337
2338
2339
2340
2341
2342
2343
2344
2345
2346
2347
2348
2349
2350
2351
2352
2353
2354
2355
2356
2357
2358
2359
2360
2361
2362
2363
2364
2365
2366
2367
2368
2369
2370
2371
2372
2373
2374
2375
2376
2377
2378
2379
2380
2381
2382
2383
2384
2385
2386
2387
2388
2389
2390
2391
2392
2393
2394
2395
2396
2397
2398
2399
2400
2401
2402
2403
2404
2405
2406
2407
2408
2409
2410
2411
2412
2413
2414
2415
2416
2417
2418
2419
2420
2421
2422
2423
2424
2425
2426
2427
2428
2429
2430
2431
2432
2433
2434
2435
2436
2437
2438
2439
2440
2441
2442
2443
2444
2445
2446
2447
2448
2449
2450
2451
2452
2453
2454
2455
2456
2457
2458
2459
2460
2461
2462
2463
2464
2465
2466
2467
2468
2469
2470
2471
2472
2473
2474
2475
2476
2477
2478
2479
2480
2481
2482
2483
2484
2485
2486
2487
2488
2489
2490
2491
2492
2493
2494
2495
2496
2497
2498
2499
2500
2501
2502
2503
2504
2505
2506
2507
2508
2509
2510
2511
2512
2513
2514
2515
2516
2517
2518
2519
2520
2521
2522
2523
2524
2525
2526
2527
2528
2529
2530
2531
2532
2533
2534
2535
2536
2537
2538
2539
2540
2541
2542
2543
2544
2545
2546
2547
2548
2549
2550
2551
2552
2553
2554
2555
2556
2557
2558
2559
2560
2561
2562
2563
2564
2565
2566
2567
2568
2569
2570
2571
2572
2573
2574
2575
2576
2577
2578
2579
2580
2581
2582
2583
2584
2585
2586
2587
2588
2589
2590
2591
2592
2593
2594
2595
2596
2597
2598
2599
2600
2601
2602
2603
2604
2605
2606
2607
2608
2609
2610
2611
2612
2613
2614
2615
2616
2617
2618
2619
2620
2621
2622
2623
2624
2625
2626
2627
2628
2629
2630
2631
2632
2633
2634
2635
2636
2637
2638
2639
2640
2641
2642
2643
2644
2645
2646
2647
2648
2649
2650
2651
2652
2653
2654
2655
2656
2657
2658
2659
2660
2661
2662
2663
2664
2665
2666
2667
2668
2669
2670
2671
2672
2673
2674
2675
2676
2677
2678
2679
2680
2681
2682
2683
2684
2685
2686
2687
2688
2689
2690
2691
2692
2693
2694
2695
2696
2697
2698
2699
2700
2701
2702
2703
2704
2705
2706
2707
2708
2709
2710
2711
2712
2713
2714
2715
2716
2717
2718
2719
2720
2721
2722
2723
2724
2725
2726
2727
2728
2729
2730
2731
2732
2733
2734
2735
2736
2737
2738
2739
2740
2741
2742
2743
2744
2745
2746
2747
2748
2749
2750
2751
2752
2753
2754
2755
2756
2757
2758
2759
2760
2761
2762
2763
2764
2765
2766
2767
2768
2769
2770
2771
2772
2773
2774
2775
2776
2777
2778
2779
2780
2781
2782
2783
2784
2785
2786
2787
2788
2789
2790
2791
2792
2793
2794
2795
2796
2797
2798
2799
2800
2801
2802
2803
2804
2805
2806
2807
2808
2809
2810
2811
2812
2813
2814
2815
2816
2817
2818
2819
2820
2821
2822
2823
2824
2825
2826
2827
2828
2829
2830
2831
2832
2833
2834
2835
2836
2837
2838
2839
2840
2841
2842
2843
2844
2845
2846
2847
2848
2849
2850
2851
2852
2853
2854
2855
2856
2857
2858
2859
2860
2861
2862
2863
2864
2865
2866
2867
2868
2869
2870
2871
2872
2873
2874
2875
2876
2877
2878
2879
2880
2881
2882
2883
2884
2885
2886
2887
2888
2889
2890
2891
2892
2893
2894
2895
2896
2897
2898
2899
2900
2901
2902
2903
2904
2905
2906
2907
2908
2909
2910
2911
2912
2913
2914
2915
2916
2917
2918
2919
2920
2921
2922
2923
2924
2925
2926
2927
2928
2929
2930
2931
2932
2933
2934
2935
2936
2937
2938
2939
2940
2941
2942
2943
2944
2945
2946
2947
2948
2949
2950
2951
2952
2953
2954
2955
2956
2957
2958
2959
2960
2961
2962
2963
2964
2965
2966
2967
2968
2969
2970
2971
2972
2973
2974
2975
2976
2977
2978
2979
2980
2981
2982
2983
2984
2985
2986
2987
2988
2989
2990
2991
2992
2993
2994
2995
2996
2997
2998
2999
3000
3001
3002
3003
3004
3005
3006
3007
3008
3009
3010
3011
3012
3013
3014
3015
3016
3017
3018
3019
3020
3021
3022
3023
3024
3025
3026
3027
3028
3029
3030
3031
3032
3033
3034
3035
3036
3037
3038
3039
3040
3041
3042
3043
3044
3045
3046
3047
3048
3049
3050
3051
3052
3053
3054
3055
3056
3057
3058
3059
3060
3061
3062
3063
3064
3065
3066
3067
3068
3069
3070
3071
3072
3073
3074
3075
3076
3077
3078
3079
3080
3081
3082
3083
3084
3085
3086
3087
3088
3089
3090
3091
3092
3093
3094
3095
3096
3097
3098
3099
3100
3101
/*
SPDX-License-Identifier: MIT OR Apache-2.0
SPDX-FileCopyrightText: © 2023-2026 Bruce D'Arcus and Citum contributors
*/

use crate::reference::{Bibliography, Reference};
use crate::values::ProcHints;
use citum_schema::options::{Config, GivennameRule};
use citum_schema::reference::Title;
use std::collections::{HashMap, HashSet};
use std::fmt::Write as _;

use crate::sorting::{ReferenceSorter, compare_none_last};
use citum_schema::grouping::GroupSort;
use citum_schema::locale::Locale;

/// Handles disambiguation logic for author-date citations.
///
/// Disambiguation resolves ambiguities when multiple references produce
/// identical rendered strings. The processor applies strategies in cascade:
///
/// 1. **Name expansion** (`disambiguate-add-names`): If et-al is triggered
///    in the base citation, try expanding the author list to differentiate
///    references with same first author and year.
///
/// 2. **Given name expansion** (`disambiguate-add-givenname`): Add initials
///    or full given names to author list to resolve remaining collisions
///    (e.g., "Smith, John" vs "Smith, Jane").
///
/// 3. **Combined expansion**: Try showing both more names AND given names
///    to maximize differentiation before falling back to year suffix.
///
/// 4. **Year suffix fallback** (`disambiguate-add-year-suffix`): If above
///    strategies fail, append letters (a, b, c, ..., z, aa, ab, ...) to
///    the year. Ordering follows the resolved per-group sort when one is
///    configured, otherwise lowercase reference title order.
///
/// ## Algorithm Overview
///
/// - References are grouped by their base collision key
///   (for example, `smith:2020` or a label key)
/// - For each group with 2+ collisions, strategies are applied in order
/// - Once a strategy resolves ambiguity, higher-priority strategies skip
/// - Year suffix assignment is deterministic from the resolved per-group sort
///
/// ## Output
///
/// Returns `ProcHints` for each reference containing:
/// - `group_index`: Position within collision group (1-indexed)
/// - `group_length`: Total references in collision group
/// - `group_key`: Author-year key used for grouping
/// - `disamb_condition`: Whether year suffix should be applied
/// - `expand_given_names`: Whether to show given names/initials
/// - `min_names_to_show`: Minimum author count for name expansion
pub struct Disambiguator<'a> {
    bibliography: &'a Bibliography,
    config: &'a Config,
    /// Effective bibliography config governing bibliography-owned date-slot
    /// grouping and multilingual/locale sort-key policy. Year-suffix grouping
    /// and ordering must use this — not `config` — when the bibliography
    /// supplies the corresponding template or sort behavior.
    sort_config: &'a Config,
    locale: &'a Locale,
    group_sort: Option<&'a GroupSort>,
    citation_spec: Option<&'a citum_schema::CitationSpec>,
    citation_primary_may_be_list: bool,
    bibliography_spec: Option<&'a citum_schema::BibliographySpec>,
    /// Whether the resolved bibliography sort breaks ties by reference id, as
    /// `ReferenceSorter::sort_references_with_id_tiebreak` does. Mirrors the
    /// renderer's tiebreak in `sort_group_for_year_suffix` so year-suffix
    /// order agrees with render order even when the sort keys alone don't
    /// fully determine it. csl26-m8la.
    id_tiebreak: bool,
}

#[derive(Clone, Copy, Default)]
struct DisambiguationFlags {
    add_names: bool,
    add_givenname: bool,
    year_suffix: bool,
    is_label_mode: bool,
    primary_givenname_only: bool,
}

struct GroupDisambiguationContext<'a> {
    key: &'a str,
    group: &'a [&'a CachedReference<'a>],
    flags: DisambiguationFlags,
    author_group_lengths: &'a HashMap<String, usize>,
}

#[derive(Clone, Copy)]
struct HintPlan<'a> {
    key: &'a str,
    expand_given_names: bool,
    expand_given_names_primary_only: bool,
    min_names_to_show: Option<usize>,
    disamb_condition: bool,
}

#[derive(Clone, Copy)]
enum HintOrder {
    Encountered,
    GroupSorted,
}

enum GroupHintAction<'a> {
    Singleton(&'a CachedReference<'a>),
    LabelYearSuffix,
    NamePartitions {
        min_names_to_show: usize,
        partitions: HashMap<String, Vec<&'a CachedReference<'a>>>,
    },
    GivennameResolution,
    CombinedResolution {
        min_names_to_show: usize,
        primary_only_requires_suffix: bool,
    },
    FallbackYearSuffix,
}

type ReferenceCache<'a> = Vec<CachedReference<'a>>;

#[derive(Clone, Debug, Eq, Hash, PartialEq)]
enum ReferenceCacheKey {
    Id(String),
    Index(usize),
}

struct CachedReference<'a> {
    reference: &'a Reference,
    #[allow(dead_code, reason = "Cache key policy is asserted in unit tests.")]
    key: ReferenceCacheKey,
    data: CachedReferenceData,
}

struct CachedReferenceData {
    author_key: String,
    group_key: String,
    names: Vec<crate::reference::FlatName>,
    title_key: Option<String>,
    /// Position of this reference in the bibliography's registry
    /// (`IndexMap`) order — the same order `ReferenceSorter` falls back to
    /// when a resolved sort has no keys, or no keys, left to compare. Used by
    /// `sort_group_for_year_suffix` to mirror the renderer's tiebreak instead
    /// of an independently-computed title order. csl26-m8la.
    index: usize,
}

impl<'a> Disambiguator<'a> {
    /// Creates a disambiguator that uses the default title-based fallback order.
    ///
    /// `sort_config` is the effective bibliography config; pass the same
    /// config used to render and sort the final bibliography so bibliography-
    /// owned date grouping and year-suffix order agree with its output.
    #[must_use]
    pub fn new(
        bibliography: &'a Bibliography,
        config: &'a Config,
        sort_config: &'a Config,
        locale: &'a Locale,
    ) -> Self {
        Self {
            bibliography,
            config,
            sort_config,
            locale,
            group_sort: None,
            citation_spec: None,
            citation_primary_may_be_list: false,
            bibliography_spec: None,
            id_tiebreak: false,
        }
    }

    /// Creates a disambiguator with an explicit per-group sort specification.
    ///
    /// `sort_config` is the effective bibliography config; pass the same
    /// config used to render and sort the final bibliography so bibliography-
    /// owned date grouping and year-suffix order agree with its output.
    #[must_use]
    pub fn with_group_sort(
        bibliography: &'a Bibliography,
        config: &'a Config,
        sort_config: &'a Config,
        locale: &'a Locale,
        group_sort: &'a GroupSort,
    ) -> Self {
        Self {
            bibliography,
            config,
            sort_config,
            locale,
            group_sort: Some(group_sort),
            citation_spec: None,
            citation_primary_may_be_list: false,
            bibliography_spec: None,
            id_tiebreak: false,
        }
    }

    /// Resolve disambiguation names from the effective citation template.
    #[must_use]
    pub fn with_citation_spec(mut self, spec: &'a citum_schema::CitationSpec) -> Self {
        self.citation_spec = Some(spec);
        self.citation_primary_may_be_list = crate::sorting::citation_may_have_list_primary(spec);
        self
    }

    /// Resolve year-suffix sort keys from the effective bibliography template.
    #[must_use]
    pub fn with_bibliography_spec(mut self, spec: &'a citum_schema::BibliographySpec) -> Self {
        self.bibliography_spec = Some(spec);
        self
    }

    /// Mark that the resolved bibliography sort breaks ties by reference id.
    ///
    /// Pass the same flag `Processor::resolved_bibliography_sort` returns for
    /// the sort used to render the final bibliography
    /// (`ReferenceSorter::sort_references_with_id_tiebreak`), so year-suffix
    /// order agrees with render order.
    #[must_use]
    pub fn with_id_tiebreak(mut self, id_tiebreak: bool) -> Self {
        self.id_tiebreak = id_tiebreak;
        self
    }

    /// Calculate processing hints for disambiguation across all references.
    ///
    /// This is a single-pass algorithm that:
    /// 1. Groups references by their base collision key
    /// 2. For each group with multiple references, applies disambiguation
    ///    strategies in cascade order
    /// 3. Returns pre-calculated hints for the renderer
    ///
    /// ## Cascade Order
    ///
    /// For each collision group:
    /// - Try expanding author list (et-al → full names)
    /// - Try adding given names/initials
    /// - Try combined approach (more names + given names)
    /// - Fall back to year suffix (a, b, c, ...)
    ///
    /// ## Performance
    ///
    /// - O(n) for grouping, where n = number of references
    /// - O(g²) for collision detection within each group g
    /// - Total: O(n + Σ(g²)) where typical g << n
    ///
    /// ## Example
    ///
    /// Input bibliography:
    /// - Smith, John (2020) - "Article A"
    /// - Smith, Jane (2020) - "Article B"
    /// - Brown, Tom (2020) - "Article C"
    ///
    /// Output hints:
    /// - "item-1": { `group_key`: "smith:2020", `expand_given_names`: true, `group_length`: 2 }
    /// - "item-2": { `group_key`: "smith:2020", `expand_given_names`: true, `group_length`: 2 }
    /// - "item-3": { `group_key`: "brown:2020" } (no collision)
    #[must_use]
    pub fn calculate_hints(&self) -> HashMap<String, ProcHints> {
        let mut hints = HashMap::new();
        let refs: Vec<&Reference> = self.bibliography.values().collect();
        let flags = self.disambiguation_flags();
        // Always populate title_key when year-suffix disambiguation is active so that
        // sort_group_for_year_suffix can use it as a stable tie-breaker regardless of
        // whether a group_sort is configured.
        let needs_title_key = flags.year_suffix;
        let cache = self.build_reference_cache(&refs, needs_title_key);
        let grouped = self.group_references(&cache);
        let author_group_lengths = self.author_group_lengths(&cache);

        for (key, group) in grouped {
            self.apply_group_hints(
                &mut hints,
                GroupDisambiguationContext {
                    key: &key,
                    group: &group,
                    flags,
                    author_group_lengths: &author_group_lengths,
                },
            );
        }

        hints
    }

    /// Resolves disambiguation configuration from the processor config.
    fn disambiguation_flags(&self) -> DisambiguationFlags {
        let disamb_config = self.config.effective_processing().config().disambiguate;

        DisambiguationFlags {
            add_names: disamb_config.as_ref().is_some_and(|d| d.names),
            add_givenname: disamb_config.as_ref().is_some_and(|d| d.add_givenname),
            year_suffix: disamb_config.as_ref().is_some_and(|d| d.year_suffix),
            is_label_mode: self
                .config
                .processing
                .as_ref()
                .is_some_and(|p| matches!(p, citum_schema::options::Processing::Label(_))),
            primary_givenname_only: disamb_config.as_ref().is_some_and(|d| {
                matches!(
                    d.givenname_rule,
                    GivennameRule::PrimaryName | GivennameRule::PrimaryNameWithInitials
                )
            }),
        }
    }

    /// Builds an internal cache of reference data (author keys, group keys, titles)
    /// to avoid redundant string generation during disambiguation.
    fn build_reference_cache<'b>(
        &self,
        refs: &[&'b Reference],
        needs_title_key: bool,
    ) -> ReferenceCache<'b> {
        // Grouping must resolve the substitute chain from `sort_config` (the
        // effective bibliography config, per its doc comment), not `config`
        // (which may be citation-scoped). A style can override the
        // bibliography-scope substitute independently of the citation-scope
        // one (e.g. GB/T 7714 author-date's constant `佚名` anonymous-author
        // fallback, csl26-6eak) — if grouping used the citation substitute
        // instead, it would see a per-reference substituted title where the
        // bibliography renders the same constant text for every such
        // reference, so those references would each form a singleton group
        // instead of colliding on year like a real shared author.
        let substitute = citum_schema::options::SubstituteConfig::resolve_or_default(
            self.sort_config.substitute.as_ref(),
        );
        refs.iter()
            .enumerate()
            .map(|(index, reference)| {
                let names = if self.citation_primary_may_be_list {
                    self.citation_spec
                        .and_then(|spec| {
                            crate::sorting::primary_contributor_for_citation(spec, reference)
                        })
                        .filter(|component| component.contributor.is_multiple())
                        .map_or_else(
                            || {
                                crate::values::contributor::substitute::effective_primary_names(
                                    reference,
                                    substitute.as_ref(),
                                    self.config,
                                    self.locale,
                                )
                            },
                            |component| {
                                crate::values::contributor::merged::semantic_names(
                                    &component,
                                    reference,
                                    self.config,
                                    self.locale,
                                )
                            },
                        )
                } else {
                    crate::values::contributor::substitute::effective_primary_names(
                        reference,
                        substitute.as_ref(),
                        self.config,
                        self.locale,
                    )
                };
                let author_key = self.build_author_slot_key(reference, &names, substitute.as_ref());
                let group_key = self.build_group_key(index, reference, &author_key);
                // Year-suffix letters (a, b, c…) must follow the effective bibliography
                // sort order. Reuse the bibliography title sort key (leading-article
                // stripping + locale collation) so suffix assignment cannot diverge from
                // the rendered order — a raw lowercased title sorts "An Ecology" before
                // "Biology", producing `2019b` before `2019a` (DISAMBIGUATION.md §3).
                let title_key = needs_title_key.then(|| {
                    crate::sort_support::title_sort_key_with_options(
                        reference,
                        self.locale,
                        &crate::sort_support::SortKeyOptions::from_config(self.sort_config),
                    )
                });

                CachedReference {
                    reference,
                    key: Self::reference_cache_key(index, reference),
                    data: CachedReferenceData {
                        author_key,
                        group_key,
                        names,
                        title_key,
                        index,
                    },
                }
            })
            .collect()
    }

    fn build_author_slot_key(
        &self,
        reference: &Reference,
        author_names: &[crate::reference::FlatName],
        substitute: &citum_schema::options::Substitute,
    ) -> String {
        let author_key = self.build_author_key(author_names);
        if !author_key.is_empty() {
            return author_key;
        }

        match crate::values::contributor::substitute::effective_primary(
            reference,
            substitute,
            self.config,
            self.locale,
        ) {
            Some(crate::values::contributor::substitute::EffectivePrimary::Title {
                title, ..
            }) => Self::title_substitute_key(title),
            // The substitute chain is exhausted with no contributor or title
            // to promote. Unlike a substituted title (which already varies
            // per reference and so needs no further disambiguation), a
            // component-level `TemplateContributor.fallback` (e.g. GB/T
            // 7714's `佚名`/`Anon` anonymous-author term, csl26-6eak) renders
            // the *same* constant text for every such reference sharing a
            // language — so, like a real shared author name, these entries
            // must collide on year for suffix assignment rather than each
            // forming its own singleton group. Scoped by the reference's own
            // effective language (the same driver the bibliography renderer
            // uses to pick a `locales:` branch, `core.rs`'s
            // `effective_item_language`) because the rendered term itself
            // varies by language (`佚名` vs `Anon`) — a Chinese and an
            // English anonymous item must not share one year-suffix letter
            // sequence when their rendered author text actually differs.
            None => format!(
                "{}{}",
                Self::ANONYMOUS_FALLBACK_KEY,
                crate::values::effective_item_language(reference).unwrap_or_default()
            ),
            Some(_) => String::new(),
        }
    }

    /// Sentinel author-slot key for references with no contributor, no
    /// substitute title, and no substitute contributor — see
    /// [`Self::build_author_slot_key`]. Not derived from any rendered text
    /// (the caller doesn't know the active template's `fallback:` content),
    /// just a stable, non-empty grouping key shared by every reference in
    /// this state.
    const ANONYMOUS_FALLBACK_KEY: &'static str = "\u{0}anonymous-fallback";

    /// Calculates how many references in `refs` share the same `author_key`.
    /// The returned map is keyed only by `author_key` and is later used when
    /// populating `ProcHints::group_length`, rather than representing the size
    /// of a per-`group_key` collision group.
    fn author_group_lengths(&self, refs: &ReferenceCache<'_>) -> HashMap<String, usize> {
        let mut author_group_lengths = HashMap::new();
        for reference in refs {
            let author_key = &reference.data.author_key;
            if !author_key.is_empty() {
                *author_group_lengths.entry(author_key.clone()).or_insert(0) += 1;
            }
        }
        author_group_lengths
    }

    /// Orchestrates the disambiguation cascade for a single collision group.
    /// It attempts strategies in increasing order of disruptiveness (expansion -> year suffix).
    fn apply_group_hints(
        &self,
        hints: &mut HashMap<String, ProcHints>,
        context: GroupDisambiguationContext<'_>,
    ) {
        match self.select_group_hint_action(&context) {
            GroupHintAction::Singleton(reference) => {
                self.insert_hint(
                    hints,
                    reference,
                    context.author_group_lengths,
                    ProcHints::default(),
                );
            }
            GroupHintAction::LabelYearSuffix => {
                self.apply_year_suffix(hints, &context, false, None);
            }
            GroupHintAction::NamePartitions {
                min_names_to_show,
                partitions,
            } => self.apply_name_partitions(hints, &context, min_names_to_show, &partitions),
            GroupHintAction::GivennameResolution => {
                self.apply_resolution(hints, context.group, &context, true, None);
            }
            GroupHintAction::CombinedResolution {
                min_names_to_show,
                primary_only_requires_suffix,
            } => {
                if primary_only_requires_suffix {
                    self.apply_year_suffix_for_group(
                        hints,
                        context.group,
                        &context,
                        true,
                        Some(min_names_to_show),
                    );
                } else {
                    self.apply_resolution(
                        hints,
                        context.group,
                        &context,
                        true,
                        Some(min_names_to_show),
                    );
                }
            }
            GroupHintAction::FallbackYearSuffix => {
                self.apply_year_suffix(hints, &context, false, None);
            }
        }
    }

    /// Selects the first applicable disambiguation action without mutating hint state.
    fn select_group_hint_action<'b>(
        &self,
        context: &GroupDisambiguationContext<'b>,
    ) -> GroupHintAction<'b> {
        if let Some(reference) = self.select_singleton_hint(context) {
            return GroupHintAction::Singleton(reference);
        }

        if self.select_label_mode_year_suffix(context) {
            return GroupHintAction::LabelYearSuffix;
        }

        if let Some((min_names_to_show, partitions)) = self.select_name_partitions(context) {
            return GroupHintAction::NamePartitions {
                min_names_to_show,
                partitions,
            };
        }

        if self.select_givenname_resolution(context) {
            return GroupHintAction::GivennameResolution;
        }

        if let Some((min_names_to_show, primary_only_requires_suffix)) =
            self.select_combined_resolution(context)
        {
            return GroupHintAction::CombinedResolution {
                min_names_to_show,
                primary_only_requires_suffix,
            };
        }

        GroupHintAction::FallbackYearSuffix
    }

    /// Selects singleton handling for groups with only one reference (no collision).
    fn select_singleton_hint<'b>(
        &self,
        context: &GroupDisambiguationContext<'b>,
    ) -> Option<&'b CachedReference<'b>> {
        if context.group.len() == 1 {
            #[allow(clippy::indexing_slicing, reason = "context.group.len() == 1")]
            return Some(context.group[0]);
        }

        None
    }

    /// Selects year-suffix disambiguation specifically for label-based styles (e.g. [Knu84a]).
    fn select_label_mode_year_suffix(&self, context: &GroupDisambiguationContext<'_>) -> bool {
        context.flags.is_label_mode && context.flags.year_suffix
    }

    /// Selects partitions produced by expanding the number of names shown (et al. expansion).
    fn select_name_partitions<'b>(
        &self,
        context: &GroupDisambiguationContext<'b>,
    ) -> Option<(usize, HashMap<String, Vec<&'b CachedReference<'b>>>)> {
        context
            .flags
            .add_names
            .then(|| self.partition_by_name_expansion(context.group))
            .flatten()
    }

    /// Selects collision resolution by adding given names or initials.
    fn select_givenname_resolution(&self, context: &GroupDisambiguationContext<'_>) -> bool {
        // Use full-expansion keys to determine whether givenname expansion can help at all.
        // (With n=1, the full and primary-only keys are equivalent — both inspect only the
        // primary author — so no separate primary-only check is needed here.)
        context.flags.add_givenname && self.check_givenname_resolution(context.group, None, false)
    }

    /// Selects collision resolution by using both more names AND given name expansion.
    ///
    /// When `primary_givenname_only` is active, the renderer only shows given names for
    /// the first author. `find_combined_resolution` uses full-expansion keys to find the
    /// minimum name count that would work in theory; this function then verifies whether
    /// that resolution also holds under the restricted primary-only rendering.
    fn select_combined_resolution(
        &self,
        context: &GroupDisambiguationContext<'_>,
    ) -> Option<(usize, bool)> {
        if !context.flags.add_names || !context.flags.add_givenname {
            return None;
        }

        let min_names_to_show = self.find_combined_resolution(context.group)?;
        let primary_only_requires_suffix = context.flags.primary_givenname_only
            && !self.check_givenname_resolution(context.group, Some(min_names_to_show), true);

        Some((min_names_to_show, primary_only_requires_suffix))
    }

    /// Applies a name-expansion partition plan, suffixing any unresolved subgroups.
    fn apply_name_partitions(
        &self,
        hints: &mut HashMap<String, ProcHints>,
        context: &GroupDisambiguationContext<'_>,
        min_names_to_show: usize,
        partitions: &HashMap<String, Vec<&CachedReference<'_>>>,
    ) {
        for subgroup in partitions.values() {
            if subgroup.len() == 1 {
                self.apply_resolution(hints, subgroup, context, false, Some(min_names_to_show));
                continue;
            }

            if context.flags.add_givenname
                && self.check_givenname_resolution(subgroup, Some(min_names_to_show), false)
            {
                // Under primary-name rules, secondary given names are not rendered.
                // If the full-expansion check passes but primary-only does not, the
                // subgroup must fall back to year-suffix (with expansion retained).
                if context.flags.primary_givenname_only
                    && !self.check_givenname_resolution(subgroup, Some(min_names_to_show), true)
                {
                    self.apply_year_suffix_for_group(
                        hints,
                        subgroup,
                        context,
                        true,
                        Some(min_names_to_show),
                    );
                } else {
                    self.apply_resolution(hints, subgroup, context, true, Some(min_names_to_show));
                }
                continue;
            }

            self.apply_year_suffix_for_group(
                hints,
                subgroup,
                context,
                false,
                Some(min_names_to_show),
            );
        }
    }

    /// Searches for the minimum number of names that, when combined with given name expansion,
    /// resolves the collision group.
    fn find_combined_resolution(&self, group: &[&CachedReference<'_>]) -> Option<usize> {
        let max_authors = group
            .iter()
            .map(|reference| reference.data.names.len())
            .max()
            .unwrap_or(0);

        // Use full-expansion keys (primary_only: false) to find the minimum name count.
        // The caller is responsible for verifying the result under primary-only rendering
        // when primary_givenname_only is active.
        (2..=max_authors).find(|&n| self.check_givenname_resolution(group, Some(n), false))
    }

    /// Finalizes a successful disambiguation strategy by inserting the calculated hints into the map.
    fn apply_resolution(
        &self,
        hints: &mut HashMap<String, ProcHints>,
        group: &[&CachedReference<'_>],
        context: &GroupDisambiguationContext<'_>,
        expand_given_names: bool,
        min_names_to_show: Option<usize>,
    ) {
        self.insert_group_hints(
            hints,
            group,
            context.author_group_lengths,
            HintPlan {
                key: context.key,
                expand_given_names,
                expand_given_names_primary_only: context.flags.primary_givenname_only,
                min_names_to_show,
                disamb_condition: false,
            },
            HintOrder::Encountered,
        );
    }

    /// Inserts a single hint into the hints map, ensuring the author group length is correctly set.
    fn insert_hint(
        &self,
        hints: &mut HashMap<String, ProcHints>,
        reference: &CachedReference<'_>,
        author_group_lengths: &HashMap<String, usize>,
        mut hint: ProcHints,
    ) {
        hint.group_length = self
            .author_group_length(reference, author_group_lengths)
            .unwrap_or(1);
        hints.insert(
            reference.reference.id().unwrap_or_default().to_string(),
            hint,
        );
    }

    /// Retrieves the number of references sharing the author key for a specific reference.
    fn author_group_length(
        &self,
        reference: &CachedReference<'_>,
        author_group_lengths: &HashMap<String, usize>,
    ) -> Option<usize> {
        let author_key = &reference.data.author_key;
        author_group_lengths.get(author_key).copied()
    }

    /// Applies year-suffix disambiguation to the entire group in the context.
    fn apply_year_suffix(
        &self,
        hints: &mut HashMap<String, ProcHints>,
        context: &GroupDisambiguationContext<'_>,
        expand_given_names: bool,
        min_names_to_show: Option<usize>,
    ) {
        self.apply_year_suffix_for_group(
            hints,
            context.group,
            context,
            expand_given_names,
            min_names_to_show,
        );
    }

    /// Applies year-suffix disambiguation to a specific (sub)group of references.
    fn apply_year_suffix_for_group(
        &self,
        hints: &mut HashMap<String, ProcHints>,
        group: &[&CachedReference<'_>],
        context: &GroupDisambiguationContext<'_>,
        expand_given_names: bool,
        min_names_to_show: Option<usize>,
    ) {
        self.insert_group_hints(
            hints,
            group,
            context.author_group_lengths,
            HintPlan {
                key: context.key,
                expand_given_names,
                expand_given_names_primary_only: context.flags.primary_givenname_only,
                min_names_to_show,
                disamb_condition: true,
            },
            HintOrder::GroupSorted,
        );
    }

    /// Iterates through a group of references and inserts hints according to the specified order.
    fn insert_group_hints(
        &self,
        hints: &mut HashMap<String, ProcHints>,
        group: &[&CachedReference<'_>],
        author_group_lengths: &HashMap<String, usize>,
        plan: HintPlan<'_>,
        order: HintOrder,
    ) {
        match order {
            HintOrder::Encountered => {
                for (idx, reference) in group.iter().enumerate() {
                    self.insert_planned_hint(hints, reference, author_group_lengths, plan, idx + 1);
                }
            }
            HintOrder::GroupSorted => {
                for (idx, reference) in self.sort_group_for_year_suffix(group).iter().enumerate() {
                    self.insert_planned_hint(hints, reference, author_group_lengths, plan, idx + 1);
                }
            }
        }
    }

    /// Helper to insert a hint with common planned fields (key, expand flags, group index).
    fn insert_planned_hint(
        &self,
        hints: &mut HashMap<String, ProcHints>,
        reference: &CachedReference<'_>,
        author_group_lengths: &HashMap<String, usize>,
        plan: HintPlan<'_>,
        group_index: usize,
    ) {
        self.insert_hint(
            hints,
            reference,
            author_group_lengths,
            ProcHints {
                disamb_condition: plan.disamb_condition,
                group_index,
                group_key: plan.key.to_string(),
                expand_given_names: plan.expand_given_names,
                expand_given_names_primary_only: plan.expand_given_names_primary_only,
                min_names_to_show: plan.min_names_to_show,
                ..Default::default()
            },
        );
    }

    /// Sorts a collision group to determine the deterministic order for year-suffix assignment.
    /// It uses the provided group sort specification or falls back to title-based sorting.
    fn sort_group_for_year_suffix<'b>(
        &self,
        group: &[&'b CachedReference<'b>],
    ) -> Vec<&'b CachedReference<'b>> {
        if let Some(sort_spec) = self.group_sort {
            let mut sorter =
                ReferenceSorter::with_bibliography_config(self.locale, self.sort_config);
            if let Some(spec) = self.bibliography_spec {
                sorter = sorter.with_bibliography_spec(spec);
            } else if let Some(spec) = self.citation_spec {
                sorter = sorter.with_citation_spec(spec);
            }
            // Pre-sort so entries that compare equal under the primary sort_spec keep a
            // stable, deterministic order — matching the renderer, not an independently
            // computed title order. `sort_by_keys` uses sort_by (stable), so the pre-sort
            // order survives for entries that tie under the primary key.
            //
            // The renderer (`ReferenceSorter::sort_references_impl`, sorting.rs) stable-
            // sorts the registry-ordered bibliography and, only when the resolved sort
            // opts into it, breaks ties by reference id afterward (`compare_cached_ids`).
            // An empty template is a renderer no-op — `sort_references_impl` early-
            // returns on `compiled_keys.is_empty()` — so neither the id nor the date
            // comparison below may run for it; registry order must survive untouched.
            // Only once the template is non-empty does the renderer's stable sort
            // actually engage those finer tiebreaks, so both steps are gated on that,
            // not just on `id_tiebreak`.
            //
            // No date comparison here: `sort_by_keys` below (shared with the real
            // bibliography renderer) already compares full issued dates — not just the
            // year — for a resolved `Issued` sort key
            // (`ReferenceSorter::compare_by_issued`/`issued_date_parts`, sorting.rs). A
            // same-year, no-title collision pair that used to tie under a year-only
            // Issued key (`chicago-author-date-18th`'s May/September Gourmet magazine
            // entries) now resolves through that one shared comparator instead of a
            // second, independently-maintained date comparison here — duplicating it
            // would only risk the two drifting apart again. Only registry `index` is
            // still needed as the final tiebreak, for entries that remain fully tied
            // after every key in the resolved template. Gated on a non-empty template:
            // an empty one is a renderer no-op (`sort_references_impl`'s early return),
            // so `sort_by_keys` never runs and `index` alone must decide order.
            let mut pre_sorted: Vec<&CachedReference<'_>> = group.to_vec();
            if sort_spec.template.is_empty() {
                pre_sorted.sort_by_key(|cached| cached.data.index);
            } else if self.id_tiebreak {
                pre_sorted.sort_by(|a, b| {
                    compare_none_last(
                        a.reference.id().map(|id| id.0),
                        b.reference.id().map(|id| id.0),
                    )
                    .then_with(|| a.data.index.cmp(&b.data.index))
                });
            } else {
                pre_sorted.sort_by_key(|cached| cached.data.index);
            }
            sorter.sort_by_keys(pre_sorted, &sort_spec.template, |cached| {
                Some(cached.reference)
            })
        } else {
            let mut sorted: Vec<&CachedReference<'_>> = group.to_vec();
            sorted.sort_by(|a, b| {
                let a_title = a.data.title_key.as_deref().unwrap_or_default();
                let b_title = b.data.title_key.as_deref().unwrap_or_default();
                a_title.cmp(b_title).then_with(|| {
                    year_suffix_date_key(a.reference).cmp(&year_suffix_date_key(b.reference))
                })
            });
            sorted
        }
    }

    /// Partition a collision group by showing more names, preserving `et al.`
    /// distinction when some references still have hidden trailing names.
    fn partition_by_name_expansion<'b>(
        &self,
        group: &[&'b CachedReference<'b>],
    ) -> Option<(usize, HashMap<String, Vec<&'b CachedReference<'b>>>)> {
        let max_authors = group
            .iter()
            .map(|reference| reference.data.names.len())
            .max()
            .unwrap_or(0);

        let mut buf = String::new();
        for n in 2..=max_authors {
            let mut partitions: HashMap<String, Vec<&'b CachedReference<'b>>> = HashMap::new();
            for reference in group {
                let names = &reference.data.names;
                buf.clear();
                self.append_name_expansion_key(&mut buf, names, n);
                if let Some(v) = partitions.get_mut(buf.as_str()) {
                    v.push(*reference);
                } else {
                    partitions.insert(buf.clone(), vec![*reference]);
                }
            }

            if partitions.len() > 1 {
                return Some((n, partitions));
            }
        }

        None
    }

    /// Check if expanding to full names resolves ambiguity in the group.
    ///
    /// If `min_names` is `Some(n)`, it checks resolution when showing `n` names.
    ///
    /// When `primary_only` is `true`, only the first author's given name is included
    /// in the resolution key — mirroring what `primary-name` and
    /// `primary-name-with-initials` actually render.  Use this to validate that a
    /// candidate expansion still works under restricted rendering before committing.
    fn check_givenname_resolution(
        &self,
        group: &[&CachedReference<'_>],
        min_names: Option<usize>,
        primary_only: bool,
    ) -> bool {
        let mut seen = HashSet::new();
        let mut buf = String::new();
        let n = min_names.unwrap_or(1);
        for reference in group {
            let names = &reference.data.names;
            buf.clear();
            self.append_givenname_resolution_key(&mut buf, names, n, primary_only);
            if !seen.insert(buf.clone()) {
                return false;
            }
        }
        true
    }

    /// Group references by their base collision key for disambiguation.
    fn group_references<'b>(
        &self,
        references: &'b ReferenceCache<'b>,
    ) -> HashMap<String, Vec<&'b CachedReference<'b>>> {
        let mut groups: HashMap<String, Vec<&'b CachedReference<'b>>> = HashMap::new();

        for reference in references {
            let key = reference.data.group_key.clone();
            groups.entry(key).or_default().push(reference);
        }

        groups
    }

    /// Generates a normalized author string used for grouping and et-al detection.
    fn build_author_key(&self, names: &[crate::reference::FlatName]) -> String {
        let shorten = self
            .config
            .contributors
            .as_ref()
            .and_then(|c| c.shorten.as_ref());

        if names.is_empty() {
            return String::new();
        }

        let mut key = String::new();
        if let Some(opts) = shorten
            && names.len() >= opts.min as usize
        {
            self.append_lowercased_families(&mut key, names, opts.use_first as usize, ',');
            if !key.is_empty() {
                key.push(',');
            }
            key.push_str("et-al");
            return key;
        }

        self.append_lowercased_families(&mut key, names, names.len(), ',');
        key
    }

    fn title_substitute_key(title: Title) -> String {
        let mut key = String::new();
        Self::push_lowercased(&mut key, title.to_string().trim());
        key
    }

    /// Create a grouping key for a reference based on its base citation form.
    fn build_group_key(&self, index: usize, reference: &Reference, author_key: &str) -> String {
        // In label mode, group by base label string rather than author-year.
        // This ensures disambiguation happens at the label level (Knu84a/Knu84b)
        // rather than the author-year level.
        if let Some(citum_schema::options::Processing::Label(config)) = &self.config.processing {
            let params = config.effective_params();
            return crate::processor::labels::generate_base_label(reference, &params);
        }

        // Anonymous entries (no author key) must not be grouped together for year-suffix
        // assignment. CSL year-suffix disambiguates entries with the same *author* —
        // anonymous entries are already distinguished by their title substitution.
        // Give each anonymous reference a unique key so it forms its own singleton group.
        if author_key.is_empty() {
            if let Some(ref_id) = reference.id().filter(|id| !id.is_empty()) {
                return format!("anon:{ref_id}");
            }
            return format!("anon:index:{index}");
        }

        let mut key = String::with_capacity(author_key.len() + 8);
        key.push_str(author_key);
        key.push(':');
        if let Some(year) = reference
            .effective_issued_date()
            .and_then(|d| d.year().parse::<i32>().ok())
        {
            let _ = write!(key, "{year}");
            return key;
        }

        // No issued year. Collision grouping must reflect what the style's
        // resolved date slot actually yields for this reference, not a
        // uniform "no date" assumption — a type-conditional date macro (e.g.
        // GB/T 7714's article-journal branch, which never reaches the
        // no-date term) renders different text for different reference
        // types, and those references are already visually distinguishable.
        // See csl26-huuz.
        key.push_str(&self.date_slot_discriminant(reference));
        key
    }

    /// Discriminant for the date half of the collision key when a reference
    /// has no issued year. Reads the reference's effective resolved
    /// template — the first non-suppressed date component under the author
    /// (`crate::sorting::first_date_component_for_bibliography`, preferring
    /// the bibliography spec when present, else the citation spec) — and
    /// returns text identifying what it actually renders:
    ///
    /// - the date variable resolves to a real, non-empty value → the text
    ///   it would actually render (`form`-restricted and marker-applied,
    ///   the same formatting `TemplateDate::values` uses — not the raw
    ///   stored value, which can carry more precision than `form` shows);
    /// - the variable is empty and the resolved fallback chain (explicit or
    ///   the implicit no-date-term branch) renders the locale's no-date
    ///   term → a discriminant for that term, scoped by the reference's
    ///   effective language (mirrors `build_author_slot_key`'s
    ///   `ANONYMOUS_FALLBACK_KEY` scoping — the rendered term itself varies
    ///   by language, "无日期" vs "n.d.");
    ///
    /// Access dates (`DateVariable::Accessed`), whether the slot's own
    /// primary variable or a fallback candidate, are never used as a
    /// discriminant even when present — an access date is retrieval
    /// metadata, not part of a work's identity, so two otherwise identical
    /// undated entries must not be distinguished by it.
    ///
    /// Bibliography-preferred, not citation-preferred: mirrors
    /// `sort_group_for_year_suffix`'s existing precedent (`csl26-m8la`) for
    /// the same reason — collision grouping is measured against the
    /// bibliography oracle, and a style's citation template is commonly a
    /// simpler, non-type-differentiated form of the same date logic (GB/T
    /// author-date's `citation:` section has one flat `date: issued` with no
    /// `type-variants:` at all, unlike its bibliography section). Preferring
    /// citation_spec here would let that undifferentiated template collapse
    /// every undated reference onto the same discriminant regardless of
    /// type, defeating the type-conditional split this function exists to
    /// make. Confirmed empirically: an in-tree literal `bibliography_spec`
    /// vs `citation_spec` preference swap was compared against the GB/T
    /// oracle before landing this order.
    ///
    /// Returns the empty string both when nothing resolves at all (an
    /// explicit `fallback: []`) and when there is no template to resolve
    /// (no citation or bibliography spec configured) — `build_group_key`'s
    /// existing undiscriminated key for that case.
    fn date_slot_discriminant(&self, reference: &Reference) -> String {
        let component_and_config = self
            .bibliography_spec
            .and_then(|spec| crate::sorting::first_date_component_for_bibliography(spec, reference))
            .map(|component| (component, self.sort_config))
            .or_else(|| {
                self.citation_spec
                    .and_then(|spec| {
                        crate::sorting::first_date_component_for_citation(spec, reference)
                    })
                    .map(|component| (component, self.config))
            });
        let Some((component, config)) = component_and_config else {
            return String::new();
        };
        Self::date_component_discriminant(
            &component,
            reference,
            self.locale,
            config,
            &reference.ref_type(),
        )
    }

    /// The literal locale message ID the implicit no-date branch in
    /// `TemplateDate::values` (`values/date.rs`) evaluates, and the same ID
    /// every GB/T-style explicit `message: term.no-date` fallback names.
    /// Both render identical text, so both must produce the same
    /// discriminant here.
    const IMPLICIT_NO_DATE_TERM: &'static str = "term.no-date";

    /// Classify what a resolved date component renders for a reference with
    /// no issued year. See `date_slot_discriminant`'s doc comment for the
    /// cases.
    ///
    /// A resolving candidate's *rendered* text is used, not the raw stored
    /// date value — `DateValue`'s `Display` is the unformatted EDTF/literal
    /// string, which can carry more precision than the component's `form`
    /// shows (e.g. a day-precision `copyright` date under `form: year`
    /// renders as a bare year, but its raw value still has the day). Reading
    /// the raw value here could split a collision group whose members
    /// render identical date-slot text, defeating the discriminant's whole
    /// purpose. See csl26-huuz, flagged in PR review.
    fn date_component_discriminant(
        component: &citum_schema::template::TemplateDate,
        reference: &Reference,
        locale: &citum_schema::locale::Locale,
        config: &citum_schema::options::Config,
        ref_type: &str,
    ) -> String {
        use citum_schema::template::{DateVariable, TemplateComponent};

        let date_config = config.dates.as_ref();

        if matches!(component.date, DateVariable::Accessed) {
            if crate::values::date::resolve_date_variable(&component.date, reference)
                .is_some_and(|value| !value.is_empty())
            {
                // An access date carries no identity even when present —
                // this is the terminal case for this slot, not a signal to
                // keep looking at a fallback chain.
                return String::new();
            }
        } else if let Some(value) =
            crate::values::date::resolve_date_variable(&component.date, reference)
                .filter(|value| !value.is_empty())
        {
            // The primary variable is present, so — mirroring
            // `TemplateDate::values`'s own normal-value branch, which never
            // consults `self.fallback` once the primary date resolves —
            // this is terminal even when the value fails to format (e.g. a
            // literal date under a numeric `form`, which the renderer also
            // shows as nothing). Reuses the same fallback-candidate helper as
            // the loop below: its visible rendering configuration is inert
            // here (constant across every reference resolving this same
            // component, so it can never split two references from each
            // other), but `date.note` is per-reference *data*, not
            // per-component config, so including it is defensive even though
            // a note-bearing value can't reach this branch under the current
            // data model (a note-bearing date is structured and parseable,
            // so `build_group_key`'s own year check already returns before
            // this function ever runs).
            return crate::values::date::fallback_candidate_discriminant(
                &value,
                &component.form,
                &component.rendering,
                component.suppress_note,
                locale,
                date_config,
            )
            .unwrap_or_default();
        }

        let source =
            crate::values::date::effective_date_candidate_source(component, config, ref_type);
        let Some(fallbacks) = source.template_components() else {
            return if matches!(component.date, DateVariable::Issued) {
                crate::values::date::fallback_message_discriminant(
                    &citum_schema::template::TemplateMessage {
                        message: Self::IMPLICIT_NO_DATE_TERM.to_string(),
                        form: Some(citum_schema::locale::TermForm::Short),
                        ..Default::default()
                    },
                    locale,
                    config,
                )
                .unwrap_or_default()
            } else {
                String::new()
            };
        };

        for candidate in fallbacks.iter() {
            match candidate {
                TemplateComponent::Message(message) => {
                    let Some(discriminant) =
                        crate::values::date::fallback_message_discriminant(message, locale, config)
                    else {
                        // Rendering skips unresolved or suppressed messages and
                        // continues to the next fallback candidate.
                        continue;
                    };
                    return discriminant;
                }
                TemplateComponent::Date(inner) => {
                    let Some(value) =
                        crate::values::date::resolve_date_variable(&inner.date, reference)
                            .filter(|value| !value.is_empty())
                    else {
                        // This candidate doesn't resolve — not selected,
                        // keep scanning the chain (e.g. GB/T's accessed
                        // fallback when no accessed date exists at all).
                        continue;
                    };
                    let Some(discriminant) = crate::values::date::fallback_candidate_discriminant(
                        &value,
                        &inner.form,
                        &inner.rendering,
                        inner.suppress_note,
                        locale,
                        date_config,
                    ) else {
                        // Present but renders nothing (e.g. a literal date
                        // under a numeric form) — `render_date_fallback_chain`
                        // treats an unrendering candidate the same as an
                        // absent one and keeps scanning, so the discriminant
                        // must too.
                        continue;
                    };
                    // A resolving, rendering candidate is the terminal case
                    // for this slot: citeproc-js's underlying if/else-if
                    // branching (which this fallback chain mirrors) never
                    // falls through to a later branch once one is selected —
                    // even when, as with an access date, that branch's own
                    // content carries no identity and this discriminant is
                    // therefore empty rather than the date's text.
                    return if matches!(inner.date, DateVariable::Accessed) {
                        String::new()
                    } else {
                        discriminant
                    };
                }
                _ => {}
            }
        }

        String::new()
    }

    /// Appends a sequence of family names to the key buffer, lowercased.
    fn append_lowercased_families(
        &self,
        key: &mut String,
        names: &[crate::reference::FlatName],
        take: usize,
        separator: char,
    ) {
        for (idx, name) in names.iter().take(take).enumerate() {
            if idx > 0 {
                key.push(separator);
            }
            Self::push_lowercased(key, name.family_or_literal());
        }
    }

    /// Creates a key representing the citation form when n names are shown.
    fn append_name_expansion_key(
        &self,
        key: &mut String,
        names: &[crate::reference::FlatName],
        n: usize,
    ) {
        self.append_lowercased_families(key, names, n, '|');
        if names.len() > n {
            if !key.is_empty() {
                key.push('|');
            }
            key.push_str("et-al");
        }
    }

    /// Creates a key including full name parts (given names, particles) for exact resolution.
    ///
    /// When `primary_only` is `true`, only the first author (index 0) receives full
    /// given-name/particle parts; subsequent authors contribute only their family name.
    /// This mirrors what `primary-name` and `primary-name-with-initials` actually render,
    /// allowing resolution checks to validate against the real rendered surface form.
    fn append_givenname_resolution_key(
        &self,
        key: &mut String,
        names: &[crate::reference::FlatName],
        n: usize,
        primary_only: bool,
    ) {
        for (idx, name) in names.iter().take(n).enumerate() {
            if idx > 0 {
                key.push_str("||");
            }
            Self::append_optional_part(key, name.family.as_deref());
            if primary_only && idx > 0 {
                // Secondary authors: family name only under primary-name rules.
                continue;
            }
            key.push('|');
            Self::append_optional_part(key, name.given.as_deref());
            key.push('|');
            Self::append_optional_part(key, name.non_dropping_particle.as_deref());
            key.push('|');
            Self::append_optional_part(key, name.dropping_particle.as_deref());
        }
    }

    /// Serializes an optional name part into the key buffer with its length.
    fn append_optional_part(key: &mut String, value: Option<&str>) {
        match value {
            Some(value) => {
                let _ = write!(key, "{}:", value.len());
                key.push_str(value);
            }
            None => key.push('-'),
        }
    }

    /// Pushes a lowercased version of the string to the buffer, optimized for ASCII.
    fn push_lowercased(key: &mut String, value: &str) {
        if value.is_ascii() {
            key.reserve(value.len());
            for byte in value.bytes() {
                key.push((byte as char).to_ascii_lowercase());
            }
        } else {
            key.push_str(&value.to_lowercase());
        }
    }

    /// Returns the stable per-run cache key used for disambiguation metadata.
    fn reference_cache_key(index: usize, reference: &Reference) -> ReferenceCacheKey {
        reference
            .id()
            .map_or(ReferenceCacheKey::Index(index), |id| {
                ReferenceCacheKey::Id(id.to_string())
            })
    }
}

fn year_suffix_date_key(reference: &Reference) -> String {
    reference
        .effective_issued_date()
        .map(|date| date.to_string())
        .unwrap_or_default()
}

#[cfg(test)]
#[allow(
    clippy::unwrap_used,
    clippy::expect_used,
    clippy::panic,
    clippy::indexing_slicing,
    clippy::todo,
    clippy::unimplemented,
    clippy::unreachable,
    clippy::get_unwrap,
    reason = "Panicking is acceptable and often desired in tests."
)]
mod tests {
    use super::*;
    use crate::Processor;
    use citum_schema::citation::Citation;
    use citum_schema::grouping::{GroupSort, GroupSortKey, SortKey};
    use citum_schema::options::dates::DateConfig;
    use citum_schema::options::{
        Config, ContributorConfig, DisplayAsSort, MultilingualConfig, NameForm, SortingConfig,
        SortingMultilingualMode,
    };
    use citum_schema::reference::types::MultilingualComplex;
    use citum_schema::reference::{
        Contributor, DateValue, InputReference as Reference, Monograph, MonographType,
        MultilingualString, StructuredName, Title,
    };
    use citum_schema::template::{
        DateForm, DateVariable, Rendering, TemplateComponent, TemplateDate, TemplateMessage,
        WrapConfig, WrapPunctuation,
    };
    use citum_schema::{BibliographySpec, CitationSpec, Style, StyleInfo};
    use rstest::rstest;

    fn make_ref(id: &str, family: &str, given: &str, year: i32) -> Reference {
        let title = format!("Title {id}");
        Reference::Monograph(Box::new(Monograph {
            id: Some(id.into()),
            r#type: MonographType::Book,
            title: Some(Title::Single(title.clone())),
            short_title: None,
            container: None,
            author: Some(Contributor::StructuredName(StructuredName {
                family: MultilingualString::Simple(family.to_string()),
                given: MultilingualString::Simple(given.to_string()),
                suffix: None,
                dropping_particle: None,
                non_dropping_particle: None,
            })),
            editor: None,
            translator: None,
            issued: DateValue::new(year.to_string()),
            ..Default::default()
        }))
    }

    /// Like `make_ref`, but with an independently chosen title — `make_ref`'s
    /// title is derived from `id`, which makes id order and title order
    /// coincide and so cannot distinguish which one a sort actually used.
    fn make_ref_with_title(
        id: &str,
        family: &str,
        given: &str,
        year: i32,
        title: &str,
    ) -> Reference {
        Reference::Monograph(Box::new(Monograph {
            id: Some(id.into()),
            r#type: MonographType::Book,
            title: Some(Title::Single(title.to_string())),
            short_title: None,
            container: None,
            author: Some(Contributor::StructuredName(StructuredName {
                family: MultilingualString::Simple(family.to_string()),
                given: MultilingualString::Simple(given.to_string()),
                suffix: None,
                dropping_particle: None,
                non_dropping_particle: None,
            })),
            editor: None,
            translator: None,
            issued: DateValue::new(year.to_string()),
            ..Default::default()
        }))
    }

    fn make_ref_without_id(title_suffix: &str, family: &str, given: &str, year: i32) -> Reference {
        let title = format!("Title {title_suffix}");
        Reference::Monograph(Box::new(Monograph {
            id: None,
            r#type: MonographType::Book,
            title: Some(Title::Single(title)),
            short_title: None,
            container: None,
            author: Some(Contributor::StructuredName(StructuredName {
                family: MultilingualString::Simple(family.to_string()),
                given: MultilingualString::Simple(given.to_string()),
                suffix: None,
                dropping_particle: None,
                non_dropping_particle: None,
            })),
            editor: None,
            translator: None,
            issued: DateValue::new(year.to_string()),
            ..Default::default()
        }))
    }

    fn make_multi_author_ref(id: &str, authors: &[(&str, &str)], year: i32) -> Reference {
        let title = format!("Title {id}");
        Reference::Monograph(Box::new(Monograph {
            id: Some(id.into()),
            r#type: MonographType::Book,
            title: Some(Title::Single(title)),
            short_title: None,
            container: None,
            author: Some(Contributor::ContributorList(
                citum_schema::reference::ContributorList(
                    authors
                        .iter()
                        .map(|(family, given)| {
                            Contributor::StructuredName(StructuredName {
                                family: MultilingualString::Simple((*family).to_string()),
                                given: MultilingualString::Simple((*given).to_string()),
                                suffix: None,
                                dropping_particle: None,
                                non_dropping_particle: None,
                            })
                        })
                        .collect(),
                ),
            )),
            editor: None,
            translator: None,
            issued: DateValue::new(year.to_string()),
            ..Default::default()
        }))
    }

    fn make_author_date_style(config: Config, bibliography_sort: Option<GroupSort>) -> Style {
        Style {
            info: StyleInfo {
                title: Some("Disambiguation Test".to_string()),
                id: Some("disambiguation-test".into()),
                ..Default::default()
            },
            options: Some(config),
            citation: Some(CitationSpec {
                template: Some(
                    vec![
                        citum_schema::tc_contributor!(Author, Short),
                        citum_schema::tc_date!(Issued, Year, prefix = ", "),
                    ]
                    .into(),
                ),
                wrap: Some(WrapPunctuation::Parentheses.into()),
                ..Default::default()
            }),
            bibliography: Some(BibliographySpec {
                sort: bibliography_sort.map(citum_schema::grouping::GroupSortEntry::Explicit),
                template: Some(
                    vec![TemplateComponent::Title(
                        citum_schema::template::TemplateTitle {
                            title: citum_schema::template::TitleType::Primary,
                            ..Default::default()
                        },
                    )]
                    .into(),
                ),
                ..Default::default()
            }),
            ..Default::default()
        }
    }

    #[test]
    fn test_group_aware_year_suffix_sort() {
        use citum_schema::options::{Disambiguation, Processing, ProcessingCustom};

        let r1 = make_ref("r1", "Smith", "Same", 2020);
        let r2 = make_ref("r2", "Smith", "Same", 2020);

        let mut bib = Bibliography::new();
        bib.insert("r1".to_string(), r1);
        bib.insert("r2".to_string(), r2);

        let config = Config::default();
        let locale = Locale::en_us();

        // 1. Default sorting (by title): r1 should be 'a', r2 should be 'b'.
        // Title r1 < Title r2 alphabetically, so r1 gets group_index 1.
        let disamb_default = Disambiguator::new(&bib, &config, &config, &locale);
        let hints_default = disamb_default.calculate_hints();

        assert_eq!(hints_default.get("r1").unwrap().group_index, 1);
        assert_eq!(hints_default.get("r2").unwrap().group_index, 2);

        // 2. Custom group sort: Sort by title descending -> r2 should be 'a', r1 should be 'b'
        let sort_spec = GroupSort {
            template: vec![GroupSortKey {
                key: SortKey::Title,
                ascending: false,
                order: None,
                sort_order: None,
            }],
        };

        let disamb_custom =
            Disambiguator::with_group_sort(&bib, &config, &config, &locale, &sort_spec);
        let hints_custom = disamb_custom.calculate_hints();

        assert_eq!(hints_custom.get("r2").unwrap().group_index, 1);
        assert_eq!(hints_custom.get("r1").unwrap().group_index, 2);

        let style = make_author_date_style(
            Config {
                processing: Some(Processing::Custom(ProcessingCustom {
                    base: None,
                    disambiguate: Some(Disambiguation {
                        names: false,
                        add_givenname: false,
                        givenname_rule: GivennameRule::default(),
                        year_suffix: true,
                    }),
                    ..Default::default()
                })),
                contributors: Some(ContributorConfig {
                    display_as_sort: Some(DisplayAsSort::First),
                    ..Default::default()
                }),
                ..Default::default()
            },
            Some(sort_spec),
        );
        let processor = Processor::new(style, bib);

        let rendered_r1 = processor.process_citation(&Citation::simple("r1")).unwrap();
        let rendered_r2 = processor.process_citation(&Citation::simple("r2")).unwrap();

        assert!(
            rendered_r1.contains("2020b"),
            "expected r1 to sort second: {rendered_r1}"
        );
        assert!(
            rendered_r2.contains("2020a"),
            "expected r2 to sort first: {rendered_r2}"
        );
    }

    /// Two same-author/same-year references whose registration order
    /// disagrees with both title order ("Alpha Report" < "Beta Report") and id order
    /// ("a-ref" < "b-ref"), so each ordering is independently distinguishable
    /// in the tests below. csl26-m8la.
    fn build_diverging_order_group() -> Bibliography {
        let mut bib = Bibliography::new();
        bib.insert(
            "b-ref".to_string(),
            make_ref_with_title("b-ref", "Smith", "Same", 2020, "Beta Report"),
        );
        bib.insert(
            "a-ref".to_string(),
            make_ref_with_title("a-ref", "Smith", "Same", 2020, "Alpha Report"),
        );
        bib
    }

    #[test]
    fn test_empty_group_sort_template_follows_registration_order() {
        let bib = build_diverging_order_group();
        let config = Config::default();
        let locale = Locale::en_us();
        let sort_spec = GroupSort { template: vec![] };

        let disamb = Disambiguator::with_group_sort(&bib, &config, &config, &locale, &sort_spec);
        let hints = disamb.calculate_hints();

        // Registered first, not title-first ("Alpha Report" would win under the old
        // title-alphabetical pre-sort) or id-first ("a-ref" < "b-ref").
        assert_eq!(hints.get("b-ref").unwrap().group_index, 1);
        assert_eq!(hints.get("a-ref").unwrap().group_index, 2);
    }

    #[test]
    fn test_empty_group_sort_template_ignores_id_tiebreak() {
        let bib = build_diverging_order_group();
        let config = Config::default();
        let locale = Locale::en_us();
        let sort_spec = GroupSort { template: vec![] };

        // An empty template is a renderer no-op regardless of id_tiebreak
        // (ReferenceSorter::sort_references_impl's early return) — the flag
        // must not reorder by id here.
        let disamb = Disambiguator::with_group_sort(&bib, &config, &config, &locale, &sort_spec)
            .with_id_tiebreak(true);
        let hints = disamb.calculate_hints();

        assert_eq!(hints.get("b-ref").unwrap().group_index, 1);
        assert_eq!(hints.get("a-ref").unwrap().group_index, 2);
    }

    #[test]
    fn test_non_empty_template_with_equal_keys_follows_registration_order_without_id_tiebreak() {
        let bib = build_diverging_order_group();
        let config = Config::default();
        let locale = Locale::en_us();
        // Author and issued are equal across the group, so this template
        // doesn't itself resolve the tie.
        let sort_spec = GroupSort {
            template: vec![
                GroupSortKey {
                    key: SortKey::Author,
                    ascending: true,
                    order: None,
                    sort_order: None,
                },
                GroupSortKey {
                    key: SortKey::Issued,
                    ascending: true,
                    order: None,
                    sort_order: None,
                },
            ],
        };

        let disamb = Disambiguator::with_group_sort(&bib, &config, &config, &locale, &sort_spec);
        let hints = disamb.calculate_hints();

        assert_eq!(hints.get("b-ref").unwrap().group_index, 1);
        assert_eq!(hints.get("a-ref").unwrap().group_index, 2);
    }

    #[test]
    fn test_non_empty_template_with_equal_keys_follows_id_order_with_id_tiebreak() {
        let bib = build_diverging_order_group();
        let config = Config::default();
        let locale = Locale::en_us();
        let sort_spec = GroupSort {
            template: vec![
                GroupSortKey {
                    key: SortKey::Author,
                    ascending: true,
                    order: None,
                    sort_order: None,
                },
                GroupSortKey {
                    key: SortKey::Issued,
                    ascending: true,
                    order: None,
                    sort_order: None,
                },
            ],
        };

        let disamb = Disambiguator::with_group_sort(&bib, &config, &config, &locale, &sort_spec)
            .with_id_tiebreak(true);
        let hints = disamb.calculate_hints();

        // "a-ref" < "b-ref" — id order, not the "b-ref" first registration order.
        assert_eq!(hints.get("a-ref").unwrap().group_index, 1);
        assert_eq!(hints.get("b-ref").unwrap().group_index, 2);
    }

    #[test]
    fn test_id_tiebreak_sorts_missing_id_last() {
        let mut bib = Bibliography::new();
        // Registered first but has no id: must still sort *after* the
        // reference that does, mirroring ReferenceSorter::compare_cached_ids.
        bib.insert(
            "missing".to_string(),
            make_ref_without_id("missing", "Smith", "Same", 2020),
        );
        bib.insert(
            "with-id".to_string(),
            make_ref("with-id", "Smith", "Same", 2020),
        );

        let config = Config::default();
        let locale = Locale::en_us();
        let sort_spec = GroupSort {
            template: vec![
                GroupSortKey {
                    key: SortKey::Author,
                    ascending: true,
                    order: None,
                    sort_order: None,
                },
                GroupSortKey {
                    key: SortKey::Issued,
                    ascending: true,
                    order: None,
                    sort_order: None,
                },
            ],
        };

        let disamb = Disambiguator::with_group_sort(&bib, &config, &config, &locale, &sort_spec)
            .with_id_tiebreak(true);
        let hints = disamb.calculate_hints();

        // Missing-id references key the hints map under the empty string
        // (`insert_hint`'s `id().unwrap_or_default()`).
        assert_eq!(hints.get("with-id").unwrap().group_index, 1);
        assert_eq!(hints.get("").unwrap().group_index, 2);
    }

    #[test]
    fn test_non_empty_template_title_key_still_governs_over_registration_and_id_order() {
        let bib = build_diverging_order_group();
        let config = Config::default();
        let locale = Locale::en_us();
        let sort_spec = GroupSort {
            template: vec![
                GroupSortKey {
                    key: SortKey::Author,
                    ascending: true,
                    order: None,
                    sort_order: None,
                },
                GroupSortKey {
                    key: SortKey::Issued,
                    ascending: true,
                    order: None,
                    sort_order: None,
                },
                GroupSortKey {
                    key: SortKey::Title,
                    ascending: true,
                    order: None,
                    sort_order: None,
                },
            ],
        };

        let disamb = Disambiguator::with_group_sort(&bib, &config, &config, &locale, &sort_spec)
            .with_id_tiebreak(true);
        let hints = disamb.calculate_hints();

        // A real Title sort key resolves the tie itself: "Alpha Report" < "Beta Report",
        // overriding both registration order ("b-ref" first) and id order
        // ("a-ref" < "b-ref" would coincidentally agree here, but the point is
        // this is driven by the template's own Title key, not our tiebreak).
        assert_eq!(hints.get("a-ref").unwrap().group_index, 1);
        assert_eq!(hints.get("b-ref").unwrap().group_index, 2);
    }

    #[test]
    fn test_author_date_default_uses_year_suffix_without_name_expansion() {
        use citum_schema::options::Processing;

        let r1 = make_ref("r1", "Smith", "John", 2020);
        let r2 = make_ref("r2", "Smith", "Alice", 2020);

        let mut bib = Bibliography::new();
        bib.insert("r1".to_string(), r1);
        bib.insert("r2".to_string(), r2);

        let config = Config {
            processing: Some(Processing::AuthorDate),
            ..Default::default()
        };
        let locale = Locale::en_us();

        let disamb = Disambiguator::new(&bib, &config, &config, &locale);
        let hints = disamb.calculate_hints();
        let r1_hints = hints.get("r1").unwrap();
        let r2_hints = hints.get("r2").unwrap();

        assert!(r1_hints.disamb_condition);
        assert!(r2_hints.disamb_condition);
        assert!(!r1_hints.expand_given_names);
        assert!(!r2_hints.expand_given_names);
        assert_eq!(r1_hints.min_names_to_show, None);
        assert_eq!(r2_hints.min_names_to_show, None);

        let style = make_author_date_style(config, None);
        let processor = Processor::new(style, bib);

        let rendered_r1 = processor.process_citation(&Citation::simple("r1")).unwrap();
        let rendered_r2 = processor.process_citation(&Citation::simple("r2")).unwrap();

        assert!(
            rendered_r1.contains("2020a") || rendered_r1.contains("2020b"),
            "expected r1 to receive a year suffix: {rendered_r1}"
        );
        assert!(
            rendered_r2.contains("2020a") || rendered_r2.contains("2020b"),
            "expected r2 to receive a year suffix: {rendered_r2}"
        );
        assert!(
            !rendered_r1.contains("John") && !rendered_r1.contains("J."),
            "expected r1 to avoid given-name expansion: {rendered_r1}"
        );
        assert!(
            !rendered_r2.contains("Alice") && !rendered_r2.contains("A."),
            "expected r2 to avoid given-name expansion: {rendered_r2}"
        );
    }

    #[test]
    fn test_disambiguate_given_names() {
        use citum_schema::options::{Disambiguation, Processing, ProcessingCustom};

        // Use different given names to test if expansion resolves the collision
        let r1 = make_ref("r1", "Smith", "John", 2020);
        let r2 = make_ref("r2", "Smith", "Alice", 2020);

        let mut bib = Bibliography::new();
        bib.insert("r1".to_string(), r1);
        bib.insert("r2".to_string(), r2);

        let config = Config {
            processing: Some(Processing::Custom(ProcessingCustom {
                base: None,
                disambiguate: Some(Disambiguation {
                    names: false,
                    add_givenname: true,
                    givenname_rule: GivennameRule::AllNames,
                    year_suffix: false,
                }),
                ..Default::default()
            })),
            ..Default::default()
        };
        let locale = Locale::en_us();

        let disamb = Disambiguator::new(&bib, &config, &config, &locale);
        let hints = disamb.calculate_hints();

        // Both should have expand_given_names set to true to resolve the Smith (2020) collision
        assert!(hints.get("r1").unwrap().expand_given_names);
        assert!(hints.get("r2").unwrap().expand_given_names);

        // Should NOT have year suffix since it's disabled in config (and given names resolve it)
        assert!(!hints.get("r1").unwrap().disamb_condition);
        assert!(!hints.get("r2").unwrap().disamb_condition);

        // Collision resolved: entries occupy distinct positions
        assert_ne!(
            hints.get("r1").unwrap().group_index,
            hints.get("r2").unwrap().group_index
        );

        let style = make_author_date_style(
            Config {
                processing: Some(Processing::Custom(ProcessingCustom {
                    base: None,
                    disambiguate: Some(Disambiguation {
                        names: false,
                        add_givenname: true,
                        givenname_rule: GivennameRule::AllNames,
                        year_suffix: false,
                    }),
                    ..Default::default()
                })),
                contributors: Some(ContributorConfig {
                    initialize_with: Some(". ".to_string()),
                    name_form: Some(NameForm::Initials),
                    ..Default::default()
                }),
                ..Default::default()
            },
            None,
        );
        let processor = Processor::new(style, bib);

        let rendered_r1 = processor.process_citation(&Citation::simple("r1")).unwrap();
        let rendered_r2 = processor.process_citation(&Citation::simple("r2")).unwrap();

        assert!(
            rendered_r1.contains("J. Smith"),
            "expected expanded given name for r1: {rendered_r1}"
        );
        assert!(
            rendered_r2.contains("A. Smith"),
            "expected expanded given name for r2: {rendered_r2}"
        );
    }

    /// When `primary-name` is active and expanding the first author's given name does
    /// not resolve the collision (both works share an identical primary author), the
    /// disambiguator must fall back to year-suffix while retaining the et-al expansion
    /// that was found.  Concretely: hints must have `expand_given_names: true`,
    /// `expand_given_names_primary_only: true`, `min_names_to_show: Some(2)`, and
    /// `disamb_condition: true` (year-suffix), with distinct `group_index` values.
    #[test]
    fn test_primary_name_identical_primary_falls_back_to_year_suffix() {
        use citum_schema::options::{
            Disambiguation, Processing, ProcessingCustom, ShortenListOptions,
        };

        // Primary author ("Asthma/Albert") is identical; secondary authors differ only
        // in given name ("Brandon" vs "Edward") — identical families.
        let r1 = make_multi_author_ref(
            "r1",
            &[
                ("Asthma", "Albert"),
                ("Bronchitis", "Brandon"),
                ("Cold", "Crispin"),
            ],
            1990,
        );
        let r2 = make_multi_author_ref(
            "r2",
            &[
                ("Asthma", "Albert"),
                ("Bronchitis", "Edward"),
                ("Cold", "Crispin"),
            ],
            1990,
        );

        let mut bib = Bibliography::new();
        bib.insert("r1".to_string(), r1);
        bib.insert("r2".to_string(), r2);

        let config = Config {
            processing: Some(Processing::Custom(ProcessingCustom {
                base: None,
                disambiguate: Some(Disambiguation {
                    names: true,
                    add_givenname: true,
                    givenname_rule: GivennameRule::PrimaryName,
                    year_suffix: true,
                }),
                ..Default::default()
            })),
            contributors: Some(ContributorConfig {
                shorten: Some(ShortenListOptions {
                    min: 3,
                    use_first: 1,
                    ..Default::default()
                }),
                ..Default::default()
            }),
            ..Default::default()
        };
        let locale = Locale::en_us();

        let hints = Disambiguator::new(&bib, &config, &config, &locale).calculate_hints();

        let h1 = hints.get("r1").expect("r1 must have a hint");
        let h2 = hints.get("r2").expect("r2 must have a hint");

        // Et-al expansion to two names must be retained.
        assert_eq!(
            h1.min_names_to_show,
            Some(2),
            "r1: expected min_names_to_show=2"
        );
        assert_eq!(
            h2.min_names_to_show,
            Some(2),
            "r2: expected min_names_to_show=2"
        );

        // Given-name expansion must be active (primary author initial shown).
        assert!(h1.expand_given_names, "r1: expected expand_given_names");
        assert!(h2.expand_given_names, "r2: expected expand_given_names");

        // Primary-only flag must be propagated.
        assert!(
            h1.expand_given_names_primary_only,
            "r1: expected primary-only"
        );
        assert!(
            h2.expand_given_names_primary_only,
            "r2: expected primary-only"
        );

        // Year-suffix must be assigned (disamb_condition true, distinct indices).
        assert!(
            h1.disamb_condition,
            "r1: expected disamb_condition (year-suffix)"
        );
        assert!(
            h2.disamb_condition,
            "r2: expected disamb_condition (year-suffix)"
        );
        assert_ne!(
            h1.group_index, h2.group_index,
            "r1 and r2 must receive distinct year-suffix positions"
        );
    }

    #[test]
    fn test_build_reference_cache_populates_title_keys_when_year_suffix_is_active() {
        // title_key must be populated whenever year-suffix is on (regardless of group_sort)
        // so that sort_group_for_year_suffix can use it as a stable tie-breaker.
        use citum_schema::options::{Disambiguation, Processing, ProcessingCustom};

        let mut bib = Bibliography::new();
        bib.insert("r1".to_string(), make_ref("r1", "Smith", "John", 2020));
        let refs: Vec<&Reference> = bib.values().collect();
        let locale = Locale::en_us();

        let disabled_config = Config {
            processing: Some(Processing::Custom(ProcessingCustom {
                base: None,
                disambiguate: Some(Disambiguation {
                    names: false,
                    add_givenname: true,
                    givenname_rule: GivennameRule::default(),
                    year_suffix: false,
                }),
                ..Default::default()
            })),
            ..Default::default()
        };
        let disabled = Disambiguator::new(&bib, &disabled_config, &disabled_config, &locale);
        let disabled_flags = disabled.disambiguation_flags();
        // year_suffix=false → title_key must be None
        let disabled_cache = disabled.build_reference_cache(&refs, disabled_flags.year_suffix);
        assert!(
            disabled_cache
                .iter()
                .all(|reference| reference.data.title_key.is_none())
        );

        let enabled_config = Config {
            processing: Some(Processing::Custom(ProcessingCustom {
                base: None,
                disambiguate: Some(Disambiguation {
                    names: false,
                    add_givenname: false,
                    givenname_rule: GivennameRule::default(),
                    year_suffix: true,
                }),
                ..Default::default()
            })),
            ..Default::default()
        };
        let enabled = Disambiguator::new(&bib, &enabled_config, &enabled_config, &locale);
        let enabled_flags = enabled.disambiguation_flags();
        // year_suffix=true → title_key must be Some regardless of group_sort
        let enabled_cache = enabled.build_reference_cache(&refs, enabled_flags.year_suffix);
        assert!(
            enabled_cache
                .iter()
                .all(|reference| reference.data.title_key.is_some())
        );
    }

    #[test]
    fn test_reference_cache_key_uses_reference_id_or_index_fallback() {
        let with_id = make_ref("r1", "Smith", "John", 2020);
        let without_id = make_ref_without_id("missing-id", "Smith", "Jane", 2020);

        assert_eq!(
            Disambiguator::reference_cache_key(7, &with_id),
            ReferenceCacheKey::Id("r1".to_string())
        );
        assert_eq!(
            Disambiguator::reference_cache_key(7, &without_id),
            ReferenceCacheKey::Index(7)
        );

        let mut bib = Bibliography::new();
        bib.insert("r1".to_string(), with_id);
        bib.insert("missing".to_string(), without_id);
        let refs: Vec<&Reference> = bib.values().collect();
        let cache = Disambiguator::new(
            &bib,
            &Config::default(),
            &Config::default(),
            &Locale::en_us(),
        )
        .build_reference_cache(&refs, false);

        assert_eq!(cache[0].key, ReferenceCacheKey::Id("r1".to_string()));
        assert_eq!(cache[1].key, ReferenceCacheKey::Index(1));
    }

    #[test]
    fn test_anonymous_refs_do_not_receive_year_suffix() {
        // Anonymous entries (no author) sharing the same year must each be placed in
        // their own singleton group, even when an embedded reference id is empty or missing.
        use citum_schema::options::{Disambiguation, Processing, ProcessingCustom};

        let mut bib = Bibliography::new();
        bib.insert("a1".to_string(), make_ref("a1", "", "", 2020));
        bib.insert("a2".to_string(), make_ref("a2", "", "", 2020));
        bib.insert("a3".to_string(), make_ref("", "", "", 2020));
        bib.insert(
            "a4".to_string(),
            make_ref_without_id("missing-id", "", "", 2020),
        );
        let locale = Locale::en_us();
        let config = Config {
            processing: Some(Processing::Custom(ProcessingCustom {
                base: None,
                disambiguate: Some(Disambiguation {
                    names: true,
                    add_givenname: true,
                    givenname_rule: GivennameRule::default(),
                    year_suffix: true,
                }),
                ..Default::default()
            })),
            ..Default::default()
        };
        let disambiguator = Disambiguator::new(&bib, &config, &config, &locale);
        let refs: Vec<&Reference> = bib.values().collect();
        let cache = disambiguator.build_reference_cache(&refs, false);
        let grouped = disambiguator.group_references(&cache);

        assert_eq!(grouped.len(), 4);
        assert!(!grouped.contains_key("anon:"));
        assert!(grouped.values().all(|group| group.len() == 1));
    }

    #[test]
    fn test_push_lowercased_matches_str_lowercase_for_non_ascii() {
        let mut key = String::new();
        let value = "ΟΣ";

        Disambiguator::push_lowercased(&mut key, value);

        assert_eq!(key, value.to_lowercase());
    }

    #[test]
    fn test_partitioned_name_expansion_keeps_unique_items_and_suffixes_remainders() {
        use citum_schema::options::{
            ContributorConfig, Disambiguation, Processing, ProcessingCustom, ShortenListOptions,
        };

        let mut bib = Bibliography::new();
        bib.insert(
            "r1".to_string(),
            make_multi_author_ref("r1", &[("Smith", "John"), ("Jones", "Peter")], 2020),
        );
        bib.insert(
            "r2".to_string(),
            make_multi_author_ref("r2", &[("Smith", "John"), ("Brown", "Alice")], 2020),
        );
        bib.insert(
            "r3".to_string(),
            make_multi_author_ref("r3", &[("Smith", "John"), ("Brown", "Adam")], 2020),
        );

        let config = Config {
            processing: Some(Processing::Custom(ProcessingCustom {
                base: None,
                disambiguate: Some(Disambiguation {
                    names: true,
                    add_givenname: false,
                    givenname_rule: GivennameRule::default(),
                    year_suffix: true,
                }),
                ..Default::default()
            })),
            contributors: Some(ContributorConfig {
                shorten: Some(ShortenListOptions {
                    min: 2,
                    use_first: 1,
                    ..Default::default()
                }),
                ..Default::default()
            }),
            ..Default::default()
        };
        let locale = Locale::en_us();

        let hints = Disambiguator::new(&bib, &config, &config, &locale).calculate_hints();

        let unique = hints.get("r1").unwrap();
        assert!(!unique.disamb_condition);
        assert_eq!(unique.group_index, 1);
        assert_eq!(unique.min_names_to_show, Some(2));
        assert_eq!(unique.group_length, 3);

        let remaining_a = hints.get("r2").unwrap();
        let remaining_b = hints.get("r3").unwrap();
        assert!(remaining_a.disamb_condition);
        assert!(remaining_b.disamb_condition);
        assert_eq!(remaining_a.min_names_to_show, Some(2));
        assert_eq!(remaining_b.min_names_to_show, Some(2));
        assert_eq!(remaining_a.group_length, 3);
        assert_eq!(remaining_b.group_length, 3);
        assert_ne!(remaining_a.group_index, remaining_b.group_index);
    }

    #[test]
    fn test_label_mode_skips_name_strategies_and_suffixes_by_label_group() {
        use citum_schema::options::{LabelConfig, LabelPreset, Processing};

        let mut bib = Bibliography::new();
        bib.insert("r1".to_string(), make_ref("r1", "Kuhn", "Thomas", 1962));
        bib.insert("r2".to_string(), make_ref("r2", "Kuhn", "Thomas", 1962));

        let config = Config {
            processing: Some(Processing::Label(LabelConfig {
                preset: LabelPreset::Din,
                ..Default::default()
            })),
            ..Default::default()
        };
        let locale = Locale::en_us();

        let hints = Disambiguator::new(&bib, &config, &config, &locale).calculate_hints();
        let first = hints.get("r1").unwrap();
        let second = hints.get("r2").unwrap();

        assert!(first.disamb_condition);
        assert!(second.disamb_condition);
        assert!(!first.expand_given_names);
        assert!(!second.expand_given_names);
        assert_eq!(first.min_names_to_show, None);
        assert_eq!(second.min_names_to_show, None);
        assert_eq!(first.group_key, second.group_key);
        assert!(!first.group_key.contains(':'));
        assert_ne!(first.group_index, second.group_index);
    }

    /// Build a reference whose author is `Contributor::Multilingual` with distinct
    /// `original` but a shared `transliterations` entry keyed by `translit_tag`.
    fn make_multilingual_ref(
        id: &str,
        original_family: &str,
        translit_family: &str,
        translit_tag: &str,
        year: i32,
    ) -> Reference {
        use citum_schema::reference::contributor::MultilingualName;
        use std::collections::HashMap;

        let mut transliterations = HashMap::new();
        transliterations.insert(
            translit_tag.to_string(),
            StructuredName {
                family: MultilingualString::Simple(translit_family.to_string()),
                given: MultilingualString::Simple("A.".to_string()),
                ..Default::default()
            },
        );
        Reference::Monograph(Box::new(Monograph {
            id: Some(id.into()),
            r#type: MonographType::Book,
            title: Some(Title::Single(format!("Title {id}"))),
            author: Some(Contributor::Multilingual(MultilingualName {
                original: StructuredName {
                    family: MultilingualString::Simple(original_family.to_string()),
                    given: MultilingualString::Simple("A.".to_string()),
                    ..Default::default()
                },
                lang: Some("ja".into()),
                sort_as: None,
                transliterations,
                translations: HashMap::new(),
            })),
            issued: DateValue::new(year.to_string()),
            ..Default::default()
        }))
    }

    /// DISAMBIGUATION.md §4: when display mode is `Transliterated`, two references
    /// whose transliterations collide must produce the same author key (→ one
    /// collision group). When mode is `Primary` (distinct originals), keys must differ.
    #[test]
    fn test_multilingual_key_generation_respects_display_mode() {
        use citum_schema::options::MultilingualConfig;
        use citum_schema::options::MultilingualMode;

        // Two distinct Japanese authors that share the same romanisation.
        // Original families differ ("田中" vs "谷中"), but transliteration is "Tanaka".
        let r1 = make_multilingual_ref("r1", "田中", "Tanaka", "ja-Latn", 2020);
        let r2 = make_multilingual_ref("r2", "谷中", "Tanaka", "ja-Latn", 2020);

        let mut bib = Bibliography::new();
        bib.insert("r1".to_string(), r1);
        bib.insert("r2".to_string(), r2);

        let locale = Locale::en_us();

        // --- case 1: Transliterated mode → same key (collision) ---
        let config_translit = Config {
            multilingual: Some(MultilingualConfig {
                name_mode: Some(MultilingualMode::Transliterated),
                preferred_transliteration: Some(vec!["ja-Latn".to_string()]),
                ..Default::default()
            }),
            ..Default::default()
        };

        let cache_translit = Disambiguator::new(&bib, &config_translit, &config_translit, &locale)
            .build_reference_cache(&[bib.get("r1").unwrap(), bib.get("r2").unwrap()], false);

        let ck_r1 = ReferenceCacheKey::Id("r1".to_string());
        let ck_r2 = ReferenceCacheKey::Id("r2".to_string());
        let ak_r1 = &cache_translit
            .iter()
            .find(|reference| reference.key == ck_r1)
            .expect("r1 cache entry")
            .data
            .author_key;
        let ak_r2 = &cache_translit
            .iter()
            .find(|reference| reference.key == ck_r2)
            .expect("r2 cache entry")
            .data
            .author_key;

        assert_eq!(
            ak_r1, ak_r2,
            "transliterated mode: colliding transliterations must produce the same author key"
        );
        assert_eq!(
            ak_r1, "tanaka",
            "key should be the lowercased transliteration"
        );

        // --- case 2: Primary mode → distinct keys (no collision) ---
        let config_primary = Config::default(); // multilingual: None → falls through to original

        let cache_primary = Disambiguator::new(&bib, &config_primary, &config_primary, &locale)
            .build_reference_cache(&[bib.get("r1").unwrap(), bib.get("r2").unwrap()], false);

        let ak_r1_primary = &cache_primary
            .iter()
            .find(|reference| reference.key == ck_r1)
            .expect("r1 cache entry")
            .data
            .author_key;
        let ak_r2_primary = &cache_primary
            .iter()
            .find(|reference| reference.key == ck_r2)
            .expect("r2 cache entry")
            .data
            .author_key;

        assert_ne!(
            ak_r1_primary, ak_r2_primary,
            "primary mode: distinct originals must produce different author keys"
        );
    }

    /// Effective bibliography config for `sorting.multilingual: romanized`, with
    /// a preferred transliteration — mirrors `sorting.rs`'s `romanized_config`.
    fn romanized_config() -> Config {
        Config {
            sorting: Some(SortingConfig {
                multilingual: Some(SortingMultilingualMode::Romanized),
                ..Default::default()
            }),
            multilingual: Some(MultilingualConfig {
                preferred_transliteration: Some(vec!["ru-Latn-alalc97".to_string()]),
                ..Default::default()
            }),
            ..Default::default()
        }
    }

    /// Two same-author, same-year references whose original (Cyrillic) title
    /// order is the *opposite* of their `sort-as` (romanized) title order.
    ///
    /// - `r-alpha`: original starts with "Я" (sorts last in Cyrillic collation),
    ///   `sort-as` starts with "Apple" (sorts first once romanized).
    /// - `r-beta`: original starts with "А" (sorts first in Cyrillic collation),
    ///   `sort-as` starts with "Zebra" (sorts last once romanized).
    ///
    /// So uniform sorting orders them beta-then-alpha, while romanized sorting
    /// orders them alpha-then-beta — the two policies deliberately disagree.
    fn multilingual_year_suffix_pair() -> (Reference, Reference) {
        let make = |id: &str, original: &str, sort_as: &str| {
            Reference::Monograph(Box::new(Monograph {
                id: Some(id.into()),
                r#type: MonographType::Book,
                title: Some(Title::Multilingual(MultilingualComplex {
                    original: original.to_string(),
                    lang: Some("ru".into()),
                    sort_as: Some(sort_as.to_string()),
                    transliterations: HashMap::new(),
                    translations: HashMap::new(),
                })),
                short_title: None,
                container: None,
                author: Some(Contributor::StructuredName(StructuredName {
                    family: MultilingualString::Simple("Smith".to_string()),
                    given: MultilingualString::Simple("Jordan".to_string()),
                    suffix: None,
                    dropping_particle: None,
                    non_dropping_particle: None,
                })),
                editor: None,
                translator: None,
                issued: DateValue::new("2020".to_string()),
                ..Default::default()
            }))
        };

        (
            make("r-alpha", "Яблоко", "Apple Studies"),
            make("r-beta", "Абрикос", "Zebra Studies"),
        )
    }

    fn title_group_sort() -> GroupSort {
        GroupSort {
            template: vec![GroupSortKey {
                key: SortKey::Title,
                ascending: true,
                order: None,
                sort_order: None,
            }],
        }
    }

    #[test]
    fn year_suffix_order_follows_romanized_bibliography_sort_policy() {
        let (r_alpha, r_beta) = multilingual_year_suffix_pair();
        let mut bib = Bibliography::new();
        bib.insert("r-alpha".to_string(), r_alpha);
        bib.insert("r-beta".to_string(), r_beta);

        let locale = Locale::en_us();
        let config = Config::default();
        let sort_spec = title_group_sort();

        // Uniform policy (the historical bug): year-suffix order follows the
        // original Cyrillic title order, independent of any bibliography
        // multilingual/locale sort configuration.
        let uniform_disamb =
            Disambiguator::with_group_sort(&bib, &config, &config, &locale, &sort_spec);
        let uniform_hints = uniform_disamb.calculate_hints();
        assert_eq!(
            uniform_hints.get("r-beta").unwrap().group_index,
            1,
            "uniform policy: original-text order puts r-beta ('Абрикос') first"
        );
        assert_eq!(
            uniform_hints.get("r-alpha").unwrap().group_index,
            2,
            "uniform policy: original-text order puts r-alpha ('Яблоко') second"
        );

        // Romanized policy: year-suffix order must follow the same sort-key
        // policy the final bibliography uses (sort-as / romanized order),
        // which is the opposite of the uniform original-text order here.
        let romanized_sort_config = romanized_config();
        let romanized_disamb = Disambiguator::with_group_sort(
            &bib,
            &config,
            &romanized_sort_config,
            &locale,
            &sort_spec,
        );
        let romanized_hints = romanized_disamb.calculate_hints();
        assert_eq!(
            romanized_hints.get("r-alpha").unwrap().group_index,
            1,
            "romanized policy: sort-as order puts r-alpha ('Apple Studies') first"
        );
        assert_eq!(
            romanized_hints.get("r-beta").unwrap().group_index,
            2,
            "romanized policy: sort-as order puts r-beta ('Zebra Studies') second"
        );

        // Tie the assertion explicitly to the final bibliography's own sorter,
        // so this test fails if the two ever diverge again.
        let refs: Vec<&Reference> = vec![bib.get("r-alpha").unwrap(), bib.get("r-beta").unwrap()];
        let sorter = ReferenceSorter::with_bibliography_config(&locale, &romanized_sort_config);
        let sorted_ids: Vec<String> = sorter
            .sort_references(refs, &sort_spec)
            .into_iter()
            .map(|reference| reference.id().expect("id").to_string())
            .collect();
        assert_eq!(
            sorted_ids,
            vec!["r-alpha".to_string(), "r-beta".to_string()],
            "final bibliography order must match the year-suffix group order"
        );
    }

    /// Reproduces the group-local disambiguation call site
    /// (`processor/bibliography/grouping.rs::build_group_local_hints`), which
    /// passes the same effective bibliography config as both `config` and
    /// `sort_config`. Confirms the fix applies to the group-local path too,
    /// not just the global `calculate_hints` path in `processor/setup.rs`.
    #[test]
    fn group_local_disambiguation_also_follows_romanized_bibliography_sort_policy() {
        let (r_alpha, r_beta) = multilingual_year_suffix_pair();
        let mut group_bibliography = Bibliography::new();
        group_bibliography.insert("r-alpha".to_string(), r_alpha);
        group_bibliography.insert("r-beta".to_string(), r_beta);

        let locale = Locale::en_us();
        let bibliography_config = romanized_config();
        let sort_spec = title_group_sort();

        let disambiguator = Disambiguator::with_group_sort(
            &group_bibliography,
            &bibliography_config,
            &bibliography_config,
            &locale,
            &sort_spec,
        );
        let hints = disambiguator.calculate_hints();

        assert_eq!(
            hints.get("r-alpha").unwrap().group_index,
            1,
            "group-local path: romanized sort-as order puts r-alpha first"
        );
        assert_eq!(
            hints.get("r-beta").unwrap().group_index,
            2,
            "group-local path: romanized sort-as order puts r-beta second"
        );
    }

    // csl26-huuz: collision grouping must reflect what the resolved date
    // slot actually renders for an undated reference, not a uniform "no
    // date" assumption.

    /// A reference with an explicit issued/accessed pair and a real shared
    /// author. `date_component_discriminant` never reads the author; the
    /// integration test below shares one author across every case so only
    /// the date half of the collision key varies.
    fn make_dated_ref(id: &str, family: &str, issued: &str, accessed: Option<&str>) -> Reference {
        Reference::Monograph(Box::new(Monograph {
            id: Some(id.into()),
            r#type: MonographType::Book,
            title: Some(Title::Single(format!("Title {id}"))),
            author: Some(Contributor::StructuredName(StructuredName {
                family: MultilingualString::Simple(family.to_string()),
                given: MultilingualString::Simple(String::new()),
                suffix: None,
                dropping_particle: None,
                non_dropping_particle: None,
            })),
            issued: DateValue::new(issued),
            accessed: accessed.map(DateValue::new),
            ..Default::default()
        }))
    }

    /// The GB/T-shaped date component under test: primary `issued`, falling
    /// back to an access year (never a discriminant, per csl26-huuz) and
    /// then to the locale's no-date term.
    fn issued_with_accessed_fallback() -> TemplateDate {
        TemplateDate {
            date: DateVariable::Issued,
            form: DateForm::Year,
            fallback: Some(vec![
                TemplateComponent::Date(TemplateDate {
                    date: DateVariable::Accessed,
                    form: DateForm::Year,
                    ..Default::default()
                }),
                TemplateComponent::Message(TemplateMessage {
                    message: "term.no-date".to_string(),
                    ..Default::default()
                }),
            ]),
            ..Default::default()
        }
    }

    #[rstest]
    #[case::real_issued_value_wins_without_consulting_fallback(
        "2020",
        None,
        "2020||None|None|None|None|None|None|None|None"
    )]
    #[case::present_accessed_stops_the_chain_with_no_identity("", Some("2020"), "")]
    #[case::absent_accessed_falls_through_to_the_no_date_term(
        "",
        None,
        "no date|None|None|None|None|None|None|None|None"
    )]
    #[case::empty_string_accessed_is_treated_as_absent(
        "",
        Some(""),
        "no date|None|None|None|None|None|None|None|None"
    )]
    fn given_an_issued_with_accessed_fallback_when_computing_the_collision_discriminant_then_it_matches(
        #[case] issued: &str,
        #[case] accessed: Option<&str>,
        #[case] expected: &str,
    ) {
        let reference = make_dated_ref("d1", "Smith", issued, accessed);
        let component = issued_with_accessed_fallback();

        let locale = Locale::en_us();
        let discriminant = Disambiguator::date_component_discriminant(
            &component,
            &reference,
            &locale,
            &Config::default(),
            &reference.ref_type(),
        );

        assert_eq!(discriminant, expected);
    }

    #[rstest]
    #[case::explicit_message_fallback(Some(vec![TemplateComponent::Message(TemplateMessage {
        message: "term.no-date".to_string(),
        form: Some(citum_schema::locale::TermForm::Short),
        ..Default::default()
    })]))]
    #[case::implicit_no_fallback_at_all(None)]
    fn given_an_undated_issued_slot_when_the_no_date_term_is_reached_then_the_discriminant_is_the_same_either_way(
        #[case] fallback: Option<Vec<TemplateComponent>>,
    ) {
        let reference = make_dated_ref("d2", "Smith", "", None);
        let component = TemplateDate {
            date: DateVariable::Issued,
            form: DateForm::Year,
            fallback,
            ..Default::default()
        };

        let locale = Locale::en_us();
        let discriminant = Disambiguator::date_component_discriminant(
            &component,
            &reference,
            &locale,
            &Config::default(),
            &reference.ref_type(),
        );

        // Both the implicit (no `fallback:` at all) and explicit
        // (`fallback: [message: term.no-date]`) paths render the identical
        // locale term via TemplateDate::values, so they must produce the
        // identical collision-key discriminant — otherwise a style that
        // mixes the two forms across type-variants would split undated
        // references that render identical text.
        assert_eq!(discriminant, "n.d.|None|None|None|None|None|None|None|None");
    }

    #[test]
    fn unresolved_message_fallback_continues_to_the_next_candidate() {
        let reference = make_dated_ref("d2", "Smith", "", None);
        let component = TemplateDate {
            date: DateVariable::Issued,
            form: DateForm::Year,
            fallback: Some(vec![
                TemplateComponent::Message(TemplateMessage {
                    message: "term.does-not-exist".to_string(),
                    ..TemplateMessage::default()
                }),
                TemplateComponent::Message(TemplateMessage {
                    message: "term.no-date".to_string(),
                    ..TemplateMessage::default()
                }),
            ]),
            ..TemplateDate::default()
        };

        let locale = Locale::en_us();
        let discriminant = Disambiguator::date_component_discriminant(
            &component,
            &reference,
            &locale,
            &Config::default(),
            &reference.ref_type(),
        );

        assert_eq!(
            discriminant,
            "no date|None|None|None|None|None|None|None|None"
        );
    }

    #[test]
    fn empty_explicit_fallback_list_yields_empty_discriminant() {
        let reference = make_dated_ref("d3", "Smith", "", None);
        let component = TemplateDate {
            date: DateVariable::Issued,
            form: DateForm::Year,
            fallback: Some(Vec::new()),
            ..Default::default()
        };

        let locale = Locale::en_us();
        let discriminant = Disambiguator::date_component_discriminant(
            &component,
            &reference,
            &locale,
            &Config::default(),
            &reference.ref_type(),
        );

        assert_eq!(discriminant, "");
    }

    #[test]
    fn fallback_candidate_note_obeys_the_candidate_suppress_note_flag() {
        let date = DateValue {
            value: "1947".to_string(),
            note: Some("民国36年".to_string()),
        };
        let rendering = Rendering {
            prefix: Some("c".into()),
            ..Default::default()
        };
        let date_config = DateConfig {
            note_wrap: Some(WrapConfig {
                punctuation: WrapPunctuation::Parentheses,
                inner_prefix: None,
                inner_suffix: None,
            }),
            ..Default::default()
        };
        let locale = Locale::en_us();

        let visible = crate::values::date::fallback_candidate_discriminant(
            &date,
            &DateForm::Year,
            &rendering,
            None,
            &locale,
            Some(&date_config),
        );
        let suppressed = crate::values::date::fallback_candidate_discriminant(
            &date,
            &DateForm::Year,
            &rendering,
            Some(true),
            &locale,
            Some(&date_config),
        );

        assert_eq!(
            visible.as_deref(),
            Some("1947|民国36年|None|None|None|None|None|Some(Custom(\"c\"))|None|None")
        );
        assert_eq!(
            suppressed.as_deref(),
            Some("1947||None|None|None|None|None|Some(Custom(\"c\"))|None|None")
        );
    }

    #[test]
    fn identity_date_slot_uses_the_configuration_from_its_effective_scope() {
        let reference = Reference::Monograph(Box::new(Monograph {
            id: Some("scope-date".into()),
            r#type: MonographType::Book,
            title: Some(Title::Single("Scoped date".to_string())),
            issued: DateValue::new(""),
            copyright: Some(DateValue {
                value: "1995".to_string(),
                note: Some("source calendar".to_string()),
            }),
            ..Default::default()
        }));
        let date_component = TemplateDate {
            date: DateVariable::Copyright,
            form: DateForm::Year,
            ..Default::default()
        };
        let bibliography_spec = BibliographySpec {
            template: Some(vec![TemplateComponent::Date(date_component.clone())].into()),
            ..Default::default()
        };
        let citation_spec = CitationSpec {
            template: Some(vec![TemplateComponent::Date(date_component)].into()),
            ..Default::default()
        };
        let note_dates = DateConfig {
            note_wrap: Some(WrapConfig {
                punctuation: WrapPunctuation::Parentheses,
                inner_prefix: None,
                inner_suffix: None,
            }),
            ..Default::default()
        };
        let with_note = Config {
            dates: Some(note_dates),
            ..Default::default()
        };
        let without_note = Config::default();
        let bibliography = Bibliography::new();
        let locale = Locale::en_us();

        let bibliography_owned =
            Disambiguator::new(&bibliography, &without_note, &with_note, &locale)
                .with_citation_spec(&citation_spec)
                .with_bibliography_spec(&bibliography_spec)
                .date_slot_discriminant(&reference);
        let citation_owned = Disambiguator::new(&bibliography, &with_note, &without_note, &locale)
            .with_citation_spec(&citation_spec)
            .date_slot_discriminant(&reference);

        assert_eq!(
            bibliography_owned, "1995|source calendar|None|None|None|None|None|None|None|None",
            "a bibliography-selected slot must use effective bibliography date options"
        );
        assert_eq!(
            citation_owned, "1995|source calendar|None|None|None|None|None|None|None|None",
            "the citation fallback slot must use effective citation date options"
        );
    }

    /// A reference whose only date is a `copyright` fallback candidate with
    /// day precision — mirrors GB/T 7714's `book,thesis,map` fallback chain
    /// (`date: copyright, form: year`).
    fn make_ref_with_copyright(id: &str, family: &str, copyright: &str) -> Reference {
        Reference::Monograph(Box::new(Monograph {
            id: Some(id.into()),
            r#type: MonographType::Book,
            title: Some(Title::Single(format!("Title {id}"))),
            author: Some(Contributor::StructuredName(StructuredName {
                family: MultilingualString::Simple(family.to_string()),
                given: MultilingualString::Simple(String::new()),
                suffix: None,
                dropping_particle: None,
                non_dropping_particle: None,
            })),
            issued: DateValue::new(""),
            copyright: Some(DateValue::new(copyright)),
            ..Default::default()
        }))
    }

    fn issued_with_copyright_fallback() -> TemplateDate {
        TemplateDate {
            date: DateVariable::Issued,
            form: DateForm::Year,
            fallback: Some(vec![TemplateComponent::Date(TemplateDate {
                date: DateVariable::Copyright,
                form: DateForm::Year,
                ..Default::default()
            })]),
            ..Default::default()
        }
    }

    #[rstest]
    #[case::day_precision_early_in_the_year("1995-03-01")]
    #[case::day_precision_late_in_the_year("1995-11-20")]
    fn given_a_copyright_fallback_date_with_day_precision_when_the_form_is_year_then_the_discriminant_is_the_bare_year(
        #[case] copyright: &str,
    ) {
        // `DateValue`'s `Display` is the raw stored EDTF string. Reading it
        // directly here would give "1995-03-01" and "1995-11-20" — two
        // different discriminants for two references that both render as
        // the bare year "1995" under `form: year`, wrongly treating them as
        // already distinguishable. Flagged in PR review for csl26-huuz.
        let component = issued_with_copyright_fallback();
        let reference = make_ref_with_copyright("r1", "Smith", copyright);
        let locale = Locale::en_us();

        let discriminant = Disambiguator::date_component_discriminant(
            &component,
            &reference,
            &locale,
            &Config::default(),
            &reference.ref_type(),
        );

        assert_eq!(
            discriminant,
            "1995||None|None|None|None|None|None|None|None"
        );
    }

    /// GB/T 7714's real `book,thesis,map` fallback chain: `copyright`
    /// prefixed with `c`, `printing` suffixed with `印刷`. A reference
    /// resolving one and a reference resolving the other can share a bare
    /// formatted year (`"1995"`) while rendering visibly different text
    /// (`c1995` vs `1995印刷`) — the discriminant must not collapse them.
    /// Flagged in PR review for csl26-huuz.
    #[test]
    fn copyright_and_printing_fallbacks_with_the_same_year_do_not_collide() {
        let component = TemplateDate {
            date: DateVariable::Issued,
            form: DateForm::Year,
            fallback: Some(vec![
                TemplateComponent::Date(TemplateDate {
                    date: DateVariable::Copyright,
                    form: DateForm::Year,
                    rendering: Rendering {
                        prefix: Some("c".into()),
                        ..Default::default()
                    },
                    ..Default::default()
                }),
                TemplateComponent::Date(TemplateDate {
                    date: DateVariable::Printing,
                    form: DateForm::Year,
                    rendering: Rendering {
                        suffix: Some("印刷".into()),
                        ..Default::default()
                    },
                    ..Default::default()
                }),
            ]),
            ..Default::default()
        };
        let copyright_ref = Reference::Monograph(Box::new(Monograph {
            id: Some("copyright-ref".into()),
            r#type: MonographType::Book,
            title: Some(Title::Single("Title copyright-ref".to_string())),
            author: Some(Contributor::StructuredName(StructuredName {
                family: MultilingualString::Simple("Smith".to_string()),
                given: MultilingualString::Simple(String::new()),
                suffix: None,
                dropping_particle: None,
                non_dropping_particle: None,
            })),
            issued: DateValue::new(""),
            copyright: Some(DateValue::new("1995")),
            ..Default::default()
        }));
        let printing_ref = Reference::Monograph(Box::new(Monograph {
            id: Some("printing-ref".into()),
            r#type: MonographType::Book,
            title: Some(Title::Single("Title printing-ref".to_string())),
            author: Some(Contributor::StructuredName(StructuredName {
                family: MultilingualString::Simple("Smith".to_string()),
                given: MultilingualString::Simple(String::new()),
                suffix: None,
                dropping_particle: None,
                non_dropping_particle: None,
            })),
            issued: DateValue::new(""),
            copyright: None,
            printing: Some(DateValue::new("1995")),
            ..Default::default()
        }));
        let locale = Locale::en_us();

        let copyright_discriminant = Disambiguator::date_component_discriminant(
            &component,
            &copyright_ref,
            &locale,
            &Config::default(),
            &copyright_ref.ref_type(),
        );
        let printing_discriminant = Disambiguator::date_component_discriminant(
            &component,
            &printing_ref,
            &locale,
            &Config::default(),
            &printing_ref.ref_type(),
        );

        assert_ne!(
            copyright_discriminant, printing_discriminant,
            "c1995 and 1995印刷 render visibly different text and must not collide"
        );
    }

    #[test]
    fn differing_access_dates_still_collide_via_shared_disambiguator() {
        // Mirrors GB/T 7714's webpage type-variant: an access date never
        // carries identity, so two references with *different* access years
        // must still collide (form one suffixed group), while a reference
        // with no access date at all — reaching the no-date term instead —
        // must land in a *separate* group. Both groups share the same
        // author, so only the date-slot discriminant can be responsible for
        // the split. See csl26-huuz.
        use citum_schema::options::{Disambiguation, Processing, ProcessingCustom};

        let mut bib = Bibliography::new();
        bib.insert(
            "b1".to_string(),
            make_dated_ref("b1", "Smith", "", Some("2020")),
        );
        bib.insert(
            "b2".to_string(),
            make_dated_ref("b2", "Smith", "", Some("2019")),
        );
        bib.insert("b3".to_string(), make_dated_ref("b3", "Smith", "", None));
        bib.insert("b4".to_string(), make_dated_ref("b4", "Smith", "", None));

        let locale = Locale::en_us();
        let config = Config {
            processing: Some(Processing::Custom(ProcessingCustom {
                base: None,
                disambiguate: Some(Disambiguation {
                    names: false,
                    add_givenname: false,
                    givenname_rule: GivennameRule::default(),
                    year_suffix: true,
                }),
                ..Default::default()
            })),
            ..Default::default()
        };
        let bibliography_spec = BibliographySpec {
            template: Some(
                vec![
                    citum_schema::tc_contributor!(Author, Long),
                    TemplateComponent::Date(issued_with_accessed_fallback()),
                ]
                .into(),
            ),
            ..Default::default()
        };
        let disambiguator = Disambiguator::new(&bib, &config, &config, &locale)
            .with_bibliography_spec(&bibliography_spec);
        let hints = disambiguator.calculate_hints();

        let accessed_group_key = hints.get("b1").unwrap().group_key.clone();
        let no_date_group_key = hints.get("b3").unwrap().group_key.clone();

        assert_eq!(
            hints.get("b2").unwrap().group_key,
            accessed_group_key,
            "different access years still share one group — the value never discriminates"
        );
        assert_eq!(
            hints.get("b4").unwrap().group_key,
            no_date_group_key,
            "both no-access-date references share the other group"
        );
        assert_ne!(
            accessed_group_key, no_date_group_key,
            "an access-date group must not merge with the no-date-term group"
        );

        // `group_length` reports same-*author* count (documented on
        // `author_group_lengths`), not collision-group size — all four
        // share author "Smith", so it's 4 for every entry here regardless
        // of which of the two date-discriminant groups they're actually in.
        // `group_index` is the field that reflects actual collision-group
        // membership: each 2-member group gets index 1 and 2.
        let b1_index = hints.get("b1").unwrap().group_index;
        let b2_index = hints.get("b2").unwrap().group_index;
        let b3_index = hints.get("b3").unwrap().group_index;
        let b4_index = hints.get("b4").unwrap().group_index;
        assert_eq!(
            [b1_index, b2_index]
                .into_iter()
                .collect::<std::collections::BTreeSet<_>>(),
            [1, 2].into_iter().collect(),
            "the access-date pair is indexed 1 and 2 within its own group"
        );
        assert_eq!(
            [b3_index, b4_index]
                .into_iter()
                .collect::<std::collections::BTreeSet<_>>(),
            [1, 2].into_iter().collect(),
            "the no-date pair is indexed 1 and 2 within its own, separate group"
        );

        for id in ["b1", "b2", "b3", "b4"] {
            assert!(
                hints.get(id).unwrap().disamb_condition,
                "{id}: both groups need a suffix"
            );
        }
    }
}