solidb 1.0.1

A lightweight, high-performance structured database server written in Rust.
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
1205
1206
1207
1208
1209
1210
1211
1212
1213
1214
1215
1216
1217
1218
1219
1220
1221
1222
1223
1224
1225
1226
1227
1228
1229
1230
1231
1232
1233
1234
1235
1236
1237
1238
1239
1240
1241
1242
1243
1244
1245
1246
1247
1248
1249
1250
1251
1252
1253
1254
1255
1256
1257
1258
1259
1260
1261
1262
1263
1264
1265
1266
1267
1268
1269
1270
1271
1272
1273
1274
1275
1276
1277
1278
1279
1280
1281
1282
1283
1284
1285
1286
1287
1288
1289
1290
1291
1292
1293
1294
1295
1296
1297
1298
1299
1300
1301
1302
1303
1304
1305
1306
1307
1308
1309
1310
1311
1312
1313
1314
1315
1316
1317
1318
1319
1320
1321
1322
1323
1324
1325
1326
1327
1328
1329
1330
1331
1332
1333
1334
1335
1336
1337
1338
1339
1340
1341
1342
1343
1344
1345
1346
1347
1348
1349
1350
1351
1352
1353
1354
1355
1356
1357
1358
1359
1360
1361
1362
1363
1364
1365
1366
1367
1368
1369
1370
1371
1372
1373
1374
1375
1376
1377
1378
1379
1380
1381
1382
1383
1384
1385
1386
1387
1388
1389
1390
1391
1392
1393
1394
1395
1396
1397
1398
1399
1400
1401
1402
1403
1404
1405
1406
1407
1408
1409
1410
1411
1412
1413
1414
1415
1416
1417
1418
1419
1420
1421
1422
1423
1424
1425
1426
1427
1428
1429
1430
1431
1432
1433
1434
1435
1436
1437
1438
1439
1440
1441
1442
1443
1444
1445
1446
1447
1448
1449
1450
1451
1452
1453
1454
1455
1456
1457
1458
1459
1460
1461
1462
1463
1464
1465
1466
1467
1468
1469
1470
1471
1472
1473
1474
1475
1476
1477
1478
1479
1480
1481
1482
1483
1484
1485
1486
1487
1488
1489
1490
1491
1492
1493
1494
1495
1496
1497
1498
1499
1500
1501
1502
1503
1504
1505
1506
1507
1508
1509
1510
1511
1512
1513
1514
1515
1516
1517
1518
1519
1520
1521
1522
1523
1524
1525
1526
1527
1528
1529
1530
1531
1532
1533
1534
1535
1536
1537
1538
1539
1540
1541
1542
1543
1544
1545
1546
1547
1548
1549
1550
1551
1552
1553
1554
1555
1556
1557
1558
1559
1560
1561
1562
1563
1564
1565
1566
1567
1568
1569
1570
1571
1572
1573
1574
1575
1576
1577
1578
1579
1580
1581
1582
1583
1584
1585
1586
1587
1588
1589
1590
1591
1592
1593
1594
1595
1596
1597
1598
1599
1600
1601
1602
1603
1604
1605
1606
1607
1608
1609
1610
1611
1612
1613
1614
1615
1616
1617
1618
1619
1620
1621
1622
1623
1624
1625
1626
1627
1628
1629
1630
1631
1632
1633
1634
1635
1636
1637
1638
1639
1640
1641
1642
1643
1644
1645
1646
1647
1648
1649
1650
1651
1652
1653
1654
1655
1656
1657
1658
1659
1660
1661
1662
1663
1664
1665
1666
1667
1668
1669
1670
1671
1672
1673
1674
1675
1676
1677
1678
1679
1680
1681
1682
1683
1684
1685
1686
1687
1688
1689
1690
1691
1692
1693
1694
1695
1696
1697
1698
1699
1700
1701
1702
1703
1704
1705
1706
1707
1708
1709
1710
1711
1712
1713
1714
1715
1716
1717
1718
1719
1720
1721
1722
1723
1724
1725
1726
1727
1728
1729
1730
1731
1732
1733
1734
1735
1736
1737
1738
1739
1740
1741
1742
1743
1744
1745
1746
1747
1748
1749
1750
1751
1752
1753
1754
1755
1756
1757
1758
1759
1760
1761
1762
1763
1764
1765
1766
1767
1768
1769
1770
1771
1772
1773
1774
1775
1776
1777
1778
1779
1780
1781
1782
1783
1784
1785
1786
1787
1788
1789
1790
1791
1792
1793
1794
1795
1796
1797
1798
1799
1800
1801
1802
1803
1804
1805
1806
1807
1808
1809
1810
1811
1812
1813
1814
1815
1816
1817
1818
1819
1820
1821
1822
1823
1824
1825
1826
1827
1828
1829
1830
1831
1832
1833
1834
1835
1836
1837
1838
1839
1840
1841
1842
1843
1844
1845
1846
1847
1848
1849
1850
1851
1852
1853
1854
1855
1856
1857
1858
1859
1860
1861
1862
1863
1864
1865
1866
1867
1868
1869
1870
1871
1872
1873
1874
1875
1876
1877
1878
1879
1880
1881
1882
1883
1884
1885
1886
1887
1888
1889
1890
1891
1892
1893
1894
1895
1896
1897
1898
1899
1900
1901
1902
1903
1904
1905
1906
1907
1908
1909
1910
1911
1912
1913
1914
1915
1916
1917
1918
1919
1920
1921
1922
1923
1924
1925
1926
1927
1928
1929
1930
1931
1932
1933
1934
1935
1936
1937
1938
1939
1940
1941
1942
1943
1944
1945
1946
1947
1948
1949
1950
1951
1952
1953
1954
1955
1956
1957
1958
1959
1960
1961
1962
1963
1964
1965
1966
1967
1968
1969
1970
1971
1972
1973
1974
1975
1976
1977
1978
1979
1980
1981
1982
1983
1984
1985
1986
1987
1988
1989
1990
1991
1992
1993
1994
1995
1996
1997
1998
1999
2000
2001
2002
2003
2004
2005
2006
2007
2008
2009
2010
2011
2012
2013
2014
2015
2016
2017
2018
2019
2020
2021
2022
2023
2024
2025
2026
2027
2028
2029
2030
2031
2032
2033
2034
2035
2036
2037
2038
2039
2040
2041
2042
2043
2044
2045
2046
2047
2048
2049
2050
2051
2052
2053
2054
2055
2056
2057
2058
2059
2060
2061
2062
2063
2064
2065
2066
2067
2068
2069
2070
2071
2072
2073
2074
2075
2076
2077
2078
2079
2080
2081
2082
2083
2084
2085
2086
2087
2088
2089
2090
2091
2092
2093
2094
2095
2096
2097
2098
2099
2100
2101
2102
2103
2104
2105
2106
2107
2108
2109
2110
2111
2112
2113
2114
2115
2116
2117
2118
2119
2120
2121
2122
2123
2124
2125
2126
2127
2128
2129
2130
2131
2132
2133
2134
2135
2136
2137
2138
2139
2140
2141
2142
2143
2144
2145
2146
2147
2148
2149
2150
2151
2152
2153
2154
2155
2156
2157
2158
2159
2160
2161
2162
2163
2164
2165
2166
2167
2168
2169
2170
2171
2172
2173
2174
2175
2176
2177
2178
2179
2180
2181
2182
2183
2184
2185
2186
2187
2188
2189
2190
2191
2192
2193
2194
2195
2196
2197
2198
2199
2200
2201
2202
2203
2204
2205
2206
2207
2208
2209
2210
2211
2212
2213
2214
2215
2216
2217
2218
2219
2220
2221
2222
2223
2224
2225
2226
2227
2228
2229
2230
2231
2232
2233
2234
2235
2236
2237
2238
2239
2240
2241
2242
2243
2244
2245
2246
2247
2248
2249
2250
2251
2252
2253
2254
2255
2256
2257
2258
2259
2260
2261
2262
2263
2264
2265
2266
2267
2268
2269
2270
2271
2272
2273
2274
2275
2276
2277
2278
2279
2280
2281
2282
2283
2284
2285
2286
2287
2288
2289
2290
2291
2292
2293
2294
2295
2296
2297
2298
2299
2300
2301
2302
2303
2304
2305
2306
2307
2308
2309
2310
2311
2312
2313
2314
2315
2316
2317
2318
2319
2320
2321
2322
2323
2324
2325
2326
2327
2328
2329
2330
2331
2332
2333
2334
2335
2336
2337
2338
2339
2340
2341
2342
2343
2344
2345
2346
2347
2348
2349
2350
2351
2352
2353
2354
2355
2356
2357
2358
2359
2360
2361
2362
2363
2364
2365
2366
2367
2368
2369
2370
2371
2372
2373
2374
2375
2376
2377
2378
2379
2380
2381
2382
2383
2384
2385
2386
2387
2388
2389
2390
2391
2392
2393
2394
2395
2396
2397
2398
2399
2400
2401
2402
2403
2404
2405
2406
2407
2408
2409
2410
2411
2412
2413
2414
2415
2416
2417
2418
2419
2420
2421
2422
2423
2424
2425
2426
2427
2428
2429
2430
2431
2432
2433
2434
2435
2436
2437
2438
2439
2440
2441
2442
2443
2444
2445
2446
2447
2448
2449
2450
2451
2452
2453
2454
2455
2456
2457
2458
2459
2460
2461
2462
2463
2464
2465
2466
2467
2468
2469
2470
2471
2472
2473
2474
2475
2476
2477
2478
2479
2480
2481
2482
2483
2484
2485
2486
2487
2488
2489
2490
2491
2492
2493
2494
2495
2496
2497
2498
2499
2500
2501
2502
2503
2504
2505
2506
2507
2508
2509
2510
2511
2512
2513
2514
2515
2516
2517
2518
2519
2520
2521
2522
2523
2524
2525
2526
2527
2528
2529
2530
2531
2532
2533
2534
2535
2536
2537
2538
2539
2540
2541
2542
2543
2544
2545
2546
2547
2548
2549
2550
2551
2552
2553
2554
2555
2556
2557
2558
2559
2560
2561
2562
2563
2564
2565
2566
2567
2568
2569
2570
2571
2572
2573
2574
2575
2576
2577
2578
2579
2580
2581
2582
2583
2584
2585
2586
2587
2588
2589
2590
2591
2592
2593
2594
2595
2596
2597
2598
2599
2600
2601
2602
2603
2604
2605
2606
2607
2608
2609
2610
2611
2612
2613
2614
2615
2616
2617
2618
2619
2620
2621
2622
2623
2624
2625
2626
2627
2628
2629
2630
2631
2632
2633
2634
2635
2636
2637
2638
2639
2640
2641
2642
2643
2644
2645
2646
2647
2648
2649
2650
2651
2652
2653
2654
2655
2656
2657
2658
2659
2660
2661
2662
2663
2664
2665
2666
2667
2668
2669
2670
2671
2672
2673
2674
2675
2676
2677
2678
2679
2680
2681
2682
2683
2684
2685
2686
2687
2688
2689
2690
2691
2692
2693
2694
2695
2696
2697
2698
2699
2700
2701
2702
2703
2704
2705
2706
2707
2708
2709
2710
2711
2712
2713
2714
2715
2716
2717
2718
2719
2720
2721
2722
2723
2724
2725
2726
2727
2728
2729
2730
2731
2732
2733
2734
2735
2736
2737
2738
2739
2740
2741
2742
2743
2744
2745
2746
2747
2748
2749
2750
2751
2752
2753
2754
2755
2756
2757
2758
2759
2760
2761
2762
2763
2764
2765
2766
2767
2768
2769
2770
2771
2772
2773
2774
2775
2776
2777
2778
2779
2780
2781
2782
2783
2784
2785
2786
2787
2788
2789
2790
2791
2792
2793
2794
2795
2796
2797
2798
2799
2800
2801
2802
2803
2804
2805
2806
2807
2808
2809
2810
2811
2812
2813
2814
2815
2816
2817
2818
2819
2820
2821
2822
2823
2824
2825
2826
2827
2828
2829
2830
2831
2832
2833
2834
2835
2836
2837
2838
2839
2840
2841
2842
2843
2844
2845
2846
2847
2848
2849
2850
2851
2852
2853
2854
2855
2856
2857
2858
2859
2860
2861
2862
2863
2864
2865
2866
2867
2868
2869
2870
2871
2872
2873
2874
2875
2876
2877
2878
2879
2880
2881
2882
2883
2884
2885
2886
2887
2888
2889
2890
2891
2892
2893
2894
2895
2896
2897
2898
2899
2900
2901
2902
2903
2904
2905
2906
2907
2908
2909
2910
2911
2912
2913
2914
2915
2916
2917
2918
2919
2920
2921
2922
2923
2924
2925
2926
2927
2928
2929
2930
2931
2932
2933
2934
2935
2936
2937
2938
2939
2940
2941
2942
2943
2944
2945
2946
2947
2948
2949
2950
2951
2952
2953
2954
2955
2956
2957
2958
2959
2960
2961
2962
2963
2964
2965
2966
2967
2968
2969
2970
2971
2972
2973
2974
2975
2976
2977
2978
2979
2980
2981
2982
2983
2984
2985
2986
2987
2988
2989
2990
2991
2992
2993
2994
2995
2996
2997
2998
2999
3000
3001
3002
3003
3004
3005
3006
3007
3008
3009
3010
3011
3012
3013
3014
3015
3016
3017
3018
3019
3020
3021
3022
3023
3024
3025
3026
3027
3028
3029
3030
3031
3032
3033
3034
3035
3036
3037
3038
3039
3040
3041
3042
3043
3044
3045
3046
3047
3048
3049
3050
3051
3052
3053
3054
3055
3056
3057
3058
3059
3060
3061
3062
3063
3064
3065
3066
3067
3068
3069
3070
3071
3072
3073
3074
3075
3076
3077
3078
3079
3080
3081
3082
3083
3084
3085
3086
3087
3088
3089
3090
3091
3092
3093
3094
3095
3096
3097
3098
3099
3100
3101
3102
3103
3104
3105
3106
3107
3108
3109
3110
3111
3112
3113
3114
3115
3116
3117
3118
3119
3120
3121
3122
3123
3124
3125
3126
3127
3128
3129
3130
3131
3132
3133
3134
3135
3136
3137
3138
3139
3140
3141
3142
3143
3144
3145
3146
3147
3148
3149
3150
3151
3152
3153
3154
3155
3156
3157
3158
3159
3160
3161
3162
3163
3164
3165
3166
3167
3168
3169
3170
3171
3172
3173
3174
3175
3176
3177
3178
3179
3180
3181
3182
3183
3184
3185
3186
3187
3188
3189
3190
3191
3192
3193
3194
3195
3196
3197
3198
3199
3200
3201
3202
3203
3204
3205
3206
3207
3208
3209
3210
3211
3212
3213
3214
3215
3216
3217
3218
3219
3220
3221
3222
3223
3224
3225
3226
3227
3228
3229
3230
3231
3232
3233
3234
3235
3236
3237
3238
3239
3240
3241
3242
3243
3244
3245
3246
3247
3248
3249
3250
3251
3252
3253
3254
3255
3256
3257
3258
3259
3260
3261
3262
3263
3264
3265
3266
3267
3268
3269
3270
3271
3272
3273
3274
3275
3276
3277
3278
3279
3280
3281
3282
3283
3284
3285
3286
3287
3288
3289
3290
3291
3292
3293
3294
3295
3296
3297
3298
3299
3300
3301
3302
3303
3304
3305
3306
3307
3308
3309
3310
3311
3312
3313
3314
3315
3316
3317
3318
3319
3320
3321
3322
3323
3324
3325
3326
3327
3328
3329
3330
3331
3332
3333
3334
3335
3336
3337
3338
3339
3340
3341
3342
3343
3344
3345
3346
3347
3348
3349
3350
3351
3352
3353
3354
3355
3356
3357
3358
3359
3360
3361
3362
3363
3364
3365
3366
3367
3368
3369
3370
3371
3372
3373
3374
3375
3376
3377
3378
3379
3380
3381
3382
3383
3384
3385
3386
3387
3388
3389
3390
3391
3392
3393
3394
3395
3396
3397
3398
3399
3400
3401
3402
3403
3404
3405
3406
3407
3408
3409
3410
3411
3412
3413
3414
3415
3416
3417
3418
3419
3420
3421
3422
3423
3424
3425
3426
3427
3428
3429
3430
3431
3432
3433
3434
3435
3436
3437
3438
3439
3440
3441
3442
3443
3444
3445
3446
3447
3448
3449
3450
3451
3452
3453
3454
3455
3456
3457
3458
3459
3460
3461
3462
3463
3464
3465
3466
3467
3468
3469
3470
3471
3472
3473
3474
3475
3476
3477
3478
3479
3480
3481
3482
3483
3484
3485
3486
3487
3488
3489
3490
3491
3492
3493
3494
3495
3496
3497
3498
3499
3500
3501
3502
3503
3504
3505
3506
3507
3508
3509
3510
3511
3512
3513
3514
3515
3516
3517
3518
3519
3520
3521
3522
3523
3524
3525
3526
3527
3528
3529
3530
3531
3532
3533
3534
3535
3536
3537
3538
3539
3540
3541
3542
3543
3544
3545
3546
3547
3548
3549
3550
3551
3552
3553
3554
3555
3556
3557
3558
3559
3560
3561
3562
3563
3564
3565
3566
3567
3568
3569
3570
3571
3572
3573
3574
3575
3576
3577
3578
3579
3580
3581
3582
3583
3584
3585
3586
3587
3588
3589
3590
3591
3592
3593
3594
3595
3596
3597
3598
3599
3600
3601
3602
3603
3604
3605
3606
3607
3608
3609
3610
3611
3612
3613
3614
3615
3616
3617
3618
3619
3620
3621
3622
3623
3624
3625
3626
3627
3628
3629
3630
3631
3632
3633
3634
3635
3636
3637
3638
3639
3640
3641
3642
3643
3644
3645
3646
3647
3648
3649
3650
3651
3652
3653
3654
3655
3656
3657
3658
3659
3660
3661
3662
3663
3664
3665
3666
3667
3668
3669
3670
3671
3672
3673
3674
3675
3676
3677
3678
3679
3680
3681
3682
3683
3684
3685
3686
3687
3688
3689
3690
3691
3692
3693
3694
3695
3696
3697
3698
3699
3700
3701
3702
3703
3704
3705
3706
3707
3708
3709
3710
3711
3712
3713
3714
3715
3716
3717
3718
3719
3720
3721
3722
3723
3724
3725
3726
3727
3728
3729
3730
3731
3732
3733
3734
3735
3736
3737
3738
3739
3740
3741
3742
3743
3744
3745
3746
3747
3748
3749
3750
3751
3752
3753
3754
3755
3756
3757
3758
3759
3760
3761
3762
3763
3764
3765
3766
3767
3768
3769
3770
3771
3772
3773
3774
3775
3776
3777
3778
3779
3780
3781
3782
3783
3784
3785
3786
3787
3788
3789
3790
3791
3792
3793
3794
3795
3796
3797
3798
3799
3800
3801
3802
3803
3804
3805
3806
3807
3808
3809
3810
3811
3812
3813
3814
3815
3816
3817
3818
3819
3820
3821
3822
3823
3824
3825
3826
3827
3828
3829
3830
3831
3832
3833
3834
3835
3836
3837
3838
3839
3840
3841
3842
3843
3844
3845
3846
3847
3848
//! Shard coordinator compatibility layer
//!
//! This provides the old ShardCoordinator API backed by the new sync module.

