gtars-refget 0.9.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
//! 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 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_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);
    assert_eq!(retrieved_record.sequence().unwrap(), 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_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 (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 (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 (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 (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_meta = seq1.unwrap().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.total_disk_size();
    assert!(disk_size > 0);

    let manual: usize = store
        .list_sequences()
        .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_loaded, 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_loaded, 0);

    let seq = loaded_store.get_sequence_by_name(&digest, "chr1");
    assert!(seq.is_err());

    loaded_store.load_collection(&digest).unwrap();

    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_loaded, 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();
    assert_eq!(stats_after.n_sequences_loaded, 0);
    assert_eq!(stats_after.n_collections_loaded, 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());

    loaded_store.load_sequence(&seq_digest).unwrap();

    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_loaded, 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);
}

// =========================================================================
// 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().len(), 2);
    store.remove_collection(&digest, false).unwrap();
    assert_eq!(store.list_sequences().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().len(), 2);
    store.remove_collection(&digest, true).unwrap();
    assert_eq!(store.list_sequences().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().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().len(), 2);

    let coll = store.get_collection(&meta2.digest).unwrap();
    assert_eq!(coll.sequences.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());
}

// =========================================================================
// 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_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()
        .into_iter()
        .map(|(m, _)| m.digest)
        .collect()
}

#[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
        );
    }
}

// =========================================================================
// 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_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);
}