gtars-refget 0.11.0

Rust implementation of the refget standard for accessing reference sequences
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
1205
1206
1207
1208
1209
1210
1211
1212
1213
1214
1215
1216
1217
1218
1219
1220
1221
1222
1223
1224
1225
1226
1227
1228
1229
1230
1231
1232
1233
1234
1235
1236
1237
1238
1239
1240
1241
1242
1243
1244
1245
1246
1247
1248
1249
1250
1251
1252
1253
1254
1255
1256
1257
1258
1259
1260
1261
1262
1263
1264
1265
1266
1267
1268
1269
1270
1271
1272
1273
1274
1275
1276
1277
1278
1279
1280
1281
1282
1283
1284
1285
1286
1287
1288
1289
1290
1291
1292
1293
1294
1295
1296
1297
1298
1299
1300
1301
1302
1303
1304
1305
1306
1307
1308
1309
1310
1311
1312
1313
1314
1315
1316
1317
1318
1319
1320
1321
1322
1323
1324
1325
1326
1327
1328
1329
1330
1331
1332
1333
1334
1335
1336
1337
1338
1339
1340
1341
1342
1343
1344
1345
1346
1347
1348
1349
1350
1351
1352
1353
1354
1355
1356
1357
1358
1359
1360
1361
1362
1363
1364
1365
1366
1367
1368
1369
1370
1371
1372
1373
1374
1375
1376
1377
1378
1379
1380
1381
1382
1383
1384
1385
1386
1387
1388
1389
1390
1391
1392
1393
1394
1395
1396
1397
1398
1399
1400
1401
1402
1403
1404
1405
1406
1407
1408
1409
1410
1411
1412
1413
1414
1415
1416
1417
1418
1419
1420
1421
1422
1423
1424
1425
1426
1427
1428
1429
1430
1431
1432
1433
1434
1435
1436
1437
1438
1439
1440
1441
1442
1443
1444
1445
1446
1447
1448
1449
1450
1451
1452
1453
1454
1455
1456
1457
1458
1459
1460
1461
1462
1463
1464
1465
1466
1467
1468
1469
1470
1471
1472
1473
1474
1475
1476
1477
1478
1479
1480
1481
1482
1483
1484
1485
1486
1487
1488
1489
1490
1491
1492
1493
1494
1495
1496
1497
1498
1499
1500
1501
1502
1503
1504
1505
1506
1507
1508
1509
1510
1511
1512
1513
1514
1515
1516
1517
1518
1519
1520
1521
1522
1523
1524
1525
1526
1527
1528
1529
1530
1531
1532
1533
1534
1535
1536
1537
1538
1539
1540
1541
1542
1543
1544
1545
1546
1547
1548
1549
1550
1551
1552
1553
1554
1555
1556
1557
1558
1559
1560
1561
1562
1563
1564
1565
1566
1567
1568
1569
1570
1571
1572
1573
1574
1575
1576
1577
1578
1579
1580
1581
1582
1583
1584
1585
1586
1587
1588
1589
1590
1591
1592
1593
1594
1595
1596
1597
1598
1599
1600
1601
1602
1603
1604
1605
1606
1607
1608
1609
1610
1611
1612
1613
1614
1615
1616
1617
1618
1619
1620
1621
1622
1623
1624
1625
1626
1627
1628
1629
1630
1631
1632
1633
1634
1635
1636
1637
1638
1639
1640
1641
1642
1643
1644
1645
1646
1647
1648
1649
1650
1651
1652
1653
1654
1655
1656
1657
1658
1659
1660
1661
1662
1663
1664
1665
1666
1667
1668
1669
1670
1671
1672
1673
1674
1675
1676
1677
1678
1679
1680
1681
1682
1683
1684
1685
1686
1687
1688
1689
1690
1691
1692
1693
1694
1695
1696
1697
1698
1699
1700
1701
1702
1703
1704
1705
1706
1707
1708
1709
1710
1711
1712
1713
1714
1715
1716
1717
1718
1719
1720
1721
1722
1723
1724
1725
1726
1727
1728
1729
1730
1731
1732
1733
1734
1735
1736
1737
1738
1739
1740
1741
1742
1743
1744
1745
1746
1747
1748
1749
1750
1751
1752
1753
1754
1755
1756
1757
1758
1759
1760
1761
1762
1763
1764
1765
1766
1767
1768
1769
1770
1771
1772
1773
1774
1775
1776
1777
1778
1779
1780
1781
1782
1783
1784
1785
1786
1787
1788
1789
1790
1791
1792
1793
1794
1795
1796
1797
1798
1799
1800
1801
1802
1803
1804
1805
1806
1807
1808
1809
1810
1811
1812
1813
1814
1815
1816
1817
1818
1819
1820
1821
1822
1823
1824
1825
1826
1827
1828
1829
1830
1831
1832
1833
1834
1835
1836
1837
1838
1839
1840
1841
1842
1843
1844
1845
1846
1847
1848
1849
1850
1851
1852
1853
1854
1855
1856
1857
1858
1859
1860
1861
1862
1863
1864
1865
1866
1867
1868
1869
1870
1871
1872
1873
1874
1875
1876
1877
1878
1879
1880
1881
1882
1883
1884
1885
1886
1887
1888
1889
1890
1891
1892
1893
1894
1895
1896
1897
1898
1899
1900
1901
1902
1903
1904
1905
1906
1907
1908
1909
1910
1911
1912
1913
1914
1915
1916
1917
1918
1919
1920
1921
1922
1923
1924
1925
1926
1927
1928
1929
1930
1931
1932
1933
1934
1935
1936
1937
1938
1939
1940
1941
1942
1943
1944
1945
1946
1947
1948
1949
1950
1951
1952
1953
1954
1955
1956
1957
1958
1959
1960
1961
1962
1963
1964
1965
1966
1967
1968
1969
1970
1971
1972
1973
1974
1975
1976
1977
1978
1979
1980
1981
1982
1983
1984
1985
1986
1987
1988
1989
1990
1991
1992
1993
1994
1995
1996
1997
1998
1999
2000
2001
2002
2003
2004
2005
2006
2007
2008
2009
2010
2011
2012
2013
2014
2015
2016
2017
2018
2019
2020
2021
2022
2023
2024
2025
2026
2027
2028
2029
2030
2031
2032
2033
2034
2035
2036
2037
2038
2039
2040
2041
2042
2043
2044
2045
2046
2047
2048
2049
2050
2051
2052
2053
2054
2055
2056
2057
2058
2059
2060
2061
2062
2063
2064
2065
2066
2067
2068
2069
2070
2071
2072
2073
2074
2075
2076
2077
2078
2079
2080
2081
2082
2083
2084
2085
2086
2087
2088
2089
2090
2091
2092
2093
2094
2095
2096
2097
2098
2099
2100
2101
2102
2103
2104
2105
2106
2107
2108
2109
2110
2111
2112
2113
2114
2115
2116
2117
2118
2119
2120
2121
2122
2123
2124
2125
2126
2127
2128
2129
2130
2131
2132
2133
2134
2135
2136
2137
2138
2139
2140
2141
2142
2143
2144
2145
2146
2147
2148
2149
2150
2151
2152
2153
2154
2155
2156
2157
2158
2159
2160
2161
2162
2163
2164
2165
2166
2167
2168
2169
2170
2171
2172
2173
2174
2175
2176
2177
2178
2179
2180
2181
2182
2183
2184
2185
2186
2187
2188
2189
2190
2191
2192
2193
2194
2195
2196
2197
2198
2199
2200
2201
2202
2203
2204
2205
2206
2207
2208
2209
2210
2211
2212
2213
2214
2215
2216
2217
2218
2219
2220
2221
2222
2223
2224
2225
2226
2227
2228
2229
2230
2231
2232
2233
2234
2235
2236
2237
2238
2239
2240
2241
2242
2243
2244
2245
2246
2247
2248
2249
2250
2251
2252
2253
2254
2255
2256
2257
2258
2259
2260
2261
2262
2263
2264
2265
2266
2267
2268
2269
2270
2271
2272
2273
2274
2275
2276
2277
2278
2279
2280
2281
2282
2283
2284
2285
2286
2287
2288
2289
2290
2291
2292
2293
2294
2295
2296
2297
2298
2299
2300
2301
2302
2303
2304
2305
2306
2307
2308
2309
2310
2311
2312
2313
2314
2315
2316
2317
2318
2319
2320
2321
2322
2323
2324
2325
2326
2327
2328
2329
2330
2331
2332
2333
2334
2335
2336
2337
2338
2339
2340
2341
2342
2343
2344
2345
2346
2347
2348
2349
2350
2351
2352
2353
2354
2355
2356
2357
2358
2359
2360
2361
2362
2363
2364
2365
2366
2367
2368
2369
2370
2371
2372
2373
2374
2375
2376
2377
2378
2379
2380
2381
2382
2383
2384
2385
2386
2387
2388
2389
2390
2391
2392
2393
2394
2395
2396
2397
2398
2399
2400
2401
2402
2403
2404
2405
2406
2407
2408
2409
2410
2411
2412
2413
2414
2415
2416
2417
2418
2419
2420
2421
2422
2423
2424
2425
2426
2427
2428
2429
2430
2431
2432
2433
2434
2435
2436
2437
2438
2439
2440
2441
2442
2443
2444
2445
2446
2447
2448
2449
2450
2451
2452
2453
2454
2455
2456
2457
2458
2459
2460
2461
2462
2463
2464
2465
2466
2467
2468
2469
2470
2471
2472
2473
2474
2475
2476
2477
2478
2479
2480
2481
2482
2483
2484
2485
2486
2487
2488
2489
2490
2491
2492
2493
2494
2495
2496
2497
2498
2499
2500
2501
2502
2503
2504
2505
2506
2507
2508
2509
2510
2511
2512
2513
2514
2515
2516
2517
2518
2519
2520
2521
2522
2523
2524
2525
2526
2527
2528
2529
2530
2531
2532
2533
2534
2535
2536
2537
2538
2539
2540
2541
2542
2543
2544
2545
2546
2547
2548
2549
2550
2551
2552
2553
2554
2555
2556
2557
2558
2559
2560
2561
2562
2563
2564
2565
2566
2567
2568
2569
2570
2571
2572
2573
2574
2575
2576
2577
2578
2579
2580
2581
2582
2583
2584
2585
2586
2587
2588
2589
2590
2591
2592
2593
2594
2595
2596
2597
2598
2599
2600
2601
2602
2603
2604
2605
2606
2607
2608
2609
2610
2611
2612
2613
2614
2615
2616
2617
2618
2619
2620
2621
2622
2623
2624
2625
2626
2627
2628
2629
2630
2631
2632
2633
2634
2635
2636
2637
2638
2639
2640
2641
2642
2643
2644
2645
2646
2647
2648
2649
2650
2651
2652
2653
2654
2655
2656
2657
2658
2659
2660
2661
2662
2663
2664
2665
2666
2667
2668
2669
2670
2671
2672
2673
2674
2675
2676
2677
2678
2679
2680
2681
2682
2683
2684
2685
2686
2687
2688
2689
2690
2691
2692
2693
2694
2695
2696
2697
2698
2699
2700
2701
2702
2703
2704
2705
2706
2707
2708
2709
2710
2711
2712
2713
2714
2715
2716
2717
2718
2719
2720
2721
2722
2723
2724
2725
2726
2727
2728
2729
2730
2731
2732
2733
2734
2735
2736
2737
2738
2739
2740
2741
2742
2743
2744
2745
2746
2747
2748
2749
2750
2751
2752
2753
2754
2755
2756
2757
2758
2759
2760
2761
2762
2763
2764
2765
2766
2767
2768
2769
2770
2771
2772
2773
2774
2775
2776
2777
2778
2779
2780
2781
2782
2783
2784
2785
2786
2787
2788
2789
2790
2791
2792
2793
2794
2795
2796
2797
2798
2799
2800
2801
2802
2803
2804
2805
2806
2807
2808
2809
2810
2811
2812
2813
2814
2815
2816
2817
2818
2819
2820
2821
2822
2823
2824
2825
2826
2827
2828
2829
2830
2831
2832
2833
2834
2835
2836
2837
2838
2839
2840
2841
2842
2843
2844
2845
2846
2847
2848
2849
2850
2851
2852
2853
2854
2855
2856
2857
2858
2859
2860
2861
2862
2863
2864
2865
2866
2867
2868
2869
2870
2871
2872
2873
2874
2875
2876
2877
2878
2879
2880
2881
2882
2883
2884
2885
2886
2887
2888
2889
2890
2891
2892
2893
2894
2895
2896
2897
2898
2899
2900
2901
2902
2903
2904
2905
2906
2907
2908
2909
2910
2911
2912
2913
2914
2915
2916
2917
2918
2919
2920
2921
2922
2923
2924
2925
2926
2927
2928
2929
2930
2931
2932
2933
2934
2935
2936
2937
2938
2939
2940
2941
2942
2943
2944
2945
2946
2947
2948
2949
2950
2951
2952
2953
2954
2955
2956
2957
2958
2959
2960
2961
2962
2963
2964
2965
2966
2967
2968
2969
2970
2971
2972
2973
2974
2975
2976
2977
2978
2979
2980
2981
2982
2983
2984
2985
2986
2987
2988
2989
2990
2991
2992
2993
2994
2995
2996
2997
2998
2999
3000
3001
3002
3003
3004
3005
3006
3007
3008
3009
3010
3011
3012
3013
3014
3015
3016
3017
3018
3019
3020
3021
3022
3023
3024
3025
3026
3027
3028
3029
3030
3031
3032
3033
3034
3035
3036
3037
3038
3039
3040
3041
3042
3043
3044
3045
3046
3047
3048
3049
3050
3051
3052
3053
3054
3055
3056
3057
3058
3059
3060
3061
3062
3063
3064
3065
3066
3067
3068
3069
3070
3071
3072
3073
3074
3075
3076
3077
3078
3079
3080
3081
3082
3083
3084
3085
3086
3087
3088
3089
3090
3091
3092
3093
3094
3095
3096
3097
3098
3099
3100
3101
3102
3103
3104
3105
3106
3107
3108
3109
3110
3111
3112
3113
3114
3115
3116
3117
3118
3119
3120
3121
3122
3123
3124
3125
3126
3127
3128
3129
3130
3131
3132
3133
3134
3135
3136
3137
3138
3139
3140
3141
3142
3143
3144
3145
3146
3147
3148
3149
3150
3151
3152
3153
3154
3155
3156
3157
3158
3159
3160
3161
3162
3163
3164
3165
3166
3167
3168
3169
3170
3171
3172
3173
3174
3175
3176
3177
3178
3179
3180
3181
3182
3183
3184
3185
3186
3187
3188
3189
3190
3191
3192
3193
3194
3195
3196
3197
3198
3199
3200
3201
3202
3203
3204
3205
3206
3207
3208
3209
3210
3211
3212
3213
3214
3215
3216
3217
3218
3219
3220
3221
3222
3223
3224
3225
3226
3227
3228
3229
3230
3231
3232
3233
3234
3235
3236
3237
3238
3239
3240
3241
3242
3243
3244
3245
3246
3247
3248
3249
3250
3251
3252
3253
3254
3255
3256
3257
3258
3259
3260
3261
3262
3263
3264
3265
3266
3267
3268
3269
3270
3271
3272
3273
3274
3275
3276
3277
3278
3279
3280
3281
3282
3283
3284
3285
3286
3287
3288
3289
3290
3291
3292
3293
3294
3295
3296
3297
3298
3299
3300
3301
3302
3303
3304
3305
3306
3307
3308
3309
3310
3311
3312
3313
3314
3315
3316
3317
3318
3319
3320
3321
3322
3323
3324
3325
3326
3327
3328
3329
3330
3331
3332
3333
3334
3335
3336
3337
3338
3339
3340
3341
3342
3343
3344
3345
3346
3347
3348
3349
3350
3351
3352
3353
3354
3355
3356
3357
3358
3359
3360
3361
3362
3363
3364
3365
3366
3367
3368
3369
3370
3371
3372
3373
3374
3375
3376
3377
3378
3379
3380
3381
3382
3383
3384
3385
3386
3387
3388
3389
3390
3391
3392
3393
3394
3395
3396
3397
3398
3399
3400
3401
3402
3403
3404
3405
3406
3407
3408
3409
3410
3411
3412
3413
3414
3415
3416
3417
3418
3419
3420
3421
3422
3423
3424
3425
3426
3427
3428
3429
3430
3431
3432
3433
3434
3435
3436
3437
3438
3439
3440
3441
3442
3443
3444
3445
3446
3447
3448
3449
3450
3451
3452
3453
3454
3455
3456
3457
3458
3459
3460
3461
3462
3463
3464
3465
3466
3467
3468
3469
3470
3471
3472
3473
3474
3475
3476
3477
3478
3479
3480
3481
3482
3483
3484
3485
3486
3487
3488
3489
3490
3491
3492
3493
3494
3495
3496
3497
3498
3499
3500
3501
3502
3503
3504
3505
3506
3507
3508
3509
3510
3511
3512
3513
3514
3515
3516
3517
3518
3519
3520
3521
3522
3523
3524
3525
3526
3527
3528
3529
3530
3531
3532
3533
3534
3535
3536
3537
3538
3539
3540
3541
3542
3543
3544
3545
3546
3547
3548
3549
3550
3551
3552
3553
3554
3555
3556
3557
3558
3559
3560
3561
3562
3563
3564
3565
3566
3567
3568
3569
3570
3571
3572
3573
3574
3575
3576
3577
3578
3579
3580
3581
3582
3583
3584
3585
3586
3587
3588
3589
3590
3591
3592
3593
3594
3595
3596
3597
3598
3599
3600
3601
3602
3603
3604
3605
3606
3607
3608
3609
3610
3611
3612
3613
3614
3615
3616
3617
3618
3619
3620
3621
3622
3623
3624
3625
3626
3627
3628
3629
3630
3631
3632
3633
3634
3635
3636
3637
3638
3639
3640
3641
3642
3643
3644
3645
3646
3647
3648
3649
3650
3651
3652
3653
3654
3655
3656
3657
3658
3659
3660
3661
3662
3663
3664
3665
3666
3667
3668
3669
3670
3671
3672
3673
3674
3675
3676
3677
3678
3679
3680
3681
3682
3683
3684
3685
3686
3687
3688
3689
3690
3691
3692
3693
3694
3695
3696
3697
3698
3699
3700
3701
3702
3703
3704
3705
3706
3707
3708
3709
3710
3711
3712
3713
3714
3715
3716
3717
3718
3719
3720
3721
3722
3723
3724
3725
3726
3727
3728
3729
3730
3731
3732
3733
3734
3735
3736
3737
3738
3739
3740
3741
3742
3743
3744
3745
3746
3747
3748
3749
3750
3751
3752
3753
3754
3755
3756
3757
3758
3759
3760
3761
3762
3763
3764
3765
3766
3767
3768
3769
3770
3771
3772
3773
3774
3775
3776
3777
3778
3779
3780
3781
3782
3783
3784
3785
3786
3787
3788
3789
3790
3791
3792
3793
3794
3795
3796
3797
3798
3799
3800
3801
3802
3803
3804
3805
3806
3807
3808
3809
3810
3811
3812
3813
3814
3815
3816
3817
3818
3819
3820
3821
3822
3823
3824
3825
3826
3827
3828
3829
3830
3831
3832
3833
3834
3835
3836
3837
3838
3839
3840
3841
3842
3843
3844
3845
3846
3847
3848
3849
3850
3851
3852
3853
3854
3855
3856
3857
3858
3859
3860
3861
3862
3863
3864
3865
3866
3867
3868
3869
3870
3871
3872
3873
3874
3875
3876
3877
3878
3879
3880
3881
3882
3883
3884
3885
3886
3887
3888
3889
3890
3891
3892
3893
3894
3895
3896
3897
3898
3899
3900
3901
3902
3903
3904
3905
3906
3907
3908
3909
3910
3911
3912
3913
3914
3915
3916
3917
3918
3919
3920
3921
3922
3923
3924
3925
3926
3927
3928
3929
3930
3931
3932
3933
3934
3935
3936
3937
3938
3939
3940
3941
3942
3943
3944
3945
3946
3947
3948
3949
3950
3951
3952
3953
3954
3955
3956
3957
3958
3959
3960
3961
3962
3963
3964
3965
3966
3967
3968
3969
3970
3971
3972
3973
3974
3975
3976
3977
3978
3979
3980
3981
3982
3983
3984
3985
3986
3987
3988
3989
3990
3991
3992
3993
3994
3995
3996
3997
3998
3999
4000
4001
4002
4003
4004
4005
4006
4007
4008
4009
4010
4011
4012
4013
4014
4015
4016
4017
4018
4019
4020
4021
4022
4023
4024
4025
4026
4027
4028
4029
4030
4031
4032
4033
4034
4035
4036
4037
4038
4039
4040
4041
4042
4043
4044
4045
4046
4047
4048
4049
4050
4051
4052
4053
4054
4055
4056
4057
4058
4059
4060
4061
4062
4063
4064
4065
4066
4067
4068
4069
4070
4071
4072
4073
4074
4075
4076
4077
4078
4079
4080
4081
4082
4083
4084
4085
4086
4087
4088
4089
4090
4091
4092
4093
4094
4095
4096
4097
4098
4099
4100
4101
4102
4103
4104
4105
4106
4107
4108
4109
4110
4111
4112
4113
4114
4115
4116
4117
4118
4119
4120
4121
4122
4123
4124
4125
4126
4127
4128
4129
4130
4131
4132
4133
4134
4135
4136
4137
4138
4139
4140
4141
4142
4143
4144
4145
4146
4147
4148
4149
4150
4151
4152
4153
4154
4155
4156
4157
4158
4159
4160
4161
4162
4163
4164
4165
4166
4167
4168
4169
4170
4171
4172
4173
4174
4175
4176
4177
4178
4179
4180
4181
4182
4183
4184
4185
4186
4187
4188
4189
4190
4191
4192
4193
4194
4195
4196
4197
4198
4199
4200
4201
4202
4203
4204
4205
4206
4207
4208
4209
4210
4211
4212
4213
4214
4215
4216
4217
4218
4219
4220
4221
4222
4223
4224
4225
4226
4227
4228
4229
4230
4231
4232
4233
4234
4235
4236
4237
4238
4239
4240
4241
4242
4243
4244
4245
4246
4247
4248
4249
4250
4251
4252
4253
4254
4255
4256
4257
4258
4259
4260
4261
4262
4263
4264
4265
4266
4267
4268
4269
4270
4271
4272
4273
4274
4275
4276
4277
4278
4279
4280
4281
4282
4283
4284
4285
4286
4287
4288
4289
4290
4291
4292
4293
4294
4295
4296
4297
4298
4299
4300
4301
4302
4303
4304
4305
4306
4307
4308
4309
4310
4311
4312
4313
4314
4315
4316
4317
4318
4319
4320
4321
4322
4323
4324
4325
4326
4327
4328
4329
4330
4331
4332
4333
4334
4335
4336
4337
4338
4339
4340
4341
4342
4343
4344
4345
4346
4347
4348
4349
4350
4351
4352
4353
4354
4355
4356
4357
4358
4359
4360
4361
4362
4363
4364
4365
4366
4367
4368
4369
4370
4371
4372
4373
4374
4375
4376
4377
4378
4379
4380
4381
4382
4383
4384
4385
4386
4387
4388
4389
4390
4391
4392
4393
4394
4395
4396
4397
4398
4399
4400
4401
4402
4403
4404
4405
4406
4407
4408
4409
4410
4411
4412
4413
4414
4415
4416
4417
4418
4419
4420
4421
4422
4423
4424
4425
4426
4427
4428
4429
4430
4431
4432
4433
4434
4435
4436
4437
4438
4439
4440
4441
4442
4443
4444
4445
4446
4447
4448
4449
4450
4451
4452
4453
4454
4455
4456
4457
4458
4459
4460
4461
4462
4463
4464
4465
4466
4467
4468
4469
4470
4471
4472
4473
4474
4475
4476
4477
4478
4479
4480
4481
4482
4483
4484
4485
4486
4487
4488
4489
4490
4491
4492
4493
4494
4495
4496
4497
4498
4499
4500
4501
4502
4503
4504
4505
4506
4507
4508
4509
4510
4511
4512
4513
4514
4515
4516
4517
4518
4519
4520
4521
4522
4523
4524
4525
4526
4527
4528
4529
4530
4531
4532
4533
4534
4535
4536
4537
4538
4539
4540
4541
4542
4543
4544
4545
4546
4547
4548
4549
4550
4551
4552
4553
4554
4555
4556
4557
4558
4559
4560
4561
4562
4563
4564
4565
4566
4567
4568
4569
4570
4571
4572
4573
4574
4575
4576
4577
4578
4579
4580
4581
4582
4583
4584
4585
4586
4587
4588
4589
4590
4591
4592
4593
4594
4595
4596
4597
4598
4599
4600
4601
4602
4603
4604
4605
4606
4607
4608
4609
4610
4611
4612
4613
4614
4615
4616
4617
4618
4619
4620
4621
4622
4623
4624
4625
4626
4627
4628
4629
4630
4631
4632
4633
4634
4635
4636
4637
4638
4639
4640
4641
4642
4643
4644
4645
4646
4647
4648
4649
4650
4651
4652
4653
4654
4655
4656
4657
4658
4659
4660
4661
4662
4663
4664
4665
4666
4667
4668
4669
4670
4671
4672
4673
4674
4675
4676
4677
4678
4679
4680
4681
4682
4683
4684
4685
4686
4687
4688
4689
4690
4691
4692
4693
4694
4695
4696
4697
4698
4699
4700
4701
4702
4703
4704
4705
4706
4707
4708
4709
4710
4711
4712
4713
4714
4715
4716
4717
4718
4719
4720
4721
4722
4723
4724
4725
4726
4727
4728
4729
4730
4731
4732
4733
4734
4735
4736
4737
4738
4739
4740
4741
4742
4743
4744
4745
4746
4747
4748
4749
4750
4751
4752
4753
4754
4755
4756
4757
4758
4759
4760
4761
4762
4763
4764
4765
4766
4767
4768
4769
4770
4771
4772
4773
4774
4775
4776
4777
4778
4779
4780
4781
4782
4783
4784
4785
4786
4787
4788
4789
4790
4791
4792
4793
4794
4795
4796
4797
4798
4799
4800
4801
4802
4803
4804
4805
4806
4807
4808
4809
4810
4811
4812
4813
4814
4815
4816
4817
4818
4819
4820
4821
4822
4823
4824
4825
4826
4827
4828
4829
4830
4831
4832
4833
4834
4835
4836
4837
4838
4839
4840
4841
4842
4843
4844
4845
4846
4847
4848
4849
4850
4851
4852
4853
4854
4855
4856
4857
4858
4859
4860
4861
4862
4863
4864
4865
4866
4867
4868
4869
4870
4871
4872
4873
4874
4875
4876
4877
4878
4879
4880
4881
4882
4883
4884
4885
4886
4887
4888
4889
4890
4891
4892
4893
4894
4895
4896
4897
4898
4899
4900
4901
4902
4903
4904
4905
4906
4907
4908
4909
4910
4911
4912
4913
4914
4915
4916
4917
4918
4919
4920
4921
4922
4923
4924
4925
4926
4927
4928
4929
4930
4931
4932
4933
4934
4935
4936
4937
4938
4939
4940
4941
4942
4943
4944
4945
4946
4947
4948
4949
4950
4951
4952
4953
4954
4955
4956
4957
4958
4959
4960
4961
4962
4963
4964
4965
4966
4967
4968
4969
4970
4971
4972
4973
4974
4975
4976
4977
4978
4979
4980
4981
4982
4983
4984
4985
4986
4987
4988
4989
4990
4991
4992
4993
4994
4995
4996
4997
4998
4999
5000
5001
5002
5003
5004
5005
5006
5007
5008
5009
5010
5011
5012
5013
5014
5015
5016
5017
5018
5019
5020
5021
5022
5023
5024
5025
5026
5027
5028
5029
5030
5031
5032
5033
5034
5035
5036
5037
5038
5039
5040
5041
5042
5043
5044
5045
5046
5047
5048
5049
5050
5051
5052
5053
5054
5055
5056
5057
5058
5059
5060
5061
5062
5063
5064
5065
5066
5067
5068
5069
5070
5071
5072
5073
5074
5075
5076
5077
5078
5079
5080
5081
5082
5083
5084
5085
5086
5087
5088
5089
5090
5091
5092
5093
5094
5095
5096
5097
5098
5099
5100
5101
5102
5103
5104
5105
5106
5107
5108
5109
5110
5111
5112
5113
5114
5115
5116
5117
5118
5119
5120
5121
5122
5123
5124
5125
5126
5127
5128
5129
5130
5131
5132
5133
5134
5135
5136
5137
5138
5139
5140
5141
5142
5143
5144
5145
5146
5147
5148
5149
5150
5151
5152
5153
5154
5155
5156
5157
5158
5159
5160
5161
5162
5163
5164
5165
5166
5167
5168
5169
5170
5171
5172
5173
5174
5175
5176
5177
5178
5179
5180
5181
5182
5183
5184
5185
5186
5187
5188
5189
5190
5191
5192
5193
5194
5195
5196
5197
5198
5199
5200
5201
5202
5203
5204
5205
5206
5207
5208
5209
5210
5211
5212
5213
5214
5215
5216
5217
5218
5219
5220
5221
5222
5223
5224
5225
5226
5227
5228
5229
5230
5231
5232
5233
5234
5235
5236
5237
5238
5239
5240
5241
5242
5243
5244
5245
5246
5247
5248
5249
5250
5251
5252
5253
5254
5255
5256
5257
5258
5259
5260
5261
5262
5263
5264
5265
5266
5267
5268
5269
5270
5271
5272
5273
5274
5275
5276
5277
5278
5279
5280
5281
5282
5283
5284
5285
5286
5287
5288
5289
5290
5291
5292
5293
5294
5295
5296
5297
5298
5299
5300
5301
5302
5303
5304
5305
5306
5307
5308
5309
5310
5311
5312
5313
5314
5315
5316
5317
5318
5319
5320
5321
5322
5323
5324
5325
5326
5327
5328
5329
5330
5331
5332
5333
5334
5335
5336
5337
5338
5339
5340
5341
5342
5343
5344
5345
5346
5347
5348
5349
5350
5351
5352
5353
5354
5355
5356
5357
5358
5359
5360
5361
5362
5363
5364
5365
5366
5367
5368
5369
5370
5371
5372
5373
5374
5375
5376
5377
5378
5379
5380
5381
5382
5383
5384
5385
5386
5387
5388
5389
5390
5391
5392
5393
5394
5395
5396
5397
5398
5399
5400
5401
5402
5403
5404
5405
5406
5407
5408
5409
5410
5411
5412
5413
5414
5415
5416
5417
5418
5419
5420
5421
5422
5423
5424
5425
5426
5427
5428
5429
5430
5431
5432
5433
5434
5435
5436
5437
5438
5439
5440
5441
5442
5443
5444
5445
5446
5447
5448
5449
5450
5451
5452
5453
5454
5455
5456
5457
5458
5459
5460
5461
5462
5463
5464
5465
5466
5467
5468
5469
5470
5471
5472
5473
5474
5475
5476
5477
5478
5479
5480
5481
5482
5483
//! Store integration tests -- cross-cutting concerns (import, export, persistence, lazy-loading).