use serde::{Deserialize, Serialize};
use std::collections::HashMap;
use std::sync::atomic::{AtomicBool, Ordering};
use std::sync::{Arc, RwLock};

use crate::cluster::manager::ClusterManager;
use crate::sharding::migration::BatchSender;
use crate::storage::http_client::get_http_client;
use crate::storage::StorageEngine;
use crate::sync::{LogEntry, Operation};
use crate::DbError;

/// Configuration for a sharded collection
#[derive(Debug, Clone, Serialize, Deserialize, Default)]
pub struct CollectionShardConfig {
    pub num_shards: u16,
    pub shard_key: String,
    pub replication_factor: u16,
}

/// Shard assignment information
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct ShardAssignment {
    pub shard_id: u16,
    pub primary_node: String,
    pub replica_nodes: Vec<String>,
}

/// Shard table for a collection
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct ShardTable {
    pub database: String,
    pub collection: String,
    pub num_shards: u16,
    pub replication_factor: u16,
    pub shard_key: String,
    pub assignments: HashMap<u16, ShardAssignment>,
}
/// Helper struct to implement BatchSender for ShardCoordinator
/// This allows passing the coordinator to the migration module
struct CoordinatorBatchSender<'a> {
    coordinator: &'a ShardCoordinator,
}

#[async_trait::async_trait]
impl<'a> BatchSender for CoordinatorBatchSender<'a> {
    async fn send_batch(
        &self,
        db_name: &str,
        coll_name: &str,
        config: &CollectionShardConfig,
        batch: Vec<(String, serde_json::Value)>,
    ) -> Result<Vec<String>, String> {
        self.coordinator
            .send_migrated_batch(db_name, coll_name, config, batch)
            .await
    }

    async fn should_pause_resharding(&self) -> bool {
        self.coordinator.should_pause_resharding()
    }
}

/// Coordinator for managing shard assignments
pub struct ShardCoordinator {
    storage: Arc<StorageEngine>,
    cluster_manager: Option<Arc<ClusterManager>>,
    shard_tables: RwLock<HashMap<String, ShardTable>>,
    replication_log: Option<Arc<crate::sync::log::SyncLog>>,
    is_rebalancing: AtomicBool,
    recently_failed_nodes: RwLock<HashMap<String, std::time::Instant>>,
    /// Timestamp of last resharding completion - used to delay healing
    last_reshard_time: RwLock<Option<std::time::Instant>>,
}

impl ShardCoordinator {
    pub const MAX_BLOB_REPLICAS: u16 = 10;
    pub const MIN_BLOB_REPLICAS: u16 = 2;

    pub fn new(
        storage: Arc<StorageEngine>,
        cluster_manager: Option<Arc<ClusterManager>>,
        replication_log: Option<Arc<crate::sync::log::SyncLog>>,
    ) -> Self {
        Self {
            storage,
            cluster_manager,
            shard_tables: RwLock::new(HashMap::new()),
            replication_log,
            is_rebalancing: AtomicBool::new(false),
            recently_failed_nodes: RwLock::new(HashMap::new()),
            last_reshard_time: RwLock::new(None),
        }
    }

    /// Get the cluster secret from the keyfile for inter-node HTTP authentication
    pub fn cluster_secret(&self) -> String {
        self.storage
            .cluster_config()
            .and_then(|c| c.keyfile.clone())
            .unwrap_or_default()
    }

    /// Get shard configuration for a collection
    pub fn get_shard_config(
        &self,
        database: &str,
        collection: &str,
    ) -> Option<CollectionShardConfig> {
        if let Ok(db) = self.storage.get_database(database) {
            if let Ok(coll) = db.get_collection(collection) {
                return coll.get_shard_config();
            }
        }
        None
    }

    /// Get shard table for a collection
    /// Automatically recomputes if cached table contains nodes no longer in the cluster
    /// Returns None for internal system collections (those starting with _)
    pub fn get_shard_table(&self, database: &str, collection: &str) -> Option<ShardTable> {
        let key = format!("{}.{}", database, collection);

        // Fast path: Check cache
        if let Some(table) = self.shard_tables.read().unwrap().get(&key).cloned() {
            // Validate that the cached table is not stale
            // Stale conditions:
            // 1. Primary nodes are unhealthy
            // 2. Shard count doesn't match config (expansion/contraction happened)
            let is_stale = if let Some(ref mgr) = self.cluster_manager {
                let healthy_nodes = mgr.get_healthy_nodes();
                let has_unhealthy_primary = table
                    .assignments
                    .values()
                    .any(|a| !healthy_nodes.contains(&a.primary_node));

                // Check if shard count in config differs from table
                let shard_count_mismatch = if let Ok(db) = self.storage.get_database(database) {
                    if let Ok(coll) = db.get_collection(collection) {
                        if let Some(config) = coll.get_shard_config() {
                            config.num_shards != table.num_shards
                        } else {
                            false
                        }
                    } else {
                        false
                    }
                } else {
                    false
                };

                has_unhealthy_primary || shard_count_mismatch
            } else {
                false
            };

            if !is_stale {
                return Some(table);
            }
            tracing::debug!("Cached shard table {} is stale (unhealthy primaries or shard count mismatch), checking storage for update", key);
        }

        tracing::debug!("Shard table {} not in cache, checking storage", key);

        // Slow path: Check storage and reconstruct if exists
        // This handles cases where node restarted or collection was created via API without coordinator
        if let Ok(db) = self.storage.get_database(database) {
            if let Ok(coll) = db.get_collection(collection) {
                // Skip non-sharded collections - they don't need shard tables
                let shard_config = coll.get_shard_config();
                if shard_config.is_none()
                    || shard_config.as_ref().map(|c| c.num_shards).unwrap_or(0) == 0
                {
                    return None;
                }

                // Try to load persisted table first (preserves assignments)
                if let Some(table) = coll.get_stored_shard_table() {
                    tracing::debug!("Loaded shard table {} from storage (missed cache)", key);
                    self.shard_tables
                        .write()
                        .unwrap()
                        .insert(key.clone(), table.clone());
                    return Some(table);
                } else {
                    tracing::debug!("No persisted shard table found for {}", key);
                }

                if let Some(config) = coll.get_shard_config() {
                    // Fallback: Reconstruct table (fresh computation)
                    // This creates new assignments! Only happens if persistence missing.
                    if let Ok(table) = self.compute_shard_table(database, collection, &config) {
                        tracing::info!("Computed fresh shard table for {} (fallback)", key);
                        // Persist it now so we don't lose it again
                        let _ = coll.set_shard_table(&table);

                        // Cache it
                        self.shard_tables
                            .write()
                            .unwrap()
                            .insert(key, table.clone());
                        return Some(table);
                    }
                }
            } else {
                tracing::warn!(
                    "Collection {} not found during shard table lookup (db: {})",
                    collection,
                    database
                );
            }
        } else {
            tracing::warn!("Database {} not found during shard table lookup", database);
        }

        None
    }

    /// Initialize sharding for a collection
    pub fn init_collection(
        &self,
        database: &str,
        collection: &str,
        config: &CollectionShardConfig,
    ) -> Result<ShardTable, String> {
        let table = self.compute_shard_table(database, collection, config)?;
        let key = format!("{}.{}", database, collection);

        // Save to storage
        if let Ok(db) = self.storage.get_database(database) {
            if let Ok(coll) = db.get_collection(collection) {
                let _ = coll.set_shard_table(&table);
            }
        }

        self.shard_tables
            .write()
            .unwrap()
            .insert(key, table.clone());
        Ok(table)
    }

    /// Update local shard table cache (used when receiving updates from coordinator)
    pub fn update_shard_table_cache(&self, table: ShardTable) {
        let key = format!("{}.{}", table.database, table.collection);
        if let Ok(mut tables) = self.shard_tables.write() {
            tables.insert(key.clone(), table.clone());
            tracing::info!("CACHE: Updated shard table for {}", key);

            // Also persist to local storage (so it survives restart)
            if let Ok(db) = self.storage.get_database(&table.database) {
                if let Ok(coll) = db.get_collection(&table.collection) {
                    let _ = coll.set_shard_table(&table);
                }
            }
        }
    }

    /// Compute shard table assignments based on current cluster state
    /// Only uses HEALTHY nodes to ensure data availability
    fn compute_shard_table(
        &self,
        database: &str,
        collection: &str,
        config: &CollectionShardConfig,
    ) -> Result<ShardTable, String> {
        // Get HEALTHY nodes only (not all members - dead nodes should not get shards)
        let nodes = if let Some(ref mgr) = self.cluster_manager {
            let healthy = mgr.get_healthy_nodes();
            // Sort to ensure deterministic assignment
            let mut node_ids: Vec<String> = healthy.into_iter().collect();
            node_ids.sort();
            node_ids
        } else {
            vec!["local".to_string()]
        };

        if nodes.is_empty() {
            return Err("No nodes available".to_string());
        }

        let assignments = crate::sharding::distribution::compute_assignments(
            &nodes,
            config.num_shards,
            config.replication_factor,
            None, // Initial computation has no history
        )?;

        Ok(ShardTable {
            database: database.to_string(),
            collection: collection.to_string(),
            num_shards: config.num_shards,
            replication_factor: config.replication_factor,
            shard_key: config.shard_key.clone(),
            assignments,
        })
    }

    /// Route a document key to a shard
    pub fn route(&self, key: &str, num_shards: u16) -> u16 {
        crate::sharding::router::ShardRouter::route(key, num_shards)
    }

    /// Check if this node should store a shard
    pub fn is_shard_replica(
        shard_id: u16,
        node_index: usize,
        replication_factor: u16,
        num_nodes: usize,
    ) -> bool {
        crate::sharding::router::ShardRouter::is_shard_replica(
            shard_id,
            node_index,
            replication_factor,
            num_nodes,
        )
    }

    /// Insert batch with shard-aware distribution
    pub async fn insert_batch_sharded(
        &self,
        _database: &str,
        _collection: &str,
        documents: Vec<serde_json::Value>,
    ) -> Result<Vec<serde_json::Value>, String> {
        // For now, just return documents - actual distribution would be implemented
        // when full shard coordination is needed
        Ok(documents)
    }

    /// Get all node addresses in the cluster
    pub fn get_node_addresses(&self) -> Vec<String> {
        if let Some(ref mgr) = self.cluster_manager {
            mgr.state()
                .get_all_members()
                .into_iter()
                .map(|m| m.node.address.clone())
                .collect()
        } else {
            vec!["local".to_string()]
        }
    }

    /// Get all node IDs in the cluster
    pub fn get_node_ids(&self) -> Vec<String> {
        if let Some(ref mgr) = self.cluster_manager {
            mgr.state()
                .get_all_members()
                .into_iter()
                .map(|m| m.node.id.clone())
                .collect()
        } else {
            vec!["local".to_string()]
        }
    }

    /// Get this node's address
    pub fn my_address(&self) -> String {
        if let Some(ref mgr) = self.cluster_manager {
            mgr.get_local_address()
        } else {
            "local".to_string()
        }
    }

    /// Get API address for a specific node (for scatter-gather queries)
    pub fn get_node_api_address(&self, node_id: &str) -> Option<String> {
        if let Some(ref mgr) = self.cluster_manager {
            mgr.get_node_api_address(node_id)
        } else {
            None
        }
    }

    /// Get count of healthy nodes in the cluster
    pub fn get_healthy_node_count(&self) -> usize {
        if let Some(ref mgr) = self.cluster_manager {
            mgr.get_healthy_nodes().len()
        } else {
            1
        }
    }

    /// Calculate optimal replication factor for blob collections
    /// Formula: min(max(2, healthy_nodes / 2), MAX_BLOB_REPLICAS)
    /// Example: 10 nodes -> 5 replicas
    pub fn calculate_blob_replication_factor(&self) -> u16 {
        let healthy_count = self.get_healthy_node_count() as u16;
        (healthy_count / 2).clamp(Self::MIN_BLOB_REPLICAS, Self::MAX_BLOB_REPLICAS)
    }

    /// Get my node ID
    pub fn my_node_id(&self) -> String {
        if let Some(ref mgr) = self.cluster_manager {
            mgr.local_node_id()
        } else {
            "local".to_string()
        }
    }

    /// Reload shard tables from persistent storage
    /// This is called before cleanup to ensure we have the latest shard config
    /// (e.g., when another node reduced shard count)
    pub async fn reload_shard_tables_from_storage(&self) {
        tracing::info!("Reloading shard tables from storage");

        for db_name in self.storage.list_databases() {
            if let Ok(db) = self.storage.get_database(&db_name) {
                for coll_name in db.list_collections() {
                    // Skip system collections and physical shards
                    if coll_name.starts_with('_') || coll_name.contains("_s") {
                        continue;
                    }

                    if let Ok(coll) = db.get_collection(&coll_name) {
                        // Load shard table from storage
                        if let Some(table) = coll.get_stored_shard_table() {
                            let key = format!("{}.{}", db_name, coll_name);
                            if let Ok(mut tables) = self.shard_tables.write() {
                                tables.insert(key.clone(), table);
                                tracing::debug!("Reloaded shard table for {}", key);
                            }
                        }
                    }
                }
            }
        }
    }

    /// Implementation of BatchSender trait for ShardCoordinator
    /// This allows the migration module to use the coordinator's networking capabilities
    async fn send_migrated_batch(
        &self,
        db_name: &str,
        coll_name: &str,
        config: &CollectionShardConfig,
        batch: Vec<(String, serde_json::Value)>,
    ) -> Result<Vec<String>, String> {
        self.upsert_batch_to_shards(db_name, coll_name, config, batch)
            .await
            .map_err(|e| e.to_string())
    }

    /// Rebalance shards across healthy nodes
    ///
    /// This recalculates shard assignments based on current active nodes
    /// and redistributes shards to maintain equal distribution using the
    /// new resilient distribution logic.
    pub async fn rebalance(&self) -> Result<(), crate::error::DbError> {
        // Prevent concurrent rebalancing operations which can cause deadlocks
        if self.is_rebalancing.load(Ordering::SeqCst) {
            tracing::warn!(
                "REBALANCE: Another rebalancing operation is already in progress, skipping"
            );
            return Ok(());
        }
        self.is_rebalancing.store(true, Ordering::SeqCst);

        let initial_res = async {
            tracing::info!("Starting shard rebalance (New Implementation)");

            // DEADLOCK PREVENTION: Add coordination delay to prevent distributed deadlocks
            // When expanding shards (e.g., 3->4), all nodes start resharding simultaneously
            // and try to communicate with each other, potentially causing circular waits.
            // Nodes with higher IDs wait longer to allow lower-ID nodes to establish first.
            if let Some(ref mgr) = self.cluster_manager {
                let my_id = mgr.local_node_id();
                let my_hash = my_id
                    .bytes()
                    .fold(0u32, |acc, b| acc.wrapping_add(b as u32));
                let coordination_delay_ms = (my_hash % 3000) as u64; // 0-3 second staggered delay

                tracing::info!(
                    "REBALANCE: Waiting {}ms for coordination to prevent distributed deadlocks",
                    coordination_delay_ms
                );
                tokio::time::sleep(tokio::time::Duration::from_millis(coordination_delay_ms)).await;
            }

            // Get current active node IDs
            let nodes = if let Some(ref mgr) = self.cluster_manager {
                let healthy = mgr.get_healthy_nodes();
                let mut node_ids: Vec<String> = healthy.into_iter().collect();
                node_ids.sort();
                node_ids
            } else {
                vec!["local".to_string()]
            };

            if nodes.is_empty() {
                return Ok(());
            }

            // Iterate over all sharded collections
            let mut sharded_collections = Vec::new();
            for db_name in self.storage.list_databases() {
                if let Ok(db) = self.storage.get_database(&db_name) {
                    for coll_name in db.list_collections() {
                        if coll_name.starts_with('_') || coll_name.contains("_s") {
                            continue;
                        }
                        if let Ok(coll) = db.get_collection(&coll_name) {
                            if let Some(config) = coll.get_shard_config() {
                                sharded_collections.push((
                                    db_name.clone(),
                                    coll_name.clone(),
                                    config,
                                ));
                            }
                        }
                    }
                }
            }

            for (db_name, coll_name, config) in sharded_collections {
                let key = format!("{}.{}", db_name, coll_name);
                let mut needs_migration = false;
                let mut old_shards = config.num_shards;
                let mut old_assignments = HashMap::new();

                // Get current table to check for changes
                let current_table = self.get_shard_table(&db_name, &coll_name);

                // 1. Detect Config vs Table mismatch (Expansion/Contraction)
                if let Some(ref table) = current_table {
                    // Check if we need to adjust shard count based on node count
                    // (Auto-scale down if nodes < shards, but usually explicit config wins)
                    // Let's stick to explicit config for now, or the user's wish for resilience.
                    // The user asked for "Adding a new shard should reshard... Removing...".
                    // This implies config change drives it.

                    if table.num_shards != config.num_shards {
                        tracing::info!(
                            "REBALANCE: Config change detected for {}: {} -> {} shards",
                            key,
                            table.num_shards,
                            config.num_shards
                        );
                        old_shards = table.num_shards;
                        old_assignments = table.assignments.clone();
                        needs_migration = true;
                    }
                }

                // 2. Compute NEW Assignments
                let previous_assignments = current_table.as_ref().map(|t| &t.assignments);

                let new_assignments = match crate::sharding::distribution::compute_assignments(
                    &nodes,
                    config.num_shards,
                    config.replication_factor,
                    previous_assignments,
                ) {
                    Ok(a) => a,
                    Err(e) => {
                        tracing::error!("Failed to compute assignments for {}: {}", key, e);
                        continue;
                    }
                };

                // 3. Persist New Table
                let new_table = ShardTable {
                    database: db_name.clone(),
                    collection: coll_name.clone(),
                    num_shards: config.num_shards,
                    replication_factor: config.replication_factor,
                    shard_key: config.shard_key.clone(),
                    assignments: new_assignments.clone(),
                };

                // Save to storage
                if let Ok(db) = self.storage.get_database(&db_name) {
                    if let Ok(coll) = db.get_collection(&coll_name) {
                        let _ = coll.set_shard_table(&new_table);
                    }
                }
                // Update cache
                self.shard_tables
                    .write()
                    .unwrap()
                    .insert(key.clone(), new_table.clone());

                // 4. Create Physical Shards (if expansion or new)
                if let Err(e) = self.create_shards(&db_name, &coll_name).await {
                    tracing::error!("Failed to create shards for {}: {}", key, e);
                }

                // 5. Trigger Data Migration
                // Migration is needed if:
                // - Shard count changed (resharding)
                // - Assignments changed (rebalancing) - though reshard logic covers this too
                // For safety, we can run resharding check if ANYTHING changed.
                // But full scan is expensive.
                // If only assignments changed (nodes added/removed), strictly speaking we just need to move shards.
                // However, the user asked for "fully rewritten" and "reshard the data evenly".
                // Our `reshard_collection` handles moving misplaced docs.
                // If shard count is same, but primary owner changed, `reshard_collection` will see mismatched `new_shard_id` vs `current_physical_location`?
                // Wait, `reshard_collection` checks `ShardRouter::route(key, new_shards)`.
                // If `new_shards` == `old_shards`, routing doesn't change shard ID.
                // But if the *assignment* of that shard ID changed from Node A to Node B,
                // Node A (old primary) still has the data in `_sN`.
                // `reshard_collection` on Node A sees it has `_sN`.
                // It routes key -> `N`.
                // It checks if `N` != `s` (current physical). They are Equal.
                // So it does NOT move it.
                // PROBLEM: `reshard_collection` logic (as implemented in migration.rs) handles *SHARD ID* changes (rehashing).
                // It does NOT handle "Shard N moved from Node A to Node B".
                // Node A still has `_sN`. Node B has empty `_sN`.
                // We need `move_shard` logic for that.

                // Let's implement move logic here or inside migration?
                // Actually `reshard_collection` in migration.rs was designed for resharding (rehashing).

                // If only assignments changed, we should use the `heal_shards` mechanism or similar
                // by treating the new primary as "healthy replica" and old primary as "to be removed".
                // But `heal_shards` (existing) copies FROM source TO target.
                // We can use that!

                // But if shard COUNT determines we need migration (rehashing):
                if needs_migration {
                    // This handles 4->5 or 5->4.
                    // We need a struct that implements BatchSender.
                    // Since we are inside `rebalance`, we can't implement trait on `&self` easily if we need `async`.
                    // But we can genericize or wrap.
                    // Or implement BatchSender for ShardCoordinator wrapper.

                    tracing::info!(
                        "REBALANCE: Resharding {} from {} to {} shards",
                        key,
                        old_shards,
                        config.num_shards
                    );

                    let sender = CoordinatorBatchSender { coordinator: self };
                    let my_node_id = self.my_node_id();

                    // We need to determine if we act on old assignments (removed shards) or current
                    // The migration logic iterates `max(old, new)`.
                    let current_assignments_map = new_table.assignments.clone();

                    if let Err(_e) = crate::sharding::migration::reshard_collection(
                        &self.storage,
                        &sender,
                        &db_name,
                        &coll_name,
                        old_shards,
                        config.num_shards,
                        &my_node_id,
                        &old_assignments,
                        &current_assignments_map,
                    )
                    .await
                    {
                        tracing::error!("Resharding failed for {}: {}", key, _e);
                    }
                }

                // Handle removed shards during contraction
                if old_shards > config.num_shards {
                    // We shrunk, so we need to migrate data from removed shards on all nodes
                    if let Err(e) = self
                        .broadcast_reshard_removed_shards(
                            &db_name,
                            &coll_name,
                            old_shards,
                            config.num_shards,
                        )
                        .await
                    {
                        tracing::error!("Failed to broadcast reshard for removed shards: {}", e);
                    }
                }

                // After potentially re-hashing, we check for pure assignment moves (Node A -> Node B)
                // This is covered by `heal_shards` which ensures the new primary gets data,
                // and `cleanup_orphaned_shards` which removes data from old owners.
                // So we don't need explicit move logic here, provided `heal_shards` works.
            }

            Ok::<(), crate::error::DbError>(())
        }
        .await;

        // Mark resharding completed - this delays healing for 60 seconds to allow stabilization
        self.mark_reshard_completed();
        self.is_rebalancing.store(false, Ordering::SeqCst);
        initial_res
    }

    /// Check if rebalancing is in progress
    pub fn is_rebalancing(&self) -> bool {
        self.is_rebalancing.load(Ordering::SeqCst)
    }

    /// Check if a node recently failed and came back online
    /// This helps avoid using stale data from nodes that just recovered
    fn was_recently_failed(&self, node_id: &str) -> bool {
        crate::sharding::healing::was_recently_failed(&self.recently_failed_nodes, node_id)
    }

    /// Record that a node failed (called when failover occurs)
    pub fn record_node_failure(&self, node_id: &str) {
        crate::sharding::healing::record_node_failure(&self.recently_failed_nodes, node_id);
    }

    /// Clear failure record when node is confirmed healthy
    pub fn clear_node_failure(&self, node_id: &str) {
        crate::sharding::healing::clear_node_failure(&self.recently_failed_nodes, node_id);
    }

    /// Clean up old failure records
    pub fn cleanup_old_failures(&self) {
        crate::sharding::healing::cleanup_old_failures(&self.recently_failed_nodes);
    }

    /// Broadcast reshard requests for removed shards to all nodes
    async fn broadcast_reshard_removed_shards(
        &self,
        db_name: &str,
        coll_name: &str,
        old_shards: u16,
        new_shards: u16,
    ) -> Result<(), crate::error::DbError> {
        crate::sharding::rebalance::broadcast_reshard_removed_shards(
            &self.cluster_manager,
            &self.cluster_secret(),
            db_name,
            coll_name,
            old_shards,
            new_shards,
        )
        .await
    }

    /// Check if we recently completed resharding (to avoid aggressive healing)
    fn check_recent_resharding(&self) -> bool {
        crate::sharding::rebalance::check_recent_resharding(
            &self.is_rebalancing,
            &self.last_reshard_time,
        )
    }

    /// Record that resharding has completed - used to prevent aggressive healing
    pub fn mark_reshard_completed(&self) {
        crate::sharding::rebalance::mark_reshard_completed(&self.last_reshard_time);
    }

    /// Check if resharding should be paused due to cluster health issues
    fn should_pause_resharding(&self) -> bool {
        crate::sharding::healing::should_pause_resharding(
            &self.cluster_manager,
            &self.recently_failed_nodes,
        )
    }

    /// Clear failure records for nodes that are currently healthy
    pub fn clear_failures_for_healthy_nodes(&self) {
        crate::sharding::healing::clear_failures_for_healthy_nodes(
            &self.recently_failed_nodes,
            &self.cluster_manager,
        );
    }

    /// Repair sharded collection by checking for misplaced documents and fixing them
    /// This cleans up duplicates left over from failed migration cleanups
    pub async fn repair_collection(
        &self,
        db_name: &str,
        coll_name: &str,
    ) -> Result<String, String> {
        let db = self
            .storage
            .get_database(db_name)
            .map_err(|e| e.to_string())?;
        let main_coll = db.get_collection(coll_name).map_err(|e| e.to_string())?;
        let config = main_coll
            .get_shard_config()
            .ok_or("Missing shard config".to_string())?;

        let mut report = String::new();
        let mut total_fixed = 0;
        let mut total_moved = 0;
        let mut total_errors = 0;

        report.push_str(&format!(
            "Repairing {}.{} (Num Shards: {})\n",
            db_name, coll_name, config.num_shards
        ));

        // Iterate through ALL potential physical shards (current num_shards)
        // Note: usage of 0..num_shards checks shards that SHOULD exist.
        // But duplicates might be in orphaned shards too?
        // Orphaned shards are usually removed by `remove_orphaned_shards`.
        // Duplicates here are likely in shards 0..3 (if expanded 3->4).
        // Check 0..config.num_shards.
        for s in 0..config.num_shards {
            let physical_name = format!("{}_s{}", coll_name, s);

            if let Ok(physical_coll) = db.get_collection(&physical_name) {
                let documents = physical_coll.all();
                let doc_count = documents.len();
                let mut shard_fixed = 0;
                let mut shard_moved = 0;

                tracing::info!(
                    "REPAIR: Scanning shard {} ({} docs)...",
                    physical_name,
                    doc_count
                );

                let mut redundant_keys = Vec::new();
                let mut misplaced_docs = Vec::new();
                let mut misplaced_keys = Vec::new(); // Keep track of keys for deletion after move

                // 1. Scan and Classify
                for doc in documents {
                    let id_str = doc.key.clone();
                    let route_key = doc.key.clone();

                    let target_shard =
                        crate::sharding::router::ShardRouter::route(&route_key, config.num_shards);

                    if target_shard != s {
                        // Document is misplaced!

                        // Check if it exists in expected location
                        let exists = self.get(db_name, coll_name, &id_str).await.is_ok();

                        if exists {
                            // It exists in target -> Redundant Duplicate
                            redundant_keys.push(id_str);
                            shard_fixed += 1;
                        } else {
                            // It DOES NOT exist -> Misplaced (needs move)
                            misplaced_docs.push(doc.to_value());
                            misplaced_keys.push(id_str);
                        }
                    }
                }

                // 2. Batch Move Misplaced Docs
                if !misplaced_docs.is_empty() {
                    let total_to_move = misplaced_docs.len();
                    tracing::info!(
                        "REPAIR: Moving {} misplaced docs from {}...",
                        total_to_move,
                        physical_name
                    );

                    match self
                        .insert_batch(db_name, coll_name, &config, misplaced_docs)
                        .await
                    {
                        Ok((success, fail)) => {
                            if fail == 0 {
                                // Move successful (all), now we can delete them from source
                                redundant_keys.extend(misplaced_keys);
                                shard_moved += success; // Actually moved
                            } else {
                                // Partial failure. Safety check: DO NOT DELETE from source to avoid data loss.
                                // We could try to identify which failed, but insert_batch doesn't return that.
                                // User can run repair again.
                                tracing::warn!("REPAIR: Batch move had failures (success={}, fail={}). Skipping delete for safety.", success, fail);
                                total_errors += fail;
                            }
                        }
                        Err(e) => {
                            tracing::error!(
                                "REPAIR: Batch move failed for {}: {}",
                                physical_name,
                                e
                            );
                            total_errors += 1;
                            // We do NOT delete misplaced_keys if move failed.
                        }
                    }
                }

                // 3. Batch Delete Redundant Docs
                if !redundant_keys.is_empty() {
                    match physical_coll.delete_batch(redundant_keys) {
                        Ok(_n) => {
                            // n duplicates deleted
                            // shard_fixed/shard_moved counts track logic, n tracks actual deletes
                        }
                        Err(e) => {
                            tracing::error!(
                                "REPAIR: Batch delete failed for {}: {}",
                                physical_name,
                                e
                            );
                            total_errors += 1;
                        }
                    }
                }

                if shard_fixed > 0 || shard_moved > 0 {
                    report.push_str(&format!(
                        "  Shard {}: Removed {} duplicates (already in target), Moved {} docs\n",
                        s, shard_fixed, shard_moved
                    ));
                    total_fixed += shard_fixed;
                    total_moved += shard_moved;
                }
            }
        }

        report.push_str(&format!("----------------------------------\nTotal: {} duplicates removed, {} docs moved, {} errors.\n", total_fixed, total_moved, total_errors));
        tracing::info!("{}", report);
        Ok(report)
    }

    /// Promote a healthy replica to be the new primary for a shard
    /// Returns the new primary node ID if successful
    pub fn promote_replica(
        &self,
        database: &str,
        collection: &str,
        shard_id: u16,
    ) -> Option<String> {
        let key = format!("{}.{}", database, collection);
        let mut table_to_persist = None;
        let mut result = None;

        {
            let mut tables = self.shard_tables.write().ok()?;
            let table = tables.get_mut(&key)?;

            let assignment = table.assignments.get(&shard_id)?;

            // Find a healthy replica
            if let Some(mgr) = &self.cluster_manager {
                for replica in &assignment.replica_nodes {
                    if mgr.is_node_healthy(replica) {
                        // Promote this replica to primary
                        let new_primary = replica.clone();
                        let old_primary = assignment.primary_node.clone();

                        // Update the assignment
                        let mut new_replicas: Vec<String> = assignment
                            .replica_nodes
                            .iter()
                            .filter(|n| *n != &new_primary)
                            .cloned()
                            .collect();

                        // Old primary becomes a replica (for when it comes back)
                        new_replicas.push(old_primary.clone());

                        table.assignments.insert(
                            shard_id,
                            ShardAssignment {
                                shard_id,
                                primary_node: new_primary.clone(),
                                replica_nodes: new_replicas,
                            },
                        );

                        tracing::warn!(
                            "FAILOVER: Promoted {} to primary for shard {} (was: {})",
                            new_primary,
                            shard_id,
                            old_primary
                        );

                        // Record that the old primary failed (for future healing decisions)
                        self.record_node_failure(&old_primary);

                        table_to_persist = Some(table.clone());
                        result = Some(new_primary);
                        break;
                    }
                }
            }
        } // Drop lock

        // Persist the changes
        if let Some(table) = table_to_persist {
            if let Ok(db) = self.storage.get_database(database) {
                if let Ok(coll) = db.get_collection(collection) {
                    let _ = coll.set_shard_table(&table);
                }
            }
        }

        result
    }