use super::*;

use crate::collection::SequenceCollectionExt;
use crate::digest::types::{
    SequenceCollection, SequenceCollectionMetadata, SequenceMetadata, SequenceRecord,
};
use crate::digest::{AlphabetType, md5, sha512t24u};
use crate::hashkeyable::{DigestKey, HashKeyable};
use std::fs;
use std::path::PathBuf;
use tempfile::tempdir;

// =========================================================================
// Test helpers
// =========================================================================

/// Copy a test FASTA to a temp directory to avoid writing RGSI cache files
/// into the test data directory.
fn copy_test_fasta(temp_dir: &std::path::Path, name: &str) -> std::path::PathBuf {
    let src = format!("../tests/data/fasta/{}", name);
    let dst = temp_dir.join(name);
    std::fs::copy(&src, &dst)
        .unwrap_or_else(|e| panic!("Failed to copy {} to tempdir: {}", src, e));
    dst
}

fn calculate_test_digests(sequence: &[u8]) -> (String, String) {
    (sha512t24u(sequence), md5(sequence))
}

/// Helper: create an in-memory store with one collection from a FASTA string.
fn store_with_one_collection(fasta_content: &str) -> (RefgetStore, String) {
    let dir = tempdir().unwrap();
    let fasta = dir.path().join("test.fa");
    fs::write(&fasta, fasta_content).unwrap();

    let mut store = RefgetStore::in_memory();
    let (meta, _) = store
        .add_sequence_collection_from_fasta(&fasta, FastaImportOptions::new())
        .unwrap();
    (store, meta.digest)
}

/// Creates a test store with 3 sequences for export testing.
fn setup_export_test_store(temp_path: &std::path::Path) -> (RefgetStore, DigestKey) {
    let fasta_content = ">chr1\nATGCATGCATGC\n>chr2\nGGGGAAAA\n>chr3\nTTTTCCCC\n";
    let temp_fasta_path = temp_path.join("test.fa");
    fs::write(&temp_fasta_path, fasta_content).expect("Failed to write test FASTA file");

    let mut store = RefgetStore::in_memory();
    store
        .add_sequence_collection_from_fasta(&temp_fasta_path, FastaImportOptions::new())
        .unwrap();

    let collections: Vec<_> = store.collections.keys().cloned().collect();
    let collection_digest = collections[0];

    (store, collection_digest)
}

// =========================================================================
// Template and path tests (merged parametric)
// =========================================================================
// `test_expand_template`, `test_sanitize_relative_path`, and `test_mode_basics`
// are non-filesystem tests; they live in the always-compiled `nofs_tests`
// module in `store/mod.rs` so they run under `--no-default-features`.

// =========================================================================
// Mode tests
// =========================================================================

#[test]
fn test_mode_switching() {
    let temp_dir = tempdir().expect("Failed to create temporary directory");
    let temp_path = temp_dir.path();
    let fasta_content = ">chr1\nATGCATGCATGC\n>chr2\nGGGGAAAA\n";
    let temp_fasta_path = temp_path.join("test.fa");
    fs::write(&temp_fasta_path, fasta_content).expect("Failed to write test FASTA file");

    let (chr1_sha, _) = calculate_test_digests(b"ATGCATGCATGC");
    let chr1_key = chr1_sha.as_bytes().to_key();

    // Test Raw -> Encoded
    {
        let mut store = RefgetStore::in_memory();
        store.disable_encoding();
        store
            .add_sequence_collection_from_fasta(&temp_fasta_path, FastaImportOptions::new())
            .unwrap();

        if let Some(SequenceRecord::Full { sequence, .. }) = store.sequence_store.get(&chr1_key) {
            assert_eq!(&sequence[..], b"ATGCATGCATGC");
        }
        let seq_before = store.get_sequence(&chr1_sha).unwrap().decode().unwrap();

        store.set_encoding_mode(StorageMode::Encoded);

        if let Some(SequenceRecord::Full { sequence, .. }) = store.sequence_store.get(&chr1_key) {
            assert_eq!(sequence.len(), 3);
        }
        let seq_after = store.get_sequence(&chr1_sha).unwrap().decode().unwrap();
        assert_eq!(seq_before, seq_after);
    }

    // Test Encoded -> Raw
    {
        let mut store = RefgetStore::in_memory();
        store
            .add_sequence_collection_from_fasta(&temp_fasta_path, FastaImportOptions::new())
            .unwrap();

        if let Some(SequenceRecord::Full { sequence, .. }) = store.sequence_store.get(&chr1_key) {
            assert_eq!(sequence.len(), 3);
        }
        let seq_before = store.get_sequence(&chr1_sha).unwrap().decode().unwrap();

        store.disable_encoding();

        if let Some(SequenceRecord::Full { sequence, .. }) = store.sequence_store.get(&chr1_key) {
            assert_eq!(&sequence[..], b"ATGCATGCATGC");
        }
        let seq_after = store.get_sequence(&chr1_sha).unwrap().decode().unwrap();
        assert_eq!(seq_before, seq_after);
    }
}

// =========================================================================
// Import and retrieval tests
// =========================================================================

#[test]
fn test_refget_store_retrieve_seq_and_vec() {
    let temp_dir = tempdir().expect("Failed to create temporary directory");
    let temp_path = temp_dir.path();

    let fasta_content = "\
>chr1
ATGCATGCATGC
>chr2
GGGGAAAA
";
    let temp_fasta_path = temp_path.join("test.fa");
    fs::write(&temp_fasta_path, fasta_content).expect("Failed to write test FASTA file");

    let mut store = RefgetStore::in_memory();
    store
        .add_sequence_collection_from_fasta(&temp_fasta_path, FastaImportOptions::new())
        .unwrap();

    let collection_digest_ref: &str = "uC_UorBNf3YUu1YIDainBhI94CedlNeH";

    // Test BED-based export
    let bed_content = "\
chr1\t0\t5
chr1\t8\t12
chr2\t0\t4
";
    let temp_bed_path = temp_path.join("test.bed");
    fs::write(&temp_bed_path, bed_content).expect("Failed to write test BED file");

    let temp_output_fa_path = temp_path.join("output.fa");

    store
        .export_fasta_from_regions(
            collection_digest_ref,
            temp_bed_path.to_str().unwrap(),
            temp_output_fa_path.to_str().unwrap(),
        )
        .expect("export_fasta_from_regions failed");

    let output_fa_content =
        fs::read_to_string(&temp_output_fa_path).expect("Failed to read output FASTA file");

    let expected_fa_content = ">chr1:0-5\nATGCA\n>chr1:8-12\nATGC\n>chr2:0-4\nGGGG\n";
    assert_eq!(
        output_fa_content.trim(),
        expected_fa_content.trim(),
        "Output FASTA file content mismatch"
    );

    // Test substrings_from_regions iterator
    let vec_result: Vec<_> = store
        .substrings_from_regions(collection_digest_ref, temp_bed_path.to_str().unwrap())
        .expect("substrings_from_regions failed")
        .collect::<Result<Vec<_>, _>>()
        .expect("substrings_from_regions had errors");

    let expected_vec = vec![
        RetrievedSequence {
            sequence: "ATGCA".to_string(),
            chrom_name: "chr1".to_string(),
            start: 0,
            end: 5,
        },
        RetrievedSequence {
            sequence: "ATGC".to_string(),
            chrom_name: "chr1".to_string(),
            start: 8,
            end: 12,
        },
        RetrievedSequence {
            sequence: "GGGG".to_string(),
            chrom_name: "chr2".to_string(),
            start: 0,
            end: 4,
        },
    ];

    assert_eq!(vec_result, expected_vec, "Retrieved sequence vector mismatch");
}

#[test]
fn test_substrings_from_region_vectors() {
    let temp_dir = tempdir().expect("Failed to create temporary directory");
    let temp_path = temp_dir.path();

    let fasta_content = ">chr1\nATGCATGCATGC\n>chr2\nGGGGAAAA\n";
    let temp_fasta_path = temp_path.join("test.fa");
    fs::write(&temp_fasta_path, fasta_content).expect("Failed to write test FASTA file");

    let mut store = RefgetStore::in_memory();
    store
        .add_sequence_collection_from_fasta(&temp_fasta_path, FastaImportOptions::new())
        .unwrap();

    let collection_digest_ref: &str = "uC_UorBNf3YUu1YIDainBhI94CedlNeH";

    // Parallel input vectors equivalent to the BED rows used in the file-based test.
    let chroms = ["chr1", "chr1", "chr2"];
    let starts = [0u32, 8, 0];
    let ends = [5u32, 12, 4];

    let vec_result: Vec<_> = store
        .substrings_from_region_vectors(collection_digest_ref, &chroms, &starts, &ends)
        .expect("substrings_from_region_vectors failed")
        .collect::<Result<Vec<_>, _>>()
        .expect("substrings_from_region_vectors had errors");

    let expected_vec = vec![
        RetrievedSequence {
            sequence: "ATGCA".to_string(),
            chrom_name: "chr1".to_string(),
            start: 0,
            end: 5,
        },
        RetrievedSequence {
            sequence: "ATGC".to_string(),
            chrom_name: "chr1".to_string(),
            start: 8,
            end: 12,
        },
        RetrievedSequence {
            sequence: "GGGG".to_string(),
            chrom_name: "chr2".to_string(),
            start: 0,
            end: 4,
        },
    ];

    assert_eq!(
        vec_result, expected_vec,
        "Vectors-based retrieval mismatch vs expected"
    );

    // Missing-sequence case: a chrom not in the collection returns an Err with the
    // "Region N" label.
    let missing_chroms = ["chrX"];
    let missing_starts = [0u32];
    let missing_ends = [4u32];
    let missing_result: Result<Vec<_>, _> = store
        .substrings_from_region_vectors(
            collection_digest_ref,
            &missing_chroms,
            &missing_starts,
            &missing_ends,
        )
        .expect("constructor should succeed for equal-length vectors")
        .collect();
    let missing_err = missing_result.unwrap_err().to_string();
    assert!(
        missing_err.contains("Region 1") && missing_err.contains("not found"),
        "unexpected missing-sequence error: {missing_err}"
    );
}

#[test]
fn test_substrings_from_region_vectors_mismatched_lengths() {
    let temp_dir = tempdir().expect("Failed to create temporary directory");
    let temp_path = temp_dir.path();

    let fasta_content = ">chr1\nATGCATGCATGC\n>chr2\nGGGGAAAA\n";
    let temp_fasta_path = temp_path.join("test.fa");
    fs::write(&temp_fasta_path, fasta_content).expect("Failed to write test FASTA file");

    let mut store = RefgetStore::in_memory();
    store
        .add_sequence_collection_from_fasta(&temp_fasta_path, FastaImportOptions::new())
        .unwrap();

    let collection_digest_ref: &str = "uC_UorBNf3YUu1YIDainBhI94CedlNeH";

    let chroms = ["chr1", "chr2"];
    let starts = [0u32]; // intentionally shorter
    let ends = [5u32, 4];

    let result =
        store.substrings_from_region_vectors(collection_digest_ref, &chroms, &starts, &ends);
    let err_msg = match result {
        Ok(_) => panic!("mismatched lengths should error"),
        Err(e) => e.to_string(),
    };
    assert!(
        err_msg.contains("Mismatched region vector lengths"),
        "unexpected error: {err_msg}"
    );
}

#[test]
fn test_negative_bed_coordinates() {
    let temp_dir = tempdir().expect("Failed to create temporary directory");
    let temp_path = temp_dir.path();

    let fasta_content = ">chr1\nATGCATGCATGC\n>chr2\nGGGGAAAA\n";
    let temp_fasta_path = temp_path.join("test.fa");
    fs::write(&temp_fasta_path, fasta_content).expect("Failed to write test FASTA file");

    let mut store = RefgetStore::in_memory();
    store
        .add_sequence_collection_from_fasta(&temp_fasta_path, FastaImportOptions::new())
        .unwrap();

    let collections: Vec<_> = store.collections.keys().cloned().collect();
    let collection_digest_ref: &str =
        std::str::from_utf8(&collections[0]).expect("invalid collection digest");

    // Negative start
    let bed_content = "chr1\t-5\t100\n";
    let temp_bed_path = temp_path.join("negative.bed");
    fs::write(&temp_bed_path, bed_content).expect("Failed to write test BED file");

    let result = store.substrings_from_regions(collection_digest_ref, temp_bed_path.to_str().unwrap());
    let collected: Result<Vec<_>, _> = result.unwrap().collect();
    let error_msg = collected.unwrap_err().to_string();
    assert!(error_msg.contains("invalid start or end coordinates"));

    // Negative end
    let bed_content_neg_end = "chr1\t0\t-10\n";
    let temp_bed_path_neg_end = temp_path.join("negative_end.bed");
    fs::write(&temp_bed_path_neg_end, bed_content_neg_end).expect("Failed to write test BED file");

    let result = store.substrings_from_regions(collection_digest_ref, temp_bed_path_neg_end.to_str().unwrap());
    let collected: Result<Vec<_>, _> = result.unwrap().collect();
    let error_msg = collected.unwrap_err().to_string();
    assert!(error_msg.contains("invalid start or end coordinates"));
}

#[test]
fn test_global_refget_store() {
    let sequence = b"ACGT";
    let name = "test_seq";

    let mut collection = SequenceCollection {
        metadata: SequenceCollectionMetadata {
            digest: "test_collection".to_string(),
            n_sequences: 0,
            names_digest: "test".to_string(),
            sequences_digest: "test".to_string(),
            lengths_digest: "test".to_string(),
            name_length_pairs_digest: None,
            sorted_name_length_pairs_digest: None,
            sorted_sequences_digest: None,
            file_path: None,
        },
        sequences: Vec::new(),
    };

    let seq_metadata = SequenceMetadata {
        name: name.to_string(),
        description: None,
        length: sequence.len(),
        sha512t24u: sha512t24u(sequence),
        md5: md5(sequence),
        alphabet: AlphabetType::Dna2bit,
        fai: None,
    };

    let record = SequenceRecord::Full {
        metadata: seq_metadata.clone(),
        sequence: std::sync::Arc::new(sequence.to_vec()),
    };

    collection.sequences.push(record);

    let mut store = RefgetStore::in_memory();
    store.add_sequence_collection(collection.clone()).unwrap();

    assert!(!store.sequence_store.is_empty());

    let retrieved_by_name_str = store.get_sequence_by_name(&collection.metadata.digest, name);
    assert!(retrieved_by_name_str.is_ok());
    let retrieved_record = retrieved_by_name_str.unwrap();
    assert_eq!(retrieved_record.metadata().name, name);
    // Encoded stores pack the hand-built ASCII record on insertion.
    let decoded = store
        .get_substring(&seq_metadata.sha512t24u, 0, sequence.len())
        .unwrap();
    assert_eq!(decoded.as_bytes(), sequence);

    let retrieved_by_name_key =
        store.get_sequence_by_name(collection.metadata.digest.to_key(), name);
    assert!(retrieved_by_name_key.is_ok());

    let retrieved_by_sha512_str = store.get_sequence(&seq_metadata.sha512t24u);
    assert!(retrieved_by_sha512_str.is_ok());

    let retrieved_by_sha512_key = store.get_sequence(seq_metadata.sha512t24u.to_key());
    assert!(retrieved_by_sha512_key.is_ok());
}

#[test]
fn test_get_substring_by_md5() {
    // get_substring must resolve an md5 digest via the md5_lookup map,
    // matching the behavior of get_substrings / get_sequence.
    let sequence = b"ACGTACGTAC";
    let name = "test_seq";

    let mut collection = SequenceCollection {
        metadata: SequenceCollectionMetadata {
            digest: "test_collection".to_string(),
            n_sequences: 0,
            names_digest: "test".to_string(),
            sequences_digest: "test".to_string(),
            lengths_digest: "test".to_string(),
            name_length_pairs_digest: None,
            sorted_name_length_pairs_digest: None,
            sorted_sequences_digest: None,
            file_path: None,
        },
        sequences: Vec::new(),
    };

    let seq_metadata = SequenceMetadata {
        name: name.to_string(),
        description: None,
        length: sequence.len(),
        sha512t24u: sha512t24u(sequence),
        md5: md5(sequence),
        alphabet: AlphabetType::Dna2bit,
        fai: None,
    };

    collection.sequences.push(SequenceRecord::Full {
        metadata: seq_metadata.clone(),
        sequence: std::sync::Arc::new(sequence.to_vec()),
    });

    let mut store = RefgetStore::in_memory();
    store.add_sequence_collection(collection).unwrap();

    // Baseline: resolution by sha512t24u digest.
    let by_sha = store
        .get_substring(&seq_metadata.sha512t24u, 2, 6)
        .expect("get_substring by sha512t24u should succeed");
    assert_eq!(by_sha.len(), 4);

    // The fix: resolution by md5 digest must yield identical bytes.
    let by_md5 = store
        .get_substring(&seq_metadata.md5, 2, 6)
        .expect("get_substring by md5 should succeed");
    assert_eq!(by_md5, by_sha);
}

#[test]
fn test_get_substring_zero_length_range() {
    // CONTRACT: a zero-length range (start == end) is a valid empty interval and
    // returns "" (matching wasm/JS RemoteRefgetStore.getSubstring), while an
    // inverted range (start > end) is still rejected. Verified on:
    //   1. a resident (in-memory `Full`) sequence, and
    //   2. a disk-backed `Stub` sequence (exercises get_substring_from_disk),
    // both via single-range get_substring and batch get_substrings, so all
    // retrieval paths agree on the contract.
    let temp_dir = tempdir().unwrap();
    let temp_path = temp_dir.path();
    let temp_fasta = copy_test_fasta(temp_path, "base.fa.gz");

    let mut store = RefgetStore::in_memory();
    store
        .add_sequence_collection_from_fasta(&temp_fasta, FastaImportOptions::new())
        .unwrap();

    // Pick a non-empty resident sequence.
    let (digest, length) = store
        .sequence_metadata()
        .find(|m| m.length > 1)
        .map(|m| (m.sha512t24u.clone(), m.length))
        .expect("expected at least one non-empty sequence");

    // --- Resident (Full) path ---
    // Zero-length range anywhere within bounds returns "".
    assert_eq!(
        store.get_substring(&digest, 0, 0).unwrap(),
        "",
        "resident: start == end == 0 should return empty string"
    );
    assert_eq!(
        store.get_substring(&digest, 3, 3).unwrap(),
        "",
        "resident: interior zero-length range should return empty string"
    );
    // Zero-length range at the sequence end is also valid/empty.
    assert_eq!(
        store.get_substring(&digest, length, length).unwrap(),
        "",
        "resident: zero-length range at end should return empty string"
    );
    // Inverted range (start > end) still errors.
    assert!(
        store.get_substring(&digest, 5, 2).is_err(),
        "resident: inverted range (start > end) must error"
    );
    // Batch path agrees: empty ranges -> "", interleaved with a real range.
    let batch = store
        .get_substrings(&digest, &[(0, 0), (1, 4), (3, 3)])
        .unwrap();
    assert_eq!(batch.len(), 3);
    assert_eq!(batch[0], "");
    assert_eq!(batch[1].len(), 3);
    assert_eq!(batch[2], "");
    // Batch with an inverted range still errors.
    assert!(
        store.get_substrings(&digest, &[(5, 2)]).is_err(),
        "batch: inverted range must error"
    );

    // --- Disk-backed (Stub -> get_substring_from_disk) path ---
    store
        .write_store_to_dir(temp_path, Some("sequences/%s2/%s.seq"))
        .unwrap();
    let disk_store = RefgetStore::open_local(temp_path).unwrap();
    // Sequence is a Stub on disk (not resident), so this exercises the
    // partial-read path, which must also honor the zero-length contract.
    assert!(
        !disk_store.is_sequence_loaded(&digest),
        "disk-backed sequence should be a stub, not resident"
    );
    assert_eq!(
        disk_store.get_substring(&digest, 0, 0).unwrap(),
        "",
        "disk: start == end == 0 should return empty string"
    );
    assert_eq!(
        disk_store.get_substring(&digest, 4, 4).unwrap(),
        "",
        "disk: interior zero-length range should return empty string"
    );
    assert!(
        disk_store.get_substring(&digest, 5, 2).is_err(),
        "disk: inverted range (start > end) must error"
    );
    let disk_batch = disk_store
        .get_substrings(&digest, &[(2, 2), (0, 3)])
        .unwrap();
    assert_eq!(disk_batch[0], "");
    assert_eq!(disk_batch[1].len(), 3);
}

#[test]
fn test_resident_overlay_byte_identical_and_evicts() {
    // The `&self` resident overlay (load_resident) must produce output
    // BYTE-IDENTICAL to the on-disk partial-read path, for both get_substring
    // and get_substrings, and eviction must fall back to disk correctly.
    let temp_dir = tempdir().unwrap();
    let temp_path = temp_dir.path();
    let temp_fasta = copy_test_fasta(temp_path, "base.fa.gz");

    let mut store = RefgetStore::in_memory();
    store
        .add_sequence_collection_from_fasta(&temp_fasta, FastaImportOptions::new())
        .unwrap();
    store
        .write_store_to_dir(temp_path, Some("sequences/%s2/%s.seq"))
        .unwrap();
    let disk_store = RefgetStore::open_local(temp_path).unwrap();

    let (digest, length) = disk_store
        .sequence_metadata()
        .find(|m| m.length > 5)
        .map(|m| (m.sha512t24u.clone(), m.length))
        .expect("expected a non-trivial sequence");

    // Ranges within bounds (single + batch), including an interior empty range.
    let ranges: Vec<(usize, usize)> = vec![
        (0, length.min(4)),
        (1, length.min(5)),
        (length / 2, (length / 2 + 2).min(length)),
        (2, 2),
        (length - 1, length),
    ];

    // 1. Reference: pure disk path (sequence is a Stub, not resident).
    assert!(!disk_store.is_sequence_loaded(&digest));
    assert_eq!(disk_store.resident_bytes(), 0);
    let disk_single: Vec<String> = ranges
        .iter()
        .map(|&(s, e)| disk_store.get_substring(&digest, s, e).unwrap())
        .collect();
    let disk_batch = disk_store.get_substrings(&digest, &ranges).unwrap();

    // 2. Promote to resident. Bytes loaded should be > 0 and match resident_bytes.
    let loaded = disk_store.load_resident(&[digest.clone()]).unwrap();
    assert!(loaded > 0, "load_resident should report bytes loaded");
    assert_eq!(disk_store.resident_len(), 1);
    assert_eq!(disk_store.resident_bytes(), loaded);
    // The record itself is still a Stub -- the overlay is separate from `Full`.
    assert!(!disk_store.is_sequence_loaded(&digest));

    // 3. Overlay path must be byte-identical to the disk path.
    let res_single: Vec<String> = ranges
        .iter()
        .map(|&(s, e)| disk_store.get_substring(&digest, s, e).unwrap())
        .collect();
    let res_batch = disk_store.get_substrings(&digest, &ranges).unwrap();
    assert_eq!(res_single, disk_single, "overlay get_substring must match disk");
    assert_eq!(res_batch, disk_batch, "overlay get_substrings must match disk");

    // 4. Re-loading is idempotent and reports 0 new bytes.
    let reloaded = disk_store.load_resident(&[digest.clone()]).unwrap();
    assert_eq!(reloaded, 0, "already-resident digest loads 0 new bytes");

    // 5. Eviction falls back to disk, still byte-identical.
    disk_store.evict_resident(&[digest.clone()]);
    assert_eq!(disk_store.resident_bytes(), 0);
    assert_eq!(disk_store.resident_len(), 0);
    let after_evict: Vec<String> = ranges
        .iter()
        .map(|&(s, e)| disk_store.get_substring(&digest, s, e).unwrap())
        .collect();
    assert_eq!(after_evict, disk_single, "post-evict disk path must match");

    // 6. evict_all_resident clears everything.
    disk_store.load_resident(&[digest.clone()]).unwrap();
    assert_eq!(disk_store.resident_len(), 1);
    disk_store.evict_all_resident();
    assert_eq!(disk_store.resident_len(), 0);
}

#[test]
fn test_resident_overlay_concurrent_readers() {
    // Readers must see correct output while another thread promotes/evicts the
    // resident overlay concurrently (the RwLock + clone-Arc-then-decode design).
    use std::sync::Arc;
    use std::thread;

    let temp_dir = tempdir().unwrap();
    let temp_path = temp_dir.path();
    let temp_fasta = copy_test_fasta(temp_path, "base.fa.gz");

    let mut store = RefgetStore::in_memory();
    store
        .add_sequence_collection_from_fasta(&temp_fasta, FastaImportOptions::new())
        .unwrap();
    store
        .write_store_to_dir(temp_path, Some("sequences/%s2/%s.seq"))
        .unwrap();

    let disk_store = RefgetStore::open_local(temp_path).unwrap();
    let (digest, length) = disk_store
        .sequence_metadata()
        .find(|m| m.length > 5)
        .map(|m| (m.sha512t24u.clone(), m.length))
        .expect("expected a non-trivial sequence");
    // Expected value from the disk path before any resident load.
    let expected = disk_store.get_substring(&digest, 0, length.min(6)).unwrap();

    let shared = Arc::new(disk_store.into_readonly());
    let end = length.min(6);

    let mut handles = Vec::new();
    for _ in 0..4 {
        let s = Arc::clone(&shared);
        let d = digest.clone();
        let exp = expected.clone();
        handles.push(thread::spawn(move || {
            for _ in 0..500 {
                let got = s.get_substring(&d, 0, end).unwrap();
                assert_eq!(got, exp, "reader saw wrong bytes during concurrent load/evict");
            }
        }));
    }
    // Churn the overlay concurrently with the readers.
    for _ in 0..50 {
        shared.load_resident(&[digest.clone()]).unwrap();
        shared.evict_resident(&[digest.clone()]);
    }
    for h in handles {
        h.join().unwrap();
    }
}

#[test]
fn test_import_fasta() {
    let temp_dir = tempdir().expect("Failed to create temporary directory");
    let temp_path = temp_dir.path();

    let test_fa = "../tests/data/fasta/base.fa";
    let temp_fa = temp_path.join("base.fa");
    std::fs::copy(test_fa, &temp_fa).expect("Failed to copy test FASTA file");

    let mut store = RefgetStore::in_memory();
    store.add_sequence_collection_from_fasta(temp_fa, FastaImportOptions::new()).unwrap();

    assert!(!store.sequence_store.is_empty());

    let seq_template = "sequences/%s2/%s.seq";
    store
        .write_store_to_dir(temp_path.to_str().unwrap(), Some(seq_template))
        .unwrap();
}

// =========================================================================
// Persistence tests
// =========================================================================

#[test]
fn test_disk_persistence() {
    let temp_dir = tempdir().unwrap();
    let temp_path = temp_dir.path();
    let temp_fasta = copy_test_fasta(temp_path, "base.fa.gz");

    let mut store = RefgetStore::in_memory();
    store
        .add_sequence_collection_from_fasta(&temp_fasta, FastaImportOptions::new())
        .unwrap();

    let sequence_keys: Vec<DigestKey> = store.sequence_store.keys().cloned().collect();
    assert_eq!(sequence_keys.len(), 3);

    let sha512_key1 = sequence_keys[0];
    let sha512_key2 = sequence_keys[1];

    let original_seq1 = store.sequence_store.get(&sha512_key1).unwrap().clone();
    let original_seq2 = store.sequence_store.get(&sha512_key2).unwrap().clone();

    let seq_template = "sequences/%s2/%s.seq";
    store.write_store_to_dir(temp_path, Some(seq_template)).unwrap();

    assert!(temp_path.join("sequences").exists());
    assert!(temp_path.join("sequences").read_dir().unwrap().count() > 0);
    assert!(temp_path.join("rgstore.json").exists());
    assert!(temp_path.join("sequences.rgsi").exists());
    assert!(temp_path.join("collections.rgci").exists());
    assert!(temp_path.join("collections").exists());

    let mut loaded_store = RefgetStore::open_local(temp_path).unwrap();

    assert_eq!(loaded_store.sequence_store.len(), 3);
    assert!(loaded_store.sequence_store.contains_key(&sha512_key1));
    assert!(loaded_store.sequence_store.contains_key(&sha512_key2));

    let loaded_seq1 = loaded_store.sequence_store.get(&sha512_key1).unwrap();
    let loaded_seq2 = loaded_store.sequence_store.get(&sha512_key2).unwrap();

    assert_eq!(original_seq1.metadata().name, loaded_seq1.metadata().name);
    assert_eq!(original_seq1.metadata().length, loaded_seq1.metadata().length);
    assert_eq!(original_seq1.metadata().sha512t24u, loaded_seq1.metadata().sha512t24u);
    assert_eq!(original_seq1.metadata().md5, loaded_seq1.metadata().md5);

    assert_eq!(original_seq2.metadata().name, loaded_seq2.metadata().name);
    assert_eq!(original_seq2.metadata().length, loaded_seq2.metadata().length);
    assert_eq!(original_seq2.metadata().sha512t24u, loaded_seq2.metadata().sha512t24u);
    assert_eq!(original_seq2.metadata().md5, loaded_seq2.metadata().md5);

    assert!(!loaded_seq1.is_loaded());
    assert!(!loaded_seq2.is_loaded());

    assert_eq!(loaded_store.md5_lookup.len(), 3);
    assert_eq!(loaded_store.collections.len(), store.collections.len());

    loaded_store.load_all_collections().unwrap();
    loaded_store.load_all_sequences().unwrap();

    for (digest, original_record) in &store.sequence_store {
        let loaded_record = loaded_store.get_sequence(*digest).unwrap();
        assert_eq!(original_record.metadata().name, loaded_record.metadata().name);
        assert_eq!(original_record.metadata().length, loaded_record.metadata().length);

        if original_record.metadata().length > 0 {
            let substring_len = std::cmp::min(5, original_record.metadata().length);
            let substring = loaded_store.get_substring(digest, 0, substring_len);
            assert!(substring.is_ok());
        }
    }
}

// =========================================================================
// Export tests
// =========================================================================

#[test]
fn test_export_fasta_all_sequences() {
    let temp_dir = tempdir().expect("Failed to create temporary directory");
    let (mut store, collection_digest) = setup_export_test_store(temp_dir.path());

    let output_path = temp_dir.path().join("exported_all.fa");
    store
        .export_fasta(&collection_digest, &output_path, None, Some(80))
        .unwrap();

    let exported = fs::read_to_string(&output_path).unwrap();
    assert!(exported.contains(">chr1") && exported.contains(">chr2") && exported.contains(">chr3"));
    assert!(exported.contains("ATGCATGCATGC") && exported.contains("GGGGAAAA") && exported.contains("TTTTCCCC"));
}