    /// Heal shards by creating new replicas when nodes are unhealthy
    /// This maintains the replication factor when nodes fail
    pub async fn heal_shards(&self) -> Result<usize, crate::error::DbError> {
        // Skip healing if rebalancing is in progress to prevent data duplication
        if self.is_rebalancing() {
            tracing::debug!("HEAL: Skipping - rebalancing in progress");
            return Ok(0);
        }

        // Skip aggressive healing right after resharding to allow assignments to stabilize
        // Check if we recently completed resharding by looking at a timestamp or flag
        // For now, be more conservative and only heal shards that clearly need it
        let recently_resharded = self.check_recent_resharding();
        if recently_resharded {
            tracing::debug!(
                "HEAL: Skipping aggressive healing - recently resharded, allowing stabilization"
            );
            return Ok(0);
        }

        let mgr = match &self.cluster_manager {
            Some(m) => m,
            None => return Ok(0), // No cluster manager, nothing to heal
        };

        let healthy_nodes = mgr.get_healthy_nodes();
        if healthy_nodes.is_empty() {
            return Ok(0);
        }

        // Clear failure records for nodes that are now healthy
        self.clear_failures_for_healthy_nodes();

        let my_node_id = self.my_node_id();
        let mut healed_count = 0usize;

        tracing::debug!(
            "HEAL: Starting shard healing check. Healthy nodes: {:?}",
            healthy_nodes
        );

        // Get all shard tables
        let tables: Vec<(String, ShardTable)> = {
            let guard = self
                .shard_tables
                .read()
                .map_err(|_| crate::error::DbError::InternalError("Lock poisoned".to_string()))?;
            guard.iter().map(|(k, v)| (k.clone(), v.clone())).collect()
        };

        tracing::debug!("HEAL: Checking {} shard tables", tables.len());

        for (key, table) in &tables {
            let parts: Vec<&str> = key.split('.').collect();
            if parts.len() != 2 {
                continue;
            }
            let (database, collection) = (parts[0], parts[1]);

            // Get collection shard config for replication factor
            let replication_factor = if let Ok(db) = self.storage.get_database(database) {
                if let Ok(coll) = db.get_collection(collection) {
                    coll.get_shard_config()
                        .map(|c| c.replication_factor)
                        .unwrap_or(1)
                } else {
                    1
                }
            } else {
                1
            };

            for (shard_id, assignment) in &table.assignments {
                // Check if primary is unhealthy
                let primary_healthy = healthy_nodes.contains(&assignment.primary_node);

                // Count healthy replicas
                let healthy_replicas: Vec<&String> = assignment
                    .replica_nodes
                    .iter()
                    .filter(|n| healthy_nodes.contains(*n))
                    .collect();

                // Need (replication_factor - 1) replicas (primary is 1, replicas are the rest)
                let needed_replicas = (replication_factor as usize).saturating_sub(1);
                let current_replicas = healthy_replicas.len();

                tracing::debug!(
                    "HEAL: Shard {}/{}/s{}: primary={} (healthy={}), replicas={:?} (healthy={:?}), needed={}, current={}",
                    database, collection, shard_id,
                    assignment.primary_node, primary_healthy,
                    assignment.replica_nodes, healthy_replicas,
                    needed_replicas, current_replicas
                );

                if !primary_healthy || current_replicas < needed_replicas {
                    // Find a healthy node that doesn't already have this shard
                    // IMPORTANT: Only exclude HEALTHY nodes that have the shard.
                    // Dead nodes should NOT block choosing a healthy candidate.
                    let nodes_with_shard: std::collections::HashSet<&String> = {
                        let mut set = std::collections::HashSet::new();
                        // Only add primary if it's healthy
                        if primary_healthy {
                            set.insert(&assignment.primary_node);
                        }
                        // Only add replicas that are healthy
                        for replica in &assignment.replica_nodes {
                            if healthy_nodes.contains(replica) {
                                set.insert(replica);
                            }
                        }
                        set
                    };

                    let available_nodes: Vec<&String> = healthy_nodes
                        .iter()
                        .filter(|n| !nodes_with_shard.contains(*n))
                        .collect();

                    if available_nodes.is_empty() {
                        tracing::debug!("HEAL: No available nodes to heal shard {}/{}/s{} (all nodes already have this shard assigned)",
                            database, collection, shard_id);
                        continue;
                    }

                    // Pick a node (round-robin based on shard_id for distribution)
                    let target_node =
                        available_nodes[*shard_id as usize % available_nodes.len()].clone();

                    // Find a source node (healthy primary or replica)
                    // Prefer nodes that haven't recently failed to avoid stale data
                    let source_node = if primary_healthy
                        && !self.was_recently_failed(&assignment.primary_node)
                    {
                        assignment.primary_node.clone()
                    } else if let Some(replica) = healthy_replicas
                        .iter()
                        .find(|r| !self.was_recently_failed(r))
                    {
                        (*replica).clone()
                    } else if primary_healthy {
                        // Fallback to primary even if recently failed (better than no source)
                        tracing::warn!(
                            "HEAL: Using recently failed primary {} as source for {}/{}/s{}",
                            assignment.primary_node,
                            database,
                            collection,
                            shard_id
                        );
                        assignment.primary_node.clone()
                    } else if let Some(replica) = healthy_replicas.first() {
                        // Fallback to any healthy replica
                        tracing::warn!(
                            "HEAL: Using recently failed replica {} as source for {}/{}/s{}",
                            replica,
                            database,
                            collection,
                            shard_id
                        );
                        (*replica).clone()
                    } else {
                        tracing::warn!("HEAL: Skipping shard {}/{}/s{} - no suitable source available (all candidates recently failed or unhealthy)",
                            database, collection, shard_id);
                        continue;
                    };

                    tracing::info!(
                        "HEAL: Creating replica for shard {}/{}/s{} on {} (source: {})",
                        database,
                        collection,
                        shard_id,
                        target_node,
                        source_node
                    );

                    // If target is us, copy data from source
                    // If target is another node, tell that node to copy from source
                    let physical_coll = format!("{}_s{}", collection, shard_id);

                    if target_node == my_node_id {
                        // We delegate the "Do I need to copy?" check to the copy function itself
                        // This allows checking for Stale data (Count mismatch) instead of just "Empty vs Non-Empty"
                        if let Err(e) = self
                            .copy_shard_from_source(database, &physical_coll, &source_node)
                            .await
                        {
                            tracing::error!("HEAL: Failed to copy shard locally: {}", e);
                            continue;
                        }
                    } else {
                        // Tell target node to copy from source
                        if let Some(target_addr) = mgr.get_node_api_address(&target_node) {
                            let url = format!(
                                "http://{}/_api/database/{}/collection/{}/_copy_shard",
                                target_addr, database, physical_coll
                            );
                            let secret = self.cluster_secret();

                            let source_addr =
                                mgr.get_node_api_address(&source_node).unwrap_or_default();

                            let client = get_http_client();
                            let res = client
                                .post(&url)
                                .header("X-Cluster-Secret", &secret)
                                .header("X-Shard-Direct", "true") // Required for auth bypass
                                .json(&serde_json::json!({ "source_address": source_addr }))
                                .timeout(std::time::Duration::from_secs(60))
                                .send()
                                .await;

                            if let Err(e) = res {
                                tracing::error!(
                                    "HEAL: Failed to trigger copy on {}: {}",
                                    target_node,
                                    e
                                );
                                continue;
                            }
                        }
                    }

                    // Update shard table with new replica
                    {
                        let mut tables = self.shard_tables.write().map_err(|_| {
                            crate::error::DbError::InternalError("Lock poisoned".to_string())
                        })?;
                        if let Some(table) = tables.get_mut(key) {
                            if let Some(assignment) = table.assignments.get_mut(shard_id) {
                                if !assignment.replica_nodes.contains(&target_node) {
                                    assignment.replica_nodes.push(target_node.clone());
                                    healed_count += 1;
                                    tracing::info!(
                                        "HEAL: Added {} as replica for shard {}",
                                        target_node,
                                        shard_id
                                    );
                                }
                            }
                        }
                    }
                }
            }
        }

        if healed_count > 0 {
            tracing::info!("HEAL: Successfully healed {} shard replicas", healed_count);
        }

        // Additional check: Resync stale replicas AND primaries
        // If this node is a replica/primary but has significantly less data than the source, resync
        for (key, table) in &tables {
            let parts: Vec<&str> = key.split('.').collect();
            if parts.len() != 2 {
                continue;
            }
            let (database, collection) = (parts[0], parts[1]);

            for (shard_id, assignment) in &table.assignments {
                // Check if this node is involved in this shard (replica OR primary)
                let is_replica = assignment.replica_nodes.contains(&my_node_id);
                let is_primary = assignment.primary_node == my_node_id;

                if !is_replica && !is_primary {
                    continue;
                }

                tracing::debug!(
                    "HEAL: Node {} is {} for {}_s{}",
                    my_node_id,
                    if is_primary { "PRIMARY" } else { "REPLICA" },
                    collection,
                    shard_id
                );

                // Get local document count
                let physical_coll = format!("{}_s{}", collection, shard_id);
                let local_count = if let Ok(db) = self.storage.get_database(database) {
                    if let Ok(coll) = db.get_collection(&physical_coll) {
                        coll.count()
                    } else {
                        0
                    }
                } else {
                    0
                };

                // Find a healthy source node to sync from
                // If we're a replica, use the primary. If we're the primary, use a healthy replica.
                let source_node = if is_primary {
                    // We're primary - find a healthy replica to sync from
                    assignment
                        .replica_nodes
                        .iter()
                        .find(|r| healthy_nodes.contains(*r))
                        .cloned()
                } else {
                    // We're a replica - use the primary if healthy
                    if healthy_nodes.contains(&assignment.primary_node) {
                        Some(assignment.primary_node.clone())
                    } else {
                        None
                    }
                };

                let source_node = match source_node {
                    Some(n) => n,
                    None => continue, // No healthy source available
                };

                // Get source document count
                let source_count = if let Some(source_addr) = mgr.get_node_api_address(&source_node)
                {
                    let url = format!(
                        "http://{}/_api/database/{}/collection/{}/count",
                        source_addr, database, physical_coll
                    );
                    let secret = self.cluster_secret();
                    let client = get_http_client();

                    match client
                        .get(&url)
                        .header("X-Cluster-Secret", &secret)
                        .header("X-Shard-Direct", "true") // Required for auth bypass
                        .timeout(std::time::Duration::from_secs(5))
                        .send()
                        .await
                    {
                        Ok(res) if res.status().is_success() => {
                            if let Ok(body) = res.json::<serde_json::Value>().await {
                                body.get("count").and_then(|c| c.as_u64()).unwrap_or(0) as usize
                            } else {
                                0
                            }
                        }
                        Ok(res) => {
                            tracing::warn!(
                                "HEAL: Count request failed for {}_s{} from {}: status {}",
                                collection,
                                shard_id,
                                source_node,
                                res.status()
                            );
                            0
                        }
                        Err(e) => {
                            tracing::warn!(
                                "HEAL: Count request error for {}_s{} from {}: {}",
                                collection,
                                shard_id,
                                source_node,
                                e
                            );
                            0
                        }
                    }
                } else {
                    0
                };

                // Log the count comparison for debugging
                tracing::debug!(
                    "HEAL: {}_s{}: local_count={}, source_count={}, source_node={}",
                    collection,
                    shard_id,
                    local_count,
                    source_count,
                    source_node
                );

                // If local has significantly fewer docs (>10% difference OR local is 0 with source > 0), resync
                let local_behind = source_count.saturating_sub(local_count);
                let local_ahead = local_count.saturating_sub(source_count);
                let threshold = if local_count == 0 && source_count > 0 {
                    1 // If we have 0 docs and source has any, always sync
                } else {
                    std::cmp::max(source_count / 10, 100)
                };

                // Case 1: Local is behind source (missing docs) - copy from source
                if local_behind >= threshold && source_count > 0 {
                    tracing::warn!(
                        "HEAL: Stale {} detected for {}_s{}: local={}, source={}, resyncing (behind)",
                        if is_primary { "primary" } else { "replica" },
                        collection, shard_id, local_count, source_count
                    );

                    // Resync by copying all data from source
                    if let Err(e) = self
                        .copy_shard_from_source(database, &physical_coll, &source_node)
                        .await
                    {
                        tracing::error!(
                            "HEAL: Failed to resync stale {}_s{}: {}",
                            collection,
                            shard_id,
                            e
                        );
                    } else {
                        healed_count += 1;
                        tracing::info!(
                            "HEAL: Resynced stale {}_s{} from {}",
                            collection,
                            shard_id,
                            source_node
                        );
                    }
                }
                // Case 2: Local REPLICA is ahead of PRIMARY (has stale data) - truncate and resync
                else if !is_primary && local_ahead > 0 && source_count > 0 {
                    tracing::warn!(
                        "HEAL: Replica {}_s{} has MORE docs than primary: local={}, source={}. Truncating and resyncing.",
                        collection, shard_id, local_count, source_count
                    );

                    // Truncate local shard
                    if let Ok(db) = self.storage.get_database(database) {
                        if let Ok(coll) = db.get_collection(&physical_coll) {
                            let _ = coll.truncate();
                        }
                    }

                    // Resync from primary
                    if let Err(e) = self
                        .copy_shard_from_source(database, &physical_coll, &source_node)
                        .await
                    {
                        tracing::error!(
                            "HEAL: Failed to resync replica {}_s{}: {}",
                            collection,
                            shard_id,
                            e
                        );
                    } else {
                        healed_count += 1;
                        tracing::info!(
                            "HEAL: Resynced oversized replica {}_s{} from primary {}",
                            collection,
                            shard_id,
                            source_node
                        );
                    }
                }
            }
        }

        Ok(healed_count)
    }

    /// Clean up orphaned shard collections on this node
    ///
    /// When a node restarts and its shards have been reassigned to other nodes,
    /// this function removes the local physical shard collections that are no longer
    /// assigned to this node (neither as primary nor replica).
    pub async fn cleanup_orphaned_shards(&self) -> Result<usize, crate::error::DbError> {
        crate::sharding::cleanup::cleanup_orphaned_shards(
            &self.storage,
            &self.shard_tables,
            &self.my_node_id(),
        )
        .await
    }

    /// Broadcast cleanup to all cluster nodes
    /// This ensures all nodes remove their orphaned shard collections after contraction
    pub async fn broadcast_cleanup_orphaned_shards(&self) -> Result<(), crate::error::DbError> {
        crate::sharding::cleanup::broadcast_cleanup_orphaned_shards(
            &self.storage,
            &self.cluster_manager,
            &self.shard_tables,
            &self.my_node_id(),
            &self.cluster_secret(),
        )
        .await
    }