#[test]
fn test_export_fasta_subset_sequences() {
    let temp_dir = tempdir().expect("Failed to create temporary directory");
    let (mut store, collection_digest) = setup_export_test_store(temp_dir.path());

    let output_path = temp_dir.path().join("exported_subset.fa");
    store
        .export_fasta(&collection_digest, &output_path, Some(vec!["chr1", "chr3"]), Some(80))
        .unwrap();

    let exported = fs::read_to_string(&output_path).unwrap();
    assert!(exported.contains(">chr1") && exported.contains(">chr3"));
    assert!(!exported.contains(">chr2") && !exported.contains("GGGGAAAA"));
}

#[test]
fn test_export_fasta_roundtrip() {
    let temp_dir = tempdir().expect("Failed to create temporary directory");
    let temp_path = temp_dir.path();

    let fasta_content = "\
>seq1
ATGCATGCATGCATGCATGCATGCATGCATGCATGCATGCATGCATGCATGCATGCATGC
ATGCATGCATGCATGCATGCATGCATGCATGCATGCATGCATGCATGCATGCATGCATGC
>seq2
GGGGAAAACCCCTTTTGGGGAAAACCCCTTTTGGGGAAAACCCCTTTTGGGGAAAACCCC
";
    let temp_fasta_path = temp_path.join("original.fa");
    fs::write(&temp_fasta_path, fasta_content).expect("Failed to write test FASTA file");

    let mut store1 = RefgetStore::in_memory();
    store1
        .add_sequence_collection_from_fasta(&temp_fasta_path, FastaImportOptions::new())
        .unwrap();

    let original_digests: Vec<String> = store1
        .sequence_store
        .values()
        .map(|r| r.metadata().sha512t24u.clone())
        .collect();

    let collections: Vec<_> = store1.collections.keys().cloned().collect();
    let collection_digest = collections[0];
    let exported_path = temp_path.join("exported.fa");
    store1.export_fasta(&collection_digest, &exported_path, None, Some(60)).expect("Failed to export FASTA");

    let mut store2 = RefgetStore::in_memory();
    store2
        .add_sequence_collection_from_fasta(&exported_path, FastaImportOptions::new())
        .unwrap();

    let new_digests: Vec<String> = store2
        .sequence_store
        .values()
        .map(|r| r.metadata().sha512t24u.clone())
        .collect();

    assert_eq!(original_digests.len(), new_digests.len());
    for digest in original_digests {
        assert!(new_digests.contains(&digest), "Digest {} should be present after roundtrip", digest);
    }
}

#[test]
fn test_export_fasta_by_digests() {
    let temp_dir = tempdir().expect("Failed to create temporary directory");
    let (mut store, _) = setup_export_test_store(temp_dir.path());

    let digests: Vec<String> = store
        .sequence_store
        .values()
        .map(|r| r.metadata().sha512t24u.clone())
        .collect();
    let digest_refs: Vec<&str> = digests.iter().map(|s| s.as_str()).collect();

    let output_path = temp_dir.path().join("exported_by_digests.fa");
    store.export_fasta_by_digests(digest_refs, &output_path, Some(80)).unwrap();

    let exported = fs::read_to_string(&output_path).unwrap();
    assert!(exported.contains(">chr1") && exported.contains(">chr2") && exported.contains(">chr3"));
}

#[test]
fn test_export_fasta_error_handling() {
    let temp_dir = tempdir().expect("Failed to create temporary directory");
    let (mut store, collection_digest) = setup_export_test_store(temp_dir.path());

    let output_path = temp_dir.path().join("should_fail.fa");

    let fake_collection = b"fake_collection_digest_12345678";
    assert!(store.export_fasta(fake_collection, &output_path, None, Some(80)).is_err());

    assert!(store.export_fasta(&collection_digest, &output_path, Some(vec!["nonexistent_chr"]), Some(80)).is_err());
}

#[test]
fn test_export_fasta_after_load_local() {
    let temp_dir = tempdir().expect("Failed to create temporary directory");
    let temp_path = temp_dir.path();
    let store_path = temp_path.join("store");

    let fasta_content = ">chr1\nACGTACGT\n>chr2\nGGGGAAAA\n";
    let fasta_path = temp_path.join("test.fa");
    fs::write(&fasta_path, fasta_content).unwrap();

    let collection_digest: DigestKey;
    {
        let mut store = RefgetStore::on_disk(&store_path).unwrap();
        store
            .add_sequence_collection_from_fasta(&fasta_path, FastaImportOptions::new())
            .unwrap();
        let collections: Vec<_> = store.collections.keys().cloned().collect();
        assert_eq!(collections.len(), 1);
        collection_digest = collections[0];
    }

    let mut loaded_store = RefgetStore::open_local(&store_path).unwrap();

    assert!(!loaded_store.is_collection_loaded(&collection_digest));

    loaded_store.load_all_collections().unwrap();
    loaded_store.load_all_sequences().unwrap();

    let output_path = temp_path.join("exported.fa");
    loaded_store
        .export_fasta(&collection_digest, &output_path, None, Some(80))
        .expect("export_fasta should work on disk-loaded stores");

    let exported = fs::read_to_string(&output_path).unwrap();
    assert!(exported.contains(">chr1"));
    assert!(exported.contains("ACGTACGT"));
    assert!(exported.contains(">chr2"));
    assert!(exported.contains("GGGGAAAA"));
}

// =========================================================================
// FASTA header and filename tests
// =========================================================================

#[test]
fn test_sequence_names_with_spaces() {
    let temp_dir = tempdir().expect("Failed to create temporary directory");
    let temp_path = temp_dir.path();

    let fasta_content = "\
>JAHKSE010000016.1 unmasked:primary_assembly HG002.alt.pat.f1_v2:JAHKSE010000016.1:1:100:1
ATGCATGCATGCATGCATGCATGCATGCATGCATGC
ATGCATGCATGCATGCATGCATGCATGCATGCATGC
>JAHKSE010000012.1 unmasked:primary_assembly HG002.alt.pat.f1_v2:JAHKSE010000012.1:1:100:1
GGGGAAAACCCCTTTTGGGGAAAACCCCTTTTGGGG
GGGGAAAACCCCTTTTGGGGAAAACCCCTTTTGGGG
";
    let temp_fasta_path = temp_path.join("spaces_in_names.fa");
    fs::write(&temp_fasta_path, fasta_content).expect("Failed to write test FASTA file");

    let mut store = RefgetStore::in_memory();
    store
        .add_sequence_collection_from_fasta(&temp_fasta_path, FastaImportOptions::new())
        .expect("Should parse FASTA headers correctly");

    assert_eq!(store.sequence_store.len(), 2);

    let name1 = "JAHKSE010000016.1";
    let name2 = "JAHKSE010000012.1";

    let collections: Vec<_> = store.collections.keys().cloned().collect();
    assert_eq!(collections.len(), 1);
    let collection_digest = collections[0];

    {
        let seq1 = store.get_sequence_by_name(&collection_digest, name1);
        assert!(seq1.is_ok());

        let seq1_record = seq1.unwrap();
        let seq1_meta = seq1_record.metadata();
        assert_eq!(seq1_meta.name, "JAHKSE010000016.1");
        assert_eq!(
            seq1_meta.description,
            Some("unmasked:primary_assembly HG002.alt.pat.f1_v2:JAHKSE010000016.1:1:100:1".to_string())
        );
    }

    {
        let seq2 = store.get_sequence_by_name(&collection_digest, name2);
        assert!(seq2.is_ok());
    }
}

#[test]
fn test_rgsi_filename_with_dots() {
    let temp_dir = tempdir().expect("Failed to create temporary directory");
    let temp_path = temp_dir.path();

    let temp_fasta = copy_test_fasta(temp_path, "HG002.alt.pat.f1_v2.unmasked.fa");

    let _seqcol = SequenceCollection::from_path_with_cache(&temp_fasta, false, true)
        .expect("Should load FASTA");

    let correct_rgsi = temp_path.join("HG002.alt.pat.f1_v2.unmasked.rgsi");
    let wrong_rgsi = temp_path.join("HG002.rgsi");

    let files: Vec<_> = std::fs::read_dir(temp_path)
        .unwrap()
        .map(|e| e.unwrap().file_name().to_string_lossy().to_string())
        .collect();

    assert!(correct_rgsi.exists(), "Expected 'HG002.alt.pat.f1_v2.unmasked.rgsi' but found: {:?}", files);
    assert!(!wrong_rgsi.exists());
}

// =========================================================================
// On-disk incremental tests
// =========================================================================

#[test]
fn test_on_disk_collection_written_incrementally() {
    let temp_dir = tempdir().unwrap();
    let temp_fasta = copy_test_fasta(temp_dir.path(), "base.fa.gz");

    let cache_path = temp_dir.path().join("cache");
    let mut store = RefgetStore::on_disk(&cache_path).unwrap();

    store
        .add_sequence_collection_from_fasta(&temp_fasta, FastaImportOptions::new())
        .unwrap();

    let collections_dir = cache_path.join("collections");
    assert!(collections_dir.exists());

    let rgsi_files: Vec<_> = std::fs::read_dir(&collections_dir)
        .unwrap()
        .map(|e| e.unwrap().file_name().to_string_lossy().to_string())
        .collect();

    assert!(!rgsi_files.is_empty());
    assert!(rgsi_files.iter().any(|f| f.ends_with(".rgsi")));
}

#[test]
fn test_disk_size_calculation() {
    let mut store = RefgetStore::in_memory();
    store
        .add_sequence_collection_from_fasta("../tests/data/fasta/base.fa.gz", FastaImportOptions::new())
        .unwrap();

    let disk_size = store.logical_sequence_bytes();
    assert!(disk_size > 0);

    let manual: usize = store
        .list_sequences()
        .unwrap()
        .iter()
        .map(|m| (m.length * m.alphabet.bits_per_symbol()).div_ceil(8))
        .sum();
    assert_eq!(disk_size, manual);
}

#[test]
fn test_incremental_index_writing() {
    let temp_dir = tempdir().unwrap();
    let temp_fasta = copy_test_fasta(temp_dir.path(), "base.fa.gz");
    let cache_path = temp_dir.path().join("store");
    let mut store = RefgetStore::on_disk(&cache_path).unwrap();

    store
        .add_sequence_collection_from_fasta(&temp_fasta, FastaImportOptions::new())
        .unwrap();

    assert!(cache_path.join("rgstore.json").exists());
    assert!(cache_path.join("sequences.rgsi").exists());
    assert!(cache_path.join("collections.rgci").exists());

    let _loaded = RefgetStore::on_disk(&cache_path).unwrap();
}

#[test]
fn test_write_method() {
    let temp_dir = tempdir().unwrap();
    let temp_fasta = copy_test_fasta(temp_dir.path(), "base.fa.gz");
    let cache_path = temp_dir.path().join("store");
    let mut store = RefgetStore::on_disk(&cache_path).unwrap();

    store
        .add_sequence_collection_from_fasta(&temp_fasta, FastaImportOptions::new())
        .unwrap();
    store.write().unwrap();

    assert!(cache_path.join("rgstore.json").exists());
}

#[test]
fn test_on_disk_smart_constructor() {
    let temp_dir = tempdir().unwrap();
    let temp_fasta = copy_test_fasta(temp_dir.path(), "base.fa.gz");
    let cache_path = temp_dir.path().join("store");

    let mut store1 = RefgetStore::on_disk(&cache_path).unwrap();
    assert_eq!(store1.mode, StorageMode::Encoded);
    store1
        .add_sequence_collection_from_fasta(&temp_fasta, FastaImportOptions::new())
        .unwrap();

    let store2 = RefgetStore::on_disk(&cache_path).unwrap();
    assert_eq!(store2.sequence_store.len(), store1.sequence_store.len());
    assert_eq!(store2.mode, StorageMode::Encoded);

    let cache_path_raw = temp_dir.path().join("store_raw");
    let mut store3 = RefgetStore::on_disk(&cache_path_raw).unwrap();
    store3.disable_encoding();
    assert_eq!(store3.mode, StorageMode::Raw);
    store3
        .add_sequence_collection_from_fasta(&temp_fasta, FastaImportOptions::new())
        .unwrap();

    let store4 = RefgetStore::on_disk(&cache_path_raw).unwrap();
    assert_eq!(store4.mode, StorageMode::Raw);

    let index_path = cache_path_raw.join("rgstore.json");
    let json = fs::read_to_string(&index_path).unwrap();
    assert!(json.contains("\"mode\":\"Raw\"") || json.contains("\"mode\": \"Raw\""));
}

// =========================================================================
// Collection metadata and loading tests
// =========================================================================

#[test]
fn test_collection_metadata_methods() {
    let temp_dir = tempdir().unwrap();
    let temp_fasta = copy_test_fasta(temp_dir.path(), "base.fa.gz");
    let cache_path = temp_dir.path().join("store");
    let mut store = RefgetStore::on_disk(&cache_path).unwrap();

    store
        .add_sequence_collection_from_fasta(&temp_fasta, FastaImportOptions::new())
        .unwrap();

    let collections = store.list_collections(0, usize::MAX, &[]).unwrap();
    assert_eq!(collections.results.len(), 1);
    let digest = collections.results[0].digest.clone();

    let meta = store.get_collection_metadata(&digest);
    assert!(meta.is_some());
    assert_eq!(meta.unwrap().n_sequences, 3);

    assert!(store.is_collection_loaded(&digest));

    let stats = store.stats();
    assert_eq!(stats.n_collections, 1);
    assert_eq!(stats.n_collections_in_memory, 1);
    assert_eq!(stats.n_sequences, 3);
}

#[test]
fn test_collection_explicit_loading() {
    let temp_dir = tempdir().unwrap();
    let temp_fasta = copy_test_fasta(temp_dir.path(), "base.fa.gz");
    let cache_path = temp_dir.path().join("store");

    let mut store = RefgetStore::on_disk(&cache_path).unwrap();
    store
        .add_sequence_collection_from_fasta(&temp_fasta, FastaImportOptions::new())
        .unwrap();
    let digest = store.list_collections(0, usize::MAX, &[]).unwrap().results[0].digest.clone();

    drop(store);
    let mut loaded_store = RefgetStore::open_local(&cache_path).unwrap();

    let meta = loaded_store.get_collection_metadata(&digest);
    assert!(meta.is_some());
    assert_eq!(meta.unwrap().n_sequences, 3);

    assert!(!loaded_store.is_collection_loaded(&digest));

    let stats_before = loaded_store.stats();
    assert_eq!(stats_before.n_collections, 1);
    assert_eq!(stats_before.n_collections_in_memory, 0);

    let seq = loaded_store.get_sequence_by_name(&digest, "chr1");
    assert!(seq.is_ok());
    assert_eq!(seq.unwrap().metadata().name, "chr1");

    assert!(loaded_store.is_collection_loaded(&digest));

    let stats_after = loaded_store.stats();
    assert_eq!(stats_after.n_collections_in_memory, 1);
}

#[test]
fn test_get_collection() {
    let temp_dir = tempdir().unwrap();
    let temp_fasta = copy_test_fasta(temp_dir.path(), "base.fa.gz");
    let cache_path = temp_dir.path().join("store");

    let mut store = RefgetStore::on_disk(&cache_path).unwrap();
    store
        .add_sequence_collection_from_fasta(&temp_fasta, FastaImportOptions::new())
        .unwrap();
    let digest = store.list_collections(0, usize::MAX, &[]).unwrap().results[0].digest.clone();
    drop(store);

    let mut loaded_store = RefgetStore::open_local(&cache_path).unwrap();

    assert!(!loaded_store.is_collection_loaded(&digest));

    let collection = loaded_store.get_collection(&digest).unwrap();
    assert!(!collection.sequences.is_empty());

    let readonly_store = RefgetStore::open_local(&cache_path).unwrap().into_readonly();
    assert!(readonly_store.get_collection(&digest).is_err());

    loaded_store.load_all_collections().unwrap();

    let collection = loaded_store.get_collection(&digest).unwrap();
    assert!(!collection.sequences.is_empty());
    assert_eq!(collection.sequences.len(), 3);

    let stats_after = loaded_store.stats();
    // RESIDENCY INVARIANT: on a disk-backed store no sequence bytes are ever
    // held in RAM by loading a collection — records are Stubs. This is 0 even
    // right after an import, which is why the field is named `_in_memory` and
    // not `_loaded`: it is not an ingest counter.
    assert_eq!(stats_after.n_sequences_in_memory, 0);
    assert_eq!(stats_after.n_collections_in_memory, 1);

    for record in loaded_store.sequence_store.values() {
        assert!(!record.is_loaded());
    }

    let seq_digest = collection.sequences[0].metadata().sha512t24u.clone();
    loaded_store.load_sequence(&seq_digest).unwrap();
    let loaded_seq = loaded_store.get_sequence(&seq_digest).unwrap();
    assert!(loaded_seq.is_loaded());
}

#[test]
fn test_get_sequence() {
    let temp_dir = tempdir().unwrap();
    let temp_fasta = copy_test_fasta(temp_dir.path(), "base.fa.gz");
    let cache_path = temp_dir.path().join("store");

    let mut store = RefgetStore::on_disk(&cache_path).unwrap();
    store
        .add_sequence_collection_from_fasta(&temp_fasta, FastaImportOptions::new())
        .unwrap();

    let seq_digest = store
        .sequence_store
        .values()
        .next()
        .unwrap()
        .metadata()
        .sha512t24u
        .clone();
    drop(store);

    let mut loaded_store = RefgetStore::open_local(&cache_path).unwrap();

    let seq_before = loaded_store.sequence_store.get(&seq_digest.to_key()).unwrap();
    assert!(!seq_before.is_loaded());

    let loaded_seq = loaded_store.get_sequence(&seq_digest).unwrap();
    assert!(loaded_seq.is_loaded());
    assert!(loaded_seq.sequence().is_some());
}

#[test]
fn test_get_collection_idempotent() {
    let temp_dir = tempdir().unwrap();
    let temp_fasta = copy_test_fasta(temp_dir.path(), "base.fa.gz");
    let cache_path = temp_dir.path().join("store");

    let mut store = RefgetStore::on_disk(&cache_path).unwrap();
    store
        .add_sequence_collection_from_fasta(&temp_fasta, FastaImportOptions::new())
        .unwrap();
    let digest = store.list_collections(0, usize::MAX, &[]).unwrap().results[0].digest.clone();
    drop(store);

    let mut loaded_store = RefgetStore::open_local(&cache_path).unwrap();
    loaded_store.load_all_collections().unwrap();

    let result1 = loaded_store.get_collection(&digest);
    assert!(result1.is_ok());

    let result2 = loaded_store.get_collection(&digest);
    assert!(result2.is_ok());

    assert_eq!(loaded_store.stats().n_collections_in_memory, 1);
}

// =========================================================================
// Stale cache and standalone record tests
// =========================================================================

#[test]
fn test_stale_rgsi_cache_is_ignored() {
    use std::io::Write;

    let temp_dir = tempdir().unwrap();

    let fasta_path = temp_dir.path().join("test.fa");
    let mut fasta_file = fs::File::create(&fasta_path).unwrap();
    writeln!(fasta_file, ">chr1\nATGCATGC\n>chr2\nGGGGAAAA").unwrap();

    let rgsi_path = temp_dir.path().join("test.rgsi");
    let mut rgsi_file = fs::File::create(&rgsi_path).unwrap();
    writeln!(rgsi_file, "#name\tlength\talphabet\tsha512t24u\tmd5\tdescription").unwrap();

    let store_path = temp_dir.path().join("store");
    let mut store = RefgetStore::on_disk(&store_path).unwrap();

    let result = store.add_sequence_collection_from_fasta(&fasta_path, FastaImportOptions::new());
    assert!(result.is_ok(), "Should handle stale cache: {:?}", result.err());

    assert_eq!(store.sequence_store.len(), 2);
}

#[test]
fn test_add_sequence_record_standalone() {
    use crate::digest::digest_sequence;

    let mut store = RefgetStore::in_memory();
    let record = digest_sequence("test", b"ACGT");
    let digest = record.metadata().sha512t24u.clone();

    store.add_sequence_record(record, false).unwrap();

    let retrieved = store.get_sequence(digest.as_bytes()).unwrap();
    assert_eq!(retrieved.metadata().length, 4);
}

#[test]
fn test_add_sequence_record_packed_bytes_in_encoded_mode() {
    // Mirrors panget's pre-packing insert pattern: digest the ASCII sequence,
    // then pack it to the alphabet's encoded byte size before inserting into
    // an Encoded-mode store. This must be accepted (not just raw ASCII).
    use crate::digest::{digest_sequence, encode_sequence, lookup_alphabet};

    let mut store = RefgetStore::in_memory();
    store.set_encoding_mode(StorageMode::Encoded);

    let record = digest_sequence("test", b"ACGTACGT");
    let digest = record.metadata().sha512t24u.clone();

    let packed_record = match record {
        SequenceRecord::Full { metadata, sequence } => {
            let alphabet = lookup_alphabet(&metadata.alphabet);
            let encoded = encode_sequence(&*sequence, alphabet);
            SequenceRecord::Full { metadata, sequence: encoded.into() }
        }
        other => other,
    };

    store.add_sequence_record(packed_record, false).unwrap();

    let substring = store.get_substring(digest.as_bytes(), 0, 8).unwrap();
    assert_eq!(substring, "ACGTACGT");
}

#[test]
fn test_add_sequence_record_raw_ascii_auto_packed_in_encoded_mode() {
    // digest_sequence() returns raw ASCII, which an Encoded store must pack.
    use crate::digest::digest_sequence;

    let mut store = RefgetStore::in_memory();
    assert_eq!(store.storage_mode(), StorageMode::Encoded);

    let record = digest_sequence("chr1", b"ACGTACGT");
    let digest = record.metadata().sha512t24u.clone();

    store.add_sequence_record(record, false).unwrap();

    let substring = store.get_substring(digest.as_bytes(), 2, 6).unwrap();
    assert_eq!(substring, "GTAC");
}

#[test]
fn test_ingest_sequence_round_trip() {
    // ingest_sequence handles the one-base case where raw and packed lengths match.
    let mut store = RefgetStore::in_memory();

    let digest = store.ingest_sequence("chr1", b"ACGTACGT").unwrap();
    let substring = store.get_substring(digest.as_bytes(), 2, 6).unwrap();
    assert_eq!(substring, "GTAC");

    // 1-base edge case.
    let digest1 = store.ingest_sequence("chr2", b"A").unwrap();
    let substring1 = store.get_substring(digest1.as_bytes(), 0, 1).unwrap();
    assert_eq!(substring1, "A");
}

#[test]
fn test_ingest_sequence_disk_backed_round_trip() {
    // Disk-backed stores persist the packed representation.
    let temp_dir = tempdir().unwrap();
    let mut store = RefgetStore::on_disk(temp_dir.path()).unwrap();

    let digest = store.ingest_sequence("chr1", b"ACGTACGT").unwrap();
    let substring = store.get_substring(digest.as_bytes(), 2, 6).unwrap();
    assert_eq!(substring, "GTAC");
}

#[test]
fn test_ingest_sequence_case_parity_with_digest_sequence() {
    // Raw ingestion uses the same case normalization as digest_sequence.
    use crate::digest::digest_sequence;

    let mut store = RefgetStore::in_memory();

    let digest = store.ingest_sequence("chr1", b"acgt").unwrap();
    let expected_digest = digest_sequence("chr1", b"ACGT").metadata().sha512t24u.clone();
    assert_eq!(digest, expected_digest);

    let substring = store.get_substring(digest.as_bytes(), 0, 4).unwrap();
    assert_eq!(substring, "ACGT");
}

#[test]
fn test_get_substring_bytes_matches_get_substring() {
    let mut store = RefgetStore::in_memory();
    let digest = store.ingest_sequence("chr1", b"ACGTACGT").unwrap();

    let bytes = store.get_substring_bytes(digest.as_bytes(), 0, 8).unwrap();
    assert_eq!(bytes, b"ACGTACGT".to_vec());

    let string = store.get_substring(digest.as_bytes(), 0, 8).unwrap();
    assert_eq!(String::from_utf8(bytes).unwrap(), string);
}

#[test]
fn test_get_substrings_bytes_matches_get_substrings() {
    let mut store = RefgetStore::in_memory();
    let digest = store.ingest_sequence("chr1", b"ACGTACGTACGT").unwrap();

    let ranges = [(0usize, 4usize), (4, 8), (8, 12)];
    let bytes = store.get_substrings_bytes(digest.as_bytes(), &ranges).unwrap();
    let strings = store.get_substrings(digest.as_bytes(), &ranges).unwrap();

    assert_eq!(bytes.len(), strings.len());
    for (b, s) in bytes.into_iter().zip(strings.into_iter()) {
        assert_eq!(String::from_utf8(b).unwrap(), s);
    }
}

// =========================================================================
// Iterator error visibility tests
// =========================================================================

#[test]
fn test_iter_collections_partial_results_on_missing_rgsi() {
    let dir = tempdir().unwrap();
    let store_path = dir.path().join("store");

    let fasta1 = dir.path().join("a.fa");
    let fasta2 = dir.path().join("b.fa");
    fs::write(&fasta1, ">seq1\nAAAA\n").unwrap();
    fs::write(&fasta2, ">seq2\nCCCC\n").unwrap();

    let mut store = RefgetStore::in_memory();
    let (meta1, _) = store.add_sequence_collection_from_fasta(&fasta1, FastaImportOptions::new()).unwrap();
    let (meta2, _) = store.add_sequence_collection_from_fasta(&fasta2, FastaImportOptions::new()).unwrap();
    store.write_store_to_dir(&store_path, None).unwrap();

    let rgsi1 = store_path.join(format!("collections/{}.rgsi", meta1.digest));
    let rgsi2 = store_path.join(format!("collections/{}.rgsi", meta2.digest));
    assert!(rgsi1.exists());
    assert!(rgsi2.exists());

    fs::remove_file(&rgsi1).unwrap();

    let mut loaded = RefgetStore::open_local(&store_path).unwrap();
    assert_eq!(loaded.collections.len(), 2);

    let result = loaded.load_all_collections();
    assert!(result.is_err());

    loaded.load_collection(&meta2.digest).unwrap();

    let collections: Vec<_> = loaded.iter_collections().collect();
    assert_eq!(collections.len(), 1);
    assert_eq!(collections[0].metadata.digest, meta2.digest);
}

#[test]
fn test_iter_sequences_returns_stubs_for_unloaded() {
    let dir = tempdir().unwrap();
    let store_path = dir.path().join("store");

    let fasta = dir.path().join("test.fa");
    fs::write(&fasta, ">seq1\nATGC\n>seq2\nGGGG\n").unwrap();

    let mut store = RefgetStore::in_memory();
    store.add_sequence_collection_from_fasta(&fasta, FastaImportOptions::new()).unwrap();
    store.write_store_to_dir(&store_path, None).unwrap();

    let seq_digests: Vec<String> = store
        .sequence_store
        .values()
        .map(|r| r.metadata().sha512t24u.clone())
        .collect();
    assert_eq!(seq_digests.len(), 2);

    let digest_to_delete = &seq_digests[0];
    let seq_file = store_path.join(format!(
        "sequences/{}/{}.seq",
        &digest_to_delete[..2],
        digest_to_delete
    ));
    assert!(seq_file.exists());
    fs::remove_file(&seq_file).unwrap();

    let mut loaded = RefgetStore::open_local(&store_path).unwrap();
    assert_eq!(loaded.sequence_store.len(), 2);

    let sequences: Vec<_> = loaded.iter_sequences().collect();
    assert_eq!(sequences.len(), 2);
    let loaded_count = sequences.iter().filter(|r| r.is_loaded()).count();
    assert_eq!(loaded_count, 0);

    let result = loaded.load_all_sequences();
    assert!(result.is_err());

    let surviving_digest = &seq_digests[1];
    loaded.load_sequence(surviving_digest).unwrap();

    let sequences: Vec<_> = loaded.iter_sequences().collect();
    let loaded_count = sequences.iter().filter(|r| r.is_loaded()).count();
    assert_eq!(loaded_count, 1);
}

// =========================================================================
// remove_collection tests
// =========================================================================

#[test]
fn test_remove_existing_collection() {
    let (mut store, digest) = store_with_one_collection(">chr1\nACGT\n>chr2\nTTTT\n");

    assert_eq!(store.list_collections(0, usize::MAX, &[]).unwrap().results.len(), 1);

    let result = store.remove_collection(&digest, false).unwrap();
    assert!(result);
    assert_eq!(store.list_collections(0, usize::MAX, &[]).unwrap().results.len(), 0);
    assert!(store.get_collection(&digest).is_err());
}

#[test]
fn test_remove_nonexistent_collection() {
    let (mut store, _digest) = store_with_one_collection(">chr1\nACGT\n");

    let result = store.remove_collection("nonexistent_digest_value", false).unwrap();
    assert!(!result);
    assert_eq!(store.list_collections(0, usize::MAX, &[]).unwrap().results.len(), 1);
}

#[test]
fn test_remove_without_orphan_cleanup_keeps_sequences() {
    let (mut store, digest) = store_with_one_collection(">chr1\nACGT\n>chr2\nTTTT\n");

    assert_eq!(store.list_sequences().unwrap().len(), 2);
    store.remove_collection(&digest, false).unwrap();
    assert_eq!(store.list_sequences().unwrap().len(), 2);
}

#[test]
fn test_remove_with_orphan_cleanup_removes_sequences() {
    let (mut store, digest) = store_with_one_collection(">chr1\nACGT\n>chr2\nTTTT\n");

    assert_eq!(store.list_sequences().unwrap().len(), 2);
    store.remove_collection(&digest, true).unwrap();
    assert_eq!(store.list_sequences().unwrap().len(), 0);
}

#[test]
fn test_remove_with_orphan_cleanup_retains_shared_sequences() {
    let dir = tempdir().unwrap();
    let fasta1 = dir.path().join("a.fa");
    let fasta2 = dir.path().join("b.fa");
    fs::write(&fasta1, ">chr1\nACGT\n>chr2\nTTTT\n").unwrap();
    fs::write(&fasta2, ">chr1\nACGT\n>chr3\nGGGG\n").unwrap();

    let mut store = RefgetStore::in_memory();
    let (meta1, _) = store
        .add_sequence_collection_from_fasta(&fasta1, FastaImportOptions::new())
        .unwrap();
    let (meta2, _) = store
        .add_sequence_collection_from_fasta(&fasta2, FastaImportOptions::new())
        .unwrap();

    assert_eq!(store.list_collections(0, usize::MAX, &[]).unwrap().results.len(), 2);
    assert_eq!(store.list_sequences().unwrap().len(), 3);

    store.remove_collection(&meta1.digest, true).unwrap();

    assert_eq!(store.list_collections(0, usize::MAX, &[]).unwrap().results.len(), 1);
    assert_eq!(store.list_sequences().unwrap().len(), 2);

    let coll = store.get_collection(&meta2.digest).unwrap();
    assert_eq!(coll.sequences.len(), 2);
}