    /// Copy shard data from a source node
    async fn copy_shard_from_source(
        &self,
        database: &str,
        physical_coll: &str,
        source_node: &str,
    ) -> Result<usize, crate::error::DbError> {
        use base64::{engine::general_purpose, Engine as _};

        let mgr = self.cluster_manager.as_ref().ok_or_else(|| {
            crate::error::DbError::InternalError("No cluster manager".to_string())
        })?;

        let source_addr = mgr.get_node_api_address(source_node).ok_or_else(|| {
            crate::error::DbError::InternalError("Source node address not found".to_string())
        })?;

        // Step 1: Check Source Count using Metadata API
        let secret = self.cluster_secret();
        let client = get_http_client();

        // Use standard Collection API to get metadata (count)
        let meta_url = format!(
            "http://{}/_api/database/{}/collection/{}",
            source_addr, database, physical_coll
        );
        let meta_res = client
            .get(&meta_url)
            .header("X-Cluster-Secret", &secret)
            .header("X-Shard-Direct", "true")
            .timeout(std::time::Duration::from_secs(10))
            .send()
            .await;

        let mut source_count = 0;
        let mut check_count = false;

        if let Ok(res) = meta_res {
            if res.status().is_success() {
                if let Ok(json) = res.json::<serde_json::Value>().await {
                    if let Some(c) = json.get("count").and_then(|v| v.as_u64()) {
                        source_count = c as usize;
                        check_count = true;
                    }
                }
            }
        }

        // Local Check & Prep
        let db = self.storage.get_database(database)?;
        let coll = match db.get_collection(physical_coll) {
            Ok(c) => c,
            Err(_) => {
                db.create_collection(physical_coll.to_string(), None)?;
                db.get_collection(physical_coll)?
            }
        };

        // Optimize: If counts match and NOT a blob collection (doc count doesn't track chunks), skip
        // For blob collections, we always resync if triggered to ensure chunks are present
        let is_blob = coll.get_type() == "blob";
        if check_count {
            let local_count = coll.count();
            if local_count == source_count && !is_blob {
                return Ok(0);
            }
            if local_count != source_count || is_blob {
                tracing::info!("HEAL: Mismatch or Blob forced sync for {}/{} (Local: {}, Source: {}). Syncing.", database, physical_coll, local_count, source_count);
                let _ = coll.truncate();
            }
        }

        // Use EXPORT endpoint to stream all data (Docs + Blob Chunks)
        let scheme = std::env::var("SOLIDB_CLUSTER_SCHEME").unwrap_or_else(|_| "http".to_string());
        let url = format!(
            "{}://{}/_api/database/{}/collection/{}/export",
            scheme, source_addr, database, physical_coll
        );

        let mut resp = client
            .get(&url)
            .header("X-Cluster-Secret", &secret)
            .header("X-Shard-Direct", "true")
            .timeout(std::time::Duration::from_secs(3600)) // Long timeout for large shards
            .send()
            .await
            .map_err(|e| {
                crate::error::DbError::InternalError(format!("Export request failed: {}", e))
            })?;

        if !resp.status().is_success() {
            let status = resp.status();
            tracing::error!("HEAL: Export failed - status: {}, url: {}", status, url);
            return Err(crate::error::DbError::InternalError(format!(
                "Export failed with status {}",
                status
            )));
        }

        let mut batch_docs = Vec::with_capacity(1000);
        let mut total_copied = 0;
        let mut line_buffer = String::new();

        // Stream processing
        while let Ok(Some(chunk)) = resp.chunk().await {
            // Append chunk to buffer
            let chunk_str = String::from_utf8_lossy(&chunk);
            line_buffer.push_str(&chunk_str);

            // Process lines
            while let Some(pos) = line_buffer.find('\n') {
                let line: String = line_buffer.drain(..pos + 1).collect();
                let line = line.trim();
                if line.is_empty() {
                    continue;
                }

                if let Ok(mut doc) = serde_json::from_str::<serde_json::Value>(line) {
                    // Check if blob chunk
                    let is_blob_chunk = doc
                        .get("_type")
                        .and_then(|t| t.as_str())
                        .map(|t| t == "blob_chunk")
                        .unwrap_or(false);

                    if is_blob_chunk {
                        // Import Chunk immediately
                        if let (Some(key), Some(index), Some(data_b64)) = (
                            doc.get("_doc_key").and_then(|s| s.as_str()),
                            doc.get("_chunk_index").and_then(|n| n.as_u64()),
                            doc.get("_blob_data").and_then(|s| s.as_str()),
                        ) {
                            if let Ok(data) = general_purpose::STANDARD.decode(data_b64) {
                                if let Err(e) = coll.put_blob_chunk(key, index as u32, &data) {
                                    tracing::error!(
                                        "HEAL: Failed to write chunk {} for {}: {}",
                                        index,
                                        key,
                                        e
                                    );
                                }
                            }
                        }
                    } else {
                        // Clean metadata (same as import)
                        if let Some(obj) = doc.as_object_mut() {
                            obj.remove("_database");
                            obj.remove("_collection");
                            obj.remove("_shardConfig");
                        }

                        // Prepare for batch upsert
                        let key = doc
                            .get("_key")
                            .and_then(|k| k.as_str())
                            .unwrap_or("")
                            .to_string();
                        if !key.is_empty() {
                            batch_docs.push((key, doc));
                        }
                    }
                }
            }

            // Flush Batch if full
            if batch_docs.len() >= 1000 {
                let count = batch_docs.len();
                let batch_to_insert: Vec<(String, serde_json::Value)> =
                    std::mem::take(&mut batch_docs);
                if let Err(e) = coll.upsert_batch(batch_to_insert) {
                    tracing::error!("HEAL: Batch upsert failed: {}", e);
                } else {
                    total_copied += count;
                }
            }
        }

        // Final Flush
        if !batch_docs.len() > 0 {
            let count = batch_docs.len();
            if let Err(e) = coll.upsert_batch(batch_docs) {
                tracing::error!("HEAL: Final batch upsert failed: {}", e);
            } else {
                total_copied += count;
            }
        }

        tracing::info!(
            "HEAL: Copied {} docs (and associated chunks) to {}/{}",
            total_copied,
            database,
            physical_coll
        );
        Ok(total_copied)
    }

    /// Insert a batch of documents with shard coordination
    pub async fn insert_batch(
        &self,
        database: &str,
        collection: &str,
        config: &CollectionShardConfig,
        documents: Vec<serde_json::Value>,
    ) -> Result<(usize, usize), crate::error::DbError> {
        use crate::sharding::router::ShardRouter;
        use std::collections::HashMap;

        let table = self.get_shard_table(database, collection).ok_or_else(|| {
            crate::error::DbError::InternalError("Shard table not found".to_string())
        })?;

        let local_id = if let Some(mgr) = &self.cluster_manager {
            mgr.local_node_id()
        } else {
            "local".to_string()
        };

        // Group documents by shard
        let mut shard_batches: HashMap<u16, Vec<serde_json::Value>> = HashMap::new();

        for mut doc in documents {
            // Ensure _key exists
            let key = if let Some(k) = doc.get("_key").and_then(|v| v.as_str()) {
                k.to_string()
            } else {
                let k = uuid::Uuid::now_v7().to_string();
                if let Some(obj) = doc.as_object_mut() {
                    obj.insert("_key".to_string(), serde_json::Value::String(k.clone()));
                }
                k
            };

            // Determine shard
            let shard_key_value = if config.shard_key == "_key" {
                key
            } else {
                doc.get(&config.shard_key)
                    .and_then(|v| v.as_str())
                    .unwrap_or(&key)
                    .to_string()
            };

            let shard_id = ShardRouter::route(&shard_key_value, config.num_shards);
            shard_batches.entry(shard_id).or_default().push(doc);
        }

        let mut total_success = 0usize;
        let mut total_fail = 0usize;
        let client = get_http_client();
        let secret = self.cluster_secret();

        // Collect futures for parallel processing
        let mut local_batches = Vec::new();
        let mut remote_futures = Vec::new();

        // Separate local and remote batches
        for (shard_id, batch) in shard_batches {
            let physical_coll = format!("{}_s{}", collection, shard_id);

            let assignment = match table.assignments.get(&shard_id) {
                Some(a) => a,
                None => {
                    total_fail += batch.len();
                    continue;
                }
            };

            let primary_node = &assignment.primary_node;

            if primary_node == &local_id || primary_node == "local" {
                // Queue local batch (with shard_id for replica forwarding)
                local_batches.push((shard_id, physical_coll, batch));
            } else {
                // Queue remote batch as future
                if let Some(mgr) = &self.cluster_manager {
                    if let Some(addr) = mgr.get_node_api_address(primary_node) {
                        let url = format!(
                            "http://{}/_api/database/{}/document/{}/_batch",
                            addr, database, physical_coll
                        );
                        tracing::info!(
                            "INSERT BATCH: Queuing {} docs for remote shard {} at {}",
                            batch.len(),
                            physical_coll,
                            addr
                        );

                        let batch_size = batch.len();
                        let client = client.clone();
                        let secret = secret.clone();

                        let future = async move {
                            let res = client
                                .post(&url)
                                .header("X-Shard-Direct", "true")
                                .header("X-Cluster-Secret", &secret)
                                .json(&batch)
                                .send()
                                .await;

                            match res {
                                Ok(r) if r.status().is_success() => (batch_size, 0usize),
                                Ok(r) => {
                                    tracing::error!("Remote batch insert failed: {}", r.status());
                                    (0, batch_size)
                                }
                                Err(e) => {
                                    tracing::error!("Remote batch insert request failed: {}", e);
                                    (0, batch_size)
                                }
                            }
                        };
                        remote_futures.push(future);
                    } else {
                        total_fail += batch.len();
                    }
                } else {
                    total_fail += batch.len();
                }
            }
        }

        // Process local batches and forward to replicas
        let mut replica_futures = Vec::new();

        for (shard_id, physical_coll, batch) in local_batches {
            let db = self.storage.get_database(database)?;
            let coll = db.get_collection(&physical_coll)?;

            // Convert to keyed docs for upsert (prevents duplicates)
            let keyed_docs: Vec<(String, serde_json::Value)> = batch
                .iter()
                .map(|doc| {
                    let key = doc
                        .get("_key")
                        .and_then(|k| k.as_str())
                        .unwrap_or("")
                        .to_string();
                    (key, doc.clone())
                })
                .filter(|(key, _)| !key.is_empty())
                .collect();

            match coll.upsert_batch(keyed_docs) {
                Ok(count) => {
                    // NOTE: Do NOT log to replication log for sharded data!
                    // Shard data is partitioned - each node only stores its assigned shards.
                    // Instead, forward to REPLICA nodes for fault tolerance.
                    total_success += count;

                    // Forward to replica nodes for fault tolerance
                    if let Some(assignment) = table.assignments.get(&shard_id) {
                        if !assignment.replica_nodes.is_empty() {
                            if let Some(mgr) = &self.cluster_manager {
                                for replica_node in &assignment.replica_nodes {
                                    if let Some(addr) = mgr.get_node_api_address(replica_node) {
                                        let url = format!(
                                            "http://{}/_api/database/{}/document/{}/_replica",
                                            addr, database, physical_coll
                                        );
                                        tracing::debug!(
                                            "REPLICA: Forwarding {} docs to replica {} at {}",
                                            batch.len(),
                                            physical_coll,
                                            addr
                                        );

                                        let client = client.clone();
                                        let secret = secret.clone();
                                        let batch = batch.clone();

                                        let future = async move {
                                            let _ = client
                                                .post(&url)
                                                .header("X-Shard-Direct", "true")
                                                .header("X-Cluster-Secret", &secret)
                                                .json(&batch)
                                                .send()
                                                .await;
                                            // Replica failures are logged but don't affect success count
                                        };
                                        replica_futures.push(future);
                                    }
                                }
                            }
                        }
                    }
                }
                Err(_) => {
                    total_fail += batch.len();
                }
            }
        }

        // Process remote batches in PARALLEL
        if !remote_futures.is_empty() {
            let results = futures::future::join_all(remote_futures).await;
            for (success, fail) in results {
                total_success += success;
                total_fail += fail;
            }
        }

        // Process replica forwarding in PARALLEL (fire-and-forget, don't wait)
        if !replica_futures.is_empty() {
            futures::future::join_all(replica_futures).await;
        }

        Ok((total_success, total_fail))
    }

    /// Upsert a batch of documents to shards (insert-or-update to prevent duplicates)
    /// Used during resharding to avoid creating duplicate documents
    /// Upsert a batch of documents to their correct shards
    /// Returns a list of keys that were SUCCESSFULLY upserted
    /// This allows the caller to delete only the successful ones from source
    pub async fn upsert_batch_to_shards(
        &self,
        database: &str,
        collection: &str,
        config: &CollectionShardConfig,
        documents: Vec<(String, serde_json::Value)>, // (key, doc) pairs
    ) -> Result<Vec<String>, crate::error::DbError> {
        use crate::sharding::router::ShardRouter;
        use std::collections::HashMap;

        let table = self.get_shard_table(database, collection).ok_or_else(|| {
            crate::error::DbError::InternalError("Shard table not found".to_string())
        })?;

        let local_id = if let Some(mgr) = &self.cluster_manager {
            mgr.local_node_id()
        } else {
            "local".to_string()
        };

        // Group documents by target shard
        let mut shard_batches: HashMap<u16, Vec<(String, serde_json::Value)>> = HashMap::new();

        for (key, doc) in documents {
            let shard_key_value = if config.shard_key == "_key" {
                key.clone()
            } else {
                doc.get(&config.shard_key)
                    .and_then(|v| v.as_str())
                    .unwrap_or(&key)
                    .to_string()
            };

            let shard_id = ShardRouter::route(&shard_key_value, config.num_shards);
            shard_batches.entry(shard_id).or_default().push((key, doc));
        }

        let mut successful_keys: Vec<String> = Vec::new();

        // Process each shard batch
        // Add small delays between shards to prevent overwhelming the network during resharding
        for (idx, (shard_id, batch)) in shard_batches.into_iter().enumerate() {
            if idx > 0 {
                // Small delay to prevent all shards from being processed simultaneously
                tokio::time::sleep(tokio::time::Duration::from_millis(100)).await;
            }
            let physical_coll = format!("{}_s{}", collection, shard_id);
            // Collect keys for this batch to mark as success if operation succeeds
            let batch_keys: Vec<String> = batch.iter().map(|(k, _)| k.clone()).collect();
            let batch_len = batch_keys.len();

            let assignment = match table.assignments.get(&shard_id) {
                Some(a) => a,
                None => {
                    tracing::error!("UPSERT: No assignment found for shard {}", shard_id);
                    continue;
                }
            };

            let primary_node = &assignment.primary_node;

            if primary_node == &local_id || primary_node == "local" {
                // Local upsert - use Collection::upsert_batch to prevent duplicates
                let db = self.storage.get_database(database)?;
                let coll = match db.get_collection(&physical_coll) {
                    Ok(c) => c,
                    Err(_) => {
                        // Create shard if missing
                        db.create_collection(physical_coll.clone(), None)?;
                        db.get_collection(&physical_coll)?
                    }
                };

                match coll.upsert_batch(batch) {
                    Ok(_) => {
                        // All docs in batch succeeded (local atomic batch)
                        successful_keys.extend(batch_keys);
                    }
                    Err(e) => {
                        tracing::error!("UPSERT: Local upsert failed for {}: {}", physical_coll, e);
                    }
                }
            } else {
                // Remote upsert - forward via HTTP batch endpoint
                if let Some(mgr) = &self.cluster_manager {
                    if let Some(addr) = mgr.get_node_api_address(primary_node) {
                        // Circuit breaker: skip nodes that recently failed
                        if self.was_recently_failed(primary_node) {
                            tracing::warn!("UPSERT: Skipping batch to recently failed node {} (circuit breaker)", primary_node);
                            // Don't mark as successful - let migration handle this as a failure
                            break;
                        }

                        let url = format!(
                            "http://{}/_api/database/{}/document/{}/_batch",
                            addr, database, physical_coll
                        );
                        let secret = self.cluster_secret();
                        let client = get_http_client();

                        // Extract just values for the remote call
                        let values: Vec<serde_json::Value> =
                            batch.into_iter().map(|(_, v)| v).collect();

                        // Retry logic with exponential backoff for remote batch operations
                        let mut retry_count = 0;
                        const MAX_RETRIES: u32 = 3;
                        let mut last_error = None;

                        loop {
                            let timeout_duration = if retry_count == 0 {
                                std::time::Duration::from_secs(30)
                            } else {
                                // Exponential backoff: 30s, 60s, 120s
                                std::time::Duration::from_secs(30 * (1 << retry_count))
                            };

                            match tokio::time::timeout(
                                timeout_duration,
                                client
                                    .post(&url)
                                    .header("X-Shard-Direct", "true")
                                    .header("X-Migration", "true") // Prevent replica forwarding during resharding
                                    .header("X-Cluster-Secret", &secret)
                                    .json(&values)
                                    .send(),
                            )
                            .await
                            {
                                Ok(Ok(res)) => {
                                    if res.status().is_success() {
                                        // Success! Mark keys as successful
                                        successful_keys.extend(batch_keys);
                                        break;
                                    } else {
                                        let status = res.status();
                                        let err_msg = format!("HTTP {}", status);
                                        tracing::warn!("UPSERT: Remote batch request to {} failed: {} (attempt {}/{})",
                                            addr, err_msg, retry_count + 1, MAX_RETRIES + 1);
                                        last_error = Some(err_msg);

                                        if status.as_u16() >= 500 {
                                            // Server errors are retryable
                                            if retry_count < MAX_RETRIES {
                                                retry_count += 1;
                                                tokio::time::sleep(
                                                    std::time::Duration::from_millis(
                                                        1000 * (1 << retry_count),
                                                    ),
                                                )
                                                .await;
                                                continue;
                                            }
                                        }
                                        // Client errors or max retries reached
                                        break;
                                    }
                                }
                                Ok(Err(e)) => {
                                    tracing::warn!("UPSERT: Remote batch request to {} failed: {} (attempt {}/{})",
                                        addr, e, retry_count + 1, MAX_RETRIES + 1);
                                    last_error = Some(e.to_string());

                                    // Network errors are retryable
                                    if retry_count < MAX_RETRIES {
                                        retry_count += 1;
                                        tokio::time::sleep(std::time::Duration::from_millis(
                                            1000 * (1 << retry_count),
                                        ))
                                        .await;
                                        continue;
                                    }
                                    break;
                                }
                                Err(_) => {
                                    tracing::warn!("UPSERT: Remote batch request to {} timed out after {:?} (attempt {}/{})",
                                        addr, timeout_duration, retry_count + 1, MAX_RETRIES + 1);
                                    last_error =
                                        Some(format!("timeout after {:?}", timeout_duration));

                                    // Timeouts are retryable
                                    if retry_count < MAX_RETRIES {
                                        retry_count += 1;
                                        tokio::time::sleep(std::time::Duration::from_millis(
                                            1000 * (1 << retry_count),
                                        ))
                                        .await;
                                        continue;
                                    }
                                    break;
                                }
                            }
                        }

                        if successful_keys.is_empty() && batch_len > 0 {
                            // All retries failed, log final error and record node failure
                            tracing::error!("UPSERT: Remote batch request to {} failed after {} attempts. Last error: {}. Recording node as failed.",
                                addr, MAX_RETRIES + 1, last_error.unwrap_or("unknown".to_string()));
                            self.record_node_failure(primary_node);
                        }
                    } else {
                        tracing::error!(
                            "UPSERT: Primary node address unknown for {}",
                            primary_node
                        );
                    }
                }
            }
        }

        Ok(successful_keys)
    }