#[test]
fn test_remove_with_orphan_cleanup_clears_md5_lookup() {
    let (mut store, digest) = store_with_one_collection(">chr1\nACGT\n>chr2\nTTTT\n");

    assert_eq!(store.list_sequences().unwrap().len(), 2);
    assert_eq!(store.md5_lookup.len(), 2);

    store.remove_collection(&digest, true).unwrap();

    assert_eq!(store.list_sequences().unwrap().len(), 0);
    // Regression: md5_lookup must be emptied along with the sequences.
    assert_eq!(store.md5_lookup.len(), 0);
}

#[test]
fn test_remove_with_orphan_cleanup_md5_lookup_retains_shared_sequences() {
    let dir = tempdir().unwrap();
    let fasta1 = dir.path().join("a.fa");
    let fasta2 = dir.path().join("b.fa");
    // chr1/ACGT is shared; TTTT is unique to coll1; GGGG is unique to coll2.
    fs::write(&fasta1, ">chr1\nACGT\n>chr2\nTTTT\n").unwrap();
    fs::write(&fasta2, ">chr1\nACGT\n>chr3\nGGGG\n").unwrap();

    let mut store = RefgetStore::in_memory();
    let (meta1, _) = store
        .add_sequence_collection_from_fasta(&fasta1, FastaImportOptions::new())
        .unwrap();
    let (meta2, _) = store
        .add_sequence_collection_from_fasta(&fasta2, FastaImportOptions::new())
        .unwrap();

    let md5_shared = md5(b"ACGT").to_key(); // retained (shared)
    let md5_orphan = md5(b"TTTT").to_key(); // reclaimed (unique to coll1)
    let md5_other = md5(b"GGGG").to_key(); // retained (unique to coll2)

    assert_eq!(store.md5_lookup.len(), 3);

    store.remove_collection(&meta1.digest, true).unwrap();

    // Reclaimed sequence's md5 entry is gone...
    assert!(!store.md5_lookup.contains_key(&md5_orphan));
    // ...but retained sequences' md5 entries survive.
    assert!(store.md5_lookup.contains_key(&md5_shared));
    assert!(store.md5_lookup.contains_key(&md5_other));
    assert_eq!(store.md5_lookup.len(), 2);

    // And the surviving collection is still fully readable.
    let coll = store.get_collection(&meta2.digest).unwrap();
    assert_eq!(coll.sequences.len(), 2);
    assert_eq!(store.list_sequences().unwrap().len(), 2);
}

#[test]
fn test_remove_collection_on_disk() {
    let dir = tempdir().unwrap();
    let store_path = dir.path().join("store");

    let fasta = dir.path().join("test.fa");
    fs::write(&fasta, ">chr1\nACGT\n>chr2\nTTTT\n").unwrap();

    let mut store = RefgetStore::on_disk(&store_path).unwrap();
    let (meta, _) = store
        .add_sequence_collection_from_fasta(&fasta, FastaImportOptions::new())
        .unwrap();

    let digest = meta.digest.clone();

    let rgsi_path = store_path.join(format!("collections/{}.rgsi", digest));
    assert!(rgsi_path.exists());
    let rgci_path = store_path.join("collections.rgci");
    assert!(rgci_path.exists());

    let result = store.remove_collection(&digest, false).unwrap();
    assert!(result);

    assert!(!rgsi_path.exists());

    let rgci_content = fs::read_to_string(&rgci_path).unwrap();
    assert!(!rgci_content.contains(&digest));

    assert!(store_path.join("sequences.rgsi").exists());
    assert!(store_path.join("rgstore.json").exists());
}

#[test]
fn test_remove_collection_on_disk_with_orphan_sequences() {
    let dir = tempdir().unwrap();
    let store_path = dir.path().join("store");

    let fasta = dir.path().join("test.fa");
    fs::write(&fasta, ">chr1\nACGT\n").unwrap();

    let mut store = RefgetStore::on_disk(&store_path).unwrap();
    let (meta, _) = store
        .add_sequence_collection_from_fasta(&fasta, FastaImportOptions::new())
        .unwrap();

    let digest = meta.digest.clone();

    let seq_digest = sha512t24u(b"ACGT");
    let seq_file = store_path.join(format!("sequences/{}/{}.seq", &seq_digest[..2], seq_digest));
    assert!(seq_file.exists());

    store.remove_collection(&digest, true).unwrap();

    assert!(!seq_file.exists());

    let rgsi_content = fs::read_to_string(store_path.join("sequences.rgsi")).unwrap();
    let non_comment_lines: Vec<_> = rgsi_content.lines().filter(|l| !l.starts_with('#')).collect();
    assert!(non_comment_lines.is_empty());
}

#[test]
fn test_remove_collection_on_disk_cleans_up_empty_shard_dirs() {
    // The rmdir of the two-char shard directories is hoisted OUT of the
    // per-file unlink loop (see `remove_collection` in readonly.rs). This test
    // pins that the hoisted pass actually runs: every orphan `.seq` file is
    // unlinked AND every shard dir it emptied is removed.
    let dir = tempdir().unwrap();
    let store_path = dir.path().join("store");

    let fasta = dir.path().join("test.fa");
    fs::write(&fasta, ">chr1\nACGT\n>chr2\nTTTT\n>chr3\nGGGG\n").unwrap();

    let mut store = RefgetStore::on_disk(&store_path).unwrap();
    let (meta, _) = store
        .add_sequence_collection_from_fasta(&fasta, FastaImportOptions::new())
        .unwrap();
    let digest = meta.digest.clone();

    let seq_files: Vec<PathBuf> = [b"ACGT".as_slice(), b"TTTT".as_slice(), b"GGGG".as_slice()]
        .iter()
        .map(|seq| {
            let d = sha512t24u(seq);
            store_path.join(format!("sequences/{}/{}.seq", &d[..2], d))
        })
        .collect();

    for f in &seq_files {
        assert!(f.exists(), "expected seq file to exist before removal: {:?}", f);
    }
    // Distinct shard dirs (dedup via the set) that should be emptied by removal.
    let shard_dirs: std::collections::HashSet<PathBuf> = seq_files
        .iter()
        .map(|f| f.parent().unwrap().to_path_buf())
        .collect();
    for d in &shard_dirs {
        assert!(d.is_dir(), "expected shard dir to exist before removal: {:?}", d);
    }

    store.remove_collection(&digest, true).unwrap();

    for f in &seq_files {
        assert!(!f.exists(), "orphan seq file was not removed: {:?}", f);
    }
    for d in &shard_dirs {
        assert!(
            !d.exists(),
            "emptied shard dir was not cleaned up (hoisted rmdir pass did not run): {:?}",
            d
        );
    }
    // The `sequences/` root itself is part of the store layout and stays put.
    assert!(store_path.join("sequences").is_dir());
}

// =========================================================================
// Misc tests
// =========================================================================

#[test]
fn test_store_exists() {
    let dir = tempdir().unwrap();
    let path = dir.path();

    assert!(!RefgetStore::store_exists(path));

    let mut store = RefgetStore::on_disk(path).unwrap();
    let fasta_path = dir.path().join("test.fa");
    fs::write(&fasta_path, ">seq1\nACGT\n").unwrap();
    store
        .add_sequence_collection_from_fasta(fasta_path.to_str().unwrap(), FastaImportOptions::new())
        .unwrap();
    store.write().unwrap();

    assert!(RefgetStore::store_exists(path));
    assert!(!RefgetStore::store_exists("/nonexistent/path/to/store"));
}

#[test]
fn test_clear() {
    let dir = tempdir().unwrap();
    let fasta_path = dir.path().join("test.fa");
    fs::write(&fasta_path, ">seq1\nACGT\n>seq2\nTGCA\n").unwrap();

    let mut store = RefgetStore::in_memory();
    store
        .add_sequence_collection_from_fasta(fasta_path.to_str().unwrap(), FastaImportOptions::new())
        .unwrap();

    assert_eq!(store.sequence_digests().count(), 2);
    assert_eq!(store.collections.len(), 1);
    let name_count = store.name_lookup.len();

    store.clear();

    assert_eq!(store.sequence_digests().count(), 0);
    assert_eq!(store.collections.len(), 1);
    assert_eq!(store.name_lookup.len(), name_count);

    let fasta2 = dir.path().join("test2.fa");
    fs::write(&fasta2, ">seq3\nGGGG\n").unwrap();
    store
        .add_sequence_collection_from_fasta(fasta2.to_str().unwrap(), FastaImportOptions::new())
        .unwrap();
    assert_eq!(store.sequence_digests().count(), 1);
    assert_eq!(store.collections.len(), 2);
}

// =========================================================================
// State digest tests
// =========================================================================

#[test]
fn test_rgstore_json_contains_state_digests() {
    let dir = tempdir().unwrap();
    let store_path = dir.path().join("store");

    let mut store = RefgetStore::on_disk(&store_path).unwrap();
    store
        .add_sequence_collection_from_fasta("../tests/data/fasta/base.fa", FastaImportOptions::new())
        .unwrap();

    let json = fs::read_to_string(store_path.join("rgstore.json")).unwrap();
    let metadata: serde_json::Value = serde_json::from_str(&json).unwrap();

    assert!(metadata.get("modified").is_some(), "modified field should be present");
    assert!(metadata.get("collections_digest").is_some(), "collections_digest should be present");
    assert!(metadata.get("sequences_digest").is_some(), "sequences_digest should be present");
}

#[test]
fn test_state_digests_change_on_add() {
    let dir = tempdir().unwrap();
    let store_path = dir.path().join("store");

    let mut store = RefgetStore::on_disk(&store_path).unwrap();
    store
        .add_sequence_collection_from_fasta("../tests/data/fasta/base.fa", FastaImportOptions::new())
        .unwrap();

    let meta1 = store.store_metadata().unwrap();
    let coll_digest1 = meta1.get("collections_digest").cloned().unwrap();

    // Add another collection
    let fasta2 = dir.path().join("test2.fa");
    fs::write(&fasta2, ">seq_new\nTTTTAAAA\n").unwrap();
    store
        .add_sequence_collection_from_fasta(fasta2.to_str().unwrap(), FastaImportOptions::new())
        .unwrap();

    let meta2 = store.store_metadata().unwrap();
    let coll_digest2 = meta2.get("collections_digest").cloned().unwrap();

    assert_ne!(coll_digest1, coll_digest2, "collections_digest should change when a collection is added");
}

#[test]
fn test_aliases_digest_changes_on_alias_add() {
    let dir = tempdir().unwrap();
    let store_path = dir.path().join("store");

    let mut store = RefgetStore::on_disk(&store_path).unwrap();
    let (meta, _) = store
        .add_sequence_collection_from_fasta("../tests/data/fasta/base.fa", FastaImportOptions::new())
        .unwrap();

    let meta1 = store.store_metadata().unwrap();
    assert!(meta1.get("aliases_digest").is_none(), "no aliases yet");

    // Add an alias, then trigger index re-write by adding another collection
    store.add_sequence_alias("test_ns", "my_alias", &meta.sequences_digest).unwrap();

    let fasta2 = dir.path().join("test2.fa");
    fs::write(&fasta2, ">alias_test_seq\nAAAACCCC\n").unwrap();
    store
        .add_sequence_collection_from_fasta(fasta2.to_str().unwrap(), FastaImportOptions::new())
        .unwrap();

    let meta2 = store.store_metadata().unwrap();
    assert!(meta2.get("aliases_digest").is_some(), "aliases_digest should appear after alias + index rewrite");
}

#[test]
fn test_logical_sequence_bytes_persisted_in_manifest() {
    let dir = tempdir().unwrap();
    let store_path = dir.path().join("store");

    let mut store = RefgetStore::on_disk(&store_path).unwrap();
    store
        .add_sequence_collection_from_fasta("../tests/data/fasta/base.fa", FastaImportOptions::new())
        .unwrap();

    let expected = store.logical_sequence_bytes() as u64;
    assert!(expected > 0);

    // Read the raw rgstore.json and confirm the cached value matches.
    let json = fs::read_to_string(store_path.join("rgstore.json")).unwrap();
    let manifest: serde_json::Value = serde_json::from_str(&json).unwrap();
    assert_eq!(
        manifest.get("logical_sequence_bytes").and_then(|v| v.as_u64()),
        Some(expected),
        "manifest should cache logical_sequence_bytes matching the store"
    );

    // store_metadata() should surface it too.
    let meta = store.store_metadata().unwrap();
    assert_eq!(
        meta.get("logical_sequence_bytes").map(|s| s.as_str()),
        Some(expected.to_string().as_str())
    );
}

#[test]
fn test_logical_sequence_bytes_survives_alias_refresh() {
    let dir = tempdir().unwrap();
    let store_path = dir.path().join("store");

    let mut store = RefgetStore::on_disk(&store_path).unwrap();
    let (meta, _) = store
        .add_sequence_collection_from_fasta("../tests/data/fasta/base.fa", FastaImportOptions::new())
        .unwrap();

    let expected = store.logical_sequence_bytes() as u64;
    assert!(expected > 0);

    // Alias-only mutation goes through the cheap manifest-refresh path, which must
    // preserve the cached logical_sequence_bytes untouched.
    store.add_sequence_alias("test_ns", "my_alias", &meta.sequences_digest).unwrap();

    let json = fs::read_to_string(store_path.join("rgstore.json")).unwrap();
    let manifest: serde_json::Value = serde_json::from_str(&json).unwrap();
    assert_eq!(
        manifest.get("logical_sequence_bytes").and_then(|v| v.as_u64()),
        Some(expected),
        "logical_sequence_bytes should survive an alias-only refresh"
    );
}

#[test]
fn test_old_rgstore_json_without_state_digests_loads() {
    let dir = tempdir().unwrap();
    let store_path = dir.path().join("store");
    fs::create_dir_all(&store_path).unwrap();

    // Write a minimal rgstore.json without the new fields
    let old_metadata = serde_json::json!({
        "version": 1,
        "seqdata_path_template": "sequences/%s2/%s.seq",
        "collections_path_template": "collections/%s.rgsi",
        "sequence_index": "sequences.rgsi",
        "collection_index": "collections.rgci",
        "mode": "Raw",
        "created_at": "2026-01-01T00:00:00Z",
        "ancillary_digests": true,
        "attribute_index": false
    });
    fs::write(store_path.join("rgstore.json"), serde_json::to_string_pretty(&old_metadata).unwrap()).unwrap();

    // Write empty index files
    fs::write(store_path.join("sequences.rgsi"), "#name\tlength\talphabet\tsha512t24u\tmd5\tdescription\n").unwrap();
    fs::write(store_path.join("collections.rgci"), "#digest\tn_sequences\tnames_digest\tsequences_digest\tlengths_digest\tname_length_pairs_digest\tsorted_name_length_pairs_digest\tsorted_sequences_digest\n").unwrap();

    // Should load without error
    let store = RefgetStore::open_local(&store_path).unwrap();
    assert_eq!(store.stats().n_sequences, 0);
}

// =========================================================================
// Order preservation tests
// =========================================================================

#[test]
fn test_collection_order_preserved_after_roundtrip() {
    // Build a FASTA with many sequences in a specific order
    let fasta_content = "\
>chr1\nACGTACGT\n\
>chr2\nGGGGAAAA\n\
>chr3\nTTTTCCCC\n\
>chr10\nAAAAAAAA\n\
>chr11\nCCCCCCCC\n\
>chr22\nGGGGGGGG\n\
>chrX\nTTTTTTTT\n\
>chrY\nACACACCA\n\
";
    let expected_names: Vec<&str> = vec!["chr1","chr2","chr3","chr10","chr11","chr22","chrX","chrY"];

    // Write FASTA to a temp dir and add to a disk-backed store
    let dir = tempdir().unwrap();
    let fasta_path = dir.path().join("order_test.fa");
    fs::write(&fasta_path, fasta_content).unwrap();

    let store_path = dir.path().join("store");
    let mut store = RefgetStore::on_disk(&store_path).unwrap();
    let (meta, _) = store
        .add_sequence_collection_from_fasta(&fasta_path, FastaImportOptions::new())
        .unwrap();
    let digest = meta.digest.clone();
    store.write().unwrap();

    // Load the collection before reopening and record the names order
    store.load_all_collections().unwrap();
    let original_collection = store.get_collection(&digest).unwrap();
    let original_names: Vec<String> = original_collection
        .sequences
        .iter()
        .map(|s| s.metadata().name.clone())
        .collect();
    assert_eq!(
        original_names,
        expected_names,
        "Names should match FASTA order before roundtrip"
    );

    // Drop and reopen from disk
    drop(store);
    let mut reloaded = RefgetStore::open_local(&store_path).unwrap();
    reloaded.load_all_collections().unwrap();
    let reloaded_collection = reloaded.get_collection(&digest).unwrap();
    let reloaded_names: Vec<String> = reloaded_collection
        .sequences
        .iter()
        .map(|s| s.metadata().name.clone())
        .collect();

    assert_eq!(
        reloaded_names, original_names,
        "Sequence order must be identical after save/reload roundtrip"
    );

    // Also verify lengths and digests are in corresponding order
    let original_lengths: Vec<usize> = original_collection
        .sequences
        .iter()
        .map(|s| s.metadata().length)
        .collect();
    let reloaded_lengths: Vec<usize> = reloaded_collection
        .sequences
        .iter()
        .map(|s| s.metadata().length)
        .collect();
    assert_eq!(
        reloaded_lengths, original_lengths,
        "Lengths must be in same order after roundtrip"
    );

    let original_digests: Vec<String> = original_collection
        .sequences
        .iter()
        .map(|s| s.metadata().sha512t24u.clone())
        .collect();
    let reloaded_digests: Vec<String> = reloaded_collection
        .sequences
        .iter()
        .map(|s| s.metadata().sha512t24u.clone())
        .collect();
    assert_eq!(
        reloaded_digests, original_digests,
        "SHA512t24u digests must be in same order after roundtrip"
    );
}

/// Test that multiple collections sharing sequences under different names and different orderings
/// all preserve their correct per-collection names and element orderings across a disk roundtrip.
///
/// This covers the intersection of two previously-fixed bugs:
/// 1. HashMap ordering (fixed: inner map now IndexMap)
/// 2. Global name leakage (fixed: get_collection() overrides meta.name from name_lookup)
#[test]
fn test_shared_sequences_order_preserved_after_disk_roundtrip() {
    // FASTA A: base ordering — chrX first, then chr1, then chr2
    let fasta_a = ">chrX\nTTGGGGAA\n>chr1\nGGAA\n>chr2\nGCGC\n";
    // FASTA B: different order — chr1 first, same sequences as A
    let fasta_b = ">chr1\nGGAA\n>chr2\nGCGC\n>chrX\nTTGGGGAA\n";
    // FASTA C: name swap — chr2 has GGAA, chr1 has GCGC (opposite of A/B)
    let fasta_c = ">chrX\nTTGGGGAA\n>chr2\nGGAA\n>chr1\nGCGC\n";

    let dir = tempdir().unwrap();
    let fasta_a_path = dir.path().join("a.fa");
    let fasta_b_path = dir.path().join("b.fa");
    let fasta_c_path = dir.path().join("c.fa");
    fs::write(&fasta_a_path, fasta_a).unwrap();
    fs::write(&fasta_b_path, fasta_b).unwrap();
    fs::write(&fasta_c_path, fasta_c).unwrap();

    let store_path = dir.path().join("store");
    let mut store = RefgetStore::on_disk(&store_path).unwrap();
    store.set_quiet(true);

    let (meta_a, _) = store.add_sequence_collection_from_fasta(&fasta_a_path, FastaImportOptions::new()).unwrap();
    let (meta_b, _) = store.add_sequence_collection_from_fasta(&fasta_b_path, FastaImportOptions::new()).unwrap();
    let (meta_c, _) = store.add_sequence_collection_from_fasta(&fasta_c_path, FastaImportOptions::new()).unwrap();

    let digest_a = meta_a.digest.clone();
    let digest_b = meta_b.digest.clone();
    let digest_c = meta_c.digest.clone();

    // Load collections before write and record level2 output
    store.load_all_collections().unwrap();
    let pre_a = store.get_collection_level2(&digest_a).unwrap();
    let pre_b = store.get_collection_level2(&digest_b).unwrap();
    let pre_c = store.get_collection_level2(&digest_c).unwrap();

    // Verify pre-write ordering for FASTA A: chrX, chr1, chr2
    assert_eq!(pre_a.names, vec!["chrX", "chr1", "chr2"], "A: names before roundtrip");
    // Verify pre-write ordering for FASTA B: chr1, chr2, chrX
    assert_eq!(pre_b.names, vec!["chr1", "chr2", "chrX"], "B: names before roundtrip");
    // Verify pre-write ordering for FASTA C: chrX, chr2, chr1 (name swap)
    assert_eq!(pre_c.names, vec!["chrX", "chr2", "chr1"], "C: names before roundtrip");

    store.write().unwrap();

    // Drop and reopen from disk
    drop(store);
    let mut reloaded = RefgetStore::open_local(&store_path).unwrap();
    reloaded.load_all_collections().unwrap();

    let post_a = reloaded.get_collection_level2(&digest_a).unwrap();
    let post_b = reloaded.get_collection_level2(&digest_b).unwrap();
    let post_c = reloaded.get_collection_level2(&digest_c).unwrap();

    // Names must match exactly (order-sensitive) after roundtrip
    assert_eq!(post_a.names, pre_a.names, "A: names after roundtrip");
    assert_eq!(post_b.names, pre_b.names, "B: names after roundtrip");
    assert_eq!(post_c.names, pre_c.names, "C: names after roundtrip");

    // Lengths must match exactly after roundtrip
    assert_eq!(post_a.lengths, pre_a.lengths, "A: lengths after roundtrip");
    assert_eq!(post_b.lengths, pre_b.lengths, "B: lengths after roundtrip");
    assert_eq!(post_c.lengths, pre_c.lengths, "C: lengths after roundtrip");

    // Sequence digests must match exactly after roundtrip
    assert_eq!(post_a.sequences, pre_a.sequences, "A: sequences after roundtrip");
    assert_eq!(post_b.sequences, pre_b.sequences, "B: sequences after roundtrip");
    assert_eq!(post_c.sequences, pre_c.sequences, "C: sequences after roundtrip");

    // Cross-check: FASTA C has chr2=GGAA and chr1=GCGC (opposite of A's chr1=GGAA, chr2=GCGC)
    // The sequence digest for chr2 in C should equal chr1 in A
    assert_eq!(
        post_c.sequences[1], post_a.sequences[1],
        "C.chr2 and A.chr1 share GGAA bytes, should have same sequence digest"
    );
    assert_eq!(
        post_c.sequences[2], post_a.sequences[2],
        "C.chr1 and A.chr2 share GCGC bytes, should have same sequence digest"
    );
}

// =========================================================================
// Name source tests
// =========================================================================

/// Test that get_collection() returns per-collection names, not global last-written names.
///
/// When the same sequence bytes appear in two collections under different names
/// (e.g., "chr1" in one, "chr2" in another), get_collection() must return the
/// correct name for each collection — not the name from whichever was loaded last.
#[test]
fn test_shared_sequence_different_names() {
    let dir = tempdir().unwrap();

    // subset.fa: contains chr1=GGAA (among others)
    let fasta1_content = ">chrX\nTTGGGGAA\n>chr1\nGGAA\n";
    let fasta1_path = dir.path().join("subset.fa");
    fs::write(&fasta1_path, fasta1_content).unwrap();

    // swap_wo_coords.fa: contains chr2=GGAA (same bytes, different name)
    let fasta2_content = ">chrX\nTTGGGGAA\n>chr2\nGGAA\n>chr1\nGCGC\n";
    let fasta2_path = dir.path().join("swap_wo_coords.fa");
    fs::write(&fasta2_path, fasta2_content).unwrap();

    let mut store = RefgetStore::in_memory();

    let (meta1, _) = store
        .add_sequence_collection_from_fasta(&fasta1_path, FastaImportOptions::new())
        .unwrap();

    let (meta2, _) = store
        .add_sequence_collection_from_fasta(&fasta2_path, FastaImportOptions::new())
        .unwrap();

    // Retrieve the collection from the first FASTA (subset.fa)
    let coll1 = store.get_collection(&meta1.digest).unwrap();
    let names1: Vec<&str> = coll1.sequences.iter().map(|s| s.metadata().name.as_str()).collect();

    // The first FASTA has chrX and chr1 — "chr1" must appear, not "chr2"
    assert!(
        names1.contains(&"chr1"),
        "Collection 1 (subset.fa) should contain 'chr1', got: {:?}",
        names1
    );
    assert!(
        !names1.contains(&"chr2"),
        "Collection 1 (subset.fa) must NOT contain 'chr2', got: {:?}",
        names1
    );

    // Retrieve the collection from the second FASTA (swap_wo_coords.fa)
    let coll2 = store.get_collection(&meta2.digest).unwrap();
    let names2: Vec<&str> = coll2.sequences.iter().map(|s| s.metadata().name.as_str()).collect();

    // The second FASTA has chrX, chr2, and chr1 — the sequence GGAA is "chr2" here
    assert!(
        names2.contains(&"chr2"),
        "Collection 2 (swap_wo_coords.fa) should contain 'chr2', got: {:?}",
        names2
    );
}

// =========================================================================
// Import collection tests
// =========================================================================

/// Helper: create a disk-backed store with one collection from a FASTA string.
fn disk_store_with_one_collection(fasta_content: &str) -> (RefgetStore, String, tempfile::TempDir, tempfile::TempDir) {
    let store_dir = tempdir().unwrap();
    let fasta_dir = tempdir().unwrap();
    let fasta = fasta_dir.path().join("test.fa");
    fs::write(&fasta, fasta_content).unwrap();

    let mut store = RefgetStore::on_disk(store_dir.path()).unwrap();
    store.set_quiet(true);
    let (meta, _) = store
        .add_sequence_collection_from_fasta(&fasta, FastaImportOptions::new())
        .unwrap();
    let digest = meta.digest.clone();
    // Load collection so name_lookup is populated
    store.load_all_collections().unwrap();
    (store, digest, store_dir, fasta_dir)
}

#[test]
fn test_import_collection_basic() {
    let (mut source, digest, _src_dir, _fasta_dir) =
        disk_store_with_one_collection(">chr1\nATGC\n>chr2\nGGGG\n");
    let target_dir = tempdir().unwrap();
    let mut target = RefgetStore::on_disk(target_dir.path()).unwrap();

    target.import_collection(&mut source, &digest).unwrap();

    // Target should have the collection
    let coll = target.get_collection(&digest).unwrap();
    assert_eq!(coll.sequences.len(), 2);
}

#[test]
fn test_import_collection_copies_sequence_aliases() {
    let (mut source, digest, _src_dir, _fasta_dir) =
        disk_store_with_one_collection(">chr1\nATGC\n>chr2\nGGGG\n");

    // Add sequence aliases in source
    let coll = source.get_collection(&digest).unwrap();
    let seq0_digest = coll.sequences[0].metadata().sha512t24u.clone();
    let seq1_digest = coll.sequences[1].metadata().sha512t24u.clone();
    source.add_sequence_alias("ncbi", "NC_000001.1", &seq0_digest).unwrap();
    source.add_sequence_alias("ucsc", "chr1", &seq0_digest).unwrap();
    source.add_sequence_alias("ncbi", "NC_000002.1", &seq1_digest).unwrap();

    let target_dir = tempdir().unwrap();
    let mut target = RefgetStore::on_disk(target_dir.path()).unwrap();
    target.import_collection(&mut source, &digest).unwrap();

    // Target should have the sequence aliases
    let ns = target.list_sequence_alias_namespaces();
    assert!(ns.contains(&"ncbi".to_string()), "Missing ncbi namespace: {:?}", ns);
    assert!(ns.contains(&"ucsc".to_string()), "Missing ucsc namespace: {:?}", ns);

    // Verify forward lookup
    let resolved = target.get_sequence_metadata_by_alias("ncbi", "NC_000001.1");
    assert!(resolved.is_some(), "ncbi alias NC_000001.1 not found in target");
    assert_eq!(resolved.unwrap().sha512t24u, seq0_digest);
}

#[test]
fn test_import_collection_copies_collection_aliases() {
    let (mut source, digest, _src_dir, _fasta_dir) =
        disk_store_with_one_collection(">chr1\nATGC\n>chr2\nGGGG\n");

    source.add_collection_alias("insdc", "GCA_000001.1", &digest).unwrap();
    source.add_collection_alias("refseq", "GCF_000001.1", &digest).unwrap();

    let target_dir = tempdir().unwrap();
    let mut target = RefgetStore::on_disk(target_dir.path()).unwrap();
    target.import_collection(&mut source, &digest).unwrap();

    let ns = target.list_collection_alias_namespaces();
    assert!(ns.contains(&"insdc".to_string()), "Missing insdc namespace: {:?}", ns);
    assert!(ns.contains(&"refseq".to_string()), "Missing refseq namespace: {:?}", ns);

    let aliases = target.get_aliases_for_collection(&digest);
    assert_eq!(aliases.len(), 2, "Expected 2 collection aliases, got {:?}", aliases);
}

#[test]
fn test_import_collection_copies_fhr_metadata() {
    use super::fhr_metadata::FhrMetadata;

    let (mut source, digest, _src_dir, _fasta_dir) =
        disk_store_with_one_collection(">chr1\nATGC\n");

    let fhr = FhrMetadata {
        genome: Some("Homo sapiens".to_string()),
        ..Default::default()
    };
    source.set_fhr_metadata(&digest, fhr).unwrap();

    let target_dir = tempdir().unwrap();
    let mut target = RefgetStore::on_disk(target_dir.path()).unwrap();
    target.import_collection(&mut source, &digest).unwrap();

    let fhr = target.get_fhr_metadata(&digest);
    assert!(fhr.is_some(), "FHR metadata not copied");
    assert_eq!(fhr.unwrap().genome.as_deref(), Some("Homo sapiens"));
}