    /// Insert a single document with shard coordination
    pub async fn insert(
        &self,
        database: &str,
        collection: &str,
        config: &CollectionShardConfig,
        mut document: serde_json::Value,
    ) -> Result<serde_json::Value, crate::error::DbError> {
        use crate::sharding::router::ShardRouter;

        // 1. Determine Shard Key
        let key = if let Some(k) = document.get("_key").and_then(|v| v.as_str()) {
            k.to_string()
        } else {
            let k = uuid::Uuid::now_v7().to_string();
            if let Some(obj) = document.as_object_mut() {
                obj.insert("_key".to_string(), serde_json::Value::String(k.clone()));
            }
            k
        };

        let shard_key_value = if config.shard_key == "_key" {
            key.clone()
        } else {
            document
                .get(&config.shard_key)
                .and_then(|v| v.as_str())
                .unwrap_or(&key) // Fallback to key if shard key missing? Or Error?
                .to_string()
        };

        // 2. Route to Shard ID
        let shard_id = ShardRouter::route(&shard_key_value, config.num_shards);

        // 3. Get Physical Collection Name
        let physical_coll = format!("{}_s{}", collection, shard_id);

        // 4. Find Primary Node
        let table = self.get_shard_table(database, collection).ok_or_else(|| {
            crate::error::DbError::InternalError("Shard table not found".to_string())
        })?;

        let assignment = table.assignments.get(&shard_id).ok_or_else(|| {
            crate::error::DbError::InternalError("Shard assignment not found".to_string())
        })?;

        let primary_node = &assignment.primary_node;

        // 5. Check if Local
        let local_id = if let Some(mgr) = &self.cluster_manager {
            mgr.local_node_id()
        } else {
            "local".to_string()
        };

        if primary_node == &local_id || primary_node == "local" {
            // Write to LOCAL physical shard
            let db = self.storage.get_database(database)?;
            // Ensure physical collection exists (it should)
            let coll = db.get_collection(&physical_coll)?;
            let inserted = coll.insert(document)?;

            // NOTE: Do NOT log to replication log for sharded data!
            // Each node only stores its assigned shards - data is partitioned, not replicated.

            Ok(inserted.to_value())
        } else {
            // Check if primary is healthy
            let target_node = if let Some(mgr) = &self.cluster_manager {
                if mgr.is_node_healthy(primary_node) {
                    primary_node.clone()
                } else {
                    // Primary is unhealthy - promote a replica
                    tracing::warn!(
                        "Primary {} is unhealthy for shard {}, attempting failover",
                        primary_node,
                        shard_id
                    );
                    if let Some(new_primary) = self.promote_replica(database, collection, shard_id)
                    {
                        new_primary
                    } else {
                        return Err(crate::error::DbError::InternalError(format!(
                            "Primary {} unhealthy and no healthy replica for failover",
                            primary_node
                        )));
                    }
                }
            } else {
                primary_node.clone()
            };

            // Check if the new target is now local (we got promoted)
            if target_node == local_id {
                let db = self.storage.get_database(database)?;
                let coll = db.get_collection(&physical_coll)?;
                let inserted = coll.insert(document)?;
                return Ok(inserted.to_value());
            }

            // FORWARD to Remote Primary
            if let Some(mgr) = &self.cluster_manager {
                if let Some(addr) = mgr.get_node_api_address(&target_node) {
                    let client = get_http_client();
                    let url = format!(
                        "http://{}/_api/database/{}/document/{}",
                        addr, database, physical_coll
                    );

                    // Get Cluster Secret
                    let secret = self.cluster_secret();

                    let res = client
                        .post(&url)
                        .header("X-Shard-Direct", "true")
                        .header("X-Cluster-Secret", &secret)
                        .timeout(std::time::Duration::from_secs(10))
                        .json(&document)
                        .send()
                        .await
                        .map_err(|e| {
                            crate::error::DbError::InternalError(format!(
                                "Forwarding failed: {}",
                                e
                            ))
                        })?;

                    if res.status().is_success() {
                        let val: serde_json::Value = res.json().await.map_err(|e| {
                            crate::error::DbError::InternalError(format!("Invalid response: {}", e))
                        })?;
                        Ok(val)
                    } else {
                        Err(crate::error::DbError::InternalError(format!(
                            "Remote insert failed: {}",
                            res.status()
                        )))
                    }
                } else {
                    Err(crate::error::DbError::InternalError(format!(
                        "Target node {} address unknown",
                        target_node
                    )))
                }
            } else {
                Err(crate::error::DbError::InternalError(
                    "Cluster manager missing for remote write".to_string(),
                ))
            }
        }
    }

    /// Upload a blob with shard awareness
    /// Handles both metadata document routing and chunk distribution
    pub async fn upload_blob(
        &self,
        database: &str,
        collection: &str,
        config: &CollectionShardConfig,
        mut document: serde_json::Value,
        chunks: Vec<(u32, Vec<u8>)>,
    ) -> Result<serde_json::Value, crate::error::DbError> {
        use crate::sharding::router::ShardRouter;

        // 1. Determine Shard Key (same as regular insert)
        let key = if let Some(k) = document.get("_key").and_then(|v| v.as_str()) {
            k.to_string()
        } else {
            let k = uuid::Uuid::now_v7().to_string();
            if let Some(obj) = document.as_object_mut() {
                obj.insert("_key".to_string(), serde_json::Value::String(k.clone()));
            }
            k
        };

        let shard_key_value = if config.shard_key == "_key" {
            key.clone()
        } else {
            document
                .get(&config.shard_key)
                .and_then(|v| v.as_str())
                .unwrap_or(&key)
                .to_string()
        };

        // 2. Route to Shard ID
        let shard_id = ShardRouter::route(&shard_key_value, config.num_shards);

        // 3. Get Physical Collection Name
        let physical_coll = format!("{}_s{}", collection, shard_id);

        // 4. Find Primary Node
        let table = self.get_shard_table(database, collection).ok_or_else(|| {
            crate::error::DbError::InternalError("Shard table not found".to_string())
        })?;

        let assignment = table.assignments.get(&shard_id).ok_or_else(|| {
            crate::error::DbError::InternalError("Shard assignment not found".to_string())
        })?;

        let primary_node = &assignment.primary_node;

        // 5. Check if Local
        let local_id = if let Some(mgr) = &self.cluster_manager {
            mgr.local_node_id()
        } else {
            "local".to_string()
        };

        if primary_node == &local_id || primary_node == "local" {
            // Write to LOCAL physical shard
            let db = self.storage.get_database(database)?;
            let coll = db.get_collection(&physical_coll)?;

            // Store chunks first
            for (chunk_index, chunk_data) in &chunks {
                coll.put_blob_chunk(&key, *chunk_index, chunk_data)?;
            }

            // Store metadata document
            let inserted = coll.insert(document)?;

            Ok(inserted.to_value())
        } else {
            // Check if primary is healthy
            let target_node = if let Some(mgr) = &self.cluster_manager {
                if mgr.is_node_healthy(primary_node) {
                    primary_node.clone()
                } else {
                    // Primary is unhealthy - promote a replica
                    tracing::warn!(
                        "Primary {} is unhealthy for shard {}, attempting failover",
                        primary_node,
                        shard_id
                    );
                    if let Some(new_primary) = self.promote_replica(database, collection, shard_id)
                    {
                        new_primary
                    } else {
                        return Err(crate::error::DbError::InternalError(format!(
                            "Primary {} unhealthy and no healthy replica for failover",
                            primary_node
                        )));
                    }
                }
            } else {
                primary_node.clone()
            };

            // Check if the new target is now local (we got promoted)
            if target_node == local_id {
                let db = self.storage.get_database(database)?;
                let coll = db.get_collection(&physical_coll)?;

                // Store chunks first
                for (chunk_index, chunk_data) in &chunks {
                    coll.put_blob_chunk(&key, *chunk_index, chunk_data)?;
                }

                // Store metadata document
                let inserted = coll.insert(document)?;
                return Ok(inserted.to_value());
            }

            // FORWARD to Remote Primary
            if let Some(mgr) = &self.cluster_manager {
                if let Some(addr) = mgr.get_node_api_address(&target_node) {
                    let client = get_http_client();
                    let url = format!(
                        "http://{}/_internal/blob/upload/{}/{}",
                        addr, database, physical_coll
                    );

                    // Create multipart form with metadata and chunks
                    let mut form = reqwest::multipart::Form::new();

                    // Add metadata
                    let meta_json = serde_json::to_string(&document).map_err(|e| {
                        crate::error::DbError::InternalError(format!(
                            "Failed to serialize metadata: {}",
                            e
                        ))
                    })?;
                    let meta_part = reqwest::multipart::Part::text(meta_json)
                        .mime_str("application/json")
                        .map_err(|e| {
                            crate::error::DbError::InternalError(format!("Invalid mime: {}", e))
                        })?;
                    form = form.part("metadata", meta_part);

                    // Add chunks
                    for (chunk_index, chunk_data) in &chunks {
                        let part = reqwest::multipart::Part::bytes(chunk_data.clone())
                            .mime_str("application/octet-stream")
                            .map_err(|e| {
                                crate::error::DbError::InternalError(format!("Invalid mime: {}", e))
                            })?;
                        form = form.part(format!("chunk_{}", chunk_index), part);
                    }

                    // Get Cluster Secret
                    let secret = self.cluster_secret();

                    let mut req_builder = client
                        .post(&url)
                        .header("X-Shard-Direct", "true")
                        .header("X-Cluster-Secret", &secret)
                        .timeout(std::time::Duration::from_secs(60));

                    if let Some(trace_ctx) = crate::observability::get_current_trace_context() {
                        req_builder = req_builder.header("traceparent", trace_ctx.to_header());
                    }

                    let res = req_builder.multipart(form).send().await.map_err(|e| {
                        crate::error::DbError::InternalError(format!(
                            "Blob upload forwarding failed: {}",
                            e
                        ))
                    })?;

                    let status = res.status();
                    if status.is_success() {
                        let val: serde_json::Value = res.json().await.map_err(|e| {
                            crate::error::DbError::InternalError(format!(
                                "Invalid blob upload response: {}",
                                e
                            ))
                        })?;
                        Ok(val)
                    } else {
                        let error_text = res.text().await.unwrap_or_default();
                        Err(crate::error::DbError::InternalError(format!(
                            "Remote blob upload failed: {} - {}",
                            status, error_text
                        )))
                    }
                } else {
                    Err(crate::error::DbError::InternalError(format!(
                        "Target node {} address unknown",
                        target_node
                    )))
                }
            } else {
                Err(crate::error::DbError::InternalError(
                    "Cluster manager missing for remote blob upload".to_string(),
                ))
            }
        }
    }

    /// Download a blob with shard awareness
    pub async fn download_blob(
        &self,
        database: &str,
        collection: &str,
        config: &CollectionShardConfig,
        key: &str,
    ) -> Result<axum::response::Response, crate::error::DbError> {
        use crate::sharding::router::ShardRouter;
        use axum::response::Response;

        // 1. Route to Shard ID using the blob key
        let shard_id = ShardRouter::route(key, config.num_shards);

        // 2. Get Physical Collection Name
        let physical_coll = format!("{}_s{}", collection, shard_id);

        // 3. Find Primary Node
        let table = self.get_shard_table(database, collection).ok_or_else(|| {
            crate::error::DbError::InternalError("Shard table not found".to_string())
        })?;

        let assignment = table.assignments.get(&shard_id).ok_or_else(|| {
            crate::error::DbError::InternalError("Shard assignment not found".to_string())
        })?;

        let primary_node = &assignment.primary_node;

        // 4. Check if Local
        let local_id = if let Some(mgr) = &self.cluster_manager {
            mgr.local_node_id()
        } else {
            "local".to_string()
        };

        if primary_node == &local_id || primary_node == "local" {
            // Serve from LOCAL physical shard
            let db = self.storage.get_database(database)?;
            let coll = db.get_collection(&physical_coll)?;

            // Check if blob exists
            if coll.get(key).is_err() {
                return Err(DbError::DocumentNotFound(format!(
                    "Blob not found: {}",
                    key
                )));
            }

            // Get content type and filename from metadata
            let content_type = if let Ok(doc) = coll.get(key) {
                if let Some(v) = doc.get("type") {
                    if let Some(s) = v.as_str() {
                        s.to_string()
                    } else {
                        "application/octet-stream".to_string()
                    }
                } else {
                    "application/octet-stream".to_string()
                }
            } else {
                "application/octet-stream".to_string()
            };

            let file_name = if let Ok(doc) = coll.get(key) {
                doc.get("name")
                    .and_then(|v| v.as_str().map(|s| s.to_string()))
            } else {
                None
            };

            // Create streaming response
            let key = key.to_string();
            let stream = async_stream::stream! {
                let mut chunk_idx = 0;
                loop {
                    match coll.get_blob_chunk(&key, chunk_idx) {
                        Ok(Some(data)) => {
                            yield Ok::<_, std::io::Error>(axum::body::Bytes::from(data));
                            chunk_idx += 1;
                        }
                        Ok(None) => break, // End of chunks
                        Err(e) => {
                            yield Err(std::io::Error::other(e.to_string()));
                            break;
                        }
                    }
                }
            };

            let body = axum::body::Body::from_stream(stream);

            let mut builder =
                axum::response::Response::builder().header("Content-Type", content_type);

            if let Some(name) = file_name {
                let disposition = format!("attachment; filename=\"{}\"", name);
                builder = builder.header("Content-Disposition", disposition);
            }

            Ok(builder
                .body(body)
                .map_err(|e| DbError::InternalError(format!("Failed to build response: {}", e)))?)
        } else {
            // FORWARD to Remote Primary
            if let Some(mgr) = &self.cluster_manager {
                if let Some(addr) = mgr.get_node_api_address(primary_node) {
                    let client = get_http_client();
                    let url = format!(
                        "http://{}/_api/blob/{}/{}/{}",
                        addr, database, physical_coll, key
                    );

                    // Get Cluster Secret
                    let secret = self.cluster_secret();

                    let res = client
                        .get(&url)
                        .header("X-Cluster-Secret", &secret)
                        .timeout(std::time::Duration::from_secs(60))
                        .send()
                        .await
                        .map_err(|e| {
                            crate::error::DbError::InternalError(format!(
                                "Blob download forwarding failed: {}",
                                e
                            ))
                        })?;

                    if res.status().is_success() {
                        // Convert reqwest response to axum response
                        let status = res.status();
                        let headers = res.headers().clone();
                        let body = res.bytes().await.map_err(|e| {
                            crate::error::DbError::InternalError(format!(
                                "Failed to read response body: {}",
                                e
                            ))
                        })?;

                        let mut response = Response::builder().status(status);

                        // Copy headers
                        for (key, value) in headers.iter() {
                            if let Ok(val_str) = value.to_str() {
                                response = response.header(key, val_str);
                            }
                        }

                        let axum_response =
                            response.body(axum::body::Body::from(body)).map_err(|e| {
                                crate::error::DbError::InternalError(format!(
                                    "Failed to build response: {}",
                                    e
                                ))
                            })?;

                        Ok(axum_response)
                    } else {
                        Err(crate::error::DbError::InternalError(format!(
                            "Remote blob download failed: {}",
                            res.status()
                        )))
                    }
                } else {
                    Err(crate::error::DbError::InternalError(format!(
                        "Target node {} address unknown",
                        primary_node
                    )))
                }
            } else {
                Err(crate::error::DbError::InternalError(
                    "Cluster manager missing for remote blob download".to_string(),
                ))
            }
        }
    }

    /// Get a document with shard awareness
    pub async fn get(
        &self,
        database: &str,
        collection: &str,
        key: &str,
    ) -> Result<serde_json::Value, crate::error::DbError> {
        use crate::sharding::router::ShardRouter;

        let table = self.get_shard_table(database, collection).ok_or_else(|| {
            crate::error::DbError::InternalError("Shard table not found".to_string())
        })?;

        // For custom shard keys, we can't directly route by _key since the shard
        // is determined by the custom shard key value, not the _key.
        // We must try all shards in this case.
        if table.shard_key != "_key" {
            return self
                .get_from_all_shards(database, collection, key, &table)
                .await;
        }

        let shard_id = ShardRouter::route(key, table.num_shards);
        let physical_coll = format!("{}_s{}", collection, shard_id);

        let assignment = table.assignments.get(&shard_id).ok_or_else(|| {
            crate::error::DbError::InternalError("Shard assignment not found".to_string())
        })?;
        let primary_node = &assignment.primary_node;

        // Check local
        let local_id = if let Some(mgr) = &self.cluster_manager {
            mgr.local_node_id()
        } else {
            "local".to_string()
        };

        if primary_node == &local_id || primary_node == "local" {
            let db = self.storage.get_database(database)?;
            let coll = db.get_collection(&physical_coll)?;
            let doc = coll.get(key)?;
            Ok(doc.to_value())
        } else {
            // Check if primary is healthy, otherwise try replicas
            let nodes_to_try = if let Some(mgr) = &self.cluster_manager {
                if mgr.is_node_healthy(primary_node) {
                    // Primary is healthy, try it first, then replicas
                    let mut nodes = vec![primary_node.clone()];
                    nodes.extend(assignment.replica_nodes.iter().cloned());
                    nodes
                } else {
                    // Primary is unhealthy, try replicas only
                    tracing::warn!(
                        "Primary {} is unhealthy for shard {}, trying replicas",
                        primary_node,
                        shard_id
                    );
                    assignment.replica_nodes.clone()
                }
            } else {
                vec![primary_node.clone()]
            };

            if nodes_to_try.is_empty() {
                return Err(crate::error::DbError::InternalError(
                    "No healthy nodes for shard".to_string(),
                ));
            }

            // Try nodes in order until one succeeds
            let client = get_http_client();
            let secret = self.cluster_secret();

            for node_id in &nodes_to_try {
                if let Some(mgr) = &self.cluster_manager {
                    if let Some(addr) = mgr.get_node_api_address(node_id) {
                        let url = format!(
                            "http://{}/_api/database/{}/document/{}/{}",
                            addr, database, physical_coll, key
                        );

                        let res = client
                            .get(&url)
                            .header("X-Shard-Direct", "true")
                            .header("X-Cluster-Secret", &secret)
                            .timeout(std::time::Duration::from_secs(5))
                            .send()
                            .await;

                        match res {
                            Ok(r) if r.status().is_success() => {
                                return r.json().await.map_err(|e| {
                                    crate::error::DbError::InternalError(format!(
                                        "Invalid response: {}",
                                        e
                                    ))
                                });
                            }
                            Ok(r) if r.status() == reqwest::StatusCode::NOT_FOUND => {
                                return Err(crate::error::DbError::DocumentNotFound(
                                    key.to_string(),
                                ));
                            }
                            _ => {
                                tracing::debug!("Failed to get from {}, trying next node", node_id);
                                continue;
                            }
                        }
                    }
                }
            }

            Err(crate::error::DbError::InternalError(
                "All nodes failed for shard read".to_string(),
            ))
        }
    }