#[test]
fn test_import_collection_disk_roundtrip_aliases() {
    // This test catches the bug where aliases loaded from disk aren't available
    // for reverse lookup during import.
    let source_dir = tempdir().unwrap();
    let target_dir = tempdir().unwrap();
    let fasta_dir = tempdir().unwrap();
    let fasta = fasta_dir.path().join("test.fa");
    fs::write(&fasta, ">chr1\nATGC\n>chr2\nGGGG\n").unwrap();

    // Create source store on disk, add aliases, then drop it
    let digest;
    let seq0_digest;
    {
        let mut source = RefgetStore::on_disk(source_dir.path()).unwrap();
        source.set_quiet(true);
        let (meta, _) = source
            .add_sequence_collection_from_fasta(&fasta, FastaImportOptions::new())
            .unwrap();
        digest = meta.digest.clone();

        let coll = source.get_collection(&digest).unwrap();
        seq0_digest = coll.sequences[0].metadata().sha512t24u.clone();

        source.add_sequence_alias("ncbi", "NC_000001.1", &seq0_digest).unwrap();
        source.add_collection_alias("insdc", "GCA_000001.1", &digest).unwrap();
    }
    // Source is dropped here

    // Reopen from disk (this tests that aliases are loaded from disk)
    let mut source = RefgetStore::on_disk(source_dir.path()).unwrap();
    source.load_all_collections().unwrap();

    // Verify aliases were loaded from disk
    let seq_ns = source.list_sequence_alias_namespaces();
    assert!(seq_ns.contains(&"ncbi".to_string()), "Source lost seq aliases after reopen: {:?}", seq_ns);
    let coll_ns = source.list_collection_alias_namespaces();
    assert!(coll_ns.contains(&"insdc".to_string()), "Source lost coll aliases after reopen: {:?}", coll_ns);

    // Import into a new disk-backed target
    let mut target = RefgetStore::on_disk(target_dir.path()).unwrap();
    target.import_collection(&mut source, &digest).unwrap();

    // Verify target has the aliases
    let ns = target.list_sequence_alias_namespaces();
    assert!(ns.contains(&"ncbi".to_string()), "Target missing ncbi seq alias: {:?}", ns);

    let resolved = target.get_sequence_metadata_by_alias("ncbi", "NC_000001.1");
    assert!(resolved.is_some(), "Alias NC_000001.1 not found in target after disk roundtrip");
    assert_eq!(resolved.unwrap().sha512t24u, seq0_digest);

    let coll_aliases = target.get_aliases_for_collection(&digest);
    assert_eq!(coll_aliases.len(), 1, "Expected 1 collection alias in target: {:?}", coll_aliases);
}

#[test]
fn test_import_collection_file_copy_roundtrip() {
    // Verify RGSI and .seq files are byte-for-byte identical after import
    // when ancillary digests match between source and dest.
    let (mut source, digest, src_dir, _fasta_dir) =
        disk_store_with_one_collection(">chr1\nATGC\n>chr2\nGGGG\n");
    let target_dir = tempdir().unwrap();
    let mut target = RefgetStore::on_disk(target_dir.path()).unwrap();

    target.import_collection(&mut source, &digest).unwrap();

    // Verify RGSI file is byte-for-byte identical
    let src_rgsi = fs::read(
        src_dir.path().join(format!("collections/{}.rgsi", digest)),
    ).unwrap();
    let dst_rgsi = fs::read(
        target_dir.path().join(format!("collections/{}.rgsi", digest)),
    ).unwrap();
    assert_eq!(src_rgsi, dst_rgsi, "RGSI files should be byte-identical");

    // Verify .seq files are byte-for-byte identical
    let coll = target.get_collection(&digest).unwrap();
    for seq in &coll.sequences {
        let seq_digest = &seq.metadata().sha512t24u;
        let src_seq_path = source.sequence_file_path(seq_digest).unwrap();
        let dst_seq_path = target.sequence_file_path(seq_digest).unwrap();
        let src_data = fs::read(&src_seq_path).unwrap();
        let dst_data = fs::read(&dst_seq_path).unwrap();
        assert_eq!(src_data, dst_data, "Sequence file for {} should be byte-identical", seq_digest);
    }

    // Verify in-memory metadata matches
    let src_coll = source.get_collection(&digest).unwrap();
    assert_eq!(coll.metadata.digest, src_coll.metadata.digest);
    assert_eq!(coll.sequences.len(), src_coll.sequences.len());
    for (src_seq, dst_seq) in src_coll.sequences.iter().zip(coll.sequences.iter()) {
        assert_eq!(src_seq.metadata().sha512t24u, dst_seq.metadata().sha512t24u);
        assert_eq!(src_seq.metadata().name, dst_seq.metadata().name);
        assert_eq!(src_seq.metadata().length, dst_seq.metadata().length);
    }
}

#[test]
fn test_import_collection_ancillary_digest_enrichment() {
    // Source store has ancillary_digests: false, destination has ancillary_digests: true.
    // The destination RGSI should contain ancillary digest headers that the source lacks.
    let source_dir = tempdir().unwrap();
    let fasta_dir = tempdir().unwrap();
    let fasta = fasta_dir.path().join("test.fa");
    fs::write(&fasta, ">chr1\nATGC\n>chr2\nGGGG\n").unwrap();

    // Create source store with ancillary_digests: false
    let mut source = RefgetStore::on_disk(source_dir.path()).unwrap();
    source.set_quiet(true);
    source.disable_ancillary_digests();
    let (meta, _) = source
        .add_sequence_collection_from_fasta(&fasta, FastaImportOptions::new())
        .unwrap();
    let digest = meta.digest.clone();
    source.load_all_collections().unwrap();

    // Verify source RGSI lacks ancillary digests
    let src_rgsi_content = fs::read_to_string(
        source_dir.path().join(format!("collections/{}.rgsi", digest)),
    ).unwrap();
    assert!(
        !src_rgsi_content.contains("name_length_pairs_digest"),
        "Source should NOT have ancillary digests",
    );

    // Create destination store with ancillary_digests: true (default)
    let target_dir = tempdir().unwrap();
    let mut target = RefgetStore::on_disk(target_dir.path()).unwrap();
    target.enable_ancillary_digests();
    target.import_collection(&mut source, &digest).unwrap();

    // Verify destination RGSI has ancillary digest headers
    let dst_rgsi_content = fs::read_to_string(
        target_dir.path().join(format!("collections/{}.rgsi", digest)),
    ).unwrap();
    assert!(
        dst_rgsi_content.contains("name_length_pairs_digest"),
        "Destination should have ancillary digests. RGSI:\n{}",
        dst_rgsi_content,
    );
    assert!(
        dst_rgsi_content.contains("sorted_name_length_pairs_digest"),
        "Destination should have sorted_name_length_pairs_digest",
    );
    assert!(
        dst_rgsi_content.contains("sorted_sequences_digest"),
        "Destination should have sorted_sequences_digest",
    );

    // Verify in-memory metadata has non-None ancillary fields
    let coll_meta = target.get_collection_metadata(&digest).unwrap();
    assert!(coll_meta.name_length_pairs_digest.is_some(), "name_length_pairs_digest should be Some");
    assert!(coll_meta.sorted_name_length_pairs_digest.is_some(), "sorted_name_length_pairs_digest should be Some");
    assert!(coll_meta.sorted_sequences_digest.is_some(), "sorted_sequences_digest should be Some");
}

#[test]
fn test_import_collection_mode_mismatch_error() {
    // Source with Raw mode, destination with Encoded mode should fail.
    let source_dir = tempdir().unwrap();
    let fasta_dir = tempdir().unwrap();
    let fasta = fasta_dir.path().join("test.fa");
    fs::write(&fasta, ">chr1\nATGC\n").unwrap();

    // Create source store in Raw mode
    let mut source = RefgetStore::on_disk(source_dir.path()).unwrap();
    source.set_quiet(true);
    source.disable_encoding();
    let (meta, _) = source
        .add_sequence_collection_from_fasta(&fasta, FastaImportOptions::new())
        .unwrap();
    let digest = meta.digest.clone();
    source.load_all_collections().unwrap();

    // Create destination store in Encoded mode (default)
    let target_dir = tempdir().unwrap();
    let mut target = RefgetStore::on_disk(target_dir.path()).unwrap();
    // target uses Encoded mode by default

    let result = target.import_collection(&mut source, &digest);
    assert!(result.is_err(), "Should fail with mode mismatch");
    let err_msg = result.unwrap_err().to_string();
    assert!(
        err_msg.contains("matching storage modes"),
        "Error should mention storage modes: {}",
        err_msg,
    );
}

// =========================================================================
// Parallel encode parity / determinism tests
// =========================================================================

/// Recursively collect every `*.seq` file under `dir`, keyed by path relative
/// to `dir`, with its bytes. Used to compare two on-disk stores.
fn collect_seq_files(dir: &std::path::Path) -> std::collections::BTreeMap<String, Vec<u8>> {
    fn walk(
        base: &std::path::Path,
        cur: &std::path::Path,
        out: &mut std::collections::BTreeMap<String, Vec<u8>>,
    ) {
        for entry in std::fs::read_dir(cur).unwrap() {
            let entry = entry.unwrap();
            let path = entry.path();
            if path.is_dir() {
                walk(base, &path, out);
            } else if path.extension().and_then(|e| e.to_str()) == Some("seq") {
                let rel = path.strip_prefix(base).unwrap().to_string_lossy().to_string();
                out.insert(rel, std::fs::read(&path).unwrap());
            }
        }
    }
    let mut out = std::collections::BTreeMap::new();
    let seqdir = dir.join("sequences");
    if seqdir.exists() {
        walk(dir, &seqdir, &mut out);
    }
    out
}

/// Multi-record FASTA with names deliberately NOT in sorted order so that a
/// digest-sorted index would differ from FASTA (name_lookup) order, exercising
/// the order-preservation logic.
const PARITY_FASTA: &str =
    ">chrX\nTTGGGGAACCCCTTTT\n>chr1\nGGAATTCCGGAATTCC\n>chr2\nACGTACGTACGTACGT\n\
     >chrM\nGGGGCCCCAAAATTTT\n>chr10\nTACGTACGTACGTACG\n";

fn build_on_disk_store(dir: &std::path::Path, fasta: &std::path::Path, jobs: usize) -> String {
    let mut store = RefgetStore::on_disk(dir).unwrap();
    store.set_quiet(true);
    let (meta, _) = store
        .add_sequence_collection_from_fasta(fasta, FastaImportOptions::new().jobs(jobs))
        .unwrap();
    meta.digest
}

#[test]
fn test_parallel_equals_serial_on_disk() {
    let work = tempdir().unwrap();
    let fasta = work.path().join("parity.fa");
    fs::write(&fasta, PARITY_FASTA).unwrap();

    let dir_serial = tempdir().unwrap();
    let dir_parallel = tempdir().unwrap();

    let digest_serial = build_on_disk_store(dir_serial.path(), &fasta, 1);
    let digest_parallel = build_on_disk_store(dir_parallel.path(), &fasta, 8);

    // Collection digest identical.
    assert_eq!(digest_serial, digest_parallel, "collection digest must match");

    // sequences.rgsi byte-identical (digest-sorted, so order-independent).
    let rgsi_serial = fs::read(dir_serial.path().join("sequences.rgsi")).unwrap();
    let rgsi_parallel = fs::read(dir_parallel.path().join("sequences.rgsi")).unwrap();
    assert_eq!(rgsi_serial, rgsi_parallel, "sequences.rgsi must be byte-identical");

    // collections.rgci byte-identical.
    let rgci_serial = fs::read(dir_serial.path().join("collections.rgci")).unwrap();
    let rgci_parallel = fs::read(dir_parallel.path().join("collections.rgci")).unwrap();
    assert_eq!(rgci_serial, rgci_parallel, "collections.rgci must be byte-identical");

    // Every .seq file present with identical bytes (both directions).
    let seqs_serial = collect_seq_files(dir_serial.path());
    let seqs_parallel = collect_seq_files(dir_parallel.path());
    assert_eq!(
        seqs_serial, seqs_parallel,
        ".seq files must match between serial and parallel builds"
    );
    assert!(!seqs_serial.is_empty(), "expected some .seq files");
}

#[test]
fn test_parallel_name_lookup_matches_fasta_order() {
    let work = tempdir().unwrap();
    let fasta = work.path().join("parity.fa");
    fs::write(&fasta, PARITY_FASTA).unwrap();

    // Raw FASTA header order.
    let fasta_order = vec!["chrX", "chr1", "chr2", "chrM", "chr10"];

    let dir_serial = tempdir().unwrap();
    let dir_parallel = tempdir().unwrap();
    let digest = build_on_disk_store(dir_serial.path(), &fasta, 1);
    let _ = build_on_disk_store(dir_parallel.path(), &fasta, 8);

    let mut serial = RefgetStore::open_local(dir_serial.path()).unwrap();
    let mut parallel = RefgetStore::open_local(dir_parallel.path()).unwrap();
    serial.load_all_collections().unwrap();
    parallel.load_all_collections().unwrap();

    let key = digest.to_key();
    let serial_names: Vec<String> = serial
        .name_lookup
        .get(&key)
        .unwrap()
        .keys()
        .cloned()
        .collect();
    let parallel_names: Vec<String> = parallel
        .name_lookup
        .get(&key)
        .unwrap()
        .keys()
        .cloned()
        .collect();

    assert_eq!(serial_names, fasta_order, "serial name_lookup must follow FASTA order");
    assert_eq!(
        parallel_names, fasta_order,
        "parallel name_lookup must follow FASTA order"
    );
}

#[test]
fn test_parallel_equals_serial_in_memory() {
    let work = tempdir().unwrap();
    let fasta = work.path().join("parity.fa");
    fs::write(&fasta, PARITY_FASTA).unwrap();

    let mut serial = RefgetStore::in_memory();
    serial.set_quiet(true);
    let (meta_s, _) = serial
        .add_sequence_collection_from_fasta(&fasta, FastaImportOptions::new().jobs(1))
        .unwrap();

    let mut parallel = RefgetStore::in_memory();
    parallel.set_quiet(true);
    let (meta_p, _) = parallel
        .add_sequence_collection_from_fasta(&fasta, FastaImportOptions::new().jobs(8))
        .unwrap();

    assert_eq!(meta_s.digest, meta_p.digest);

    let key = meta_s.digest.to_key();

    // Identical name_lookup order and contents.
    let names_s: Vec<(String, DigestKey)> = serial
        .name_lookup
        .get(&key)
        .unwrap()
        .iter()
        .map(|(n, d)| (n.clone(), *d))
        .collect();
    let names_p: Vec<(String, DigestKey)> = parallel
        .name_lookup
        .get(&key)
        .unwrap()
        .iter()
        .map(|(n, d)| (n.clone(), *d))
        .collect();
    assert_eq!(names_s, names_p, "name_lookup order+contents must match");

    // Identical set of digests.
    let digs_s: std::collections::BTreeSet<DigestKey> = serial.sequence_digests().collect();
    let digs_p: std::collections::BTreeSet<DigestKey> = parallel.sequence_digests().collect();
    assert_eq!(digs_s, digs_p, "digest sets must match");

    // Per-digest metadata + decoded bytes parity.
    for name in ["chrX", "chr1", "chr2", "chrM", "chr10"] {
        let rec_s = serial.get_sequence_by_name(&meta_s.digest, name).unwrap();
        let rec_p = parallel.get_sequence_by_name(&meta_p.digest, name).unwrap();
        let m_s = rec_s.metadata();
        let m_p = rec_p.metadata();
        assert_eq!(m_s.sha512t24u, m_p.sha512t24u);
        assert_eq!(m_s.md5, m_p.md5);
        assert_eq!(m_s.alphabet, m_p.alphabet);
        assert_eq!(m_s.length, m_p.length);

        let sub_s = serial.get_substring(&m_s.sha512t24u, 0, m_s.length).unwrap();
        let sub_p = parallel.get_substring(&m_p.sha512t24u, 0, m_p.length).unwrap();
        assert_eq!(sub_s, sub_p, "decoded bytes must match for {}", name);
    }
}

#[test]
fn test_parallel_cached_metadata_parity() {
    // First import (no cache) writes the .rgsi cache; second import hits the
    // cached-metadata fast path. Build serial+parallel on-disk stores via the
    // cached path and assert full equality.

    // Build the rgsi cache by importing once into a throwaway store. The cache
    // is written next to the FASTA, so use a per-arm FASTA copy.
    let build_cached = |jobs: usize| -> (tempfile::TempDir, String) {
        let src_dir = tempdir().unwrap();
        let fasta = src_dir.path().join("cached.fa");
        fs::write(&fasta, PARITY_FASTA).unwrap();

        // Prime the cache (writes cached.rgsi next to the FASTA).
        let prime_dir = tempdir().unwrap();
        let mut prime = RefgetStore::on_disk(prime_dir.path()).unwrap();
        prime.set_quiet(true);
        prime
            .add_sequence_collection_from_fasta(&fasta, FastaImportOptions::new().jobs(1))
            .unwrap();
        assert!(
            src_dir.path().join("cached.rgsi").exists(),
            "rgsi cache should have been written"
        );

        // Now build a fresh store via the cached fast path.
        let dir = tempdir().unwrap();
        let mut store = RefgetStore::on_disk(dir.path()).unwrap();
        store.set_quiet(true);
        let (meta, _) = store
            .add_sequence_collection_from_fasta(&fasta, FastaImportOptions::new().jobs(jobs))
            .unwrap();
        (dir, meta.digest)
    };

    let (dir_serial, digest_serial) = build_cached(1);
    let (dir_parallel, digest_parallel) = build_cached(8);

    assert_eq!(digest_serial, digest_parallel);

    let rgsi_s = fs::read(dir_serial.path().join("sequences.rgsi")).unwrap();
    let rgsi_p = fs::read(dir_parallel.path().join("sequences.rgsi")).unwrap();
    assert_eq!(rgsi_s, rgsi_p, "cached-path sequences.rgsi must match");

    let seqs_s = collect_seq_files(dir_serial.path());
    let seqs_p = collect_seq_files(dir_parallel.path());
    assert_eq!(seqs_s, seqs_p, "cached-path .seq files must match");

    // name_lookup order should follow FASTA order in both.
    let mut serial = RefgetStore::open_local(dir_serial.path()).unwrap();
    let mut parallel = RefgetStore::open_local(dir_parallel.path()).unwrap();
    serial.load_all_collections().unwrap();
    parallel.load_all_collections().unwrap();
    let key = digest_serial.to_key();
    let names_s: Vec<String> = serial.name_lookup.get(&key).unwrap().keys().cloned().collect();
    let names_p: Vec<String> = parallel.name_lookup.get(&key).unwrap().keys().cloned().collect();
    assert_eq!(names_s, vec!["chrX", "chr1", "chr2", "chrM", "chr10"]);
    assert_eq!(names_s, names_p);
}

#[test]
fn test_parallel_duplicate_contig_dedup() {
    // Two records with identical sequence but different names. Must dedup to a
    // single .seq file / single sequence_store entry; name_lookup keeps both
    // names in FASTA order mapping to the same digest.
    let fasta_content = ">dupA\nACGTACGTACGT\n>uniq\nGGGGCCCCAAAA\n>dupB\nACGTACGTACGT\n";
    let work = tempdir().unwrap();
    let fasta = work.path().join("dup.fa");
    fs::write(&fasta, fasta_content).unwrap();

    let dir = tempdir().unwrap();
    let mut store = RefgetStore::on_disk(dir.path()).unwrap();
    store.set_quiet(true);
    let (meta, _) = store
        .add_sequence_collection_from_fasta(&fasta, FastaImportOptions::new().jobs(8))
        .unwrap();

    // Two distinct digests (the duplicate collapses).
    let digs: std::collections::BTreeSet<DigestKey> = store.sequence_digests().collect();
    assert_eq!(digs.len(), 2, "duplicate sequence must dedup to 2 entries");

    let seqs = collect_seq_files(dir.path());
    assert_eq!(seqs.len(), 2, "duplicate sequence must dedup to 2 .seq files");

    let key = meta.digest.to_key();
    let nl = store.name_lookup.get(&key).unwrap();
    let names: Vec<String> = nl.keys().cloned().collect();
    assert_eq!(names, vec!["dupA", "uniq", "dupB"], "name_lookup keeps FASTA order");
    // dupA and dupB map to same digest.
    assert_eq!(nl.get("dupA"), nl.get("dupB"));
    assert_ne!(nl.get("dupA"), nl.get("uniq"));
}

#[test]
fn test_parallel_determinism_across_runs() {
    let work = tempdir().unwrap();
    let fasta = work.path().join("parity.fa");
    fs::write(&fasta, PARITY_FASTA).unwrap();

    let mut prev: Option<Vec<u8>> = None;
    for _ in 0..3 {
        let dir = tempdir().unwrap();
        build_on_disk_store(dir.path(), &fasta, 8);
        let rgsi = fs::read(dir.path().join("sequences.rgsi")).unwrap();
        if let Some(p) = &prev {
            assert_eq!(p, &rgsi, "sequences.rgsi must be identical across parallel runs");
        }
        prev = Some(rgsi);
    }
}

// =========================================================================
// Multi-file (file-level) parallelism determinism tests
// =========================================================================

/// Collect every data/index file under a store dir EXCEPT the `rgstore.json`
/// manifest (which embeds wall-clock timestamps). Keyed by path relative to
/// `dir`, with bytes. Used to assert byte-identical stores.
fn collect_store_data_files(
    dir: &std::path::Path,
) -> std::collections::BTreeMap<String, Vec<u8>> {
    fn walk(
        base: &std::path::Path,
        cur: &std::path::Path,
        out: &mut std::collections::BTreeMap<String, Vec<u8>>,
    ) {
        for entry in std::fs::read_dir(cur).unwrap() {
            let entry = entry.unwrap();
            let path = entry.path();
            if path.is_dir() {
                walk(base, &path, out);
            } else {
                let rel = path.strip_prefix(base).unwrap().to_string_lossy().to_string();
                // rgstore.json embeds created_at/modified timestamps and the
                // hashes of those files; skip it for byte-identity comparison.
                if rel == "rgstore.json" {
                    continue;
                }
                out.insert(rel, std::fs::read(&path).unwrap());
            }
        }
    }
    let mut out = std::collections::BTreeMap::new();
    walk(dir, dir, &mut out);
    out
}

/// Write `content` gzip-compressed to `path`.
fn write_gzipped(path: &std::path::Path, content: &str) {
    use flate2::write::GzEncoder;
    use flate2::Compression;
    use std::io::Write;
    let f = fs::File::create(path).unwrap();
    let mut enc = GzEncoder::new(f, Compression::default());
    enc.write_all(content.as_bytes()).unwrap();
    enc.finish().unwrap();
}

/// Build an on-disk store from multiple FASTA files with the given `jobs`
/// (files-in-flight) setting. Returns the per-file collection digests in input
/// order.
fn build_multi(
    dir: &std::path::Path,
    files: &[std::path::PathBuf],
    jobs: usize,
) -> Vec<String> {
    let mut store = RefgetStore::on_disk(dir).unwrap();
    store.set_quiet(true);
    let opts = FastaImportOptions::new().jobs(jobs);
    store
        .add_sequence_collections_from_fastas(files, opts)
        .unwrap()
        .collections
        .into_iter()
        .map(|(m, _)| m.digest)
        .collect()
}

/// The per-run `ImportReport` counters must reflect what an import ACTUALLY
/// did, unlike `stats()`, which is a RAM-residency snapshot.
#[test]
fn test_import_report_per_run_counters() {
    let work = tempdir().unwrap();

    // Same fixture shape as the parallel-equals-serial test: file "c" shares
    // the chr1 sequence content with file "a", so 6 records are seen but only
    // 5 distinct digests exist.
    let fa_a = work.path().join("a.fa");
    let fa_b = work.path().join("b.fa");
    let fa_c = work.path().join("c.fa");
    fs::write(&fa_a, ">chr1\nGGAATTCCGGAATTCC\n>chr2\nACGTACGTACGTACGT\n").unwrap();
    fs::write(&fa_b, ">chrX\nTTGGGGAACCCCTTTT\n>chrM\nGGGGCCCCAAAATTTT\n").unwrap();
    fs::write(&fa_c, ">altchr1\nGGAATTCCGGAATTCC\n>chr9\nTACGTACGTACGTACG\n").unwrap();
    let files = vec![fa_a, fa_b, fa_c];

    let store_dir = tempdir().unwrap();
    let mut store = RefgetStore::on_disk(store_dir.path()).unwrap();
    store.set_quiet(true);

    let report = store
        .add_sequence_collections_from_fastas(&files, FastaImportOptions::new().jobs(4))
        .unwrap();

    assert_eq!(report.collections.len(), 3);
    assert_eq!(report.n_collections_new, 3);
    // Each distinct digest is written exactly once; the shared chr1 content is
    // seen twice, so exactly one record is deduped.
    assert_eq!(report.n_sequences_written, 5);
    assert_eq!(report.n_sequences_deduped, 1);
    // Every record seen across all processed files is accounted for.
    assert_eq!(
        report.n_sequences_written + report.n_sequences_deduped,
        6,
        "written + deduped must equal the records seen"
    );
    assert_eq!(collect_seq_files(store_dir.path()).len(), 5);

    // Re-importing the same files into the same store adds nothing. Whether the
    // records are counted as deduped or not seen at all depends on the `.rgsi`
    // sidecar short-circuit (which skips a present collection before its FASTA
    // is ever opened), so only the "nothing new" half is pinned here.
    let report2 = store
        .add_sequence_collections_from_fastas(&files, FastaImportOptions::new().jobs(4))
        .unwrap();
    assert_eq!(report2.collections.len(), 3);
    assert_eq!(report2.n_collections_new, 0);
    assert_eq!(
        report2.n_sequences_written, 0,
        "a re-import must write no sequence bytes"
    );
    assert!(report2.collections.iter().all(|(_, was_new)| !*was_new));

    // Contrast: the residency gauge says nothing about either run.
    assert_eq!(store.stats().n_sequences_in_memory, 0);

    // An in-memory store dispatches no disk writes at all, so it is classified
    // by a separate branch; it must produce the same counts.
    let mut mem_store = RefgetStore::in_memory();
    mem_store.set_quiet(true);
    let mem_report = mem_store
        .add_sequence_collections_from_fastas(&files, FastaImportOptions::new().jobs(4))
        .unwrap();
    assert_eq!(mem_report.n_collections_new, 3);
    assert_eq!(mem_report.n_sequences_written, 5);
    assert_eq!(mem_report.n_sequences_deduped, 1);
}

#[test]
fn test_multifile_parallel_equals_serial() {
    let work = tempdir().unwrap();

    // Three distinct collections. File "c" deliberately SHARES a sequence
    // (the chr1 record) with file "a" to exercise cross-collection dedup.
    let fa_a = work.path().join("a.fa");
    let fa_b = work.path().join("b.fa");
    let fa_c = work.path().join("c.fa");
    fs::write(&fa_a, ">chr1\nGGAATTCCGGAATTCC\n>chr2\nACGTACGTACGTACGT\n").unwrap();
    fs::write(&fa_b, ">chrX\nTTGGGGAACCCCTTTT\n>chrM\nGGGGCCCCAAAATTTT\n").unwrap();
    // Shares the chr1 sequence content with file a (different collection).
    fs::write(&fa_c, ">altchr1\nGGAATTCCGGAATTCC\n>chr9\nTACGTACGTACGTACG\n").unwrap();
    let files = vec![fa_a.clone(), fa_b.clone(), fa_c.clone()];

    let dir_serial = tempdir().unwrap();
    let dir_parallel = tempdir().unwrap();

    let digests_serial = build_multi(dir_serial.path(), &files, 1);
    let digests_parallel = build_multi(dir_parallel.path(), &files, 8);

    // Per-file collection digests identical and in the same (input) order.
    assert_eq!(
        digests_serial, digests_parallel,
        "per-file collection digests must match in input order"
    );

    // The whole store (sans rgstore.json timestamp manifest) is byte-identical.
    let serial = collect_store_data_files(dir_serial.path());
    let parallel = collect_store_data_files(dir_parallel.path());
    assert_eq!(
        serial, parallel,
        "multi-file parallel store must be byte-identical to serial store"
    );

    // Cross-collection dedup: the chr1 sequence is shared by file a and file c,
    // so the total number of distinct .seq files must be 5 (chr1, chr2, chrX,
    // chrM, chr9) -- NOT 6.
    let seqs = collect_seq_files(dir_serial.path());
    assert_eq!(seqs.len(), 5, "shared chr1 sequence must be stored once");
}

#[test]
fn test_multifile_parallel_gzipped() {
    let work = tempdir().unwrap();

    // Same content as the plain-text case, but gzipped to exercise K concurrent
    // MultiGzDecoders.
    let fa_a = work.path().join("a.fa.gz");
    let fa_b = work.path().join("b.fa.gz");
    let fa_c = work.path().join("c.fa.gz");
    write_gzipped(&fa_a, ">chr1\nGGAATTCCGGAATTCC\n>chr2\nACGTACGTACGTACGT\n");
    write_gzipped(&fa_b, ">chrX\nTTGGGGAACCCCTTTT\n>chrM\nGGGGCCCCAAAATTTT\n");
    write_gzipped(&fa_c, ">altchr1\nGGAATTCCGGAATTCC\n>chr9\nTACGTACGTACGTACG\n");
    let files = vec![fa_a, fa_b, fa_c];

    let dir_serial = tempdir().unwrap();
    let dir_parallel = tempdir().unwrap();

    let digests_serial = build_multi(dir_serial.path(), &files, 1);
    let digests_parallel = build_multi(dir_parallel.path(), &files, 8);

    assert_eq!(digests_serial, digests_parallel, "gzipped digests must match");

    let serial = collect_store_data_files(dir_serial.path());
    let parallel = collect_store_data_files(dir_parallel.path());
    assert_eq!(
        serial, parallel,
        "gzipped multi-file parallel store must be byte-identical to serial"
    );
}