    /// Get a document by trying all shards (used when custom shard keys make direct routing impossible)
    async fn get_from_all_shards(
        &self,
        database: &str,
        collection: &str,
        key: &str,
        table: &ShardTable,
    ) -> Result<serde_json::Value, crate::error::DbError> {
        let client = get_http_client();
        let secret = self.cluster_secret();
        let local_id = if let Some(mgr) = &self.cluster_manager {
            mgr.local_node_id()
        } else {
            "local".to_string()
        };

        // Try each shard
        for (shard_id, assignment) in &table.assignments {
            let physical_coll = format!("{}_s{}", collection, shard_id);
            let primary_node = &assignment.primary_node;

            if primary_node == &local_id || primary_node == "local" {
                // Try local first
                if let Ok(db) = self.storage.get_database(database) {
                    if let Ok(coll) = db.get_collection(&physical_coll) {
                        if let Ok(doc) = coll.get(key) {
                            return Ok(doc.to_value());
                        }
                    }
                }
            } else {
                // Try remote node
                if let Some(mgr) = &self.cluster_manager {
                    if let Some(addr) = mgr.get_node_api_address(primary_node) {
                        let url = format!(
                            "http://{}/_api/database/{}/document/{}/{}",
                            addr, database, physical_coll, key
                        );

                        let res = client
                            .get(&url)
                            .header("X-Shard-Direct", "true")
                            .header("X-Cluster-Secret", &secret)
                            .timeout(std::time::Duration::from_secs(5))
                            .send()
                            .await;

                        match res {
                            Ok(r) if r.status().is_success() => {
                                return r.json().await.map_err(|e| {
                                    crate::error::DbError::InternalError(format!(
                                        "Invalid response: {}",
                                        e
                                    ))
                                });
                            }
                            _ => continue,
                        }
                    }
                }
            }
        }

        Err(crate::error::DbError::DocumentNotFound(key.to_string()))
    }

    /// Get replica nodes for a given key
    pub fn get_replicas(&self, key: &str, config: &CollectionShardConfig) -> Vec<String> {
        use crate::sharding::router::ShardRouter;
        let _shard_id = ShardRouter::route(key, config.num_shards);
        if let Some(_table) = self.get_shard_table("", "") {
            // Context missing db/coll - this API is flawed
            // Try to look up assignment from cached tables?
            // But we don't know db/coll here.
            // Logic needs db/coll.
            vec![]
        } else {
            // Fallback: calculate theoretical replicas
            // This method is used by `handlers.rs` to decorate response.
            vec![] // Stub for now
        }
    }

    /// Update a document with shard coordination
    pub async fn update(
        &self,
        database: &str,
        collection: &str,
        config: &CollectionShardConfig,
        key: &str,
        document: serde_json::Value,
    ) -> Result<serde_json::Value, crate::error::DbError> {
        use crate::sharding::router::ShardRouter;

        let shard_key_value = if config.shard_key == "_key" {
            key.to_string()
        } else {
            // For update, we might not have the full doc content to extract shard key?
            // If shard key is immutable, we can assume it matches current doc?
            // But we don't have current doc.
            // If shard key is NOT _key, update(key) is ambiguous if we don't know shard key.
            // Assume _key for now.
            key.to_string()
        };

        let shard_id = ShardRouter::route(&shard_key_value, config.num_shards);
        let physical_coll = format!("{}_s{}", collection, shard_id);

        let table = self.get_shard_table(database, collection).ok_or_else(|| {
            crate::error::DbError::InternalError("Shard table not found".to_string())
        })?;
        let assignment = table.assignments.get(&shard_id).ok_or_else(|| {
            crate::error::DbError::InternalError("Shard assignment not found".to_string())
        })?;
        let primary_node = &assignment.primary_node;

        let local_id = if let Some(mgr) = &self.cluster_manager {
            mgr.local_node_id()
        } else {
            "local".to_string()
        };

        if primary_node == &local_id || primary_node == "local" {
            let db = self.storage.get_database(database)?;
            let coll = db.get_collection(&physical_coll)?;

            // Apply update locally
            // Note: handlers.rs usually does "get then merge".
            // `collection.update` does merge.
            coll.update(key, document.clone())?;

            if let Some(ref log) = self.replication_log {
                let entry = LogEntry {
                    sequence: 0,
                    node_id: "".to_string(),
                    database: database.to_string(),
                    collection: physical_coll.clone(),
                    operation: Operation::Update,
                    key: key.to_string(),
                    data: serde_json::to_vec(&document).ok(),
                    timestamp: chrono::Utc::now().timestamp_millis() as u64,
                    origin_sequence: None,
                };
                let _ = log.append(entry);
            }

            Ok(document)
        } else {
            // Forward
            if let Some(mgr) = &self.cluster_manager {
                if let Some(addr) = mgr.get_node_api_address(primary_node) {
                    let client = get_http_client();
                    let url = format!(
                        "http://{}/_api/database/{}/document/{}/{}",
                        addr, database, physical_coll, key
                    );
                    let secret = self.cluster_secret();

                    let res = client
                        .put(&url)
                        .header("X-Shard-Direct", "true")
                        .header("X-Cluster-Secret", secret)
                        .json(&document)
                        .send()
                        .await
                        .map_err(|e| {
                            crate::error::DbError::InternalError(format!(
                                "Forwarding update failed: {}",
                                e
                            ))
                        })?;

                    if res.status().is_success() {
                        let val: serde_json::Value = res.json().await.map_err(|e| {
                            crate::error::DbError::InternalError(format!("Invalid response: {}", e))
                        })?;
                        Ok(val)
                    } else {
                        Err(crate::error::DbError::InternalError(format!(
                            "Remote update failed: {}",
                            res.status()
                        )))
                    }
                } else {
                    Err(crate::error::DbError::InternalError(
                        "Primary node unknown".to_string(),
                    ))
                }
            } else {
                Err(crate::error::DbError::InternalError(
                    "Cluster manager missing".to_string(),
                ))
            }
        }
    }

    /// Delete a document with shard coordination
    pub async fn delete(
        &self,
        database: &str,
        collection: &str,
        config: &CollectionShardConfig,
        key: &str,
    ) -> Result<(), crate::error::DbError> {
        use crate::sharding::router::ShardRouter;
        // Assume _key is shard key
        let shard_id = ShardRouter::route(key, config.num_shards);
        let physical_coll = format!("{}_s{}", collection, shard_id);

        let table = self.get_shard_table(database, collection).ok_or_else(|| {
            crate::error::DbError::InternalError("Shard table not found".to_string())
        })?;
        let assignment = table.assignments.get(&shard_id).ok_or_else(|| {
            crate::error::DbError::InternalError("Shard assignment not found".to_string())
        })?;
        let primary_node = &assignment.primary_node;

        let local_id = if let Some(mgr) = &self.cluster_manager {
            mgr.local_node_id()
        } else {
            "local".to_string()
        };

        if primary_node == &local_id || primary_node == "local" {
            let db = self.storage.get_database(database)?;
            let coll = db.get_collection(&physical_coll)?;
            coll.delete(key)?;

            if let Some(ref log) = self.replication_log {
                let entry = LogEntry {
                    sequence: 0,
                    node_id: "".to_string(),
                    database: database.to_string(),
                    collection: physical_coll.clone(),
                    operation: Operation::Delete,
                    key: key.to_string(),
                    data: None,
                    timestamp: chrono::Utc::now().timestamp_millis() as u64,
                    origin_sequence: None,
                };
                let _ = log.append(entry);
            }

            Ok(())
        } else {
            // Forward
            if let Some(mgr) = &self.cluster_manager {
                if let Some(addr) = mgr.get_node_api_address(primary_node) {
                    let client = get_http_client();
                    let url = format!(
                        "http://{}/_api/database/{}/document/{}/{}",
                        addr, database, physical_coll, key
                    );
                    let secret = self.cluster_secret();

                    let res = client
                        .delete(&url)
                        .header("X-Shard-Direct", "true")
                        .header("X-Cluster-Secret", secret)
                        .send()
                        .await
                        .map_err(|e| {
                            crate::error::DbError::InternalError(format!(
                                "Forwarding delete failed: {}",
                                e
                            ))
                        })?;

                    if res.status().is_success() {
                        Ok(())
                    } else {
                        Err(crate::error::DbError::InternalError(format!(
                            "Remote delete failed: {}",
                            res.status()
                        )))
                    }
                } else {
                    Err(crate::error::DbError::InternalError(
                        "Primary node unknown".to_string(),
                    ))
                }
            } else {
                Err(crate::error::DbError::InternalError(
                    "Cluster manager missing".to_string(),
                ))
            }
        }
    }

    /// Scan all shards for documents
    pub async fn scan_all_shards(
        &self,
        database: &str,
        collection: &str,
        _config: &CollectionShardConfig,
    ) -> Result<Vec<crate::storage::Document>, crate::error::DbError> {
        let db = self.storage.get_database(database)?;
        let coll = db.get_collection(collection)?;
        let docs = coll.scan(None);
        Ok(docs)
    }

    /// Remove a node from the cluster
    ///
    /// This removes the node from all shard assignments and triggers a rebalance
    pub async fn remove_node(&self, node_addr: &str) -> Result<(), crate::error::DbError> {
        tracing::info!("Removing node {} from cluster", node_addr);

        // First, update all shard assignments to remove this node
        {
            let mut tables = self.shard_tables.write().unwrap();

            for (key, table) in tables.iter_mut() {
                let mut orphaned_shards = Vec::new();

                for (shard_id, assignment) in table.assignments.iter_mut() {
                    // Remove from replicas
                    assignment.replica_nodes.retain(|n| n != node_addr);

                    // Check if this was the primary
                    if assignment.primary_node == node_addr {
                        orphaned_shards.push(*shard_id);
                    }
                }

                if !orphaned_shards.is_empty() {
                    tracing::warn!(
                        "Node {} was primary for {} shards in {}, will reassign",
                        node_addr,
                        orphaned_shards.len(),
                        key
                    );
                }
            }
        }

        // Trigger rebalance to redistribute
        self.rebalance().await?;

        tracing::info!("Node {} removed successfully", node_addr);
        Ok(())
    }

    /// Get all nodes that have shards for a collection
    pub fn get_collection_nodes(&self, _config: &CollectionShardConfig) -> Vec<String> {
        // Stub: return all cluster nodes for now
        self.get_node_addresses()
    }

    /// Get this node's index in the sorted list of all nodes
    pub fn get_node_index(&self) -> Option<usize> {
        let nodes = self.get_node_addresses();
        let my_addr = self.my_address();
        nodes.iter().position(|n| n == &my_addr)
    }

    /// Create physical shards on all assigned nodes
    pub async fn create_shards(&self, database: &str, collection: &str) -> Result<(), String> {
        let table = self
            .get_shard_table(database, collection)
            .ok_or_else(|| "Shard table not found".to_string())?;

        // Get collection type to propagate to shards
        let collection_type = if let Ok(db) = self.storage.get_database(database) {
            if let Ok(coll) = db.get_collection(collection) {
                Some(coll.get_type().to_string())
            } else {
                None
            }
        } else {
            None
        };

        let client = get_http_client();
        let secret = self.cluster_secret();

        // Track created shards to avoid duplicates
        let mut created_shards = std::collections::HashSet::new();

        for (shard_id, assignment) in &table.assignments {
            let phys_name = format!("{}_s{}", collection, shard_id);

            // Check if we already processed this shard (unlikely given loop, but safety first)
            if created_shards.contains(&phys_name) {
                continue;
            }
            created_shards.insert(phys_name.clone());

            let is_local = if let Some(mgr) = &self.cluster_manager {
                assignment.primary_node == mgr.local_node_id()
            } else {
                true
            };

            // DEBUG LOGGING
            tracing::info!(
                "CREATE_SHARDS: Processing {} (is_local={}). Primary: {}",
                phys_name,
                is_local,
                assignment.primary_node
            );

            // DEBUG LOGGING
            tracing::info!(
                "CREATE_SHARDS: Processing {} (is_local={}). Primary: {}",
                phys_name,
                is_local,
                assignment.primary_node
            );

            // Unified loop for Primary AND Replicas
            // We want to ensure the shard exists on ALL assigned nodes
            let targets =
                std::iter::once(&assignment.primary_node).chain(assignment.replica_nodes.iter());

            for target_node in targets {
                let is_target_local = if let Some(mgr) = &self.cluster_manager {
                    target_node == &mgr.local_node_id()
                } else {
                    true
                };

                if is_target_local {
                    // Create Local
                    if let Ok(db) = self.storage.get_database(database) {
                        if db.get_collection(&phys_name).is_err() {
                            tracing::info!(
                                "CREATE_SHARDS: Creating local physical shard {} on {} type={:?}",
                                phys_name,
                                target_node,
                                collection_type
                            );
                            if let Err(e) =
                                db.create_collection(phys_name.clone(), collection_type.clone())
                            {
                                let msg =
                                    format!("Failed to create local shard {}: {}", phys_name, e);
                                tracing::error!("{}", msg);
                                // Continue to next target
                            } else {
                                // Log it
                                if let Some(log) = &self.replication_log {
                                    let entry = LogEntry {
                                        sequence: 0,
                                        node_id: "".to_string(),
                                        database: database.to_string(),
                                        collection: phys_name.clone(),
                                        operation: Operation::CreateCollection,
                                        key: "".to_string(),
                                        data: None,
                                        timestamp: chrono::Utc::now().timestamp_millis() as u64,
                                        origin_sequence: None,
                                    };
                                    let _ = log.append(entry);
                                }
                            }
                        }
                    }
                } else {
                    // Remote Create
                    if let Some(mgr) = &self.cluster_manager {
                        if let Some(addr) = mgr.get_node_api_address(target_node) {
                            let url =
                                format!("http://{}/_api/database/{}/collection", addr, database);
                            tracing::info!(
                                "CREATE_SHARDS: Remote creating {} at {} (url={}) type={:?}",
                                phys_name,
                                addr,
                                url,
                                collection_type
                            );
                            let body = serde_json::json!({
                                "name": phys_name,
                                "type": collection_type
                            });

                            match client
                                .post(&url)
                                .header("X-Shard-Direct", "true")
                                .header("X-Cluster-Secret", &secret)
                                .json(&body)
                                .send()
                                .await
                            {
                                Ok(res) => {
                                    if !res.status().is_success() {
                                        let status = res.status();
                                        if status.as_u16() == 409 {
                                            tracing::debug!("CREATE_SHARDS: Remote shard {} already exists (409)", phys_name);
                                        } else {
                                            let err_text = res.text().await.unwrap_or_default();
                                            tracing::error!("CREATE_SHARDS: Remote creation of {} failed: {} - {}", phys_name, status, err_text);
                                        }
                                    }
                                }
                                Err(e) => {
                                    tracing::error!("Request failed to {}: {}", addr, e);
                                }
                            }
                        }
                    }
                }
            }
        }
        Ok(())
    }