/// Regression test for the parallel-import "resume re-decode" bug.
///
/// On RESUME (re-importing a FASTA whose collection is already in the store and
/// whose sibling `.rgsi` cache exists), the import MUST short-circuit BEFORE
/// opening/decoding the FASTA. The old serial path did this; a refactor moved
/// the "already exists" check to `End`, AFTER the whole file had been
/// re-decoded + re-encoded -- wasting enormous CPU on resume.
///
/// This test makes the regression deterministic WITHOUT any production hooks:
/// after the first import we CORRUPT the FASTA bytes while keeping the `.rgsi`
/// sidecar intact. A correct (short-circuiting) implementation never opens the
/// corrupt FASTA, so the resume succeeds, reports `was_new = false`, and leaves
/// the store unchanged. A regressed implementation would try to decode the
/// garbage FASTA and either error or mis-build -- failing the test.
#[test]
fn test_resume_skips_present_collection_before_decoding_fasta() {
    let temp_dir = tempdir().unwrap();
    let temp_path = temp_dir.path();

    // FASTA whose collection we will import, then "resume".
    let fasta_path = temp_path.join("genome.fa");
    fs::write(
        &fasta_path,
        ">chr1\nACGTACGTACGTACGT\n>chr2\nTTTTGGGGCCCCAAAA\n",
    )
    .unwrap();

    // Disk-backed store so RGSI caching is enabled (use_cache = local_path set).
    let cache_path = temp_path.join("store");
    let mut store = RefgetStore::on_disk(&cache_path).unwrap();

    // First import: builds the collection and writes the sibling genome.rgsi.
    let (meta_first, was_new_first) = store
        .add_sequence_collection_from_fasta(&fasta_path, FastaImportOptions::new().jobs(4))
        .unwrap();
    assert!(was_new_first, "first import must add a new collection");

    let rgsi_sidecar = temp_path.join("genome.rgsi");
    assert!(
        rgsi_sidecar.exists(),
        "first import must write the sibling .rgsi cache"
    );

    // --force must NOT skip: with the FASTA still intact and the collection
    // already present, forcing must RE-PROCESS it (was_new = true), proving the
    // short-circuit respects --force. (Done before corrupting so the forced
    // decode has a valid FASTA to read.)
    let (_meta_forced, was_new_forced) = store
        .add_sequence_collection_from_fasta(
            &fasta_path,
            FastaImportOptions::new().jobs(4).force(true),
        )
        .expect("forced re-import of an intact FASTA must succeed");
    assert!(
        was_new_forced,
        "--force must bypass the skip and re-process the present collection (was_new = true)"
    );

    // Snapshot store contents to prove the resume changes nothing.
    let collections_before: Vec<DigestKey> = {
        let mut v: Vec<DigestKey> = store.collections.keys().cloned().collect();
        v.sort();
        v
    };
    let sequences_before: Vec<DigestKey> = {
        let mut v: Vec<DigestKey> = store.sequence_store.keys().cloned().collect();
        v.sort();
        v
    };

    // CORRUPT the FASTA: replace it with a record whose sequence NAME is absent
    // from the cached metadata. Any code path that actually opens + decodes this
    // FASTA fails ("Sequence '...' not found in cached metadata"). The .rgsi
    // sidecar stays intact, so the collection digest is still discoverable for
    // free -- a correct short-circuit never reaches the decode.
    fs::write(&fasta_path, b">totally_bogus_name_not_in_cache\nNNNNNNNN\n").unwrap();

    // Resume: re-import the SAME (now-corrupt) FASTA in parallel (jobs > 1).
    let (meta_resume, was_new_resume) = store
        .add_sequence_collection_from_fasta(&fasta_path, FastaImportOptions::new().jobs(4))
        .expect(
            "resume must succeed: a present collection with an intact .rgsi must be skipped \
             BEFORE the (now-corrupt) FASTA is opened/decoded",
        );

    assert!(
        !was_new_resume,
        "resume of an already-present collection must report was_new = false"
    );
    assert_eq!(
        meta_resume.digest, meta_first.digest,
        "resume must report the same collection digest from the cached .rgsi"
    );

    // Store must be byte-for-byte unchanged by the resume.
    let collections_after: Vec<DigestKey> = {
        let mut v: Vec<DigestKey> = store.collections.keys().cloned().collect();
        v.sort();
        v
    };
    let sequences_after: Vec<DigestKey> = {
        let mut v: Vec<DigestKey> = store.sequence_store.keys().cloned().collect();
        v.sort();
        v
    };
    assert_eq!(
        collections_before, collections_after,
        "resume must not change the set of collections"
    );
    assert_eq!(
        sequences_before, sequences_after,
        "resume must not change the set of sequences"
    );
}

// =========================================================================
// Many-tiny-sequence throughput (writer-pool) tests
// =========================================================================

/// Generate a FASTA with `n` short, DISTINCT sequences. Each record encodes its
/// index in base-4 as DNA so every sequence has a unique content digest (no
/// dedup), mimicking a transcriptome with hundreds of thousands of tiny records
/// -- the workload the writer pool is meant to accelerate (the old single
/// inserter did a File::create + create_dir_all per record).
fn write_many_tiny_fasta(path: &std::path::Path, n: usize) {
    use std::io::Write;
    const BASES: [u8; 4] = [b'A', b'C', b'G', b'T'];
    let f = fs::File::create(path).unwrap();
    let mut w = std::io::BufWriter::new(f);
    for i in 0..n {
        // 16-base sequence uniquely encoding `i` (4^16 ≈ 4.3e9 >> n), padded so
        // every record is distinct and a constant small size.
        let mut seq = [b'A'; 16];
        let mut v = i;
        let mut p = 15usize;
        while v > 0 {
            seq[p] = BASES[v & 0b11];
            v >>= 2;
            p = p.wrapping_sub(1);
        }
        writeln!(w, ">seq{}", i).unwrap();
        w.write_all(&seq).unwrap();
        w.write_all(b"\n").unwrap();
    }
    w.flush().unwrap();
}

/// Throughput regression test for the parallel `.seq` writer pool.
///
/// Builds an on-disk store from a synthetic FASTA with MANY tiny sequences. The
/// pre-writer-pool code funneled every per-sequence `File::create` +
/// `create_dir_all` through the single inserter thread; this test asserts the
/// build finishes well under a generous bound (so a regression that re-serializes
/// the writes -- or reintroduces a per-sequence `create_dir_all` -- shows up),
/// while staying fast and bounded (no benchmark loop, no giant dataset).
#[test]
fn test_many_tiny_sequences_throughput() {
    let work = tempdir().unwrap();
    let fasta = work.path().join("tiny.fa");
    // ~100k distinct tiny records: enough to expose a single-thread file-create
    // bottleneck, small enough to build in a few seconds.
    let n = 100_000usize;
    write_many_tiny_fasta(&fasta, n);

    let dir = tempdir().unwrap();
    let start = std::time::Instant::now();
    let mut store = RefgetStore::on_disk(dir.path()).unwrap();
    store.set_quiet(true);
    let (meta, was_new) = store
        .add_sequence_collection_from_fasta(&fasta, FastaImportOptions::new().jobs(4))
        .unwrap();
    let elapsed = start.elapsed();

    assert!(was_new, "collection must be new");
    assert_eq!(
        meta.n_sequences, n,
        "all {} distinct sequences must be registered",
        n
    );

    // Every distinct sequence must have produced a .seq file on disk (the writer
    // pool drained at the end-of-run barrier before indexes were written).
    let seqs = collect_seq_files(dir.path());
    assert_eq!(
        seqs.len(),
        n,
        "every distinct tiny sequence must have a .seq file on disk after the barrier"
    );

    // Generous wall-clock bound: this is NOT a benchmark, just a guard against a
    // re-serialized (single-thread file-create) regression. With the writer pool
    // this completes in a couple seconds on CI; 60s leaves ample slack.
    assert!(
        elapsed.as_secs() < 60,
        "building {} tiny sequences took {:?}; expected well under the single-inserter bound",
        n,
        elapsed
    );

    eprintln!(
        "throughput: built {} tiny seqs in {:?} ({:.0} seqs/sec)",
        n,
        elapsed,
        n as f64 / elapsed.as_secs_f64()
    );
}

// =========================================================================
// stream_sequence tests
// =========================================================================

fn first_seq_digest(store: &RefgetStore) -> String {
    store
        .sequence_store
        .values()
        .next()
        .unwrap()
        .metadata()
        .sha512t24u
        .clone()
}

fn first_seq_length(store: &RefgetStore) -> usize {
    store
        .sequence_store
        .values()
        .next()
        .unwrap()
        .metadata()
        .length
}

fn build_on_disk_store_streaming(mode: StorageMode) -> (tempfile::TempDir, RefgetStore, String, usize) {
    let dir = tempdir().unwrap();
    let fasta = dir.path().join("test.fa");
    fs::write(&fasta, ">chr1\nACGTACGTACGTACGTACGT\n").unwrap();
    let store_path = dir.path().join("store");
    let mut store = RefgetStore::on_disk(&store_path).unwrap();
    store.set_encoding_mode(mode);
    store
        .add_sequence_collection_from_fasta(&fasta, FastaImportOptions::new())
        .unwrap();
    let digest = first_seq_digest(&store);
    let length = first_seq_length(&store);
    (dir, store, digest, length)
}

#[test]
fn test_stream_sequence_local_full() {
    use std::io::Read;
    let (_dir, store, digest, length) = build_on_disk_store_streaming(StorageMode::Encoded);
    let mut reader = store.stream_sequence(&digest, None, None).unwrap();
    let mut out = Vec::new();
    reader.read_to_end(&mut out).unwrap();
    assert_eq!(out.len(), length);
    assert_eq!(&out[..], b"ACGTACGTACGTACGTACGT");
}

#[test]
fn test_stream_sequence_local_substring() {
    use std::io::Read;
    let (_dir, mut store, digest, length) = build_on_disk_store_streaming(StorageMode::Encoded);
    store.load_sequence(&digest).unwrap();
    let ranges: Vec<(u64, u64)> = vec![
        (0, 4),
        (1, 5),
        (2, 10),
        (5, 6),
        (0, length as u64),
        (length as u64 - 1, length as u64),
    ];
    for (s, e) in ranges {
        let mut reader = store.stream_sequence(&digest, Some(s), Some(e)).unwrap();
        let mut streamed = Vec::new();
        reader.read_to_end(&mut streamed).unwrap();

        let expected = store.get_substring(&digest, s as usize, e as usize).unwrap();
        assert_eq!(
            String::from_utf8(streamed).unwrap(),
            expected,
            "mismatch for range {}..{}",
            s,
            e
        );
    }
}

// =========================================================================
// StorageMode::Zstd round-trip tests
// =========================================================================

/// A non-trivial sequence with real repeat structure (so zstd has something to
/// compress) plus varied bases, long enough to exercise multi-window slicing.
fn zstd_test_sequence() -> Vec<u8> {
    let mut s = Vec::new();
    // Repetitive satellite-like block (compresses well).
    for _ in 0..2000 {
        s.extend_from_slice(b"ACGTAACCGGTT");
    }
    // A less regular tail so windows near the end differ from the head.
    let motifs: [&[u8]; 4] = [b"GATTACA", b"TTAGGGTT", b"CCCGGGAAA", b"ACGTN"];
    for i in 0..1000 {
        s.extend_from_slice(motifs[i % motifs.len()]);
    }
    s
}

/// Build a disk-backed store in `mode` holding one record with the given ASCII
/// bytes (added directly via `add_sequence_record`, the seam the novel/unplaced
/// store uses -- NOT the FASTA import path).
fn build_zstd_roundtrip_store(
    mode: StorageMode,
    name: &str,
    ascii: &[u8],
) -> (tempfile::TempDir, RefgetStore, String) {
    let dir = tempdir().unwrap();
    let store_path = dir.path().join("store");
    let mut store = RefgetStore::on_disk(&store_path).unwrap();
    store.set_encoding_mode(mode);
    // digest_sequence builds the ASCII SequenceRecord (metadata + raw bytes);
    // for Encoded we must 2-bit pre-pack, for Raw/Zstd we pass ASCII through
    // (the store owns zstd compression). This mirrors panget's store_fill_chunk.
    let record = crate::digest::digest_sequence(name, ascii);
    let digest = record.metadata().sha512t24u.clone();
    let record = if mode == StorageMode::Encoded {
        match record {
            SequenceRecord::Full { metadata, sequence } => {
                let alphabet = crate::digest::lookup_alphabet(&metadata.alphabet);
                let packed = crate::digest::encode_sequence(&sequence[..], alphabet);
                SequenceRecord::Full { metadata, sequence: packed.into() }
            }
            other => other,
        }
    } else {
        record
    };
    store.add_sequence_record(record, false).unwrap();
    store.write().unwrap();
    (dir, store, digest)
}

#[test]
fn test_zstd_roundtrip_matches_encoded() {
    let ascii = zstd_test_sequence();
    let len = ascii.len();
    let (_zdir, zstore, zdigest) =
        build_zstd_roundtrip_store(StorageMode::Zstd, "chrZ", &ascii);
    let (_edir, estore, edigest) =
        build_zstd_roundtrip_store(StorageMode::Encoded, "chrZ", &ascii);
    // Same ASCII -> same sha512t24u regardless of storage mode.
    assert_eq!(zdigest, edigest, "digest must be mode-independent");

    // A spread of windows: head, tail, boundaries, whole, empty.
    let windows: Vec<(usize, usize)> = vec![
        (0, 1),
        (0, 12),
        (5, 37),
        (11, 24),
        (100, 1000),
        (len / 2, len / 2 + 4321),
        (len - 1, len),
        (len - 500, len),
        (0, len),
        (7, 7), // empty
    ];

    // Disk-backed (Stub) path: get_substring reads/decompresses from the .seq.
    for &(s, e) in &windows {
        let z = zstore.get_substring(&zdigest, s, e).unwrap();
        let expect = std::str::from_utf8(&ascii[s..e]).unwrap();
        assert_eq!(z, expect, "zstd disk get_substring mismatch at {}..{}", s, e);
        let en = estore.get_substring(&edigest, s, e).unwrap();
        assert_eq!(z, en, "zstd vs encoded mismatch at {}..{}", s, e);
    }

    // get_substrings batch on the disk-backed store.
    let batch: Vec<(usize, usize)> = windows.iter().copied().filter(|&(s, e)| s != e).collect();
    let zb = zstore.get_substrings(&zdigest, &batch).unwrap();
    for (i, &(s, e)) in batch.iter().enumerate() {
        assert_eq!(zb[i], std::str::from_utf8(&ascii[s..e]).unwrap());
    }
}

#[test]
fn test_zstd_roundtrip_resident_and_stream() {
    use std::io::Read;
    let ascii = zstd_test_sequence();
    let len = ascii.len();
    let (_zdir, mut zstore, zdigest) =
        build_zstd_roundtrip_store(StorageMode::Zstd, "chrZ", &ascii);

    // Resident (Full) path: load the compressed frame into memory, then read.
    zstore.load_sequence(&zdigest).unwrap();
    let windows: Vec<(usize, usize)> = vec![(0, 12), (11, 5000), (len - 3, len), (0, len)];
    for &(s, e) in &windows {
        let got = zstore.get_substring(&zdigest, s, e).unwrap();
        assert_eq!(got, std::str::from_utf8(&ascii[s..e]).unwrap());
    }

    // Streaming from the resident record.
    for &(s, e) in &windows {
        let mut reader = zstore
            .stream_sequence(&zdigest, Some(s as u64), Some(e as u64))
            .unwrap();
        let mut out = Vec::new();
        reader.read_to_end(&mut out).unwrap();
        assert_eq!(&out[..], &ascii[s..e], "zstd stream mismatch at {}..{}", s, e);
    }
}

// =========================================================================
// Partial-read fd-cache eviction test
// =========================================================================

/// Tiny deterministic xorshift RNG so the test is reproducible without adding
/// a `rand` dependency.
struct XorShift(u64);
impl XorShift {
    fn new(seed: u64) -> Self {
        XorShift(seed | 1)
    }
    fn next_u64(&mut self) -> u64 {
        let mut x = self.0;
        x ^= x << 13;
        x ^= x >> 7;
        x ^= x << 17;
        self.0 = x;
        x
    }
    fn range(&mut self, n: usize) -> usize {
        (self.next_u64() % n as u64) as usize
    }
}

/// Build a FASTA with several distinct, multi-base sequences so byte windows
/// are non-trivial and span multiple packed bytes in Encoded mode.
fn multi_seq_fasta() -> String {
    let bases = [b'A', b'C', b'G', b'T'];
    let mut out = String::new();
    for (i, len) in [400usize, 333, 512, 271, 600].iter().enumerate() {
        out.push_str(&format!(">seq{}\n", i));
        let mut s = String::with_capacity(*len);
        // deterministic but distinct per-sequence content
        for j in 0..*len {
            s.push(bases[(i * 7 + j * 3 + (j / 5)) % 4] as char);
        }
        out.push_str(&s);
        out.push('\n');
    }
    out
}

/// With a TINY fd-cache cap (2) and reads interleaved across >2 sequences,
/// every partial-read result must be byte-identical to the resident decode
/// path. Interleaving across 5 sequences with cap 2 forces constant
/// eviction+reopen, exercising the LRU close/reopen logic. Run for both
/// Encoded and Raw storage modes.
fn run_fd_cache_eviction_for_mode(raw: bool) {
    let temp_dir = tempdir().unwrap();
    let fasta_content = multi_seq_fasta();
    let fasta = temp_dir.path().join("multi.fa");
    fs::write(&fasta, &fasta_content).unwrap();
    let store_path = temp_dir.path().join("store");

    // Build the store on disk.
    let mut builder = RefgetStore::on_disk(&store_path).unwrap();
    if raw {
        builder.disable_encoding();
    }
    let (coll_meta, _) = builder
        .add_sequence_collection_from_fasta(&fasta, FastaImportOptions::new())
        .unwrap();
    let coll_digest = coll_meta.digest.clone();
    drop(builder);

    // Reference: a resident store with everything loaded (whole-sequence decode).
    let mut resident = RefgetStore::open_local(&store_path).unwrap();
    resident.set_quiet(true);
    resident.load_all_collections().unwrap();
    resident.load_all_sequences().unwrap();

    // Subject: a stub-only store driving the partial-read path with cap=2.
    let mut partial = RefgetStore::open_local(&store_path).unwrap();
    partial.set_quiet(true);
    partial.load_all_collections().unwrap();
    partial.set_seq_fd_cache_cap_for_test(2);

    // Collect (digest, length) for each of the >2 sequences in the collection.
    let names: Vec<String> = (0..5).map(|i| format!("seq{}", i)).collect();
    let mut seqs: Vec<(String, usize)> = Vec::new();
    for name in &names {
        let rec = resident.get_sequence_by_name(&coll_digest, name).unwrap();
        seqs.push((rec.metadata().sha512t24u.clone(), rec.metadata().length));
    }
    assert!(seqs.len() > 2, "need >2 sequences to force eviction with cap 2");

    let mut rng = XorShift::new(0xC0FFEE_u64 ^ (raw as u64));
    for _ in 0..2000 {
        let (digest, len) = &seqs[rng.range(seqs.len())];
        let len = *len;
        let a = rng.range(len);
        let b = rng.range(len);
        let (start, end) = if a == b {
            (a.min(len - 1), a.min(len - 1) + 1)
        } else {
            (a.min(b), a.max(b))
        };
        let expected = resident.get_substring(digest, start, end).unwrap();
        let got = partial.get_substring(digest, start, end).unwrap();
        assert_eq!(
            got, expected,
            "partial-read mismatch (raw={}) digest={} [{}, {})",
            raw, digest, start, end
        );
    }
}

#[test]
fn test_stream_sequence_raw_mode() {
    use std::io::Read;
    let (_dir, store, digest, length) = build_on_disk_store_streaming(StorageMode::Raw);
    let mut reader = store.stream_sequence(&digest, Some(2), Some(8)).unwrap();
    let mut out = Vec::new();
    reader.read_to_end(&mut out).unwrap();
    assert_eq!(&out[..], b"GTACGT");
    assert!(length >= 8);
}

#[test]
fn test_stream_sequence_u64_bounds_compile_and_match() {
    // Compile-level guarantee: stream_sequence accepts u64 bounds.
    // Sequences > u32::MAX (>4 Gb) cannot be fixtured in unit tests, but
    // the arithmetic path (start_bit/end_bit/byte_start/byte_end/bases_to_emit)
    // is u64 throughout, so this test exercises the widened API surface.
    use std::io::Read;
    let (_dir, store, digest, _length) = build_on_disk_store_streaming(StorageMode::Encoded);
    let s: u64 = 0;
    let e: u64 = 8;
    let mut reader = store.stream_sequence(&digest, Some(s), Some(e)).unwrap();
    let mut out = Vec::new();
    reader.read_to_end(&mut out).unwrap();
    assert_eq!(out.len(), 8);
}

#[test]
fn test_stream_sequence_zero_length() {
    use std::io::Read;
    let (_dir, store, digest, _) = build_on_disk_store_streaming(StorageMode::Encoded);
    let mut reader = store.stream_sequence(&digest, Some(5), Some(5)).unwrap();
    let mut out = Vec::new();
    reader.read_to_end(&mut out).unwrap();
    assert!(out.is_empty());
}

#[test]
fn test_stream_sequence_invalid_range() {
    let (_dir, store, digest, length) = build_on_disk_store_streaming(StorageMode::Encoded);
    assert!(store.stream_sequence(&digest, Some(5), Some(3)).is_err());
    assert!(
        store
            .stream_sequence(&digest, Some(0), Some(length as u64 + 1))
            .is_err()
    );
}

#[test]
fn test_stream_sequence_bounded_memory() {
    use std::io::Read;
    let dir = tempdir().unwrap();
    let fasta = dir.path().join("big.fa");
    let mut content = String::from(">chr1\n");
    let bases = [b'A', b'C', b'G', b'T'];
    let mut seq = Vec::with_capacity(1_000_000);
    for i in 0..1_000_000 {
        seq.push(bases[i % 4]);
    }
    content.push_str(std::str::from_utf8(&seq).unwrap());
    content.push('\n');
    fs::write(&fasta, &content).unwrap();

    let store_path = dir.path().join("store");
    let mut store = RefgetStore::on_disk(&store_path).unwrap();
    store
        .add_sequence_collection_from_fasta(&fasta, FastaImportOptions::new())
        .unwrap();
    let digest = first_seq_digest(&store);

    let mut reader = store.stream_sequence(&digest, None, None).unwrap();
    let mut buf = [0u8; 4096];
    let mut collected = Vec::with_capacity(1_000_000);
    loop {
        let n = reader.read(&mut buf).unwrap();
        if n == 0 {
            break;
        }
        collected.extend_from_slice(&buf[..n]);
    }
    assert_eq!(collected, seq);
}

// =========================================================================
// Bounded-memory tests for stream_sequence
// =========================================================================
//
// These tests verify the O(1) memory claim of `stream_sequence`: regardless
// of sequence size, neither the Rust decoder nor the napi binding should
// materialize the full (sub)sequence in memory.

/// Install peak_alloc as the global allocator (tests-only) so we can measure
/// allocation deltas.
#[global_allocator]
static PEAK_ALLOC: peak_alloc::PeakAlloc = peak_alloc::PeakAlloc;

/// Serialize allocator-sensitive tests so concurrent tests don't pollute the
/// process-wide peak counter.
static ALLOC_TEST_LOCK: std::sync::Mutex<()> = std::sync::Mutex::new(());

// NOTE: `#[ignore]` because this measures the *process-global* `PEAK_ALLOC`
// high-water mark, which is polluted by any other test allocating concurrently.
// `ALLOC_TEST_LOCK` only serializes the two allocator tests against each other,
// not against the rest of the suite, so under default parallel `cargo test` the
// peak is unreliable. Run the allocation-profiling guards explicitly and serially:
//   cargo test -p gtars-refget -- --ignored --test-threads=1
#[test]
#[ignore = "allocation profiling: process-global PeakAlloc; run with --ignored --test-threads=1"]
fn test_stream_sequence_bounded_memory_full_record() {
    use std::io::Read;

    let _guard = ALLOC_TEST_LOCK.lock().unwrap_or_else(|p| p.into_inner());

    // Build a large FASTA (~1M bases) and import into an in-memory store in
    // Encoded mode. The in-memory store holds the encoded sequence as a
    // `SequenceRecord::Full { sequence: Vec<u8>, .. }` — for a 2-bit alphabet
    // that's ~250 KB encoded, decoding to ~1 MB raw bases.
    const SEQ_LEN: usize = 1_000_000;
    let dir = tempdir().unwrap();
    let fasta = dir.path().join("big.fa");
    let bases = [b'A', b'C', b'G', b'T'];
    let mut seq = Vec::with_capacity(SEQ_LEN);
    for i in 0..SEQ_LEN {
        seq.push(bases[i % 4]);
    }
    let mut content = String::from(">chr1\n");
    content.push_str(std::str::from_utf8(&seq).unwrap());
    content.push('\n');
    fs::write(&fasta, &content).unwrap();

    let mut store = RefgetStore::in_memory();
    // Use Raw mode so the Full record holds SEQ_LEN bytes verbatim. The old
    // buggy code path cloned that entire buffer during streaming; with the
    // Arc-backed reader it must not.
    store.set_encoding_mode(StorageMode::Raw);
    store
        .add_sequence_collection_from_fasta(&fasta, FastaImportOptions::new())
        .unwrap();
    let digest = first_seq_digest(&store);

    // Confirm the record is Full (in-memory resident).
    {
        use crate::hashkeyable::HashKeyable;
        let key = digest.to_key();
        let rec = store.sequence_store.get(&key).unwrap();
        assert!(rec.is_loaded(), "expected Full record for in-memory store");
    }

    // Measure peak allocation across stream_sequence + drain. The whole
    // buffer is already resident; streaming should not allocate another
    // copy of it.
    PEAK_ALLOC.reset_peak_usage();
    let baseline = PEAK_ALLOC.current_usage();

    {
        let mut reader = store.stream_sequence(&digest, None, None).unwrap();
        let mut chunk = [0u8; 4096];
        let mut total = 0usize;
        loop {
            let n = reader.read(&mut chunk).unwrap();
            if n == 0 {
                break;
            }
            total += n;
        }
        assert_eq!(total, SEQ_LEN);
    }

    let peak = PEAK_ALLOC.peak_usage();
    let peak_delta = peak.saturating_sub(baseline);

    // Streaming must not allocate anywhere near the sequence size. The
    // previous bug cloned the entire byte range (1 MB for this test); with
    // the fix, allocations are bounded by a few reader frames. The bound
    // below is loose enough to tolerate concurrent test allocator noise
    // but tight enough to catch a full-buffer clone (which would be
    // >= SEQ_LEN bytes).
    let bound: usize = SEQ_LEN / 4; // 250 KiB; a clone would cost >= 1 MiB.
    assert!(
        peak_delta < bound,
        "stream_sequence peak allocation delta {} bytes exceeds bound {} bytes \
         (SEQ_LEN={} bytes raw). \
         Streaming is cloning the buffer instead of sharing ownership.",
        peak_delta,
        bound,
        SEQ_LEN,
    );
}

// See `test_stream_sequence_bounded_memory_full_record` for why this is
// `#[ignore]`d (process-global PeakAlloc). Run via --ignored --test-threads=1.
#[test]
#[ignore = "allocation profiling: process-global PeakAlloc; run with --ignored --test-threads=1"]
fn test_stream_sequence_bounded_memory_stub_record() {
    // Regression guard for the production path: the Node proxy opens a store
    // via `open_local` / `open_remote`, so records are `Stub` (metadata only,
    // never loaded into memory) and `stream_sequence` must fall back to the
    // on-disk `.seq` file (or HTTP Range GET) without buffering the whole
    // file. This test directly measures peak allocation on that Stub-backed
    // path — analogous to `test_stream_sequence_bounded_memory_full_record`
    // but for the disk-streaming branch.
    use std::io::Read;
    use crate::hashkeyable::HashKeyable;

    let _guard = ALLOC_TEST_LOCK.lock().unwrap_or_else(|p| p.into_inner());

    // Measure peak at two very different sizes; the bound must not depend
    // on SEQ_LEN. (A full-file buffer would scale linearly; a fixed-size
    // BufReader would stay constant.) We drain into a fixed-size scratch
    // buffer — not `read_to_end` — because `read_to_end`'s geometric Vec
    // growth introduces transient realloc peaks of ~0.5 * SEQ_LEN that
    // swamp the actual streaming memory and falsely suggest scaling.
    for &SEQ_LEN in &[1_000_000usize, 16_000_000] {
    let dir = tempdir().unwrap();
    let fasta = dir.path().join("big.fa");
    let bases = [b'A', b'C', b'G', b'T'];
    let mut seq = Vec::with_capacity(SEQ_LEN);
    for i in 0..SEQ_LEN {
        seq.push(bases[i % 4]);
    }
    let mut content = String::from(">chr1\n");
    content.push_str(std::str::from_utf8(&seq).unwrap());
    content.push('\n');
    fs::write(&fasta, &content).unwrap();

    let store_path = dir.path().join("store");
    let digest;
    {
        let mut builder = RefgetStore::on_disk(&store_path).unwrap();
        builder.set_encoding_mode(StorageMode::Raw);
        builder
            .add_sequence_collection_from_fasta(&fasta, FastaImportOptions::new())
            .unwrap();
        digest = first_seq_digest(&builder);
        // Drop `builder` here — `add_sequence_collection_from_fasta` populates
        // an in-memory Full record; we want a fresh open so records are Stub.
    }

    // Reopen the store fresh — records should be Stub (metadata only).
    let store = RefgetStore::open_local(&store_path).unwrap();

    // Confirm the record is a Stub going in.
    {
        let key = digest.to_key();
        let rec = store.inner.sequence_store.get(&key).unwrap();
        assert!(
            !rec.is_loaded(),
            "expected Stub record after open_local, got Full"
        );
    }

    // Reset peak AFTER opening the store so we don't count store-open
    // allocations.
    PEAK_ALLOC.reset_peak_usage();
    let baseline = PEAK_ALLOC.current_usage();

    let mut reader = store.stream_sequence(&digest, None, None).unwrap();
    // Drain into a fixed-size buffer, checksumming as we go.
    // Avoids `read_to_end`'s geometric Vec growth, whose realloc
    // doubles transiently dominate peak (giving a false ~0.5N signal).
    let mut scratch = [0u8; 8192];
    let mut total = 0usize;
    let mut checksum: u64 = 0;
    loop {
        let n = reader.read(&mut scratch).unwrap();
        if n == 0 { break; }
        for &b in &scratch[..n] { checksum = checksum.wrapping_add(b as u64); }
        total += n;
    }

    let peak = PEAK_ALLOC.peak_usage();
    let peak_delta = peak.saturating_sub(baseline);

    assert_eq!(total, SEQ_LEN);
    let expected_checksum: u64 = seq.iter().map(|&b| b as u64).sum();
    assert_eq!(checksum, expected_checksum);

    // A full-file buffer in the Stub fallback would give peak_delta
    // proportional to SEQ_LEN. A BufReader-based stream is constant
    // (~8 KiB default). 64 KiB leaves headroom for allocator noise.
    assert!(
        peak_delta < 64 * 1024,
        "stream_sequence (Stub path) peak allocation {} bytes exceeds \
         64 KiB at SEQ_LEN={} — streaming is not O(1) in sequence size",
        peak_delta, SEQ_LEN,
    );
    }
}

#[test]
fn test_stream_sequence_no_preload_for_stub_record() {
    // Structural assertion for fix B: streaming must work when the record is
    // a Stub (not in memory), pulling bytes directly from the backing store,
    // without populating the in-memory cache. This lets the napi layer drop
    // its pre-`load_sequence` call.
    use std::io::Read;
    use crate::hashkeyable::HashKeyable;

    let (_dir, store, digest, length) = build_on_disk_store_streaming(StorageMode::Encoded);

    // Drop the in-memory sequence buffer back to Stub, preserving metadata.
    let mut store = store;
    {
        let key = digest.to_key();
        let rec = store.inner.sequence_store.get(&key).unwrap().clone();
        let meta = rec.metadata().clone();
        store
            .inner
            .sequence_store
            .insert(key, SequenceRecord::Stub(meta));
    }

    // Confirm the record is a Stub going in.
    {
        let key = digest.to_key();
        let rec = store.inner.sequence_store.get(&key).unwrap();
        assert!(!rec.is_loaded(), "expected Stub before stream_sequence");
    }

    // Stream without calling load_sequence() first.
    let mut reader = store.stream_sequence(&digest, None, None).unwrap();
    let mut out = Vec::new();
    reader.read_to_end(&mut out).unwrap();
    assert_eq!(out.len(), length);
    assert_eq!(&out[..], b"ACGTACGTACGTACGTACGT");

    // And the store should still be a Stub (no pre-loading side effect).
    let key = digest.to_key();
    let rec = store.inner.sequence_store.get(&key).unwrap();
    assert!(
        !rec.is_loaded(),
        "stream_sequence must not populate the in-memory Full record"
    );
}

// =========================================================================
// Lazy sequence index loading tests
// =========================================================================

#[test]
fn test_list_collections_without_sequence_index() {
    // Simulate a remote store where the sequence index is not yet loaded.
    // list_collections should work without triggering the sequence index download.
    let dir = tempdir().unwrap();
    let store_path = dir.path().join("store");

    // Create a store with a collection
    let fasta_content = ">chr1\nATGCATGC\n>chr2\nGGGGAAAA\n";
    let fasta_path = dir.path().join("test.fa");
    fs::write(&fasta_path, fasta_content).unwrap();

    let mut store = RefgetStore::on_disk(&store_path).unwrap();
    store.add_sequence_collection_from_fasta(&fasta_path, FastaImportOptions::new()).unwrap();

    // Re-open and clear the sequence store + mark index as not loaded
    // (simulating what open_remote now does)
    let mut store = RefgetStore::open_local(&store_path).unwrap();
    store.inner.sequence_store.clear();
    store.inner.md5_lookup.clear();
    store.inner.sequence_index_loaded = false;
    store.inner.sequence_index_path = Some("sequences.rgsi".to_string());

    // list_collections should work — it only touches collection metadata
    let result = store.list_collections(0, 100, &[]).unwrap();
    assert_eq!(result.results.len(), 1, "Should find 1 collection");
    assert!(!store.inner.sequence_index_loaded, "Sequence index should NOT be loaded after list_collections");
}

#[test]
fn test_load_all_sequences_triggers_index_load() {
    // When calling load_all_sequences on a store with deferred index,
    // it should lazily load the sequence index first.
    let dir = tempdir().unwrap();
    let store_path = dir.path().join("store");

    let fasta_content = ">chr1\nATGCATGC\n";
    let fasta_path = dir.path().join("test.fa");
    fs::write(&fasta_path, fasta_content).unwrap();

    let mut store = RefgetStore::on_disk(&store_path).unwrap();
    store.add_sequence_collection_from_fasta(&fasta_path, FastaImportOptions::new()).unwrap();

    // Simulate deferred state
    let mut store = RefgetStore::open_local(&store_path).unwrap();
    store.inner.sequence_store.clear();
    store.inner.md5_lookup.clear();
    store.inner.sequence_index_loaded = false;
    store.inner.sequence_index_path = Some("sequences.rgsi".to_string());

    assert!(!store.inner.sequence_index_loaded);

    // load_all_sequences should trigger the index load
    store.load_all_sequences().unwrap();
    assert!(store.inner.sequence_index_loaded, "Sequence index should be loaded after load_all_sequences");
    assert!(!store.inner.sequence_store.is_empty(), "Sequences should be populated");
}

#[test]
fn test_lazy_sequence_reads_load_only_requested_records() {
    let dir = tempdir().unwrap();
    let store_path = dir.path().join("store");
    let fasta_path = dir.path().join("test.fa");
    fs::write(&fasta_path, ">chr1\nATGCATGC\n>chr2\nGGGGAAAA\n").unwrap();

    let mut writer = RefgetStore::on_disk(&store_path).unwrap();
    let (collection, _) = writer
        .add_sequence_collection_from_fasta(&fasta_path, FastaImportOptions::new())
        .unwrap();
    let first = writer
        .get_sequence_by_name(&collection.digest, "chr1")
        .unwrap()
        .metadata()
        .clone();
    let second = writer
        .get_sequence_by_name(&collection.digest, "chr2")
        .unwrap()
        .metadata()
        .clone();
    drop(writer);

    // Recreate the deferred remote-index state against a local fixture.
    let mut store = RefgetStore::open_local(&store_path).unwrap();
    store.inner.sequence_store.clear();
    store.inner.md5_lookup.clear();
    store.inner.sequence_index_loaded = false;
    store.inner.sequence_index_path = Some("sequences.rgsi".to_string());

    // By-name retrieval works before the index arrives: it loads the
    // collection (registering stubs) and then only chr1's body.
    let by_name = store
        .get_sequence_by_name(&collection.digest, "chr1")
        .unwrap();
    assert_eq!(by_name.metadata().name, "chr1");
    assert!(by_name.is_loaded());
    assert!(!store.inner.sequence_index_loaded);
    assert!(store.inner.is_sequence_loaded(&first.sha512t24u));
    assert!(!store.inner.is_sequence_loaded(&second.sha512t24u));

    // Listing loads the index; regression: that must not demote chr1,
    // which was fetched into memory before the index was loaded.
    let listed = store.list_sequences().unwrap();
    assert_eq!(listed.len(), 2);
    assert!(store.inner.sequence_index_loaded);
    assert!(store.inner.is_sequence_loaded(&first.sha512t24u));
    assert!(!store.inner.is_sequence_loaded(&second.sha512t24u));

    let by_md5 = store.get_sequence(&second.md5).unwrap();
    assert!(by_md5.is_loaded());
    assert_eq!(by_md5.metadata().name, "chr2");
    assert!(store.inner.is_sequence_loaded(&second.sha512t24u));
}

#[test]
fn test_export_fasta_lazy_loads_only_requested_sequence() {
    // Same deferred-remote-index simulation as
    // test_lazy_sequence_reads_load_only_requested_records, but exercising
    // the mutable export_fasta wrapper directly from the deferred state
    // (before anything else has touched the collection or its sequences).
    let dir = tempdir().unwrap();
    let store_path = dir.path().join("store");
    let fasta_path = dir.path().join("test.fa");
    fs::write(&fasta_path, ">chr1\nATGCATGC\n>chr2\nGGGGAAAA\n").unwrap();

    let mut writer = RefgetStore::on_disk(&store_path).unwrap();
    let (collection, _) = writer
        .add_sequence_collection_from_fasta(&fasta_path, FastaImportOptions::new())
        .unwrap();
    let first = writer
        .get_sequence_by_name(&collection.digest, "chr1")
        .unwrap()
        .metadata()
        .clone();
    let second = writer
        .get_sequence_by_name(&collection.digest, "chr2")
        .unwrap()
        .metadata()
        .clone();
    drop(writer);

    // Recreate the deferred remote-index state against a local fixture.
    let mut store = RefgetStore::open_local(&store_path).unwrap();
    store.inner.sequence_store.clear();
    store.inner.md5_lookup.clear();
    store.inner.sequence_index_loaded = false;
    store.inner.sequence_index_path = Some("sequences.rgsi".to_string());

    assert!(!store.inner.is_sequence_loaded(&first.sha512t24u));
    assert!(!store.inner.is_sequence_loaded(&second.sha512t24u));

    let output_path = dir.path().join("export_chr1.fa");
    store
        .export_fasta(&collection.digest, &output_path, Some(vec!["chr1"]), None)
        .expect("export_fasta should lazily load only the requested sequence");

    let exported = fs::read_to_string(&output_path).unwrap();
    assert!(exported.contains(">chr1"));
    assert!(exported.contains("ATGCATGC"));
    assert!(!exported.contains(">chr2"));

    assert!(
        store.inner.is_sequence_loaded(&first.sha512t24u),
        "chr1 should be loaded after exporting it"
    );
    assert!(
        !store.inner.is_sequence_loaded(&second.sha512t24u),
        "chr2 should remain unloaded: it was not requested"
    );
}

#[test]
fn test_export_fasta_lazy_loads_duplicate_named_sequences() {
    // Two records share a name; export must load whichever one it writes.
    let dir = tempdir().unwrap();
    let store_path = dir.path().join("store");
    let fasta_path = dir.path().join("dup.fa");
    fs::write(&fasta_path, ">dup\nAAAA\n>dup\nCCCC\n").unwrap();

    let mut writer = RefgetStore::on_disk(&store_path).unwrap();
    let (collection, _) = writer
        .add_sequence_collection_from_fasta(&fasta_path, FastaImportOptions::new())
        .unwrap();
    drop(writer);

    let mut store = RefgetStore::open_local(&store_path).unwrap();
    let output_path = dir.path().join("dup_out.fa");
    store
        .export_fasta(&collection.digest, &output_path, Some(vec!["dup"]), None)
        .expect("export should load the sequence it writes");
    assert!(fs::read_to_string(&output_path).unwrap().starts_with(">dup\n"));
}

#[test]
fn test_open_remote_uses_cached_manifest_when_offline() {
    // Port 1 refuses connections, so the manifest refresh always fails.
    let remote_url = "http://127.0.0.1:1/store";
    let dir = tempdir().unwrap();
    let cache_path = dir.path().join("cache");
    let fasta_path = dir.path().join("test.fa");
    fs::write(&fasta_path, ">chr1\nATGCATGC\n").unwrap();

    // With nothing cached, an unreachable remote is still an error.
    assert!(RefgetStore::open_remote(dir.path().join("empty"), remote_url).is_err());

    // Simulate a cache left by an earlier online open of this remote.
    let mut writer = RefgetStore::on_disk(&cache_path).unwrap();
    let (collection, _) = writer
        .add_sequence_collection_from_fasta(&fasta_path, FastaImportOptions::new())
        .unwrap();
    drop(writer);
    fs::write(cache_path.join(".origin"), format!("{}\n", remote_url)).unwrap();

    let mut store = RefgetStore::open_remote(&cache_path, remote_url)
        .expect("a cached remote store should open offline");
    let seq = store
        .get_sequence_by_name(&collection.digest, "chr1")
        .unwrap();
    assert!(seq.is_loaded());
}

#[test]
fn test_fd_cache_eviction_matches_resident_encoded() {
    run_fd_cache_eviction_for_mode(false);
}

#[test]
fn test_fd_cache_eviction_matches_resident_raw() {
    run_fd_cache_eviction_for_mode(true);
}

/// `get_substrings` must produce output byte-identical to (a) a loop of
/// `get_substring` on the same disk-backed store and (b) the resident decode,
/// for BOTH branches of the adaptive heuristic:
///   - sparse small ranges (total coverage < WHOLE_DECODE_FRACTION) -> partial branch
///   - wide/overlapping ranges (total coverage >= WHOLE_DECODE_FRACTION) -> whole-decode branch
/// Run for both Encoded and Raw storage modes.
fn run_get_substrings_matches_for_mode(raw: bool) {
    let temp_dir = tempdir().unwrap();
    let fasta_content = multi_seq_fasta();
    let fasta = temp_dir.path().join("multi.fa");
    fs::write(&fasta, &fasta_content).unwrap();
    let store_path = temp_dir.path().join("store");

    let mut builder = RefgetStore::on_disk(&store_path).unwrap();
    if raw {
        builder.disable_encoding();
    }
    let (coll_meta, _) = builder
        .add_sequence_collection_from_fasta(&fasta, FastaImportOptions::new())
        .unwrap();
    let coll_digest = coll_meta.digest.clone();
    drop(builder);

    // Reference: resident store (whole-sequence decode held in memory).
    let mut resident = RefgetStore::open_local(&store_path).unwrap();
    resident.set_quiet(true);
    resident.load_all_collections().unwrap();
    resident.load_all_sequences().unwrap();

    // Subject: stub-only disk-backed store.
    let mut disk = RefgetStore::open_local(&store_path).unwrap();
    disk.set_quiet(true);
    disk.load_all_collections().unwrap();

    // Use seq0 (length 400) for the per-sequence range sets.
    let rec = resident.get_sequence_by_name(&coll_digest, "seq0").unwrap();
    let digest = rec.metadata().sha512t24u.clone();
    let len = rec.metadata().length;
    assert_eq!(len, 400);

    // BRANCH A (partial): many sparse small ranges; total coverage tiny relative
    // to len (well below the 0.125 threshold).
    let sparse: Vec<(usize, usize)> = vec![
        (0, 3),
        (10, 14),
        (50, 51),
        (100, 105),
        (200, 202),
        (399, 400),
    ];
    let sparse_total: usize = sparse.iter().map(|&(s, e)| e - s).sum();
    assert!((sparse_total as f64) < 0.125 * (len as f64), "branch A must be partial");

    // BRANCH B (whole-decode): wide and overlapping ranges whose total coverage
    // far exceeds the threshold.
    let wide: Vec<(usize, usize)> = vec![
        (0, 200),
        (100, 350),
        (50, 400),
        (10, 390),
    ];
    let wide_total: usize = wide.iter().map(|&(s, e)| e - s).sum();
    assert!((wide_total as f64) >= 0.125 * (len as f64), "branch B must be whole-decode");

    for ranges in [&sparse, &wide] {
        // Expected from resident decode.
        let expected_resident: Vec<String> = ranges
            .iter()
            .map(|&(s, e)| resident.get_substring(&digest, s, e).unwrap())
            .collect();
        // Loop of disk get_substring.
        let expected_disk_loop: Vec<String> = ranges
            .iter()
            .map(|&(s, e)| disk.get_substring(&digest, s, e).unwrap())
            .collect();
        // Batch.
        let batch = disk.get_substrings(&digest, ranges).unwrap();

        assert_eq!(
            batch, expected_resident,
            "batch != resident (raw={}) ranges={:?}",
            raw, ranges
        );
        assert_eq!(
            batch, expected_disk_loop,
            "batch != disk loop (raw={}) ranges={:?}",
            raw, ranges
        );
    }

    // Resident store batch path (Full arm) must also match.
    let batch_resident = resident.get_substrings(&digest, &wide).unwrap();
    let expected: Vec<String> = wide
        .iter()
        .map(|&(s, e)| resident.get_substring(&digest, s, e).unwrap())
        .collect();
    assert_eq!(batch_resident, expected, "resident Full-arm batch mismatch (raw={})", raw);

    // Invalid range must error.
    assert!(disk.get_substrings(&digest, &[(0, len + 1)]).is_err());
}

#[test]
fn test_get_substrings_matches_encoded() {
    run_get_substrings_matches_for_mode(false);
}

#[test]
fn test_get_substrings_matches_raw() {
    run_get_substrings_matches_for_mode(true);
}

// =========================================================================
// Import-time collection alias tests
// =========================================================================

/// REQUIRED REGRESSION GUARD: omitting `.collection_alias(..)` must change
/// nothing. An import with plain options registers no collection alias at all.
#[test]
fn test_import_without_collection_alias_registers_none() {
    let dir = tempdir().unwrap();
    let fasta = copy_test_fasta(dir.path(), "base.fa");

    let mut store = RefgetStore::in_memory();
    let (meta, _) = store
        .add_sequence_collection_from_fasta(&fasta, FastaImportOptions::new())
        .unwrap();

    assert!(
        store.list_collection_alias_namespaces().is_empty(),
        "plain import must not create any collection alias namespace"
    );
    assert!(
        store.get_aliases_for_collection(&meta.digest).is_empty(),
        "plain import must not name the collection"
    );
}

/// `namespaces` feeds the SEQUENCE index only; it must never name the
/// collection. Proves the two alias indexes stay decoupled.
#[test]
fn test_import_without_collection_alias_but_with_namespaces() {
    let dir = tempdir().unwrap();
    let fasta = dir.path().join("ns.fa");
    fs::write(&fasta, ">chr1 ucsc:chr1\nAAAACCCC\n>chr2 ucsc:chr2\nGGGGTTTT\n").unwrap();

    let mut store = RefgetStore::in_memory();
    let (meta, _) = store
        .add_sequence_collection_from_fasta(&fasta, FastaImportOptions::new().namespaces(&["ucsc"]))
        .unwrap();

    let seq_aliases = store
        .list_sequence_aliases("ucsc")
        .expect("ucsc sequence alias namespace should exist");
    assert!(!seq_aliases.is_empty(), "header aliases should be registered");

    assert!(
        store.list_collection_alias_namespaces().is_empty(),
        "namespaces must not leak into the collection alias index"
    );
    assert!(store.get_aliases_for_collection(&meta.digest).is_empty());
}

#[test]
fn test_import_with_collection_alias_registers_collection_alias() {
    let dir = tempdir().unwrap();
    let fasta = copy_test_fasta(dir.path(), "base.fa");

    let mut store = RefgetStore::in_memory();
    let (meta, _) = store
        .add_sequence_collection_from_fasta(
            &fasta,
            FastaImportOptions::new().collection_alias("ucsc", "hg38"),
        )
        .unwrap();

    let resolved = store
        .get_collection_metadata_by_alias("ucsc", "hg38")
        .expect("ucsc:hg38 should resolve");
    assert_eq!(resolved.digest, meta.digest);

    assert!(
        store.list_sequence_alias_namespaces().is_empty(),
        "collection alias must not leak into the sequence alias index"
    );
}

/// The collection alias works with `namespaces` unset (decision 1: the option is
/// explicit, not derived from the namespaces list).
#[test]
fn test_collection_alias_without_namespaces() {
    let dir = tempdir().unwrap();
    let fasta = dir.path().join("bare.fa");
    // Bare headers: no `ns:value` tokens anywhere in the file.
    fs::write(&fasta, ">chr1\nAAAACCCC\n>chr2\nGGGGTTTT\n").unwrap();

    let mut store = RefgetStore::in_memory();
    let opts = FastaImportOptions::new().collection_alias("ucsc", "hg38");
    assert!(opts.namespaces.is_empty(), "namespaces deliberately unset");
    let (meta, _) = store
        .add_sequence_collection_from_fasta(&fasta, opts)
        .unwrap();

    let resolved = store
        .get_collection_metadata_by_alias("ucsc", "hg38")
        .expect("ucsc:hg38 should resolve without namespaces set");
    assert_eq!(resolved.digest, meta.digest);
}

#[test]
fn test_collection_alias_persists_to_disk() {
    let dir = tempdir().unwrap();
    let store_path = dir.path().join("store");
    let fasta = copy_test_fasta(dir.path(), "base.fa");

    let mut store = RefgetStore::on_disk(&store_path).unwrap();
    let (meta, _) = store
        .add_sequence_collection_from_fasta(
            &fasta,
            FastaImportOptions::new().collection_alias("ucsc", "hg38"),
        )
        .unwrap();
    store.write().unwrap();

    let tsv = store_path.join("aliases").join("collections").join("ucsc.tsv");
    assert!(tsv.exists(), "collection alias TSV should be written");
    let contents = fs::read_to_string(&tsv).unwrap();
    assert!(
        contents.contains(&format!("hg38\t{}", meta.digest)),
        "TSV should map hg38 to the collection digest, got: {}",
        contents
    );

    // `store_metadata()` only surfaces the state digests, so read rgstore.json
    // directly for the advertised namespace list.
    let manifest_json: serde_json::Value =
        serde_json::from_str(&fs::read_to_string(store_path.join("rgstore.json")).unwrap()).unwrap();
    let coll_ns = manifest_json
        .get("collection_alias_namespaces")
        .and_then(|v| v.as_array())
        .expect("rgstore.json should carry collection_alias_namespaces");
    assert!(
        coll_ns.iter().any(|v| v.as_str() == Some("ucsc")),
        "rgstore.json should advertise the ucsc collection alias namespace, got {:?}",
        coll_ns
    );
    assert!(
        manifest_json
            .get("sequence_alias_namespaces")
            .and_then(|v| v.as_array())
            .map(|a| a.is_empty())
            .unwrap_or(true),
        "no sequence alias namespaces should be advertised"
    );

    let manifest = store.store_metadata().unwrap();
    assert!(
        manifest.get("aliases_digest").is_some(),
        "rgstore.json should carry an aliases_digest"
    );

    // Round-trip through a fresh open.
    let reopened = RefgetStore::open_local(&store_path).unwrap();
    let resolved = reopened
        .get_collection_metadata_by_alias("ucsc", "hg38")
        .expect("alias should survive a reopen");
    assert_eq!(resolved.digest, meta.digest);
}

/// Re-importing the same FASTA with the same alias is a no-op, on both the
/// in-run duplicate path and the build-side `Skip` path (fresh store from disk).
#[test]
fn test_collection_alias_idempotent_on_reimport() {
    let dir = tempdir().unwrap();
    let store_path = dir.path().join("store");
    let fasta = copy_test_fasta(dir.path(), "base.fa");

    let mut store = RefgetStore::on_disk(&store_path).unwrap();
    let (meta1, was_new1) = store
        .add_sequence_collection_from_fasta(
            &fasta,
            FastaImportOptions::new().collection_alias("ucsc", "hg38"),
        )
        .unwrap();
    assert!(was_new1);

    // In-run duplicate path: same store, same file again.
    let (meta2, was_new2) = store
        .add_sequence_collection_from_fasta(
            &fasta,
            FastaImportOptions::new().collection_alias("ucsc", "hg38"),
        )
        .unwrap();
    assert!(!was_new2, "second import of the same FASTA is not new");
    assert_eq!(meta2.digest, meta1.digest);
    assert_eq!(
        store
            .get_collection_metadata_by_alias("ucsc", "hg38")
            .unwrap()
            .digest,
        meta1.digest
    );
    store.write().unwrap();

    // Build-side Skip path: reopen from disk so the collection is in
    // `present_collections` before any decode happens.
    let mut reopened = RefgetStore::open_local(&store_path).unwrap();
    let (meta3, was_new3) = reopened
        .add_sequence_collection_from_fasta(
            &fasta,
            FastaImportOptions::new().collection_alias("ucsc", "hg38"),
        )
        .unwrap();
    assert!(!was_new3, "already-present collection should be skipped");
    assert_eq!(meta3.digest, meta1.digest);
    assert_eq!(
        reopened
            .get_collection_metadata_by_alias("ucsc", "hg38")
            .unwrap()
            .digest,
        meta1.digest
    );
}

/// A previously-imported collection that was NOT named still gets its name on a
/// later re-import via the build-side Skip path. This is the silent-drop bug.
#[test]
fn test_collection_alias_registered_on_build_side_skip() {
    let dir = tempdir().unwrap();
    let store_path = dir.path().join("store");
    let fasta = copy_test_fasta(dir.path(), "base.fa");

    let mut store = RefgetStore::on_disk(&store_path).unwrap();
    let (meta, _) = store
        .add_sequence_collection_from_fasta(&fasta, FastaImportOptions::new())
        .unwrap();
    store.write().unwrap();
    assert!(store.list_collection_alias_namespaces().is_empty());

    // Reopen: the collection is already present, so the builder emits Skip and
    // finalize_collection is never reached. The alias must still land.
    let mut reopened = RefgetStore::open_local(&store_path).unwrap();
    let (_, was_new) = reopened
        .add_sequence_collection_from_fasta(
            &fasta,
            FastaImportOptions::new().collection_alias("ucsc", "hg38"),
        )
        .unwrap();
    assert!(!was_new, "collection was already present");
    assert_eq!(
        reopened
            .get_collection_metadata_by_alias("ucsc", "hg38")
            .expect("alias must be registered even on the skip path")
            .digest,
        meta.digest
    );
}

#[test]
fn test_collection_alias_conflict_errors() {
    let dir = tempdir().unwrap();
    let fasta_a = dir.path().join("a.fa");
    fs::write(&fasta_a, ">chr1\nAAAACCCC\n").unwrap();
    let fasta_b = dir.path().join("b.fa");
    fs::write(&fasta_b, ">chr1\nGGGGTTTT\n").unwrap();

    let mut store = RefgetStore::in_memory();
    let (meta_a, _) = store
        .add_sequence_collection_from_fasta(
            &fasta_a,
            FastaImportOptions::new().collection_alias("ucsc", "hg38"),
        )
        .unwrap();

    let err = store
        .add_sequence_collection_from_fasta(
            &fasta_b,
            FastaImportOptions::new().collection_alias("ucsc", "hg38"),
        )
        .expect_err("conflicting alias must error");
    let msg = format!("{}", err);
    assert!(msg.contains("ucsc"), "error should name the namespace: {}", msg);
    assert!(msg.contains("hg38"), "error should name the alias: {}", msg);

    // The failed import must not have remapped the alias.
    assert_eq!(
        store
            .get_collection_metadata_by_alias("ucsc", "hg38")
            .unwrap()
            .digest,
        meta_a.digest
    );
}

/// A failed conflicting-alias import must not leave the collection behind.
///
/// The alias conflict is validated up front, before any part of the import is
/// committed, so a rejected import is a true no-op: the store must hold exactly
/// the one collection that succeeded. Previously the collection was inserted
/// first and the alias checked afterwards, so a "failed" import still added a
/// second collection to `store.collections`.
#[test]
fn test_collection_alias_conflict_does_not_leak_collection() {
    let dir = tempdir().unwrap();
    let fasta_a = dir.path().join("a.fa");
    fs::write(&fasta_a, ">chr1\nAAAACCCC\n").unwrap();
    let fasta_b = dir.path().join("b.fa");
    fs::write(&fasta_b, ">chr1\nGGGGTTTT\n").unwrap();

    let mut store = RefgetStore::in_memory();
    let (meta_a, _) = store
        .add_sequence_collection_from_fasta(
            &fasta_a,
            FastaImportOptions::new().collection_alias("ucsc", "hg38"),
        )
        .unwrap();
    assert_eq!(store.collections.len(), 1);

    store
        .add_sequence_collection_from_fasta(
            &fasta_b,
            FastaImportOptions::new().collection_alias("ucsc", "hg38"),
        )
        .expect_err("conflicting alias must error");

    // The rejected import must not have been committed.
    assert_eq!(
        store.collections.len(),
        1,
        "a failed import must not leave its collection in the store"
    );
    assert!(
        store.collections.contains_key(&meta_a.digest.to_key()),
        "the surviving collection should be the one that imported successfully"
    );
    assert!(
        store.name_lookup.len() <= 1,
        "no name_lookup entry should be installed for the rejected collection"
    );
}

/// Disk-backed counterpart: a rejected conflicting-alias import must not leave
/// an orphaned `collections/<digest>.rgsi` that the top-level index never
/// references. The per-collection `.rgsi` is written immediately, but
/// `collections.rgci` is only written at the end of a successful import, so
/// erroring after the collection write used to strand a file on disk.
#[test]
fn test_collection_alias_conflict_leaves_no_orphan_on_disk() {
    let dir = tempdir().unwrap();
    let store_path = dir.path().join("store");
    let fasta_a = dir.path().join("a.fa");
    fs::write(&fasta_a, ">chr1\nAAAACCCC\n").unwrap();
    let fasta_b = dir.path().join("b.fa");
    fs::write(&fasta_b, ">chr1\nGGGGTTTT\n").unwrap();

    let mut store = RefgetStore::on_disk(&store_path).unwrap();
    let (meta_a, _) = store
        .add_sequence_collection_from_fasta(
            &fasta_a,
            FastaImportOptions::new().collection_alias("ucsc", "hg38"),
        )
        .unwrap();
    store.write().unwrap();

    store
        .add_sequence_collection_from_fasta(
            &fasta_b,
            FastaImportOptions::new().collection_alias("ucsc", "hg38"),
        )
        .expect_err("conflicting alias must error");

    // Exactly one per-collection index file, and it belongs to the collection
    // that actually imported.
    let coll_dir = store_path.join("collections");
    let mut rgsi: Vec<String> = fs::read_dir(&coll_dir)
        .unwrap()
        .map(|e| e.unwrap().file_name().to_string_lossy().into_owned())
        .filter(|n| n.ends_with(".rgsi"))
        .collect();
    rgsi.sort();
    assert_eq!(
        rgsi,
        vec![format!("{}.rgsi", meta_a.digest)],
        "failed import must not leave an orphaned collection .rgsi on disk"
    );

    assert_eq!(store.collections.len(), 1);

    // The store on disk is still coherent: reopening sees exactly the one
    // collection, still reachable through the alias.
    let mut reopened = RefgetStore::open_local(&store_path).unwrap();
    assert_eq!(reopened.collections.len(), 1);
    assert_eq!(
        reopened
            .get_collection_metadata_by_alias("ucsc", "hg38")
            .expect("alias should still resolve after the failed import")
            .digest,
        meta_a.digest
    );
    // And the surviving collection is fully readable, not a dangling index row.
    reopened
        .get_collection(&meta_a.digest)
        .expect("the committed collection must still load");
}

#[test]
fn test_collection_alias_conflict_force_overwrites() {
    let dir = tempdir().unwrap();
    let fasta_a = dir.path().join("a.fa");
    fs::write(&fasta_a, ">chr1\nAAAACCCC\n").unwrap();
    let fasta_b = dir.path().join("b.fa");
    fs::write(&fasta_b, ">chr1\nGGGGTTTT\n").unwrap();

    let mut store = RefgetStore::in_memory();
    store
        .add_sequence_collection_from_fasta(
            &fasta_a,
            FastaImportOptions::new().collection_alias("ucsc", "hg38"),
        )
        .unwrap();

    let (meta_b, _) = store
        .add_sequence_collection_from_fasta(
            &fasta_b,
            FastaImportOptions::new()
                .collection_alias("ucsc", "hg38")
                .force(true),
        )
        .unwrap();

    assert_eq!(
        store
            .get_collection_metadata_by_alias("ucsc", "hg38")
            .unwrap()
            .digest,
        meta_b.digest,
        "force should remap the alias to the new collection"
    );
}

/// Disk-backed counterpart of the force test. The on-disk conflict check in
/// `commit_alias_namespace` used to consult only the handle-wide `force_alias`
/// flag, so `.force(true)` remapped the alias in memory and then errored at
/// commit against the TSV already on disk.
#[test]
fn test_collection_alias_conflict_force_overwrites_on_disk() {
    let dir = tempdir().unwrap();
    let store_path = dir.path().join("store");
    let fasta_a = dir.path().join("a.fa");
    fs::write(&fasta_a, ">chr1\nAAAACCCC\n").unwrap();
    let fasta_b = dir.path().join("b.fa");
    fs::write(&fasta_b, ">chr1\nGGGGTTTT\n").unwrap();

    let mut store = RefgetStore::on_disk(&store_path).unwrap();
    store
        .add_sequence_collection_from_fasta(
            &fasta_a,
            FastaImportOptions::new().collection_alias("ucsc", "hg38"),
        )
        .unwrap();
    store.write().unwrap();

    let mut reopened = RefgetStore::open_local(&store_path).unwrap();
    let (meta_b, _) = reopened
        .add_sequence_collection_from_fasta(
            &fasta_b,
            FastaImportOptions::new()
                .collection_alias("ucsc", "hg38")
                .force(true),
        )
        .expect("force must override the alias published on disk");

    let fresh = RefgetStore::open_local(&store_path).unwrap();
    assert_eq!(
        fresh
            .get_collection_metadata_by_alias("ucsc", "hg38")
            .unwrap()
            .digest,
        meta_b.digest,
        "the remapped alias must be what is on disk"
    );
}