    /// Get aggregated document count for a sharded collection
    pub async fn get_total_count(
        &self,
        database: &str,
        collection: &str,
        auth_header: Option<String>,
    ) -> Result<usize, crate::error::DbError> {
        let config = self
            .get_shard_config(database, collection)
            .ok_or_else(|| crate::error::DbError::CollectionNotFound(collection.to_string()))?;

        if config.num_shards == 0 {
            // Non-sharded
            let db = self.storage.get_database(database)?;
            let coll = db.get_collection(collection)?;
            return Ok(coll.count());
        }

        let table = self.get_shard_table(database, collection).ok_or_else(|| {
            crate::error::DbError::InternalError("Shard table not found".to_string())
        })?;

        let my_id = self.my_node_id();
        let client = get_http_client();
        let secret = self.cluster_secret();

        let mut total_count = 0usize;

        for shard_id in 0..config.num_shards {
            let assignment = table.assignments.get(&shard_id).ok_or_else(|| {
                crate::error::DbError::InternalError(format!(
                    "No assignment for shard {}",
                    shard_id
                ))
            })?;

            let physical_name = format!("{}_s{}", collection, shard_id);
            let mut shard_count = 0usize;
            let mut found = false;

            // Try local primary/replica first
            let has_local = assignment.primary_node == my_id
                || assignment.replica_nodes.contains(&my_id)
                || assignment.primary_node == "local";
            if has_local {
                if let Ok(db) = self.storage.get_database(database) {
                    if let Ok(coll) = db.get_collection(&physical_name) {
                        shard_count = coll.count();
                        found = true;
                    }
                }
            }

            // If not found locally, try primary node then replicas
            if !found {
                if let Some(mgr) = &self.cluster_manager {
                    // Try primary node
                    if let Some(addr) = mgr.get_node_api_address(&assignment.primary_node) {
                        let url = format!(
                            "http://{}/_api/database/{}/collection/{}/count",
                            addr, database, physical_name
                        );
                        let mut req = client
                            .get(&url)
                            .header("X-Cluster-Secret", &secret)
                            .timeout(std::time::Duration::from_secs(2));

                        if let Some(ref auth) = auth_header {
                            req = req.header("Authorization", auth);
                        }

                        match req.send().await {
                            Ok(res) if res.status().is_success() => {
                                if let Ok(json) = res.json::<serde_json::Value>().await {
                                    if let Some(c) = json.get("count").and_then(|v| v.as_u64()) {
                                        shard_count = c as usize;
                                        found = true;
                                    }
                                }
                            }
                            _ => {}
                        }
                    }

                    // If primary failed, try replicas
                    if !found {
                        for replica_node in &assignment.replica_nodes {
                            if let Some(addr) = mgr.get_node_api_address(replica_node) {
                                let url = format!(
                                    "http://{}/_api/database/{}/collection/{}/count",
                                    addr, database, physical_name
                                );
                                let mut req = client
                                    .get(&url)
                                    .header("X-Cluster-Secret", &secret)
                                    .timeout(std::time::Duration::from_secs(2));

                                if let Some(ref auth) = auth_header {
                                    req = req.header("Authorization", auth);
                                }

                                match req.send().await {
                                    Ok(res) if res.status().is_success() => {
                                        if let Ok(json) = res.json::<serde_json::Value>().await {
                                            if let Some(c) =
                                                json.get("count").and_then(|v| v.as_u64())
                                            {
                                                shard_count = c as usize;
                                                found = true;
                                                break;
                                            }
                                        }
                                    }
                                    _ => {}
                                }
                            }
                        }
                    }
                }
            }

            if found {
                total_count += shard_count;
            } else {
                tracing::warn!(
                    "Could not get count for shard {} of {} from any node",
                    shard_id,
                    collection
                );
            }
        }

        Ok(total_count)
    }

    /// Get aggregated stats (docs, chunks, size) for a sharded collection
    pub async fn get_total_stats(
        &self,
        database: &str,
        collection: &str,
        auth_header: Option<String>,
    ) -> Result<(u64, u64, u64), crate::error::DbError> {
        let config = self
            .get_shard_config(database, collection)
            .ok_or_else(|| crate::error::DbError::CollectionNotFound(collection.to_string()))?;

        if config.num_shards == 0 {
            // Non-sharded or logical base
            let db = self.storage.get_database(database)?;
            let coll = db.get_collection(collection)?;
            let stats = coll.stats();
            return Ok((
                stats.document_count as u64,
                stats.chunk_count as u64,
                stats.disk_usage.sst_files_size + stats.disk_usage.memtable_size,
            ));
        }

        let table = self.get_shard_table(database, collection).ok_or_else(|| {
            crate::error::DbError::InternalError("Shard table not found".to_string())
        })?;

        let my_id = self.my_node_id();
        let client = get_http_client();
        let secret = self.cluster_secret();

        let mut total_docs = 0u64;
        let mut total_chunks = 0u64;
        let mut total_size = 0u64;

        for shard_id in 0..config.num_shards {
            let assignment = table.assignments.get(&shard_id).ok_or_else(|| {
                crate::error::DbError::InternalError(format!(
                    "No assignment for shard {}",
                    shard_id
                ))
            })?;

            let physical_name = format!("{}_s{}", collection, shard_id);
            let mut shard_stats: Option<(u64, u64, u64)> = None;

            // 1. Try local primary/replica first
            let has_local = assignment.primary_node == my_id
                || assignment.replica_nodes.contains(&my_id)
                || assignment.primary_node == "local";
            if has_local {
                if let Ok(db) = self.storage.get_database(database) {
                    if let Ok(coll) = db.get_collection(&physical_name) {
                        let s = coll.stats();
                        shard_stats = Some((
                            s.document_count as u64,
                            s.chunk_count as u64,
                            s.disk_usage.sst_files_size + s.disk_usage.memtable_size,
                        ));
                    }
                }
            }

            // 2. If not found locally, try primary node then replicas
            if shard_stats.is_none() {
                if let Some(mgr) = &self.cluster_manager {
                    // Collect nodes to try: primary first, then replicas
                    let mut nodes_to_try = vec![assignment.primary_node.clone()];
                    nodes_to_try.extend(assignment.replica_nodes.clone());

                    for node_id in nodes_to_try {
                        if let Some(addr) = mgr.get_node_api_address(&node_id) {
                            let url = format!(
                                "http://{}/_api/database/{}/collection/{}/stats",
                                addr, database, physical_name
                            );
                            let mut req = client
                                .get(&url)
                                .header("X-Cluster-Secret", &secret)
                                .timeout(std::time::Duration::from_secs(2));

                            if let Some(ref auth) = auth_header {
                                req = req.header("Authorization", auth);
                            }

                            if let Ok(res) = req.send().await {
                                if res.status().is_success() {
                                    if let Ok(json) = res.json::<serde_json::Value>().await {
                                        let doc_count = json
                                            .get("document_count")
                                            .and_then(|v| v.as_u64())
                                            .unwrap_or(0);
                                        let chunk_count = json
                                            .get("chunk_count")
                                            .and_then(|v| v.as_u64())
                                            .unwrap_or(0);
                                        let disk_usage = json
                                            .get("disk_usage")
                                            .and_then(|v| v.get("sst_files_size"))
                                            .and_then(|v| v.as_u64())
                                            .unwrap_or(0);
                                        let mem_usage = json
                                            .get("disk_usage")
                                            .and_then(|v| v.get("memtable_size"))
                                            .and_then(|v| v.as_u64())
                                            .unwrap_or(0);
                                        shard_stats =
                                            Some((doc_count, chunk_count, disk_usage + mem_usage));
                                        break;
                                    }
                                }
                            }
                        }
                    }
                }
            }

            if let Some((d, c, s)) = shard_stats {
                total_docs += d;
                total_chunks += c;
                total_size += s;
            } else {
                tracing::warn!(
                    "Could not get stats for shard {} of {} from any node",
                    shard_id,
                    collection
                );
            }
        }

        Ok((total_docs, total_chunks, total_size))
    }
}

#[cfg(test)]
mod tests {
    use super::*;
    use tempfile::TempDir;

    fn create_test_coordinator() -> (ShardCoordinator, TempDir) {
        let tmp_dir = TempDir::new().expect("Failed to create temp dir");
        let engine = StorageEngine::new(tmp_dir.path().to_str().unwrap())
            .expect("Failed to create storage engine");

        let coordinator = ShardCoordinator::new(
            Arc::new(engine),
            None, // No cluster manager for unit tests
            None, // No replication log
        );

        (coordinator, tmp_dir)
    }

    #[test]
    fn test_new_coordinator() {
        let (coordinator, _tmp) = create_test_coordinator();

        // Should not be rebalancing initially
        assert!(!coordinator.is_rebalancing());

        // Without cluster manager, should return "local"
        assert_eq!(coordinator.my_node_id(), "local");
        assert_eq!(coordinator.my_address(), "local");
    }

    #[test]
    fn test_route_delegates_to_router() {
        let (coordinator, _tmp) = create_test_coordinator();

        // Verify routing is consistent
        let shard1 = coordinator.route("test_key", 10);
        let shard2 = coordinator.route("test_key", 10);
        assert_eq!(shard1, shard2);

        // Different keys should potentially route to different shards
        let shard_a = coordinator.route("key_a", 100);
        let shard_b = coordinator.route("key_b", 100);
        // They might be equal, but the function should work
        assert!(shard_a < 100);
        assert!(shard_b < 100);
    }

    #[test]
    fn test_is_shard_replica() {
        // Static method test
        // Shard 0, RF=2, 3 nodes: nodes 0 and 1 should have it
        assert!(ShardCoordinator::is_shard_replica(0, 0, 2, 3));
        assert!(ShardCoordinator::is_shard_replica(0, 1, 2, 3));
        assert!(!ShardCoordinator::is_shard_replica(0, 2, 2, 3));

        // Shard 1, RF=2, 3 nodes: nodes 1 and 2 should have it
        assert!(!ShardCoordinator::is_shard_replica(1, 0, 2, 3));
        assert!(ShardCoordinator::is_shard_replica(1, 1, 2, 3));
        assert!(ShardCoordinator::is_shard_replica(1, 2, 2, 3));

        // Edge cases
        assert!(!ShardCoordinator::is_shard_replica(0, 0, 0, 3)); // RF=0
        assert!(!ShardCoordinator::is_shard_replica(0, 0, 2, 0)); // num_nodes=0
    }

    #[test]
    fn test_record_and_clear_node_failure() {
        let (coordinator, _tmp) = create_test_coordinator();

        // Record failure
        coordinator.record_node_failure("node1");

        // Check it was recorded
        let failures = coordinator.recently_failed_nodes.read().unwrap();
        assert!(failures.contains_key("node1"));
        drop(failures);

        // Clear failure
        coordinator.clear_node_failure("node1");

        // Check it was cleared
        let failures = coordinator.recently_failed_nodes.read().unwrap();
        assert!(!failures.contains_key("node1"));
    }

    #[test]
    fn test_cleanup_old_failures() {
        let (coordinator, _tmp) = create_test_coordinator();

        // Record a failure
        coordinator.record_node_failure("node1");

        // Cleanup should keep recent failures
        coordinator.cleanup_old_failures();

        let failures = coordinator.recently_failed_nodes.read().unwrap();
        assert!(failures.contains_key("node1")); // Should still be there (recent)
    }

    #[test]
    fn test_is_rebalancing_flag() {
        let (coordinator, _tmp) = create_test_coordinator();

        // Initially false
        assert!(!coordinator.is_rebalancing());

        // Set to true
        coordinator.is_rebalancing.store(true, Ordering::SeqCst);
        assert!(coordinator.is_rebalancing());

        // Set back to false
        coordinator.is_rebalancing.store(false, Ordering::SeqCst);
        assert!(!coordinator.is_rebalancing());
    }

    #[test]
    fn test_mark_reshard_completed() {
        let (coordinator, _tmp) = create_test_coordinator();

        // Initially no reshard time
        {
            let last_time = coordinator.last_reshard_time.read().unwrap();
            assert!(last_time.is_none());
        }

        // Mark as completed
        coordinator.mark_reshard_completed();

        // Should now have a time
        {
            let last_time = coordinator.last_reshard_time.read().unwrap();
            assert!(last_time.is_some());
        }
    }

    #[test]
    fn test_check_recent_resharding() {
        let (coordinator, _tmp) = create_test_coordinator();

        // No recent resharding initially
        assert!(!coordinator.check_recent_resharding());

        // Mark reshard completed
        coordinator.mark_reshard_completed();

        // Should return true (within 10 second window)
        assert!(coordinator.check_recent_resharding());

        // Also returns true if currently rebalancing
        coordinator.is_rebalancing.store(true, Ordering::SeqCst);
        assert!(coordinator.check_recent_resharding());
    }

    #[test]
    fn test_calculate_blob_replication_factor_single_node() {
        let (coordinator, _tmp) = create_test_coordinator();

        // Without cluster manager, healthy_count = 1
        // Formula: min(max(2, 1/2), 10) = min(max(2, 0), 10) = min(2, 10) = 2
        let rf = coordinator.calculate_blob_replication_factor();
        assert_eq!(rf, ShardCoordinator::MIN_BLOB_REPLICAS);
    }

    #[test]
    fn test_get_node_addresses_without_cluster() {
        let (coordinator, _tmp) = create_test_coordinator();

        // Without cluster manager, should return ["local"]
        let addresses = coordinator.get_node_addresses();
        assert_eq!(addresses, vec!["local".to_string()]);
    }

    #[test]
    fn test_get_node_ids_without_cluster() {
        let (coordinator, _tmp) = create_test_coordinator();

        // Without cluster manager, should return ["local"]
        let ids = coordinator.get_node_ids();
        assert_eq!(ids, vec!["local".to_string()]);
    }

    #[test]
    fn test_get_healthy_node_count_without_cluster() {
        let (coordinator, _tmp) = create_test_coordinator();

        // Without cluster manager, should return 1
        assert_eq!(coordinator.get_healthy_node_count(), 1);
    }

    #[test]
    fn test_get_node_api_address_without_cluster() {
        let (coordinator, _tmp) = create_test_coordinator();

        // Without cluster manager, should return None
        assert!(coordinator.get_node_api_address("any_node").is_none());
    }

    #[test]
    fn test_get_shard_config_nonexistent() {
        let (coordinator, _tmp) = create_test_coordinator();

        // Non-existent database/collection should return None
        assert!(coordinator
            .get_shard_config("nonexistent_db", "nonexistent_coll")
            .is_none());
    }

    #[test]
    fn test_get_shard_table_nonexistent() {
        let (coordinator, _tmp) = create_test_coordinator();

        // Non-existent database/collection should return None
        assert!(coordinator
            .get_shard_table("nonexistent_db", "nonexistent_coll")
            .is_none());
    }

    #[test]
    fn test_should_pause_resharding_without_cluster() {
        let (coordinator, _tmp) = create_test_coordinator();

        // Without cluster manager, should return false
        assert!(!coordinator.should_pause_resharding());
    }

    #[test]
    fn test_collection_shard_config_default() {
        let config = CollectionShardConfig::default();

        assert_eq!(config.num_shards, 0);
        assert_eq!(config.shard_key, "");
        assert_eq!(config.replication_factor, 0);
    }

    #[test]
    fn test_shard_table_creation() {
        let mut assignments = HashMap::new();
        assignments.insert(
            0,
            ShardAssignment {
                shard_id: 0,
                primary_node: "node1".to_string(),
                replica_nodes: vec!["node2".to_string()],
            },
        );

        let table = ShardTable {
            database: "test_db".to_string(),
            collection: "test_coll".to_string(),
            num_shards: 4,
            replication_factor: 2,
            shard_key: "_key".to_string(),
            assignments,
        };

        assert_eq!(table.database, "test_db");
        assert_eq!(table.collection, "test_coll");
        assert_eq!(table.num_shards, 4);
        assert_eq!(table.replication_factor, 2);
        assert_eq!(table.assignments.len(), 1);
    }

    #[test]
    fn test_shard_assignment_creation() {
        let assignment = ShardAssignment {
            shard_id: 5,
            primary_node: "primary".to_string(),
            replica_nodes: vec!["replica1".to_string(), "replica2".to_string()],
        };

        assert_eq!(assignment.shard_id, 5);
        assert_eq!(assignment.primary_node, "primary");
        assert_eq!(assignment.replica_nodes.len(), 2);
    }

    #[test]
    fn test_constants() {
        assert_eq!(ShardCoordinator::MAX_BLOB_REPLICAS, 10);
        assert_eq!(ShardCoordinator::MIN_BLOB_REPLICAS, 2);
    }

    #[test]
    fn test_update_shard_table_cache() {
        let (coordinator, _tmp) = create_test_coordinator();

        let table = ShardTable {
            database: "db1".to_string(),
            collection: "coll1".to_string(),
            num_shards: 4,
            replication_factor: 2,
            shard_key: "_key".to_string(),
            assignments: HashMap::new(),
        };

        coordinator.update_shard_table_cache(table.clone());

        // Check it was cached
        let tables = coordinator.shard_tables.read().unwrap();
        assert!(tables.contains_key("db1.coll1"));
    }

    #[test]
    fn test_get_node_index_without_cluster() {
        let (coordinator, _tmp) = create_test_coordinator();

        // Without cluster manager, returns None since we can't compute index
        // Actually the implementation might differ - let's check
        let index = coordinator.get_node_index();
        // Without cluster, node index lookup fails
        assert!(index.is_none() || index == Some(0));
    }

    #[test]
    fn test_clear_failures_for_healthy_nodes_without_cluster() {
        let (coordinator, _tmp) = create_test_coordinator();

        // Record some failures
        coordinator.record_node_failure("node1");
        coordinator.record_node_failure("node2");

        // Without cluster manager, this should be a no-op
        coordinator.clear_failures_for_healthy_nodes();

        // Failures should still be there (no cluster manager to determine health)
        let failures = coordinator.recently_failed_nodes.read().unwrap();
        assert!(failures.contains_key("node1"));
        assert!(failures.contains_key("node2"));
    }
}