/// Cleanup after a failed import must only touch what that import staged.
/// It used to compute orphans as "in `sequence_store` but not in
/// `name_lookup`", which on a reopened store (stub collections, empty
/// `name_lookup`) is every pre-existing sequence -- and unlinked them all.
#[test]
fn test_failed_import_cleanup_preserves_existing_sequences() {
    let dir = tempdir().unwrap();
    let store_path = dir.path().join("store");
    let fasta_a = dir.path().join("a.fa");
    fs::write(&fasta_a, ">chr1\nAAAACCCC\n>chr2\nGGGGTTTT\n").unwrap();

    let mut store = RefgetStore::on_disk(&store_path).unwrap();
    let (meta_a, _) = store
        .add_sequence_collection_from_fasta(&fasta_a, FastaImportOptions::new())
        .unwrap();
    store.write().unwrap();
    drop(store);

    // A reopened handle: sequences are loaded as stubs, name_lookup is empty.
    let mut reopened = RefgetStore::open_local(&store_path).unwrap();
    assert!(reopened.name_lookup.is_empty());

    // Force a failure: a conflicting collection alias is rejected after the
    // import has already staged the new collection's sequences.
    reopened
        .add_collection_alias("ucsc", "hg38", &meta_a.digest)
        .unwrap();
    let fasta_b = dir.path().join("b.fa");
    fs::write(&fasta_b, ">chrX\nCCCCAAAA\n").unwrap();
    reopened
        .add_sequence_collection_from_fasta(
            &fasta_b,
            FastaImportOptions::new().collection_alias("ucsc", "hg38"),
        )
        .expect_err("conflicting alias must error");

    // Every pre-existing sequence is still readable from disk.
    let mut fresh = RefgetStore::open_local(&store_path).unwrap();
    let coll = fresh.get_collection(&meta_a.digest).unwrap();
    for rec in &coll.sequences {
        let digest = rec.metadata().sha512t24u.clone();
        fresh
            .get_substring(digest.as_str(), 0, rec.metadata().length as usize)
            .unwrap_or_else(|e| {
                panic!("sequence {} vanished after a failed import: {}", digest, e)
            });
    }
}

#[test]
fn test_collection_alias_rejected_for_multiple_files() {
    let dir = tempdir().unwrap();
    let fasta_a = dir.path().join("a.fa");
    fs::write(&fasta_a, ">chr1\nAAAACCCC\n").unwrap();
    let fasta_b = dir.path().join("b.fa");
    fs::write(&fasta_b, ">chr1\nGGGGTTTT\n").unwrap();

    let mut store = RefgetStore::in_memory();
    let err = store
        .add_sequence_collections_from_fastas(
            &[fasta_a, fasta_b],
            FastaImportOptions::new().collection_alias("ucsc", "hg38"),
        )
        .expect_err("collection_alias with multiple files must error");
    let msg = format!("{}", err);
    assert!(
        msg.contains("add_collection_alias"),
        "error should teach the per-file workaround: {}",
        msg
    );

    // The guard runs before any thread spawns, so the store must be untouched.
    assert!(store.sequence_store.is_empty(), "no sequences imported");
    assert!(store.collections.is_empty(), "no collections imported");
    assert!(store.list_collection_alias_namespaces().is_empty());
    assert!(store.list_sequence_alias_namespaces().is_empty());
}

/// The multi-file guard must be a `> 1` check, not a `!= 1` check -- the
/// single-file wrapper goes through this same entry point with a 1-element slice.
#[test]
fn test_collection_alias_single_element_slice_ok() {
    let dir = tempdir().unwrap();
    let fasta = dir.path().join("one.fa");
    fs::write(&fasta, ">chr1\nAAAACCCC\n").unwrap();

    let mut store = RefgetStore::in_memory();
    let report = store
        .add_sequence_collections_from_fastas(
            &[fasta],
            FastaImportOptions::new().collection_alias("ucsc", "hg38"),
        )
        .expect("one-element slice with an alias must succeed");
    assert_eq!(report.collections.len(), 1);
    assert_eq!(
        store
            .get_collection_metadata_by_alias("ucsc", "hg38")
            .unwrap()
            .digest,
        report.collections[0].0.digest
    );
}

// =========================================================================
// Concurrent-writer safety
//
// These are the regression tests for the 2026-07-23 incident, where four
// concurrent `genome_init` jobs wrote one store directory and one genome's
// collection was written to disk but dropped from both indexes -- its alias
// stopped resolving and the nightly build failed. Neither writer errored.
// =========================================================================

/// Build a one-collection store at `path` from an inline FASTA.
fn add_collection_to_store(store: &mut RefgetStore, dir: &std::path::Path, name: &str, fasta: &str) -> String {
    let fasta_path = dir.join(format!("{}.fa", name));
    fs::write(&fasta_path, fasta).unwrap();
    let (meta, _) = store
        .add_sequence_collection_from_fasta(&fasta_path, FastaImportOptions::new())
        .unwrap();
    meta.digest
}

/// THE incident, reproduced: two handles open the same store, each adds a
/// different collection, and they commit in an interleaved order. Before the
/// merge, whoever committed last rewrote the index from its own open-time
/// snapshot and the other's collection vanished.
#[test]
fn test_interleaved_writers_both_survive() {
    let work = tempdir().unwrap();
    let store_dir = work.path().join("store");

    // Seed the store so both writers have something to load at open time.
    let mut seed = RefgetStore::on_disk(&store_dir).unwrap();
    let seed_digest = add_collection_to_store(&mut seed, work.path(), "seed", ">chrS\nAAAACCCC\n");
    seed.write().unwrap();
    drop(seed);

    // Both writers snapshot the store at the same moment.
    let mut writer_a = RefgetStore::open_local(&store_dir).unwrap();
    let mut writer_b = RefgetStore::open_local(&store_dir).unwrap();

    // A stages its collection first...
    let digest_a = add_collection_to_store(&mut writer_a, work.path(), "a", ">chrA\nGGGGTTTT\n");
    // ...B stages and commits while A is still holding a stale snapshot...
    let digest_b = add_collection_to_store(&mut writer_b, work.path(), "b", ">chrB\nTTTTGGGG\n");
    writer_b.write().unwrap();
    // ...and only then does A commit, from the snapshot that predates B.
    writer_a.write().unwrap();
    drop(writer_a);
    drop(writer_b);

    let reopened = RefgetStore::open_local(&store_dir).unwrap();
    for (label, digest) in [("seed", &seed_digest), ("A", &digest_a), ("B", &digest_b)] {
        assert!(
            reopened.get_collection_metadata(digest).is_some(),
            "collection {} ({}) was dropped from the index by the other writer",
            label,
            digest
        );
    }
}

/// The same shape at the sequence level: rows another writer published must not
/// be dropped by a commit from a stale snapshot.
#[test]
fn test_interleaved_writers_preserve_sequence_rows() {
    let work = tempdir().unwrap();
    let store_dir = work.path().join("store");

    let mut seed = RefgetStore::on_disk(&store_dir).unwrap();
    add_collection_to_store(&mut seed, work.path(), "seed", ">chrS\nAAAACCCC\n");
    seed.write().unwrap();
    drop(seed);

    let mut writer_a = RefgetStore::open_local(&store_dir).unwrap();
    let mut writer_b = RefgetStore::open_local(&store_dir).unwrap();

    add_collection_to_store(&mut writer_a, work.path(), "a", ">chrA\nGGGGTTTT\n");
    add_collection_to_store(&mut writer_b, work.path(), "b", ">chrB\nTTTTGGGG\n");
    writer_b.write().unwrap();
    writer_a.write().unwrap();
    drop(writer_a);
    drop(writer_b);

    let mut reopened = RefgetStore::open_local(&store_dir).unwrap();
    let names: std::collections::HashSet<String> = reopened
        .list_sequences()
        .unwrap()
        .iter()
        .map(|m| m.name.clone())
        .collect();
    for expected in ["chrS", "chrA", "chrB"] {
        assert!(names.contains(expected), "sequence {} was dropped; have {:?}", expected, names);
    }
}

/// An alias namespace one writer creates must not be dropped from the manifest
/// (or deleted from disk) by another writer that never loaded it. The manifest
/// is the only discovery mechanism over HTTP, so an unadvertised TSV is
/// unreachable.
#[test]
fn test_alias_namespace_from_other_writer_survives_commit() {
    let work = tempdir().unwrap();
    let store_dir = work.path().join("store");

    let mut seed = RefgetStore::on_disk(&store_dir).unwrap();
    let seed_digest = add_collection_to_store(&mut seed, work.path(), "seed", ">chrS\nAAAACCCC\n");
    seed.write().unwrap();
    drop(seed);

    // A opens the store BEFORE the namespace exists, so it will never load it.
    let mut writer_a = RefgetStore::open_local(&store_dir).unwrap();

    let mut writer_b = RefgetStore::open_local(&store_dir).unwrap();
    writer_b
        .add_collection_alias("refgenie", "athaliana", &seed_digest)
        .unwrap();
    drop(writer_b);

    // A commits from its stale snapshot.
    add_collection_to_store(&mut writer_a, work.path(), "a", ">chrA\nGGGGTTTT\n");
    writer_a.write().unwrap();
    drop(writer_a);

    assert!(
        store_dir.join("aliases/collections/refgenie.tsv").exists(),
        "the other writer's alias TSV was deleted"
    );
    let reopened = RefgetStore::open_local(&store_dir).unwrap();
    assert!(
        reopened
            .get_collection_metadata_by_alias("refgenie", "athaliana")
            .is_some(),
        "alias stopped resolving after another writer committed"
    );
}

/// Removal must still work: a blind union would resurrect whatever
/// `remove_collection` deleted.
#[test]
fn test_removal_is_not_resurrected_by_the_merge() {
    let work = tempdir().unwrap();
    let store_dir = work.path().join("store");

    let mut store = RefgetStore::on_disk(&store_dir).unwrap();
    let keep = add_collection_to_store(&mut store, work.path(), "keep", ">chrK\nAAAACCCC\n");
    let drop_me = add_collection_to_store(&mut store, work.path(), "drop", ">chrD\nGGGGTTTT\n");
    store.write().unwrap();

    assert!(store.remove_collection(&drop_me, true).unwrap());
    drop(store);

    let reopened = RefgetStore::open_local(&store_dir).unwrap();
    assert!(reopened.get_collection_metadata(&keep).is_some());
    assert!(
        reopened.get_collection_metadata(&drop_me).is_none(),
        "removed collection came back through the merge"
    );
}

/// Orphan GC on a freshly-opened store. `open_local` loads collection STUBS and
/// never populates `name_lookup`, so the old `name_lookup`-derived live set was
/// empty here and unlinked sequences the surviving collection still needs.
/// This test fails against the pre-merge implementation.
#[test]
fn test_orphan_gc_keeps_sequences_shared_with_another_collection() {
    let work = tempdir().unwrap();
    let store_dir = work.path().join("store");

    // Two collections that SHARE chrShared, plus one sequence unique to each.
    let mut store = RefgetStore::on_disk(&store_dir).unwrap();
    let coll_a = add_collection_to_store(
        &mut store,
        work.path(),
        "a",
        ">chrShared\nAAAACCCCGGGGTTTT\n>chrOnlyA\nACACACAC\n",
    );
    let coll_b = add_collection_to_store(
        &mut store,
        work.path(),
        "b",
        ">chrShared\nAAAACCCCGGGGTTTT\n>chrOnlyB\nGTGTGTGT\n",
    );
    store.write().unwrap();
    drop(store);

    // Reopen fresh: stub load, so name_lookup is empty.
    let mut store = RefgetStore::open_local(&store_dir).unwrap();
    assert!(
        store.name_lookup.is_empty(),
        "precondition: a fresh open must not populate name_lookup"
    );

    // The dry-run must agree with what actually happens.
    let planned = store.plan_orphan_removal(&coll_a).unwrap();
    assert_eq!(
        planned.len(),
        1,
        "only chrOnlyA is an orphan; planned {:?}",
        planned
    );

    assert!(store.remove_collection(&coll_a, true).unwrap());
    drop(store);

    let mut reopened = RefgetStore::open_local(&store_dir).unwrap();
    reopened.load_collection(&coll_b).unwrap();
    let collection = reopened.get_collection(&coll_b).unwrap();
    assert_eq!(collection.sequences.len(), 2);
    for seq in &collection.sequences {
        let digest = &seq.metadata().sha512t24u;
        assert!(
            reopened.get_sequence_metadata(digest).is_some(),
            "sequence {} ({}) survived in the index but not in the store",
            seq.metadata().name,
            digest
        );
        assert!(
            reopened.get_sequence(digest).is_ok(),
            "sequence {} ({}) was unlinked from disk by the orphan GC",
            seq.metadata().name,
            digest
        );
    }
}

/// Orphan GC must fail closed. If a collection listed in the index has no
/// readable `.rgsi`, the live set is unknowable and nothing may be deleted --
/// treating a missing input as "references nothing" is how live data gets
/// unlinked.
#[test]
fn test_orphan_gc_refuses_when_a_collection_rgsi_is_missing() {
    let work = tempdir().unwrap();
    let store_dir = work.path().join("store");

    let mut store = RefgetStore::on_disk(&store_dir).unwrap();
    let coll_a = add_collection_to_store(&mut store, work.path(), "a", ">chrA\nAAAACCCC\n");
    let coll_b = add_collection_to_store(&mut store, work.path(), "b", ">chrB\nGGGGTTTT\n");
    store.write().unwrap();
    drop(store);

    fs::remove_file(store_dir.join(format!("collections/{}.rgsi", coll_b))).unwrap();

    let mut store = RefgetStore::open_local(&store_dir).unwrap();
    let err = store.remove_collection(&coll_a, true).unwrap_err();
    assert!(
        err.to_string().contains("refusing to remove orphan sequences"),
        "expected a fail-closed error, got: {}",
        err
    );
}

/// Conflicting alias bindings are a semantic conflict, not a merge detail.
/// Error by default; `--force-alias` takes the in-memory value.
#[test]
fn test_conflicting_alias_errors_unless_forced() {
    let work = tempdir().unwrap();
    let store_dir = work.path().join("store");

    let mut store = RefgetStore::on_disk(&store_dir).unwrap();
    let coll_a = add_collection_to_store(&mut store, work.path(), "a", ">chrA\nAAAACCCC\n");
    let coll_b = add_collection_to_store(&mut store, work.path(), "b", ">chrB\nGGGGTTTT\n");
    store.add_collection_alias("ucsc", "hg38", &coll_a).unwrap();
    store.write().unwrap();
    drop(store);

    // Another writer rebinds the same alias to a different collection.
    let mut other = RefgetStore::open_local(&store_dir).unwrap();
    let err = other
        .add_collection_alias("ucsc", "hg38", &coll_b)
        .expect_err("a conflicting alias binding must not be silently resolved");
    assert!(err.to_string().contains("alias conflict"), "got: {}", err);
    // The published binding is untouched by the failed commit.
    assert_eq!(
        fs::read_to_string(store_dir.join("aliases/collections/ucsc.tsv")).unwrap(),
        format!("hg38\t{}\n", coll_a)
    );

    other.set_force_alias(true);
    other
        .add_collection_alias("ucsc", "hg38", &coll_b)
        .expect("force-alias must overwrite the published binding");
    drop(other);

    let reopened = RefgetStore::open_local(&store_dir).unwrap();
    assert_eq!(
        reopened
            .get_collection_metadata_by_alias("ucsc", "hg38")
            .unwrap()
            .digest,
        coll_b
    );
}

/// `rgstore.json` is published LAST, so the digests it advertises always
/// describe files that are already on disk.
#[test]
fn test_manifest_digests_match_published_indexes() {
    let work = tempdir().unwrap();
    let store_dir = work.path().join("store");

    let mut store = RefgetStore::on_disk(&store_dir).unwrap();
    add_collection_to_store(&mut store, work.path(), "a", ">chrA\nAAAACCCC\n");
    store.write().unwrap();

    let metadata = store.store_metadata().unwrap();
    let sha = |name: &str| {
        use sha2::{Digest, Sha256};
        format!("{:x}", Sha256::digest(fs::read(store_dir.join(name)).unwrap()))
    };
    assert_eq!(metadata.get("sequences_digest").unwrap(), &sha("sequences.rgsi"));
    assert_eq!(metadata.get("collections_digest").unwrap(), &sha("collections.rgci"));
}

/// `created_at` now means what it says. It used to be stamped with `now()` on
/// every commit, making it a duplicate of `modified`.
#[test]
fn test_created_at_survives_subsequent_commits() {
    let work = tempdir().unwrap();
    let store_dir = work.path().join("store");

    let mut store = RefgetStore::on_disk(&store_dir).unwrap();
    add_collection_to_store(&mut store, work.path(), "a", ">chrA\nAAAACCCC\n");
    store.write().unwrap();

    let read_created_at = || -> String {
        let json = fs::read_to_string(store_dir.join("rgstore.json")).unwrap();
        let v: serde_json::Value = serde_json::from_str(&json).unwrap();
        v["created_at"].as_str().unwrap().to_string()
    };
    let first = read_created_at();

    add_collection_to_store(&mut store, work.path(), "b", ">chrB\nGGGGTTTT\n");
    store.write().unwrap();

    assert_eq!(read_created_at(), first, "created_at was overwritten by a later commit");
}

/// The lock serializes writers, and a store that already holds a batch lock
/// must not deadlock against the commit each mutation triggers.
#[test]
fn test_batch_lock_is_reentrant_and_exclusive() {
    let work = tempdir().unwrap();
    let store_dir = work.path().join("store");

    let mut store = RefgetStore::on_disk(&store_dir).unwrap();
    add_collection_to_store(&mut store, work.path(), "a", ">chrA\nAAAACCCC\n");
    store.write().unwrap();

    store.lock_for_batch("test-batch").unwrap();
    assert!(store.holds_batch_lock());

    // Nested commits must not block on the lock this store already holds.
    add_collection_to_store(&mut store, work.path(), "b", ">chrB\nGGGGTTTT\n");
    store.write().unwrap();

    // Meanwhile another process would be locked out.
    assert!(
        super::lock_status(&store_dir).unwrap().is_some(),
        "the batch lock should be visible on disk"
    );

    store.release_batch_lock();
    assert!(super::lock_status(&store_dir).unwrap().is_none());
}

/// Transient lock/temp files must be recognizable so anything mirroring a store
/// directory (`aws s3 sync`, integrity checkers) can skip them.
#[test]
fn test_commit_leaves_no_transient_files_behind() {
    let work = tempdir().unwrap();
    let store_dir = work.path().join("store");

    let mut store = RefgetStore::on_disk(&store_dir).unwrap();
    add_collection_to_store(&mut store, work.path(), "a", ">chrA\nAAAACCCC\n");
    store.write().unwrap();
    drop(store);

    let leftovers: Vec<String> = fs::read_dir(&store_dir)
        .unwrap()
        .filter_map(|e| e.ok())
        .filter_map(|e| e.file_name().to_str().map(String::from))
        .filter(|n| super::is_transient_store_file(n))
        .collect();
    assert!(leftovers.is_empty(), "transient files left behind: {:?}", leftovers);
}

// =========================================================================
// Delta-at-commit: a stale handle must not resurrect another writer's removal
//
// These are the regression tests for the 2026-07-28 finding. Merge-at-commit
// wrote back EVERYTHING a handle had in memory, and `open_local` loads a stub
// for every collection in the index purely so it can be read. A handle that
// opened before a removal therefore re-added the removed rows on its next
// commit -- after the `.seq` files were already unlinked. Not a lock race: the
// removal completes entirely before the offending commit begins.
// =========================================================================

/// Sequence digests of one collection, read from its on-disk `.rgsi`.
fn sequence_digests_of(store: &mut RefgetStore, digest: &str) -> Vec<String> {
    store.load_collection(digest).unwrap();
    store
        .get_collection(digest)
        .unwrap()
        .sequences
        .iter()
        .map(|s| s.metadata().sha512t24u.clone())
        .collect()
}

fn index_contains(store_dir: &std::path::Path, file: &str, needle: &str) -> bool {
    fs::read_to_string(store_dir.join(file))
        .unwrap()
        .lines()
        .any(|l| l.contains(needle))
}

/// THE resurrection bug. W opens the store, R removes a collection and its
/// orphan sequences and commits, then W commits an unrelated addition. W's
/// commit must not bring the removed collection, its sequences, or its alias
/// back.
///
/// Fails against merge-at-commit with dangling index rows: the `.seq` files are
/// gone but the rows point at them.
#[test]
fn test_stale_handle_does_not_resurrect_a_removed_collection() {
    let work = tempdir().unwrap();
    let store_dir = work.path().join("store");

    let mut seed = RefgetStore::on_disk(&store_dir).unwrap();
    let keep = add_collection_to_store(&mut seed, work.path(), "keep", ">chrK\nAAAACCCC\n");
    let victim = add_collection_to_store(
        &mut seed,
        work.path(),
        "victim",
        ">chrV1\nGGGGTTTT\n>chrV2\nTTTTGGGG\n",
    );
    seed.add_collection_alias("refgenie", "oluc", &victim).unwrap();
    seed.write().unwrap();
    let victim_sequences = sequence_digests_of(&mut seed, &victim);
    drop(seed);

    // W opens BEFORE the removal. Its snapshot contains the victim.
    let mut writer = RefgetStore::open_local(&store_dir).unwrap();
    assert!(writer.get_collection_metadata(&victim).is_some());

    // R removes the victim and commits. Disk is correct at this point.
    let mut remover = RefgetStore::open_local(&store_dir).unwrap();
    assert!(remover.remove_collection(&victim, true).unwrap());
    drop(remover);
    assert!(!index_contains(&store_dir, "collections.rgci", &victim));

    // W now commits an unrelated addition from its stale snapshot.
    let added = add_collection_to_store(&mut writer, work.path(), "added", ">chrN\nACACACAC\n");
    writer.write().unwrap();
    drop(writer);

    assert!(
        !index_contains(&store_dir, "collections.rgci", &victim),
        "the removed collection came back into collections.rgci"
    );
    for seq in &victim_sequences {
        assert!(
            !index_contains(&store_dir, "sequences.rgsi", seq),
            "orphan sequence {} came back into sequences.rgsi -- its .seq file is gone",
            seq
        );
    }
    assert!(
        !store_dir.join("aliases/collections/refgenie.tsv").exists(),
        "the removed collection's alias namespace came back"
    );

    // ...and the concurrent addition is not collateral damage.
    let reopened = RefgetStore::open_local(&store_dir).unwrap();
    assert!(reopened.get_collection_metadata(&keep).is_some());
    assert!(reopened.get_collection_metadata(&added).is_some());
    assert!(reopened.get_collection_metadata(&victim).is_none());
    assert!(
        reopened
            .get_collection_metadata_by_alias("refgenie", "oluc")
            .is_none(),
        "the alias still resolves to a collection that no longer exists"
    );
}

/// Every index row a delta commit publishes must have its `.seq` file on disk.
/// The observable symptom of the resurrection bug was not a missing row but a
/// present one that could not be read.
#[test]
fn test_no_dangling_sequence_rows_after_a_stale_commit() {
    let work = tempdir().unwrap();
    let store_dir = work.path().join("store");

    let mut seed = RefgetStore::on_disk(&store_dir).unwrap();
    add_collection_to_store(&mut seed, work.path(), "keep", ">chrK\nAAAACCCC\n");
    let victim = add_collection_to_store(&mut seed, work.path(), "victim", ">chrV\nGGGGTTTT\n");
    seed.write().unwrap();
    drop(seed);

    let mut writer = RefgetStore::open_local(&store_dir).unwrap();

    let mut remover = RefgetStore::open_local(&store_dir).unwrap();
    remover.remove_collection(&victim, true).unwrap();
    drop(remover);

    add_collection_to_store(&mut writer, work.path(), "added", ">chrN\nACACACAC\n");
    writer.write().unwrap();
    drop(writer);

    let mut reopened = RefgetStore::open_local(&store_dir).unwrap();
    let digests: Vec<String> = reopened
        .list_sequences()
        .unwrap()
        .iter()
        .map(|m| m.sha512t24u.clone())
        .collect();
    for digest in &digests {
        // `load_sequence` reads the `.seq` file, so this fails on a row whose
        // bytes were unlinked. `get_sequence` would NOT: it happily returns the
        // Stub built from the index row, which is why the corruption was
        // invisible until someone actually asked for bases.
        assert!(
            reopened.load_sequence(digest).is_ok(),
            "sequences.rgsi lists {} but its .seq file is gone",
            digest
        );
    }
}

/// The lost-update case merge-at-commit existed to prevent must not regress:
/// two handles open together, one commits, the other commits after, and both
/// additions survive.
#[test]
fn test_delta_commit_still_preserves_a_concurrent_addition() {
    let work = tempdir().unwrap();
    let store_dir = work.path().join("store");

    let mut seed = RefgetStore::on_disk(&store_dir).unwrap();
    let seed_digest = add_collection_to_store(&mut seed, work.path(), "seed", ">chrS\nAAAACCCC\n");
    seed.write().unwrap();
    drop(seed);

    let mut writer_a = RefgetStore::open_local(&store_dir).unwrap();
    let mut writer_b = RefgetStore::open_local(&store_dir).unwrap();

    let digest_a = add_collection_to_store(&mut writer_a, work.path(), "a", ">chrA\nGGGGTTTT\n");
    let digest_b = add_collection_to_store(&mut writer_b, work.path(), "b", ">chrB\nTTTTGGGG\n");
    writer_b.write().unwrap();
    writer_a.write().unwrap();
    drop(writer_a);
    drop(writer_b);

    let reopened = RefgetStore::open_local(&store_dir).unwrap();
    for (label, digest) in [("seed", &seed_digest), ("A", &digest_a), ("B", &digest_b)] {
        assert!(
            reopened.get_collection_metadata(digest).is_some(),
            "collection {} ({}) was dropped by the other writer's commit",
            label,
            digest
        );
    }
}

/// Removing one of two collections that share sequences reclaims exactly the
/// unshared digests, and the shared ones stay readable byte-for-byte.
#[test]
fn test_removal_reclaims_only_unshared_sequences() {
    let work = tempdir().unwrap();
    let store_dir = work.path().join("store");

    const SHARED: &str = "AAAACCCCGGGGTTTT";
    let mut store = RefgetStore::on_disk(&store_dir).unwrap();
    let coll_a = add_collection_to_store(
        &mut store,
        work.path(),
        "a",
        &format!(">chrShared\n{}\n>chrOnlyA\nACACACAC\n", SHARED),
    );
    let coll_b = add_collection_to_store(
        &mut store,
        work.path(),
        "b",
        &format!(">chrShared\n{}\n>chrOnlyB\nGTGTGTGT\n", SHARED),
    );
    store.write().unwrap();
    let a_sequences = sequence_digests_of(&mut store, &coll_a);
    let b_sequences = sequence_digests_of(&mut store, &coll_b);
    drop(store);

    let shared: Vec<&String> = a_sequences.iter().filter(|d| b_sequences.contains(d)).collect();
    assert_eq!(shared.len(), 1, "precondition: exactly one shared sequence");
    let only_a: Vec<&String> = a_sequences.iter().filter(|d| !b_sequences.contains(d)).collect();
    assert_eq!(only_a.len(), 1);

    let mut store = RefgetStore::open_local(&store_dir).unwrap();
    let planned = store.plan_orphan_removal(&coll_a).unwrap();
    assert_eq!(planned, vec![only_a[0].clone()], "the dry-run must name exactly chrOnlyA");
    assert!(store.remove_collection(&coll_a, true).unwrap());
    drop(store);

    let mut reopened = RefgetStore::open_local(&store_dir).unwrap();
    assert!(
        reopened.get_sequence_metadata(only_a[0]).is_none(),
        "the unshared sequence was not reclaimed"
    );
    reopened.load_sequence(shared[0]).unwrap();
    assert_eq!(
        reopened.get_substring(shared[0], 0, SHARED.len()).unwrap(),
        SHARED,
        "the shared sequence did not survive intact"
    );
}

/// A namespace this handle empties must still not be deleted when another writer
/// has added an alias to it. Intent is not the deciding factor; the merged
/// result is.
#[test]
fn test_emptying_a_namespace_spares_another_writers_alias() {
    let work = tempdir().unwrap();
    let store_dir = work.path().join("store");

    let mut seed = RefgetStore::on_disk(&store_dir).unwrap();
    let coll_a = add_collection_to_store(&mut seed, work.path(), "a", ">chrA\nAAAACCCC\n");
    let coll_b = add_collection_to_store(&mut seed, work.path(), "b", ">chrB\nGGGGTTTT\n");
    seed.add_collection_alias("refgenie", "mine", &coll_a).unwrap();
    seed.write().unwrap();
    drop(seed);

    // A opens with only `mine` in the namespace.
    let mut writer_a = RefgetStore::open_local(&store_dir).unwrap();

    // B adds a second alias to the same namespace and commits.
    let mut writer_b = RefgetStore::open_local(&store_dir).unwrap();
    writer_b.add_collection_alias("refgenie", "theirs", &coll_b).unwrap();
    drop(writer_b);

    // A removes its only alias -- emptying the namespace as far as A can see.
    assert!(writer_a.remove_collection_alias("refgenie", "mine").unwrap());
    drop(writer_a);

    let reopened = RefgetStore::open_local(&store_dir).unwrap();
    assert!(
        reopened
            .get_collection_metadata_by_alias("refgenie", "theirs")
            .is_some(),
        "the other writer's alias was deleted with the namespace"
    );
    assert!(
        reopened
            .get_collection_metadata_by_alias("refgenie", "mine")
            .is_none(),
        "the removed alias came back"
    );
}

/// Uncommitted work is visible to callers, so a caller that must not lose a
/// removal can check before dropping the handle.
#[test]
fn test_has_uncommitted_changes_tracks_the_commit() {
    let work = tempdir().unwrap();
    let store_dir = work.path().join("store");

    let mut store = RefgetStore::on_disk(&store_dir).unwrap();
    // on_disk commits after each add, so the store starts clean.
    add_collection_to_store(&mut store, work.path(), "a", ">chrA\nAAAACCCC\n");
    store.write().unwrap();
    assert!(!store.has_uncommitted_changes());

    store.lock_for_batch("test-batch").unwrap();
    let digest = add_collection_to_store(&mut store, work.path(), "b", ">chrB\nGGGGTTTT\n");
    assert!(store.get_collection_metadata(&digest).is_some());
    store.write().unwrap();
    assert!(
        !store.has_uncommitted_changes(),
        "a successful commit must clear the pending set"
    );
    store.release_batch_lock();
}