synadb 1.3.0

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

//! C-ABI Foreign Function Interface for Syna database.
//!
//! This module provides extern "C" functions for cross-language access.
//! All functions use `catch_unwind` to prevent Rust panics from unwinding
//! into foreign code.

// FFI functions intentionally take raw pointers without being marked unsafe
// because they handle null checks and use catch_unwind for safety
#![allow(clippy::not_unsafe_ptr_arg_deref)]
// Using slice::from_raw_parts_mut with Box::from_raw is intentional for FFI memory management
#![allow(clippy::cast_slice_from_raw_parts)]

use std::ffi::CStr;
use std::os::raw::c_char;

use crate::engine::{close_db, free_tensor, open_db, open_db_with_config, with_db, DbConfig};
use crate::error::{
    ERR_GENERIC, ERR_INTERNAL_PANIC, ERR_INVALID_PATH, ERR_KEY_NOT_FOUND, ERR_SUCCESS,
    ERR_TYPE_MISMATCH,
};
use crate::types::Atom;

/// Opens a database at the given path and registers it in the global registry.
///
/// # Arguments
/// * `path` - Null-terminated C string containing the path to the database file
///
/// # Returns
/// * `1` (ERR_SUCCESS) - Database opened successfully or was already open
/// * `0` (ERR_GENERIC) - Generic error during database open
/// * `-2` (ERR_INVALID_PATH) - Path is null or invalid UTF-8
/// * `-100` (ERR_INTERNAL_PANIC) - Internal panic occurred
///
/// # Safety
/// * `path` must be a valid null-terminated C string or null
///
/// _Requirements: 6.2, 6.3, 9.4_
#[no_mangle]
pub extern "C" fn SYNA_open(path: *const c_char) -> i32 {
    std::panic::catch_unwind(|| {
        // Check for null pointer
        if path.is_null() {
            return ERR_INVALID_PATH;
        }

        // Convert C string to Rust string
        let c_str = unsafe { CStr::from_ptr(path) };
        let path_str = match c_str.to_str() {
            Ok(s) => s,
            Err(_) => return ERR_INVALID_PATH,
        };

        // Open the database
        match open_db(path_str) {
            Ok(_) => ERR_SUCCESS,
            Err(_) => ERR_GENERIC,
        }
    })
    .unwrap_or(ERR_INTERNAL_PANIC)
}

/// Opens a database with sync_on_write disabled for high-throughput writes.
///
/// This is optimized for bulk ingestion scenarios where durability can be
/// traded for speed. Data is still written to disk but not fsynced after
/// each write, achieving 100K+ ops/sec instead of ~100 ops/sec.
///
/// # Arguments
/// * `path` - Null-terminated C string containing the path to the database file
/// * `sync_on_write` - 1 for sync after each write (durable), 0 for no sync (fast)
///
/// # Returns
/// * `1` (ERR_SUCCESS) - Database opened successfully or was already open
/// * `0` (ERR_GENERIC) - Generic error during database open
/// * `-2` (ERR_INVALID_PATH) - Path is null or invalid UTF-8
/// * `-100` (ERR_INTERNAL_PANIC) - Internal panic occurred
///
/// # Safety
/// * `path` must be a valid null-terminated C string or null
#[no_mangle]
pub extern "C" fn SYNA_open_with_config(path: *const c_char, sync_on_write: i32) -> i32 {
    std::panic::catch_unwind(|| {
        // Check for null pointer
        if path.is_null() {
            return ERR_INVALID_PATH;
        }

        // Convert C string to Rust string
        let c_str = unsafe { CStr::from_ptr(path) };
        let path_str = match c_str.to_str() {
            Ok(s) => s,
            Err(_) => return ERR_INVALID_PATH,
        };

        // Create config with sync_on_write setting
        let config = DbConfig {
            sync_on_write: sync_on_write != 0,
            ..DbConfig::default()
        };

        // Open the database with config
        match open_db_with_config(path_str, config) {
            Ok(_) => ERR_SUCCESS,
            Err(_) => ERR_GENERIC,
        }
    })
    .unwrap_or(ERR_INTERNAL_PANIC)
}

/// Closes a database and removes it from the global registry.
///
/// # Arguments
/// * `path` - Null-terminated C string containing the path to the database file
///
/// # Returns
/// * `1` (ERR_SUCCESS) - Database closed successfully
/// * `0` (ERR_GENERIC) - Generic error during database close
/// * `-1` (ERR_DB_NOT_FOUND) - Database not found in registry
/// * `-2` (ERR_INVALID_PATH) - Path is null or invalid UTF-8
/// * `-100` (ERR_INTERNAL_PANIC) - Internal panic occurred
///
/// # Safety
/// * `path` must be a valid null-terminated C string or null
///
/// _Requirements: 6.2_
#[no_mangle]
pub extern "C" fn SYNA_close(path: *const c_char) -> i32 {
    std::panic::catch_unwind(|| {
        // Check for null pointer
        if path.is_null() {
            return ERR_INVALID_PATH;
        }

        // Convert C string to Rust string
        let c_str = unsafe { CStr::from_ptr(path) };
        let path_str = match c_str.to_str() {
            Ok(s) => s,
            Err(_) => return ERR_INVALID_PATH,
        };

        // Close the database
        match close_db(path_str) {
            Ok(_) => ERR_SUCCESS,
            Err(crate::error::SynaError::NotFound(_)) => crate::error::ERR_DB_NOT_FOUND,
            Err(_) => ERR_GENERIC,
        }
    })
    .unwrap_or(ERR_INTERNAL_PANIC)
}

/// Writes a float value to the database.
///
/// # Arguments
/// * `path` - Null-terminated C string containing the path to the database file
/// * `key` - Null-terminated C string containing the key
/// * `value` - The f64 value to store
///
/// # Returns
/// * Positive value - The byte offset where the entry was written
/// * `-1` (ERR_DB_NOT_FOUND) - Database not found in registry
/// * `-2` (ERR_INVALID_PATH) - Path or key is null or invalid UTF-8
/// * `-100` (ERR_INTERNAL_PANIC) - Internal panic occurred
///
/// # Safety
/// * `path` and `key` must be valid null-terminated C strings or null
///
/// _Requirements: 6.2, 6.3_
#[no_mangle]
pub extern "C" fn SYNA_put_float(path: *const c_char, key: *const c_char, value: f64) -> i64 {
    std::panic::catch_unwind(|| {
        // Validate pointers
        if path.is_null() || key.is_null() {
            return ERR_INVALID_PATH as i64;
        }

        // Convert C strings to Rust strings
        let path_str = match unsafe { CStr::from_ptr(path) }.to_str() {
            Ok(s) => s,
            Err(_) => return ERR_INVALID_PATH as i64,
        };

        let key_str = match unsafe { CStr::from_ptr(key) }.to_str() {
            Ok(s) => s,
            Err(_) => return ERR_INVALID_PATH as i64,
        };

        // Call with_db to append the value
        match with_db(path_str, |db| db.append(key_str, Atom::Float(value))) {
            Ok(offset) => offset as i64,
            Err(crate::error::SynaError::NotFound(_)) => crate::error::ERR_DB_NOT_FOUND as i64,
            Err(_) => ERR_GENERIC as i64,
        }
    })
    .unwrap_or(ERR_INTERNAL_PANIC as i64)
}

/// Writes an integer value to the database.
///
/// # Arguments
/// * `path` - Null-terminated C string containing the path to the database file
/// * `key` - Null-terminated C string containing the key
/// * `value` - The i64 value to store
///
/// # Returns
/// * Positive value - The byte offset where the entry was written
/// * `-1` (ERR_DB_NOT_FOUND) - Database not found in registry
/// * `-2` (ERR_INVALID_PATH) - Path or key is null or invalid UTF-8
/// * `-100` (ERR_INTERNAL_PANIC) - Internal panic occurred
///
/// # Safety
/// * `path` and `key` must be valid null-terminated C strings or null
///
/// _Requirements: 6.2, 6.3_
#[no_mangle]
pub extern "C" fn SYNA_put_int(path: *const c_char, key: *const c_char, value: i64) -> i64 {
    std::panic::catch_unwind(|| {
        // Validate pointers
        if path.is_null() || key.is_null() {
            return ERR_INVALID_PATH as i64;
        }

        // Convert C strings to Rust strings
        let path_str = match unsafe { CStr::from_ptr(path) }.to_str() {
            Ok(s) => s,
            Err(_) => return ERR_INVALID_PATH as i64,
        };

        let key_str = match unsafe { CStr::from_ptr(key) }.to_str() {
            Ok(s) => s,
            Err(_) => return ERR_INVALID_PATH as i64,
        };

        // Call with_db to append the value
        match with_db(path_str, |db| db.append(key_str, Atom::Int(value))) {
            Ok(offset) => offset as i64,
            Err(crate::error::SynaError::NotFound(_)) => crate::error::ERR_DB_NOT_FOUND as i64,
            Err(_) => ERR_GENERIC as i64,
        }
    })
    .unwrap_or(ERR_INTERNAL_PANIC as i64)
}

/// Writes a text value to the database.
///
/// # Arguments
/// * `path` - Null-terminated C string containing the path to the database file
/// * `key` - Null-terminated C string containing the key
/// * `value` - Null-terminated C string containing the text value to store
///
/// # Returns
/// * Positive value - The byte offset where the entry was written
/// * `-1` (ERR_DB_NOT_FOUND) - Database not found in registry
/// * `-2` (ERR_INVALID_PATH) - Path, key, or value is null or invalid UTF-8
/// * `-100` (ERR_INTERNAL_PANIC) - Internal panic occurred
///
/// # Safety
/// * `path`, `key`, and `value` must be valid null-terminated C strings or null
///
/// _Requirements: 6.2, 6.3_
#[no_mangle]
pub extern "C" fn SYNA_put_text(
    path: *const c_char,
    key: *const c_char,
    value: *const c_char,
) -> i64 {
    std::panic::catch_unwind(|| {
        // Validate pointers
        if path.is_null() || key.is_null() || value.is_null() {
            return ERR_INVALID_PATH as i64;
        }

        // Convert C strings to Rust strings
        let path_str = match unsafe { CStr::from_ptr(path) }.to_str() {
            Ok(s) => s,
            Err(_) => return ERR_INVALID_PATH as i64,
        };

        let key_str = match unsafe { CStr::from_ptr(key) }.to_str() {
            Ok(s) => s,
            Err(_) => return ERR_INVALID_PATH as i64,
        };

        let value_str = match unsafe { CStr::from_ptr(value) }.to_str() {
            Ok(s) => s,
            Err(_) => return ERR_INVALID_PATH as i64,
        };

        // Call with_db to append the value
        match with_db(path_str, |db| {
            db.append(key_str, Atom::Text(value_str.to_string()))
        }) {
            Ok(offset) => offset as i64,
            Err(crate::error::SynaError::NotFound(_)) => crate::error::ERR_DB_NOT_FOUND as i64,
            Err(_) => ERR_GENERIC as i64,
        }
    })
    .unwrap_or(ERR_INTERNAL_PANIC as i64)
}

/// Writes a byte array to the database.
///
/// # Arguments
/// * `path` - Null-terminated C string containing the path to the database file
/// * `key` - Null-terminated C string containing the key
/// * `data` - Pointer to the byte array to store
/// * `len` - Length of the byte array
///
/// # Returns
/// * Positive value - The byte offset where the entry was written
/// * `-1` (ERR_DB_NOT_FOUND) - Database not found in registry
/// * `-2` (ERR_INVALID_PATH) - Path, key, or data is null or invalid UTF-8
/// * `-100` (ERR_INTERNAL_PANIC) - Internal panic occurred
///
/// # Safety
/// * `path` and `key` must be valid null-terminated C strings or null
/// * `data` must be a valid pointer to at least `len` bytes, or null
///
/// _Requirements: 6.2, 6.4_
#[no_mangle]
pub extern "C" fn SYNA_put_bytes(
    path: *const c_char,
    key: *const c_char,
    data: *const u8,
    len: usize,
) -> i64 {
    std::panic::catch_unwind(|| {
        // Validate pointers
        if path.is_null() || key.is_null() || (data.is_null() && len > 0) {
            return ERR_INVALID_PATH as i64;
        }

        // Convert C strings to Rust strings
        let path_str = match unsafe { CStr::from_ptr(path) }.to_str() {
            Ok(s) => s,
            Err(_) => return ERR_INVALID_PATH as i64,
        };

        let key_str = match unsafe { CStr::from_ptr(key) }.to_str() {
            Ok(s) => s,
            Err(_) => return ERR_INVALID_PATH as i64,
        };

        // Create Vec<u8> from raw pointer and length
        let bytes = if len == 0 {
            Vec::new()
        } else {
            unsafe { std::slice::from_raw_parts(data, len) }.to_vec()
        };

        // Call with_db to append the value
        match with_db(path_str, |db| db.append(key_str, Atom::Bytes(bytes))) {
            Ok(offset) => offset as i64,
            Err(crate::error::SynaError::NotFound(_)) => crate::error::ERR_DB_NOT_FOUND as i64,
            Err(_) => ERR_GENERIC as i64,
        }
    })
    .unwrap_or(ERR_INTERNAL_PANIC as i64)
}

/// Writes multiple float values to the database in a single batch operation.
///
/// This is optimized for high-throughput ingestion scenarios. All values are
/// written under the same key, building up a history that can be extracted
/// as a tensor with `SYNA_get_history_tensor()`.
///
/// # Arguments
/// * `path` - Null-terminated C string containing the path to the database file
/// * `key` - Null-terminated C string containing the key
/// * `values` - Pointer to array of f64 values
/// * `count` - Number of values in the array
///
/// # Returns
/// * Positive value - Number of values written
/// * `-1` (ERR_DB_NOT_FOUND) - Database not found in registry
/// * `-2` (ERR_INVALID_PATH) - Path, key, or values is null or invalid UTF-8
/// * `-100` (ERR_INTERNAL_PANIC) - Internal panic occurred
///
/// # Safety
/// * `path` and `key` must be valid null-terminated C strings or null
/// * `values` must be a valid pointer to at least `count` f64 values, or null if count is 0
///
/// # Performance
/// This function is significantly faster than calling `SYNA_put_float()` in a loop:
/// - Single FFI boundary crossing
/// - Single mutex lock for all writes
/// - Single fsync at the end (if sync_on_write is enabled)
#[no_mangle]
pub extern "C" fn SYNA_put_floats_batch(
    path: *const c_char,
    key: *const c_char,
    values: *const f64,
    count: usize,
) -> i64 {
    std::panic::catch_unwind(|| {
        // Validate pointers
        if path.is_null() || key.is_null() || (values.is_null() && count > 0) {
            return ERR_INVALID_PATH as i64;
        }

        // Convert C strings to Rust strings
        let path_str = match unsafe { CStr::from_ptr(path) }.to_str() {
            Ok(s) => s,
            Err(_) => return ERR_INVALID_PATH as i64,
        };

        let key_str = match unsafe { CStr::from_ptr(key) }.to_str() {
            Ok(s) => s,
            Err(_) => return ERR_INVALID_PATH as i64,
        };

        // Create slice from raw pointer
        let slice = if count == 0 {
            &[]
        } else {
            unsafe { std::slice::from_raw_parts(values, count) }
        };

        // Call with_db to batch append
        match with_db(path_str, |db| db.append_floats_batch(key_str, slice)) {
            Ok(n) => n as i64,
            Err(crate::error::SynaError::NotFound(_)) => crate::error::ERR_DB_NOT_FOUND as i64,
            Err(_) => ERR_GENERIC as i64,
        }
    })
    .unwrap_or(ERR_INTERNAL_PANIC as i64)
}

/// Reads a float value from the database.
///
/// # Arguments
/// * `path` - Null-terminated C string containing the path to the database file
/// * `key` - Null-terminated C string containing the key
/// * `out` - Pointer to write the f64 value to
///
/// # Returns
/// * `1` (ERR_SUCCESS) - Value read successfully
/// * `-1` (ERR_DB_NOT_FOUND) - Database not found in registry
/// * `-2` (ERR_INVALID_PATH) - Path, key, or out is null or invalid UTF-8
/// * `-5` (ERR_KEY_NOT_FOUND) - Key not found in database
/// * `-6` (ERR_TYPE_MISMATCH) - Value exists but is not a Float
/// * `-100` (ERR_INTERNAL_PANIC) - Internal panic occurred
///
/// # Safety
/// * `path` and `key` must be valid null-terminated C strings or null
/// * `out` must be a valid pointer to an f64
///
/// _Requirements: 6.2, 6.4_
#[no_mangle]
pub extern "C" fn SYNA_get_float(path: *const c_char, key: *const c_char, out: *mut f64) -> i32 {
    std::panic::catch_unwind(|| {
        // Validate pointers
        if path.is_null() || key.is_null() || out.is_null() {
            return ERR_INVALID_PATH;
        }

        // Convert C strings to Rust strings
        let path_str = match unsafe { CStr::from_ptr(path) }.to_str() {
            Ok(s) => s,
            Err(_) => return ERR_INVALID_PATH,
        };

        let key_str = match unsafe { CStr::from_ptr(key) }.to_str() {
            Ok(s) => s,
            Err(_) => return ERR_INVALID_PATH,
        };

        // Call with_db to get the value
        match with_db(path_str, |db| db.get(key_str)) {
            Ok(Some(Atom::Float(f))) => {
                // Write value to out pointer
                unsafe { *out = f };
                ERR_SUCCESS
            }
            Ok(Some(_)) => {
                // Value exists but is not a Float
                ERR_TYPE_MISMATCH
            }
            Ok(None) => {
                // Key not found
                ERR_KEY_NOT_FOUND
            }
            Err(crate::error::SynaError::NotFound(_)) => crate::error::ERR_DB_NOT_FOUND,
            Err(_) => ERR_GENERIC,
        }
    })
    .unwrap_or(ERR_INTERNAL_PANIC)
}

/// Reads an integer value from the database.
///
/// # Arguments
/// * `path` - Null-terminated C string containing the path to the database file
/// * `key` - Null-terminated C string containing the key
/// * `out` - Pointer to write the i64 value to
///
/// # Returns
/// * `1` (ERR_SUCCESS) - Value read successfully
/// * `-1` (ERR_DB_NOT_FOUND) - Database not found in registry
/// * `-2` (ERR_INVALID_PATH) - Path, key, or out is null or invalid UTF-8
/// * `-5` (ERR_KEY_NOT_FOUND) - Key not found in database
/// * `-6` (ERR_TYPE_MISMATCH) - Value exists but is not an Int
/// * `-100` (ERR_INTERNAL_PANIC) - Internal panic occurred
///
/// # Safety
/// * `path` and `key` must be valid null-terminated C strings or null
/// * `out` must be a valid pointer to an i64
///
/// _Requirements: 6.2, 6.4_
#[no_mangle]
pub extern "C" fn SYNA_get_int(path: *const c_char, key: *const c_char, out: *mut i64) -> i32 {
    std::panic::catch_unwind(|| {
        // Validate pointers
        if path.is_null() || key.is_null() || out.is_null() {
            return ERR_INVALID_PATH;
        }

        // Convert C strings to Rust strings
        let path_str = match unsafe { CStr::from_ptr(path) }.to_str() {
            Ok(s) => s,
            Err(_) => return ERR_INVALID_PATH,
        };

        let key_str = match unsafe { CStr::from_ptr(key) }.to_str() {
            Ok(s) => s,
            Err(_) => return ERR_INVALID_PATH,
        };

        // Call with_db to get the value
        match with_db(path_str, |db| db.get(key_str)) {
            Ok(Some(Atom::Int(i))) => {
                // Write value to out pointer
                unsafe { *out = i };
                ERR_SUCCESS
            }
            Ok(Some(_)) => {
                // Value exists but is not an Int
                ERR_TYPE_MISMATCH
            }
            Ok(None) => {
                // Key not found
                ERR_KEY_NOT_FOUND
            }
            Err(crate::error::SynaError::NotFound(_)) => crate::error::ERR_DB_NOT_FOUND,
            Err(_) => ERR_GENERIC,
        }
    })
    .unwrap_or(ERR_INTERNAL_PANIC)
}

/// Retrieves the complete history of float values for a key as a contiguous array.
///
/// This function is designed for AI/ML workloads where you need to feed time-series
/// data directly to frameworks like PyTorch or TensorFlow.
///
/// # Arguments
/// * `path` - Null-terminated C string containing the path to the database file
/// * `key` - Null-terminated C string containing the key
/// * `out_len` - Pointer to write the array length to
///
/// # Returns
/// * Non-null pointer to contiguous f64 array on success
/// * Null pointer on error (check out_len for error code)
///
/// # Error Codes (written to out_len on error)
/// * `0` - Empty history (no float values for this key)
///
/// # Safety
/// * `path` and `key` must be valid null-terminated C strings or null
/// * `out_len` must be a valid pointer to a usize
/// * The returned pointer MUST be freed using `SYNA_free_tensor()` to avoid memory leaks
///
/// _Requirements: 4.2, 6.4_
#[no_mangle]
pub extern "C" fn SYNA_get_history_tensor(
    path: *const c_char,
    key: *const c_char,
    out_len: *mut usize,
) -> *mut f64 {
    std::panic::catch_unwind(|| {
        // Validate pointers
        if path.is_null() || key.is_null() || out_len.is_null() {
            return std::ptr::null_mut();
        }

        // Convert C strings to Rust strings
        let path_str = match unsafe { CStr::from_ptr(path) }.to_str() {
            Ok(s) => s,
            Err(_) => return std::ptr::null_mut(),
        };

        let key_str = match unsafe { CStr::from_ptr(key) }.to_str() {
            Ok(s) => s,
            Err(_) => return std::ptr::null_mut(),
        };

        // Call with_db to get the history tensor
        match with_db(path_str, |db| db.get_history_tensor(key_str)) {
            Ok((ptr, len)) => {
                // Write length to out_len pointer
                unsafe { *out_len = len };
                ptr
            }
            Err(_) => {
                // Set out_len to 0 on error
                unsafe { *out_len = 0 };
                std::ptr::null_mut()
            }
        }
    })
    .unwrap_or(std::ptr::null_mut())
}

/// Frees memory allocated by `SYNA_get_history_tensor()`.
///
/// # Arguments
/// * `ptr` - Pointer returned by `SYNA_get_history_tensor()`
/// * `len` - Length returned by `SYNA_get_history_tensor()`
///
/// # Safety
/// * `ptr` must have been returned by `SYNA_get_history_tensor()`
/// * `len` must be the length returned alongside the pointer
/// * This function must only be called once per pointer
/// * Calling with a null pointer or zero length is safe (no-op)
///
/// _Requirements: 4.3, 6.5_
#[no_mangle]
pub extern "C" fn SYNA_free_tensor(ptr: *mut f64, len: usize) {
    std::panic::catch_unwind(|| {
        // Call internal free_tensor (safe wrapper)
        unsafe { free_tensor(ptr, len) };
    })
    .ok(); // Ignore panic result - we don't want to propagate panics from free
}

/// Deletes a key from the database by appending a tombstone entry.
///
/// # Arguments
/// * `path` - Null-terminated C string containing the path to the database file
/// * `key` - Null-terminated C string containing the key to delete
///
/// # Returns
/// * `1` (ERR_SUCCESS) - Key deleted successfully
/// * `0` (ERR_GENERIC) - Generic error during delete
/// * `-1` (ERR_DB_NOT_FOUND) - Database not found in registry
/// * `-2` (ERR_INVALID_PATH) - Path or key is null or invalid UTF-8
/// * `-100` (ERR_INTERNAL_PANIC) - Internal panic occurred
///
/// # Safety
/// * `path` and `key` must be valid null-terminated C strings or null
///
/// _Requirements: 10.1_
#[no_mangle]
pub extern "C" fn SYNA_delete(path: *const c_char, key: *const c_char) -> i32 {
    std::panic::catch_unwind(|| {
        // Validate pointers
        if path.is_null() || key.is_null() {
            return ERR_INVALID_PATH;
        }

        // Convert C strings to Rust strings
        let path_str = match unsafe { CStr::from_ptr(path) }.to_str() {
            Ok(s) => s,
            Err(_) => return ERR_INVALID_PATH,
        };

        let key_str = match unsafe { CStr::from_ptr(key) }.to_str() {
            Ok(s) => s,
            Err(_) => return ERR_INVALID_PATH,
        };

        // Call with_db to delete the key
        match with_db(path_str, |db| db.delete(key_str)) {
            Ok(_) => ERR_SUCCESS,
            Err(crate::error::SynaError::NotFound(_)) => crate::error::ERR_DB_NOT_FOUND,
            Err(_) => ERR_GENERIC,
        }
    })
    .unwrap_or(ERR_INTERNAL_PANIC)
}

/// Checks if a key exists in the database and is not deleted.
///
/// # Arguments
/// * `path` - Null-terminated C string containing the path to the database file
/// * `key` - Null-terminated C string containing the key to check
///
/// # Returns
/// * `1` - Key exists and is not deleted
/// * `0` - Key does not exist or is deleted
/// * `-1` (ERR_DB_NOT_FOUND) - Database not found in registry
/// * `-2` (ERR_INVALID_PATH) - Path or key is null or invalid UTF-8
/// * `-100` (ERR_INTERNAL_PANIC) - Internal panic occurred
///
/// # Safety
/// * `path` and `key` must be valid null-terminated C strings or null
///
/// _Requirements: 10.2_
#[no_mangle]
pub extern "C" fn SYNA_exists(path: *const c_char, key: *const c_char) -> i32 {
    std::panic::catch_unwind(|| {
        // Validate pointers
        if path.is_null() || key.is_null() {
            return ERR_INVALID_PATH;
        }

        // Convert C strings to Rust strings
        let path_str = match unsafe { CStr::from_ptr(path) }.to_str() {
            Ok(s) => s,
            Err(_) => return ERR_INVALID_PATH,
        };

        let key_str = match unsafe { CStr::from_ptr(key) }.to_str() {
            Ok(s) => s,
            Err(_) => return ERR_INVALID_PATH,
        };

        // Call with_db to check if key exists
        match with_db(path_str, |db| Ok(db.exists(key_str))) {
            Ok(true) => 1,
            Ok(false) => 0,
            Err(crate::error::SynaError::NotFound(_)) => crate::error::ERR_DB_NOT_FOUND,
            Err(_) => ERR_GENERIC,
        }
    })
    .unwrap_or(ERR_INTERNAL_PANIC)
}

/// Compacts the database by rewriting only the latest non-deleted entries.
///
/// This operation reclaims disk space by removing deleted entries and old versions.
/// After compaction, `get_history()` will only return the latest value for each key.
///
/// # Arguments
/// * `path` - Null-terminated C string containing the path to the database file
///
/// # Returns
/// * `1` (ERR_SUCCESS) - Compaction completed successfully
/// * `0` (ERR_GENERIC) - Generic error during compaction
/// * `-1` (ERR_DB_NOT_FOUND) - Database not found in registry
/// * `-2` (ERR_INVALID_PATH) - Path is null or invalid UTF-8
/// * `-100` (ERR_INTERNAL_PANIC) - Internal panic occurred
///
/// # Safety
/// * `path` must be a valid null-terminated C string or null
///
/// _Requirements: 11.1_
#[no_mangle]
pub extern "C" fn SYNA_compact(path: *const c_char) -> i32 {
    std::panic::catch_unwind(|| {
        // Validate pointer
        if path.is_null() {
            return ERR_INVALID_PATH;
        }

        // Convert C string to Rust string
        let path_str = match unsafe { CStr::from_ptr(path) }.to_str() {
            Ok(s) => s,
            Err(_) => return ERR_INVALID_PATH,
        };

        // Call with_db to compact the database
        match with_db(path_str, |db| db.compact()) {
            Ok(_) => ERR_SUCCESS,
            Err(crate::error::SynaError::NotFound(_)) => crate::error::ERR_DB_NOT_FOUND,
            Err(_) => ERR_GENERIC,
        }
    })
    .unwrap_or(ERR_INTERNAL_PANIC)
}

/// Returns a list of all non-deleted keys in the database.
///
/// # Arguments
/// * `path` - Null-terminated C string containing the path to the database file
/// * `out_len` - Pointer to write the number of keys to
///
/// # Returns
/// * Non-null pointer to array of null-terminated C strings on success
/// * Null pointer on error
///
/// # Safety
/// * `path` must be a valid null-terminated C string or null
/// * `out_len` must be a valid pointer to a usize
/// * The returned pointer MUST be freed using `SYNA_free_keys()` to avoid memory leaks
///
/// _Requirements: 10.5_
#[no_mangle]
pub extern "C" fn SYNA_keys(path: *const c_char, out_len: *mut usize) -> *mut *mut c_char {
    std::panic::catch_unwind(|| {
        // Validate pointers
        if path.is_null() || out_len.is_null() {
            return std::ptr::null_mut();
        }

        // Convert C string to Rust string
        let path_str = match unsafe { CStr::from_ptr(path) }.to_str() {
            Ok(s) => s,
            Err(_) => return std::ptr::null_mut(),
        };

        // Call with_db to get keys
        match with_db(path_str, |db| Ok(db.keys())) {
            Ok(keys) => {
                let len = keys.len();

                if len == 0 {
                    // No keys - return null with length 0
                    unsafe { *out_len = 0 };
                    return std::ptr::null_mut();
                }

                // Allocate array of C string pointers
                let mut c_strings: Vec<*mut c_char> = Vec::with_capacity(len);

                for key in keys {
                    // Convert each key to a C string
                    // Add null terminator
                    let mut bytes = key.into_bytes();
                    bytes.push(0); // null terminator

                    // Allocate memory for the C string
                    let c_str = bytes.into_boxed_slice();
                    let ptr = Box::into_raw(c_str) as *mut c_char;
                    c_strings.push(ptr);
                }

                // Write length to out_len
                unsafe { *out_len = len };

                // Convert Vec to boxed slice and leak for FFI
                let boxed = c_strings.into_boxed_slice();
                Box::into_raw(boxed) as *mut *mut c_char
            }
            Err(_) => {
                unsafe { *out_len = 0 };
                std::ptr::null_mut()
            }
        }
    })
    .unwrap_or(std::ptr::null_mut())
}

/// Frees memory allocated by `SYNA_keys()`.
///
/// # Arguments
/// * `keys` - Pointer returned by `SYNA_keys()`
/// * `len` - Length returned by `SYNA_keys()`
///
/// # Safety
/// * `keys` must have been returned by `SYNA_keys()`
/// * `len` must be the length returned alongside the pointer
/// * This function must only be called once per pointer
/// * Calling with a null pointer or zero length is safe (no-op)
///
/// _Requirements: 6.5_
#[no_mangle]
pub extern "C" fn SYNA_free_keys(keys: *mut *mut c_char, len: usize) {
    std::panic::catch_unwind(|| {
        if keys.is_null() || len == 0 {
            return;
        }

        unsafe {
            // Reconstruct the slice of pointers
            let key_slice = std::slice::from_raw_parts_mut(keys, len);

            // Free each individual string
            for key_ptr in key_slice.iter() {
                if !key_ptr.is_null() {
                    // Find the length of the C string (including null terminator)
                    let c_str = CStr::from_ptr(*key_ptr);
                    let str_len = c_str.to_bytes_with_nul().len();

                    // Reconstruct the box and drop it
                    let _ =
                        Box::from_raw(std::slice::from_raw_parts_mut(*key_ptr as *mut u8, str_len));
                }
            }

            // Free the array itself
            let _ = Box::from_raw(std::slice::from_raw_parts_mut(keys, len));
        }
    })
    .ok(); // Ignore panic result - we don't want to propagate panics from free
}

/// Reads a text value from the database.
///
/// # Arguments
/// * `path` - Null-terminated C string containing the path to the database file
/// * `key` - Null-terminated C string containing the key
/// * `out_len` - Pointer to write the string length to (excluding null terminator)
///
/// # Returns
/// * Non-null pointer to null-terminated C string on success
/// * Null pointer on error
///
/// # Error Codes (check return value)
/// * Null with out_len = 0 - Key not found or type mismatch
///
/// # Safety
/// * `path` and `key` must be valid null-terminated C strings or null
/// * `out_len` must be a valid pointer to a usize
/// * The returned pointer MUST be freed using `SYNA_free_text()` to avoid memory leaks
///
/// _Requirements: 6.2, 6.4_
#[no_mangle]
pub extern "C" fn SYNA_get_text(
    path: *const c_char,
    key: *const c_char,
    out_len: *mut usize,
) -> *mut c_char {
    std::panic::catch_unwind(|| {
        // Validate pointers
        if path.is_null() || key.is_null() || out_len.is_null() {
            return std::ptr::null_mut();
        }

        // Convert C strings to Rust strings
        let path_str = match unsafe { CStr::from_ptr(path) }.to_str() {
            Ok(s) => s,
            Err(_) => return std::ptr::null_mut(),
        };

        let key_str = match unsafe { CStr::from_ptr(key) }.to_str() {
            Ok(s) => s,
            Err(_) => return std::ptr::null_mut(),
        };

        // Call with_db to get the value
        match with_db(path_str, |db| db.get(key_str)) {
            Ok(Some(Atom::Text(s))) => {
                let len = s.len();
                unsafe { *out_len = len };

                // Convert to C string with null terminator
                let mut bytes = s.into_bytes();
                bytes.push(0); // null terminator

                let c_str = bytes.into_boxed_slice();
                Box::into_raw(c_str) as *mut c_char
            }
            Ok(Some(_)) => {
                // Value exists but is not Text
                unsafe { *out_len = 0 };
                std::ptr::null_mut()
            }
            Ok(None) => {
                // Key not found
                unsafe { *out_len = 0 };
                std::ptr::null_mut()
            }
            Err(_) => {
                unsafe { *out_len = 0 };
                std::ptr::null_mut()
            }
        }
    })
    .unwrap_or(std::ptr::null_mut())
}

/// Frees memory allocated by `SYNA_get_text()`.
///
/// # Arguments
/// * `ptr` - Pointer returned by `SYNA_get_text()`
/// * `len` - Length returned by `SYNA_get_text()` (excluding null terminator)
///
/// # Safety
/// * `ptr` must have been returned by `SYNA_get_text()`
/// * `len` must be the length returned alongside the pointer
/// * This function must only be called once per pointer
/// * Calling with a null pointer is safe (no-op)
///
/// _Requirements: 6.5_
#[no_mangle]
pub extern "C" fn SYNA_free_text(ptr: *mut c_char, len: usize) {
    std::panic::catch_unwind(|| {
        if ptr.is_null() {
            return;
        }

        unsafe {
            // Reconstruct the box (len + 1 for null terminator)
            let _ = Box::from_raw(std::slice::from_raw_parts_mut(ptr as *mut u8, len + 1));
        }
    })
    .ok();
}

/// Reads a byte array from the database.
///
/// # Arguments
/// * `path` - Null-terminated C string containing the path to the database file
/// * `key` - Null-terminated C string containing the key
/// * `out_len` - Pointer to write the array length to
///
/// # Returns
/// * Non-null pointer to byte array on success
/// * Null pointer on error
///
/// # Error Codes (check return value)
/// * Null with out_len = 0 - Key not found or type mismatch
///
/// # Safety
/// * `path` and `key` must be valid null-terminated C strings or null
/// * `out_len` must be a valid pointer to a usize
/// * The returned pointer MUST be freed using `SYNA_free_bytes()` to avoid memory leaks
///
/// _Requirements: 6.2, 6.4_
#[no_mangle]
pub extern "C" fn SYNA_get_bytes(
    path: *const c_char,
    key: *const c_char,
    out_len: *mut usize,
) -> *mut u8 {
    std::panic::catch_unwind(|| {
        // Validate pointers
        if path.is_null() || key.is_null() || out_len.is_null() {
            return std::ptr::null_mut();
        }

        // Convert C strings to Rust strings
        let path_str = match unsafe { CStr::from_ptr(path) }.to_str() {
            Ok(s) => s,
            Err(_) => return std::ptr::null_mut(),
        };

        let key_str = match unsafe { CStr::from_ptr(key) }.to_str() {
            Ok(s) => s,
            Err(_) => return std::ptr::null_mut(),
        };

        // Call with_db to get the value
        match with_db(path_str, |db| db.get(key_str)) {
            Ok(Some(Atom::Bytes(bytes))) => {
                let len = bytes.len();

                if len == 0 {
                    unsafe { *out_len = 0 };
                    return std::ptr::null_mut();
                }

                unsafe { *out_len = len };

                // Convert to boxed slice and leak for FFI
                let boxed = bytes.into_boxed_slice();
                Box::into_raw(boxed) as *mut u8
            }
            Ok(Some(_)) => {
                // Value exists but is not Bytes
                unsafe { *out_len = 0 };
                std::ptr::null_mut()
            }
            Ok(None) => {
                // Key not found
                unsafe { *out_len = 0 };
                std::ptr::null_mut()
            }
            Err(_) => {
                unsafe { *out_len = 0 };
                std::ptr::null_mut()
            }
        }
    })
    .unwrap_or(std::ptr::null_mut())
}

/// Frees memory allocated by `SYNA_get_bytes()`.
///
/// # Arguments
/// * `ptr` - Pointer returned by `SYNA_get_bytes()`
/// * `len` - Length returned by `SYNA_get_bytes()`
///
/// # Safety
/// * `ptr` must have been returned by `SYNA_get_bytes()`
/// * `len` must be the length returned alongside the pointer
/// * This function must only be called once per pointer
/// * Calling with a null pointer or zero length is safe (no-op)
///
/// _Requirements: 6.5_
#[no_mangle]
pub extern "C" fn SYNA_free_bytes(ptr: *mut u8, len: usize) {
    std::panic::catch_unwind(|| {
        if ptr.is_null() || len == 0 {
            return;
        }

        unsafe {
            let _ = Box::from_raw(std::slice::from_raw_parts_mut(ptr, len));
        }
    })
    .ok();
}

/* ============================================================================
 * Vector Functions (AI/ML Embeddings)
 * ============================================================================ */

/// Stores a vector (embedding) in the database.
///
/// Vectors are stored as `Atom::Vector(Vec<f32>, u16)` where the second
/// element is the dimensionality. This is optimized for AI/ML embedding
/// storage and similarity search.
///
/// # Arguments
/// * `path` - Null-terminated C string containing the path to the database file
/// * `key` - Null-terminated C string containing the key
/// * `data` - Pointer to f32 array containing the vector data
/// * `dimensions` - Number of dimensions (elements) in the vector
///
/// # Returns
/// * Positive value - The byte offset where the entry was written
/// * `-1` (ERR_DB_NOT_FOUND) - Database not found in registry
/// * `-2` (ERR_INVALID_PATH) - Path, key, or data is null or invalid UTF-8
/// * `-100` (ERR_INTERNAL_PANIC) - Internal panic occurred
///
/// # Safety
/// * `path` and `key` must be valid null-terminated C strings or null
/// * `data` must be a valid pointer to at least `dimensions` f32 values, or null
///
/// _Requirements: 1.1_
#[no_mangle]
pub extern "C" fn SYNA_put_vector(
    path: *const c_char,
    key: *const c_char,
    data: *const f32,
    dimensions: u16,
) -> i64 {
    std::panic::catch_unwind(|| {
        // Validate pointers
        if path.is_null() || key.is_null() || (data.is_null() && dimensions > 0) {
            return ERR_INVALID_PATH as i64;
        }

        // Convert C strings to Rust strings
        let path_str = match unsafe { CStr::from_ptr(path) }.to_str() {
            Ok(s) => s,
            Err(_) => return ERR_INVALID_PATH as i64,
        };

        let key_str = match unsafe { CStr::from_ptr(key) }.to_str() {
            Ok(s) => s,
            Err(_) => return ERR_INVALID_PATH as i64,
        };

        // Create Vec<f32> from raw pointer and dimensions
        let vector = if dimensions == 0 {
            Vec::new()
        } else {
            unsafe { std::slice::from_raw_parts(data, dimensions as usize) }.to_vec()
        };

        // Call with_db to append the vector
        match with_db(path_str, |db| {
            db.append(key_str, Atom::Vector(vector, dimensions))
        }) {
            Ok(offset) => offset as i64,
            Err(crate::error::SynaError::NotFound(_)) => crate::error::ERR_DB_NOT_FOUND as i64,
            Err(_) => ERR_GENERIC as i64,
        }
    })
    .unwrap_or(ERR_INTERNAL_PANIC as i64)
}

/// Retrieves a vector (embedding) from the database.
///
/// # Arguments
/// * `path` - Null-terminated C string containing the path to the database file
/// * `key` - Null-terminated C string containing the key
/// * `out_data` - Pointer to store the allocated f32 array pointer
/// * `out_dimensions` - Pointer to store the number of dimensions
///
/// # Returns
/// * `1` (ERR_SUCCESS) - Vector retrieved successfully
/// * `0` (ERR_GENERIC) - Generic error
/// * `-1` (ERR_DB_NOT_FOUND) - Database not found in registry
/// * `-2` (ERR_INVALID_PATH) - Path, key, or output pointers are null or invalid UTF-8
/// * `-5` (ERR_KEY_NOT_FOUND) - Key not found in database
/// * `-6` (ERR_TYPE_MISMATCH) - Value exists but is not a Vector
/// * `-100` (ERR_INTERNAL_PANIC) - Internal panic occurred
///
/// # Safety
/// * `path` and `key` must be valid null-terminated C strings or null
/// * `out_data` must be a valid pointer to a `*mut f32`
/// * `out_dimensions` must be a valid pointer to a `u16`
/// * The returned data pointer MUST be freed using `SYNA_free_vector()` to avoid memory leaks
///
/// _Requirements: 1.1_
#[no_mangle]
pub extern "C" fn SYNA_get_vector(
    path: *const c_char,
    key: *const c_char,
    out_data: *mut *mut f32,
    out_dimensions: *mut u16,
) -> i32 {
    std::panic::catch_unwind(|| {
        // Validate pointers
        if path.is_null() || key.is_null() || out_data.is_null() || out_dimensions.is_null() {
            return ERR_INVALID_PATH;
        }

        // Convert C strings to Rust strings
        let path_str = match unsafe { CStr::from_ptr(path) }.to_str() {
            Ok(s) => s,
            Err(_) => return ERR_INVALID_PATH,
        };

        let key_str = match unsafe { CStr::from_ptr(key) }.to_str() {
            Ok(s) => s,
            Err(_) => return ERR_INVALID_PATH,
        };

        // Call with_db to get the value
        match with_db(path_str, |db| db.get(key_str)) {
            Ok(Some(Atom::Vector(vec_data, dims))) => {
                // Write dimensions to output
                unsafe { *out_dimensions = dims };

                if vec_data.is_empty() {
                    // Empty vector - return null pointer with 0 dimensions
                    unsafe { *out_data = std::ptr::null_mut() };
                    return ERR_SUCCESS;
                }

                // Convert to boxed slice and leak for FFI
                let boxed = vec_data.into_boxed_slice();
                unsafe { *out_data = Box::into_raw(boxed) as *mut f32 };

                ERR_SUCCESS
            }
            Ok(Some(_)) => {
                // Value exists but is not a Vector
                unsafe {
                    *out_data = std::ptr::null_mut();
                    *out_dimensions = 0;
                }
                ERR_TYPE_MISMATCH
            }
            Ok(None) => {
                // Key not found
                unsafe {
                    *out_data = std::ptr::null_mut();
                    *out_dimensions = 0;
                }
                ERR_KEY_NOT_FOUND
            }
            Err(crate::error::SynaError::NotFound(_)) => {
                unsafe {
                    *out_data = std::ptr::null_mut();
                    *out_dimensions = 0;
                }
                crate::error::ERR_DB_NOT_FOUND
            }
            Err(_) => {
                unsafe {
                    *out_data = std::ptr::null_mut();
                    *out_dimensions = 0;
                }
                ERR_GENERIC
            }
        }
    })
    .unwrap_or(ERR_INTERNAL_PANIC)
}

/// Frees memory allocated by `SYNA_get_vector()`.
///
/// # Arguments
/// * `data` - Pointer returned by `SYNA_get_vector()` in `out_data`
/// * `dimensions` - Dimensions returned by `SYNA_get_vector()` in `out_dimensions`
///
/// # Safety
/// * `data` must have been returned by `SYNA_get_vector()`
/// * `dimensions` must be the dimensions returned alongside the pointer
/// * This function must only be called once per pointer
/// * Calling with a null pointer or zero dimensions is safe (no-op)
///
/// _Requirements: 1.1_
#[no_mangle]
pub extern "C" fn SYNA_free_vector(data: *mut f32, dimensions: u16) {
    std::panic::catch_unwind(|| {
        if data.is_null() || dimensions == 0 {
            return;
        }

        unsafe {
            let _ = Box::from_raw(std::slice::from_raw_parts_mut(data, dimensions as usize));
        }
    })
    .ok(); // Ignore panic result - we don't want to propagate panics from free
}

// =============================================================================
// VectorStore FFI Functions
// =============================================================================

use std::collections::HashMap;
use std::ffi::CString;
use std::path::{Path, PathBuf};

use once_cell::sync::Lazy;
use parking_lot::Mutex;

use crate::distance::DistanceMetric;
use crate::vector::{VectorConfig, VectorStore};

/// Thread-safe global registry for managing open VectorStore instances.
/// Uses canonicalized paths as keys to ensure uniqueness.
static VECTOR_STORE_REGISTRY: Lazy<Mutex<HashMap<String, VectorStore>>> =
    Lazy::new(|| Mutex::new(HashMap::new()));

/// Canonicalizes a path to an absolute path string for consistent registry keys.
///
/// If the path doesn't exist yet (for new databases), we use the parent directory's
/// canonical path combined with the filename.
fn canonicalize_vector_path(path: &str) -> Option<String> {
    let path_buf = PathBuf::from(path);

    // Try to canonicalize directly (works if file exists)
    if let Ok(canonical) = std::fs::canonicalize(&path_buf) {
        return Some(canonical.to_string_lossy().to_string());
    }

    // File doesn't exist yet - canonicalize parent and append filename
    let parent = path_buf.parent().unwrap_or(Path::new("."));
    let filename = path_buf.file_name()?;

    // Canonicalize parent directory
    let canonical_parent = if parent.as_os_str().is_empty() || parent == Path::new(".") {
        std::env::current_dir().ok()?
    } else {
        std::fs::canonicalize(parent).ok()?
    };

    let canonical = canonical_parent.join(filename);
    Some(canonical.to_string_lossy().to_string())
}

/// Creates a new vector store at the given path.
///
/// # Arguments
/// * `path` - Null-terminated C string containing the path to the database file
/// * `dimensions` - Number of dimensions for vectors (64-8192)
/// * `metric` - Distance metric: 0=Cosine, 1=Euclidean, 2=DotProduct
///
/// # Returns
/// * `1` (ERR_SUCCESS) - Vector store created successfully
/// * `0` (ERR_GENERIC) - Generic error during creation
/// * `-2` (ERR_INVALID_PATH) - Path is null or invalid UTF-8
/// * `-100` (ERR_INTERNAL_PANIC) - Internal panic occurred
///
/// # Safety
/// * `path` must be a valid null-terminated C string or null
///
/// _Requirements: 8.1_
#[no_mangle]
pub extern "C" fn SYNA_vector_store_new(path: *const c_char, dimensions: u16, metric: i32) -> i32 {
    std::panic::catch_unwind(|| {
        // Check for null pointer
        if path.is_null() {
            return ERR_INVALID_PATH;
        }

        // Convert C string to Rust string
        let c_str = unsafe { CStr::from_ptr(path) };
        let path_str = match c_str.to_str() {
            Ok(s) => s,
            Err(_) => return ERR_INVALID_PATH,
        };

        // Convert metric integer to DistanceMetric enum
        let distance_metric = match metric {
            0 => DistanceMetric::Cosine,
            1 => DistanceMetric::Euclidean,
            2 => DistanceMetric::DotProduct,
            _ => DistanceMetric::Cosine, // Default to Cosine for invalid values
        };

        // Create config
        let config = VectorConfig {
            dimensions,
            metric: distance_metric,
            ..Default::default()
        };

        // Canonicalize path for consistent registry keys
        let canonical_path = match canonicalize_vector_path(path_str) {
            Some(p) => p,
            None => return ERR_INVALID_PATH,
        };

        // Create the vector store
        match VectorStore::new(path_str, config) {
            Ok(store) => {
                // Register in global registry with canonicalized path
                let mut registry = VECTOR_STORE_REGISTRY.lock();
                registry.insert(canonical_path, store);
                ERR_SUCCESS
            }
            Err(_) => ERR_GENERIC,
        }
    })
    .unwrap_or(ERR_INTERNAL_PANIC)
}

/// Creates a new vector store with sync_on_write configuration.
///
/// # Arguments
/// * `path` - Null-terminated C string containing the path to the database file
/// * `dimensions` - Number of dimensions for vectors (64-8192)
/// * `metric` - Distance metric: 0=Cosine, 1=Euclidean, 2=DotProduct
/// * `sync_on_write` - 1 for sync after each write (durable), 0 for no sync (fast)
///
/// # Returns
/// * `1` (ERR_SUCCESS) - Vector store created successfully
/// * `0` (ERR_GENERIC) - Generic error during creation
/// * `-2` (ERR_INVALID_PATH) - Path is null or invalid UTF-8
/// * `-100` (ERR_INTERNAL_PANIC) - Internal panic occurred
///
/// # Safety
/// * `path` must be a valid null-terminated C string or null
#[no_mangle]
pub extern "C" fn SYNA_vector_store_new_with_config(
    path: *const c_char,
    dimensions: u16,
    metric: i32,
    sync_on_write: i32,
) -> i32 {
    std::panic::catch_unwind(|| {
        // Check for null pointer
        if path.is_null() {
            return ERR_INVALID_PATH;
        }

        // Convert C string to Rust string
        let c_str = unsafe { CStr::from_ptr(path) };
        let path_str = match c_str.to_str() {
            Ok(s) => s,
            Err(_) => return ERR_INVALID_PATH,
        };

        // Convert metric integer to DistanceMetric enum
        let distance_metric = match metric {
            0 => DistanceMetric::Cosine,
            1 => DistanceMetric::Euclidean,
            2 => DistanceMetric::DotProduct,
            _ => DistanceMetric::Cosine,
        };

        // Create config with sync_on_write setting
        let config = VectorConfig {
            dimensions,
            metric: distance_metric,
            sync_on_write: sync_on_write != 0,
            ..Default::default()
        };

        // Canonicalize path for consistent registry keys
        let canonical_path = match canonicalize_vector_path(path_str) {
            Some(p) => p,
            None => return ERR_INVALID_PATH,
        };

        // Create the vector store
        match VectorStore::new(path_str, config) {
            Ok(store) => {
                // Register in global registry with canonicalized path
                let mut registry = VECTOR_STORE_REGISTRY.lock();
                registry.insert(canonical_path, store);
                ERR_SUCCESS
            }
            Err(_) => ERR_GENERIC,
        }
    })
    .unwrap_or(ERR_INTERNAL_PANIC)
}

/// Inserts a vector into the store.
///
/// # Arguments
/// * `path` - Null-terminated C string containing the path to the database file
/// * `key` - Null-terminated C string containing the key
/// * `data` - Pointer to the f32 vector data
/// * `dimensions` - Number of dimensions in the vector
///
/// # Returns
/// * `1` (ERR_SUCCESS) - Vector inserted successfully
/// * `0` (ERR_GENERIC) - Generic error during insertion
/// * `-1` (ERR_DB_NOT_FOUND) - Vector store not found in registry
/// * `-2` (ERR_INVALID_PATH) - Path, key, or data is null or invalid UTF-8
/// * `-100` (ERR_INTERNAL_PANIC) - Internal panic occurred
///
/// # Safety
/// * `path` and `key` must be valid null-terminated C strings or null
/// * `data` must be a valid pointer to at least `dimensions` f32 values
///
/// _Requirements: 8.1_
#[no_mangle]
pub extern "C" fn SYNA_vector_store_insert(
    path: *const c_char,
    key: *const c_char,
    data: *const f32,
    dimensions: u16,
) -> i32 {
    std::panic::catch_unwind(|| {
        // Validate pointers
        if path.is_null() || key.is_null() || (data.is_null() && dimensions > 0) {
            return ERR_INVALID_PATH;
        }

        // Convert C strings to Rust strings
        let path_str = match unsafe { CStr::from_ptr(path) }.to_str() {
            Ok(s) => s,
            Err(_) => return ERR_INVALID_PATH,
        };

        let key_str = match unsafe { CStr::from_ptr(key) }.to_str() {
            Ok(s) => s,
            Err(_) => return ERR_INVALID_PATH,
        };

        // Canonicalize path for consistent registry keys
        let canonical_path = match canonicalize_vector_path(path_str) {
            Some(p) => p,
            None => return ERR_INVALID_PATH,
        };

        // Create vector from raw pointer
        let vector = if dimensions == 0 {
            Vec::new()
        } else {
            unsafe { std::slice::from_raw_parts(data, dimensions as usize) }.to_vec()
        };

        // Get the vector store from registry using canonicalized path
        let mut registry = VECTOR_STORE_REGISTRY.lock();
        match registry.get_mut(&canonical_path) {
            Some(store) => match store.insert(key_str, &vector) {
                Ok(_) => ERR_SUCCESS,
                Err(_) => ERR_GENERIC,
            },
            None => crate::error::ERR_DB_NOT_FOUND,
        }
    })
    .unwrap_or(ERR_INTERNAL_PANIC)
}

/// Inserts multiple vectors in a single batch operation.
///
/// This is significantly faster than calling `SYNA_vector_store_insert()` in a loop:
/// - Single FFI boundary crossing for all vectors
/// - Deferred index building until after all vectors are inserted
/// - Reduced lock contention
///
/// # Arguments
/// * `path` - Null-terminated C string containing the path to the database file
/// * `keys` - Array of null-terminated C strings (keys for each vector)
/// * `data` - Pointer to contiguous f32 array containing all vectors (row-major)
/// * `dimensions` - Number of dimensions per vector
/// * `count` - Number of vectors to insert
///
/// # Returns
/// * Non-negative value - Number of vectors successfully inserted
/// * `-1` (ERR_DB_NOT_FOUND) - Vector store not found in registry
/// * `-2` (ERR_INVALID_PATH) - Path, keys, or data is null or invalid
/// * `-100` (ERR_INTERNAL_PANIC) - Internal panic occurred
///
/// # Safety
/// * `path` must be a valid null-terminated C string
/// * `keys` must be a valid pointer to `count` null-terminated C strings
/// * `data` must be a valid pointer to `count * dimensions` f32 values
///
/// # Example (C)
/// ```c
/// const char* keys[] = {"doc1", "doc2", "doc3"};
/// float data[3 * 768] = { ... };  // 3 vectors of 768 dimensions
/// int32_t inserted = SYNA_vector_store_insert_batch("vectors.db", keys, data, 768, 3);
/// ```
///
/// _Requirements: 8.1_
#[no_mangle]
pub extern "C" fn SYNA_vector_store_insert_batch(
    path: *const c_char,
    keys: *const *const c_char,
    data: *const f32,
    dimensions: u16,
    count: usize,
) -> i32 {
    std::panic::catch_unwind(|| {
        // Validate pointers
        if path.is_null() || keys.is_null() || (data.is_null() && count > 0 && dimensions > 0) {
            return ERR_INVALID_PATH;
        }

        // Convert path
        let path_str = match unsafe { CStr::from_ptr(path) }.to_str() {
            Ok(s) => s,
            Err(_) => return ERR_INVALID_PATH,
        };

        // Canonicalize path
        let canonical_path = match canonicalize_vector_path(path_str) {
            Some(p) => p,
            None => return ERR_INVALID_PATH,
        };

        // Convert keys array
        let keys_slice = unsafe { std::slice::from_raw_parts(keys, count) };
        let mut key_strings: Vec<&str> = Vec::with_capacity(count);
        for key_ptr in keys_slice {
            if key_ptr.is_null() {
                return ERR_INVALID_PATH;
            }
            match unsafe { CStr::from_ptr(*key_ptr) }.to_str() {
                Ok(s) => key_strings.push(s),
                Err(_) => return ERR_INVALID_PATH,
            }
        }

        // Create vector slices from contiguous data
        let total_floats = count * dimensions as usize;
        let data_slice = if total_floats == 0 {
            &[]
        } else {
            unsafe { std::slice::from_raw_parts(data, total_floats) }
        };

        // Split into individual vectors
        let vectors: Vec<&[f32]> = data_slice.chunks(dimensions as usize).collect();

        // Get the vector store from registry
        let mut registry = VECTOR_STORE_REGISTRY.lock();
        match registry.get_mut(&canonical_path) {
            Some(store) => match store.insert_batch(&key_strings, &vectors) {
                Ok(n) => n as i32,
                Err(_) => ERR_GENERIC,
            },
            None => crate::error::ERR_DB_NOT_FOUND,
        }
    })
    .unwrap_or(ERR_INTERNAL_PANIC)
}

/// Inserts multiple vectors without updating the index (maximum write speed).
///
/// This is the fastest way to bulk-load vectors. Vectors are written to storage
/// but NOT added to the HNSW index. Call `SYNA_vector_store_build_index()` after
/// all inserts to build the index.
///
/// # Arguments
/// * `path` - Null-terminated C string containing the path to the database file
/// * `keys` - Array of null-terminated C strings (keys for each vector)
/// * `data` - Pointer to contiguous f32 array containing all vectors (row-major)
/// * `dimensions` - Number of dimensions per vector
/// * `count` - Number of vectors to insert
///
/// # Returns
/// * Non-negative value - Number of vectors successfully inserted
/// * `-1` (ERR_DB_NOT_FOUND) - Vector store not found in registry
/// * `-2` (ERR_INVALID_PATH) - Path, keys, or data is null or invalid
/// * `-100` (ERR_INTERNAL_PANIC) - Internal panic occurred
///
/// # Performance
/// This function achieves 100K+ inserts/sec by skipping index updates.
/// After bulk loading, call `SYNA_vector_store_build_index()` to enable fast search.
///
/// _Requirements: 8.1_
#[no_mangle]
pub extern "C" fn SYNA_vector_store_insert_batch_fast(
    path: *const c_char,
    keys: *const *const c_char,
    data: *const f32,
    dimensions: u16,
    count: usize,
) -> i32 {
    std::panic::catch_unwind(|| {
        if path.is_null() || keys.is_null() || (data.is_null() && count > 0 && dimensions > 0) {
            return ERR_INVALID_PATH;
        }

        let path_str = match unsafe { CStr::from_ptr(path) }.to_str() {
            Ok(s) => s,
            Err(_) => return ERR_INVALID_PATH,
        };

        let canonical_path = match canonicalize_vector_path(path_str) {
            Some(p) => p,
            None => return ERR_INVALID_PATH,
        };

        let keys_slice = unsafe { std::slice::from_raw_parts(keys, count) };
        let mut key_strings: Vec<&str> = Vec::with_capacity(count);
        for key_ptr in keys_slice {
            if key_ptr.is_null() {
                return ERR_INVALID_PATH;
            }
            match unsafe { CStr::from_ptr(*key_ptr) }.to_str() {
                Ok(s) => key_strings.push(s),
                Err(_) => return ERR_INVALID_PATH,
            }
        }

        let total_floats = count * dimensions as usize;
        let data_slice = if total_floats == 0 {
            &[]
        } else {
            unsafe { std::slice::from_raw_parts(data, total_floats) }
        };

        let vectors: Vec<&[f32]> = data_slice.chunks(dimensions as usize).collect();

        let mut registry = VECTOR_STORE_REGISTRY.lock();
        match registry.get_mut(&canonical_path) {
            Some(store) => match store.insert_batch_fast(&key_strings, &vectors, false) {
                Ok(n) => n as i32,
                Err(_) => ERR_GENERIC,
            },
            None => crate::error::ERR_DB_NOT_FOUND,
        }
    })
    .unwrap_or(ERR_INTERNAL_PANIC)
}

/// Searches for k nearest neighbors in the vector store.
///
/// Returns a JSON array of results with the following structure:
/// ```json
/// [
///   {"key": "doc1", "score": 0.123, "vector": [0.1, 0.2, ...]},
///   {"key": "doc2", "score": 0.456, "vector": [0.3, 0.4, ...]}
/// ]
/// ```
///
/// # Arguments
/// * `path` - Null-terminated C string containing the path to the database file
/// * `query` - Pointer to the f32 query vector
/// * `dimensions` - Number of dimensions in the query vector
/// * `k` - Number of nearest neighbors to return
/// * `out_json` - Pointer to write the JSON result string to
///
/// # Returns
/// * Non-negative value - Number of results found
/// * `-1` (ERR_DB_NOT_FOUND) - Vector store not found in registry
/// * `-2` (ERR_INVALID_PATH) - Path, query, or out_json is null or invalid
/// * `-100` (ERR_INTERNAL_PANIC) - Internal panic occurred
///
/// # Safety
/// * `path` must be a valid null-terminated C string or null
/// * `query` must be a valid pointer to at least `dimensions` f32 values
/// * `out_json` must be a valid pointer to a `*mut c_char`
/// * The returned JSON string MUST be freed using `SYNA_free_json()` to avoid memory leaks
///
/// _Requirements: 8.1_
#[no_mangle]
pub extern "C" fn SYNA_vector_store_search(
    path: *const c_char,
    query: *const f32,
    dimensions: u16,
    k: usize,
    out_json: *mut *mut c_char,
) -> i32 {
    std::panic::catch_unwind(|| {
        // Validate pointers
        if path.is_null() || query.is_null() || out_json.is_null() {
            return ERR_INVALID_PATH;
        }

        // Convert C string to Rust string
        let path_str = match unsafe { CStr::from_ptr(path) }.to_str() {
            Ok(s) => s,
            Err(_) => return ERR_INVALID_PATH,
        };

        // Canonicalize path for consistent registry keys
        let canonical_path = match canonicalize_vector_path(path_str) {
            Some(p) => p,
            None => return ERR_INVALID_PATH,
        };

        // Create query vector from raw pointer
        let query_vec: Vec<f32> =
            unsafe { std::slice::from_raw_parts(query, dimensions as usize) }.to_vec();

        // Get the vector store from registry using canonicalized path
        let mut registry = VECTOR_STORE_REGISTRY.lock();
        match registry.get_mut(&canonical_path) {
            Some(store) => match store.search(&query_vec, k) {
                Ok(results) => {
                    // Convert results to JSON
                    let json_results: Vec<serde_json::Value> = results
                        .iter()
                        .map(|r| {
                            serde_json::json!({
                                "key": r.key,
                                "score": r.score,
                                "vector": r.vector
                            })
                        })
                        .collect();

                    let json_str =
                        serde_json::to_string(&json_results).unwrap_or_else(|_| "[]".to_string());
                    let result_count = results.len() as i32;

                    // Convert to C string
                    match CString::new(json_str) {
                        Ok(c_string) => {
                            unsafe { *out_json = c_string.into_raw() };
                            result_count
                        }
                        Err(_) => ERR_GENERIC,
                    }
                }
                Err(_) => ERR_GENERIC,
            },
            None => crate::error::ERR_DB_NOT_FOUND,
        }
    })
    .unwrap_or(ERR_INTERNAL_PANIC)
}

/// Builds the HNSW index for a vector store.
///
/// This function manually triggers HNSW index construction for faster search.
/// The index is built automatically when vector count exceeds the threshold,
/// but this function allows explicit control.
///
/// # Arguments
/// * `path` - Null-terminated C string containing the path to the vector store
///
/// # Returns
/// * `1` (ERR_SUCCESS) - Index built successfully
/// * `0` (ERR_GENERIC) - Generic error during build
/// * `-1` (ERR_DB_NOT_FOUND) - Vector store not found in registry
/// * `-2` (ERR_INVALID_PATH) - Path is null or invalid UTF-8
/// * `-100` (ERR_INTERNAL_PANIC) - Internal panic occurred
///
/// # Safety
/// * `path` must be a valid null-terminated C string or null
///
/// _Requirements: 8.1_
#[no_mangle]
pub extern "C" fn SYNA_vector_store_build_index(path: *const c_char) -> i32 {
    std::panic::catch_unwind(|| {
        // Check for null pointer
        if path.is_null() {
            return ERR_INVALID_PATH;
        }

        // Convert path to Rust string
        let path_str = match unsafe { CStr::from_ptr(path) }.to_str() {
            Ok(s) => s,
            Err(_) => return ERR_INVALID_PATH,
        };

        // Canonicalize path for consistent registry keys
        let canonical_path = match canonicalize_vector_path(path_str) {
            Some(p) => p,
            None => return ERR_INVALID_PATH,
        };

        // Get the vector store from registry
        let mut registry = VECTOR_STORE_REGISTRY.lock();
        match registry.get_mut(&canonical_path) {
            Some(store) => match store.build_index() {
                Ok(()) => crate::error::ERR_SUCCESS,
                Err(_) => ERR_GENERIC,
            },
            None => crate::error::ERR_DB_NOT_FOUND,
        }
    })
    .unwrap_or(ERR_INTERNAL_PANIC)
}

/// Returns whether a vector store has an HNSW index built.
///
/// # Arguments
/// * `path` - Null-terminated C string containing the path to the vector store
///
/// # Returns
/// * `1` - Index is built
/// * `0` - Index is not built
/// * `-1` (ERR_DB_NOT_FOUND) - Vector store not found in registry
/// * `-2` (ERR_INVALID_PATH) - Path is null or invalid UTF-8
/// * `-100` (ERR_INTERNAL_PANIC) - Internal panic occurred
///
/// # Safety
/// * `path` must be a valid null-terminated C string or null
///
/// _Requirements: 8.1_
#[no_mangle]
pub extern "C" fn SYNA_vector_store_has_index(path: *const c_char) -> i32 {
    std::panic::catch_unwind(|| {
        // Check for null pointer
        if path.is_null() {
            return ERR_INVALID_PATH;
        }

        // Convert path to Rust string
        let path_str = match unsafe { CStr::from_ptr(path) }.to_str() {
            Ok(s) => s,
            Err(_) => return ERR_INVALID_PATH,
        };

        // Canonicalize path for consistent registry keys
        let canonical_path = match canonicalize_vector_path(path_str) {
            Some(p) => p,
            None => return ERR_INVALID_PATH,
        };

        // Get the vector store from registry
        let registry = VECTOR_STORE_REGISTRY.lock();
        match registry.get(&canonical_path) {
            Some(store) => {
                if store.has_index() {
                    1
                } else {
                    0
                }
            }
            None => crate::error::ERR_DB_NOT_FOUND,
        }
    })
    .unwrap_or(ERR_INTERNAL_PANIC)
}

/// Closes a vector store and saves any pending changes.
///
/// This function removes the vector store from the global registry and
/// triggers the Drop implementation, which saves any dirty index to disk.
///
/// # Arguments
/// * `path` - Null-terminated C string containing the path to the database file
///
/// # Returns
/// * `1` (ERR_SUCCESS) - Store closed successfully
/// * `-1` (ERR_DB_NOT_FOUND) - Store not found in registry
/// * `-2` (ERR_INVALID_PATH) - Path is null or invalid UTF-8
/// * `-100` (ERR_INTERNAL_PANIC) - Internal panic occurred
///
/// # Safety
/// * `path` must be a valid null-terminated C string or null
///
/// _Requirements: 8.1_
#[no_mangle]
pub extern "C" fn SYNA_vector_store_close(path: *const c_char) -> i32 {
    std::panic::catch_unwind(|| {
        // Check for null pointer
        if path.is_null() {
            return ERR_INVALID_PATH;
        }

        // Convert C string to Rust string
        let path_str = match unsafe { CStr::from_ptr(path) }.to_str() {
            Ok(s) => s,
            Err(_) => return ERR_INVALID_PATH,
        };

        // Canonicalize path for consistent lookup
        let canonical_path = match std::fs::canonicalize(path_str) {
            Ok(p) => p.to_string_lossy().to_string(),
            Err(_) => path_str.to_string(),
        };

        // Remove from registry (this triggers Drop which saves the index)
        let mut registry = VECTOR_STORE_REGISTRY.lock();
        match registry.remove(&canonical_path) {
            Some(_store) => {
                // Store is dropped here, triggering index save
                ERR_SUCCESS
            }
            None => crate::error::ERR_DB_NOT_FOUND,
        }
    })
    .unwrap_or(ERR_INTERNAL_PANIC)
}

/// Flushes any pending changes to disk without closing the store.
///
/// This saves the HNSW index if it has unsaved changes.
///
/// # Arguments
/// * `path` - Null-terminated C string containing the path to the database file
///
/// # Returns
/// * `1` (ERR_SUCCESS) - Flush successful
/// * `-1` (ERR_DB_NOT_FOUND) - Store not found in registry
/// * `-2` (ERR_INVALID_PATH) - Path is null or invalid UTF-8
/// * `0` (ERR_GENERIC) - Flush failed
/// * `-100` (ERR_INTERNAL_PANIC) - Internal panic occurred
///
/// # Safety
/// * `path` must be a valid null-terminated C string or null
///
/// _Requirements: 8.1_
#[no_mangle]
pub extern "C" fn SYNA_vector_store_flush(path: *const c_char) -> i32 {
    std::panic::catch_unwind(|| {
        // Check for null pointer
        if path.is_null() {
            return ERR_INVALID_PATH;
        }

        // Convert C string to Rust string
        let path_str = match unsafe { CStr::from_ptr(path) }.to_str() {
            Ok(s) => s,
            Err(_) => return ERR_INVALID_PATH,
        };

        // Canonicalize path for consistent lookup
        let canonical_path = match std::fs::canonicalize(path_str) {
            Ok(p) => p.to_string_lossy().to_string(),
            Err(_) => path_str.to_string(),
        };

        // Get store from registry
        let mut registry = VECTOR_STORE_REGISTRY.lock();
        match registry.get_mut(&canonical_path) {
            Some(store) => match store.flush() {
                Ok(_) => ERR_SUCCESS,
                Err(_) => ERR_GENERIC,
            },
            None => crate::error::ERR_DB_NOT_FOUND,
        }
    })
    .unwrap_or(ERR_INTERNAL_PANIC)
}

/// Frees a JSON string allocated by `SYNA_vector_store_search()`.
///
/// # Arguments
/// * `json` - Pointer returned by `SYNA_vector_store_search()` in `out_json`
///
/// # Safety
/// * `json` must have been returned by `SYNA_vector_store_search()`
/// * This function must only be called once per pointer
/// * Calling with a null pointer is safe (no-op)
///
/// _Requirements: 8.1_
#[no_mangle]
pub extern "C" fn SYNA_free_json(json: *mut c_char) {
    std::panic::catch_unwind(|| {
        if json.is_null() {
            return;
        }

        unsafe {
            // Reconstruct the CString and drop it
            let _ = CString::from_raw(json);
        }
    })
    .ok(); // Ignore panic result - we don't want to propagate panics from free
}

// =============================================================================
// Model Registry FFI Functions
// =============================================================================

use crate::model_registry::{ModelRegistry, ModelStage};

/// Thread-safe global registry for managing open ModelRegistry instances.
static MODEL_REGISTRY: Lazy<Mutex<HashMap<String, ModelRegistry>>> =
    Lazy::new(|| Mutex::new(HashMap::new()));

/// Opens or creates a model registry at the given path.
///
/// # Arguments
/// * `path` - Null-terminated C string containing the path to the database file
///
/// # Returns
/// * `1` (ERR_SUCCESS) - Registry opened successfully
/// * `0` (ERR_GENERIC) - Generic error during open
/// * `-2` (ERR_INVALID_PATH) - Path is null or invalid UTF-8
/// * `-100` (ERR_INTERNAL_PANIC) - Internal panic occurred
///
/// # Safety
/// * `path` must be a valid null-terminated C string or null
///
/// _Requirements: 8.1_
#[no_mangle]
pub extern "C" fn SYNA_model_registry_open(path: *const c_char) -> i32 {
    std::panic::catch_unwind(|| {
        if path.is_null() {
            return ERR_INVALID_PATH;
        }

        let path_str = match unsafe { CStr::from_ptr(path) }.to_str() {
            Ok(s) => s,
            Err(_) => return ERR_INVALID_PATH,
        };

        match ModelRegistry::new(path_str) {
            Ok(registry) => {
                let mut reg = MODEL_REGISTRY.lock();
                reg.insert(path_str.to_string(), registry);
                ERR_SUCCESS
            }
            Err(_) => ERR_GENERIC,
        }
    })
    .unwrap_or(ERR_INTERNAL_PANIC)
}

/// Saves a model to the registry with automatic versioning.
///
/// # Arguments
/// * `path` - Null-terminated C string containing the path to the registry
/// * `name` - Null-terminated C string containing the model name
/// * `data` - Pointer to the model data bytes
/// * `data_len` - Length of the model data
/// * `metadata_json` - Null-terminated JSON string with metadata (can be null for empty)
/// * `out_version` - Pointer to write the assigned version number
/// * `out_checksum` - Pointer to write the checksum string (caller must free with SYNA_free_text)
/// * `out_checksum_len` - Pointer to write the checksum string length
///
/// # Returns
/// * `1` (ERR_SUCCESS) - Model saved successfully
/// * `0` (ERR_GENERIC) - Generic error during save
/// * `-1` (ERR_DB_NOT_FOUND) - Registry not found
/// * `-2` (ERR_INVALID_PATH) - Invalid arguments
/// * `-100` (ERR_INTERNAL_PANIC) - Internal panic occurred
///
/// _Requirements: 8.1_
#[no_mangle]
pub extern "C" fn SYNA_model_save(
    path: *const c_char,
    name: *const c_char,
    data: *const u8,
    data_len: usize,
    metadata_json: *const c_char,
    out_version: *mut u32,
    out_checksum: *mut *mut c_char,
    out_checksum_len: *mut usize,
) -> i64 {
    std::panic::catch_unwind(|| {
        // Validate required pointers
        if path.is_null() || name.is_null() || (data.is_null() && data_len > 0) {
            return ERR_INVALID_PATH as i64;
        }
        if out_version.is_null() || out_checksum.is_null() || out_checksum_len.is_null() {
            return ERR_INVALID_PATH as i64;
        }

        let path_str = match unsafe { CStr::from_ptr(path) }.to_str() {
            Ok(s) => s,
            Err(_) => return ERR_INVALID_PATH as i64,
        };

        let name_str = match unsafe { CStr::from_ptr(name) }.to_str() {
            Ok(s) => s,
            Err(_) => return ERR_INVALID_PATH as i64,
        };

        // Parse metadata JSON if provided
        let metadata: std::collections::HashMap<String, String> = if metadata_json.is_null() {
            std::collections::HashMap::new()
        } else {
            match unsafe { CStr::from_ptr(metadata_json) }.to_str() {
                Ok(json_str) => serde_json::from_str(json_str).unwrap_or_default(),
                Err(_) => std::collections::HashMap::new(),
            }
        };

        // Create data slice
        let model_data = if data_len == 0 {
            &[]
        } else {
            unsafe { std::slice::from_raw_parts(data, data_len) }
        };

        // Get registry and save model
        let mut reg = MODEL_REGISTRY.lock();
        match reg.get_mut(path_str) {
            Some(registry) => {
                match registry.save_model(name_str, model_data, metadata) {
                    Ok(version) => {
                        unsafe { *out_version = version.version };

                        // Return checksum as C string
                        let checksum_len = version.checksum.len();
                        unsafe { *out_checksum_len = checksum_len };

                        let mut bytes = version.checksum.into_bytes();
                        bytes.push(0);
                        let c_str = bytes.into_boxed_slice();
                        unsafe { *out_checksum = Box::into_raw(c_str) as *mut c_char };

                        ERR_SUCCESS as i64
                    }
                    Err(_) => ERR_GENERIC as i64,
                }
            }
            None => crate::error::ERR_DB_NOT_FOUND as i64,
        }
    })
    .unwrap_or(ERR_INTERNAL_PANIC as i64)
}

/// Loads a model from the registry with checksum verification.
///
/// # Arguments
/// * `path` - Null-terminated C string containing the path to the registry
/// * `name` - Null-terminated C string containing the model name
/// * `version` - Version number to load (0 for latest)
/// * `out_data` - Pointer to write the model data pointer
/// * `out_data_len` - Pointer to write the model data length
/// * `out_meta_json` - Pointer to write the metadata JSON string
/// * `out_meta_len` - Pointer to write the metadata JSON length
///
/// # Returns
/// * `1` (ERR_SUCCESS) - Model loaded successfully
/// * `0` (ERR_GENERIC) - Generic error during load
/// * `-1` (ERR_DB_NOT_FOUND) - Registry not found
/// * `-2` (ERR_INVALID_PATH) - Invalid arguments
/// * `-5` (ERR_KEY_NOT_FOUND) - Model not found
/// * `-100` (ERR_INTERNAL_PANIC) - Internal panic occurred
///
/// _Requirements: 8.1_
#[no_mangle]
pub extern "C" fn SYNA_model_load(
    path: *const c_char,
    name: *const c_char,
    version: u32,
    out_data: *mut *mut u8,
    out_data_len: *mut usize,
    out_meta_json: *mut *mut c_char,
    out_meta_len: *mut usize,
) -> i32 {
    std::panic::catch_unwind(|| {
        if path.is_null() || name.is_null() || out_data.is_null() || out_data_len.is_null() {
            return ERR_INVALID_PATH;
        }
        if out_meta_json.is_null() || out_meta_len.is_null() {
            return ERR_INVALID_PATH;
        }

        let path_str = match unsafe { CStr::from_ptr(path) }.to_str() {
            Ok(s) => s,
            Err(_) => return ERR_INVALID_PATH,
        };

        let name_str = match unsafe { CStr::from_ptr(name) }.to_str() {
            Ok(s) => s,
            Err(_) => return ERR_INVALID_PATH,
        };

        let version_opt = if version == 0 { None } else { Some(version) };

        let mut reg = MODEL_REGISTRY.lock();
        match reg.get_mut(path_str) {
            Some(registry) => {
                match registry.load_model(name_str, version_opt) {
                    Ok((data, version_info)) => {
                        // Return model data
                        let data_len = data.len();
                        unsafe { *out_data_len = data_len };

                        if data_len > 0 {
                            let boxed = data.into_boxed_slice();
                            unsafe { *out_data = Box::into_raw(boxed) as *mut u8 };
                        } else {
                            unsafe { *out_data = std::ptr::null_mut() };
                        }

                        // Return metadata as JSON
                        let meta_json = serde_json::to_string(&version_info)
                            .unwrap_or_else(|_| "{}".to_string());
                        let meta_len = meta_json.len();
                        unsafe { *out_meta_len = meta_len };

                        let mut bytes = meta_json.into_bytes();
                        bytes.push(0);
                        let c_str = bytes.into_boxed_slice();
                        unsafe { *out_meta_json = Box::into_raw(c_str) as *mut c_char };

                        ERR_SUCCESS
                    }
                    Err(crate::error::SynaError::ModelNotFound(_)) => ERR_KEY_NOT_FOUND,
                    Err(crate::error::SynaError::ChecksumMismatch { .. }) => ERR_GENERIC,
                    Err(_) => ERR_GENERIC,
                }
            }
            None => crate::error::ERR_DB_NOT_FOUND,
        }
    })
    .unwrap_or(ERR_INTERNAL_PANIC)
}

/// Lists all versions of a model.
///
/// # Arguments
/// * `path` - Null-terminated C string containing the path to the registry
/// * `name` - Null-terminated C string containing the model name
/// * `out_json` - Pointer to write the JSON array of versions
/// * `out_len` - Pointer to write the JSON string length
///
/// # Returns
/// * Non-negative value - Number of versions found
/// * `-1` (ERR_DB_NOT_FOUND) - Registry not found
/// * `-2` (ERR_INVALID_PATH) - Invalid arguments
/// * `-100` (ERR_INTERNAL_PANIC) - Internal panic occurred
///
/// _Requirements: 8.1_
#[no_mangle]
pub extern "C" fn SYNA_model_list(
    path: *const c_char,
    name: *const c_char,
    out_json: *mut *mut c_char,
    out_len: *mut usize,
) -> i32 {
    std::panic::catch_unwind(|| {
        if path.is_null() || name.is_null() || out_json.is_null() || out_len.is_null() {
            return ERR_INVALID_PATH;
        }

        let path_str = match unsafe { CStr::from_ptr(path) }.to_str() {
            Ok(s) => s,
            Err(_) => return ERR_INVALID_PATH,
        };

        let name_str = match unsafe { CStr::from_ptr(name) }.to_str() {
            Ok(s) => s,
            Err(_) => return ERR_INVALID_PATH,
        };

        let mut reg = MODEL_REGISTRY.lock();
        match reg.get_mut(path_str) {
            Some(registry) => match registry.list_versions(name_str) {
                Ok(versions) => {
                    let count = versions.len() as i32;
                    let json =
                        serde_json::to_string(&versions).unwrap_or_else(|_| "[]".to_string());

                    unsafe { *out_len = json.len() };
                    match CString::new(json) {
                        Ok(c_string) => {
                            unsafe { *out_json = c_string.into_raw() };
                            count
                        }
                        Err(_) => ERR_GENERIC,
                    }
                }
                Err(_) => ERR_GENERIC,
            },
            None => crate::error::ERR_DB_NOT_FOUND,
        }
    })
    .unwrap_or(ERR_INTERNAL_PANIC)
}

/// Sets the deployment stage for a model version.
///
/// # Arguments
/// * `path` - Null-terminated C string containing the path to the registry
/// * `name` - Null-terminated C string containing the model name
/// * `version` - Version number to update
/// * `stage` - Stage: 0=Development, 1=Staging, 2=Production, 3=Archived
///
/// # Returns
/// * `1` (ERR_SUCCESS) - Stage updated successfully
/// * `0` (ERR_GENERIC) - Generic error
/// * `-1` (ERR_DB_NOT_FOUND) - Registry not found
/// * `-2` (ERR_INVALID_PATH) - Invalid arguments
/// * `-5` (ERR_KEY_NOT_FOUND) - Model/version not found
/// * `-100` (ERR_INTERNAL_PANIC) - Internal panic occurred
///
/// _Requirements: 8.1_
#[no_mangle]
pub extern "C" fn SYNA_model_set_stage(
    path: *const c_char,
    name: *const c_char,
    version: u32,
    stage: i32,
) -> i32 {
    std::panic::catch_unwind(|| {
        if path.is_null() || name.is_null() {
            return ERR_INVALID_PATH;
        }

        let path_str = match unsafe { CStr::from_ptr(path) }.to_str() {
            Ok(s) => s,
            Err(_) => return ERR_INVALID_PATH,
        };

        let name_str = match unsafe { CStr::from_ptr(name) }.to_str() {
            Ok(s) => s,
            Err(_) => return ERR_INVALID_PATH,
        };

        let model_stage = match stage {
            0 => ModelStage::Development,
            1 => ModelStage::Staging,
            2 => ModelStage::Production,
            3 => ModelStage::Archived,
            _ => ModelStage::Development,
        };

        let mut reg = MODEL_REGISTRY.lock();
        match reg.get_mut(path_str) {
            Some(registry) => match registry.set_stage(name_str, version, model_stage) {
                Ok(_) => ERR_SUCCESS,
                Err(crate::error::SynaError::ModelNotFound(_)) => ERR_KEY_NOT_FOUND,
                Err(_) => ERR_GENERIC,
            },
            None => crate::error::ERR_DB_NOT_FOUND,
        }
    })
    .unwrap_or(ERR_INTERNAL_PANIC)
}

// =============================================================================
// Experiment Tracking FFI Functions
// =============================================================================

use crate::experiment::{ExperimentTracker, RunStatus};

/// Thread-safe global registry for managing open ExperimentTracker instances.
static EXPERIMENT_REGISTRY: Lazy<Mutex<HashMap<String, ExperimentTracker>>> =
    Lazy::new(|| Mutex::new(HashMap::new()));

/// Opens or creates an experiment tracker at the given path.
///
/// # Arguments
/// * `path` - Null-terminated C string containing the path to the database file
///
/// # Returns
/// * `1` (ERR_SUCCESS) - Tracker opened successfully
/// * `0` (ERR_GENERIC) - Generic error during open
/// * `-2` (ERR_INVALID_PATH) - Path is null or invalid UTF-8
/// * `-100` (ERR_INTERNAL_PANIC) - Internal panic occurred
///
/// _Requirements: 8.1_
#[no_mangle]
pub extern "C" fn SYNA_exp_tracker_open(path: *const c_char) -> i32 {
    std::panic::catch_unwind(|| {
        if path.is_null() {
            return ERR_INVALID_PATH;
        }

        let path_str = match unsafe { CStr::from_ptr(path) }.to_str() {
            Ok(s) => s,
            Err(_) => return ERR_INVALID_PATH,
        };

        match ExperimentTracker::new(path_str) {
            Ok(tracker) => {
                let mut reg = EXPERIMENT_REGISTRY.lock();
                reg.insert(path_str.to_string(), tracker);
                ERR_SUCCESS
            }
            Err(_) => ERR_GENERIC,
        }
    })
    .unwrap_or(ERR_INTERNAL_PANIC)
}

/// Starts a new experiment run.
///
/// # Arguments
/// * `path` - Null-terminated C string containing the path to the tracker
/// * `experiment` - Null-terminated C string containing the experiment name
/// * `tags_json` - Null-terminated JSON array of tags (can be null for empty)
/// * `out_run_id` - Pointer to write the run ID string
/// * `out_run_id_len` - Pointer to write the run ID length
///
/// # Returns
/// * `1` (ERR_SUCCESS) - Run started successfully
/// * `0` (ERR_GENERIC) - Generic error
/// * `-1` (ERR_DB_NOT_FOUND) - Tracker not found
/// * `-2` (ERR_INVALID_PATH) - Invalid arguments
/// * `-100` (ERR_INTERNAL_PANIC) - Internal panic occurred
///
/// _Requirements: 8.1_
#[no_mangle]
pub extern "C" fn SYNA_exp_start_run(
    path: *const c_char,
    experiment: *const c_char,
    tags_json: *const c_char,
    out_run_id: *mut *mut c_char,
    out_run_id_len: *mut usize,
) -> i32 {
    std::panic::catch_unwind(|| {
        if path.is_null()
            || experiment.is_null()
            || out_run_id.is_null()
            || out_run_id_len.is_null()
        {
            return ERR_INVALID_PATH;
        }

        let path_str = match unsafe { CStr::from_ptr(path) }.to_str() {
            Ok(s) => s,
            Err(_) => return ERR_INVALID_PATH,
        };

        let exp_str = match unsafe { CStr::from_ptr(experiment) }.to_str() {
            Ok(s) => s,
            Err(_) => return ERR_INVALID_PATH,
        };

        let tags: Vec<String> = if tags_json.is_null() {
            Vec::new()
        } else {
            match unsafe { CStr::from_ptr(tags_json) }.to_str() {
                Ok(json_str) => serde_json::from_str(json_str).unwrap_or_default(),
                Err(_) => Vec::new(),
            }
        };

        let mut reg = EXPERIMENT_REGISTRY.lock();
        match reg.get_mut(path_str) {
            Some(tracker) => match tracker.start_run(exp_str, tags) {
                Ok(run_id) => {
                    let run_id_len = run_id.len();
                    unsafe { *out_run_id_len = run_id_len };

                    let mut bytes = run_id.into_bytes();
                    bytes.push(0);
                    let c_str = bytes.into_boxed_slice();
                    unsafe { *out_run_id = Box::into_raw(c_str) as *mut c_char };

                    ERR_SUCCESS
                }
                Err(_) => ERR_GENERIC,
            },
            None => crate::error::ERR_DB_NOT_FOUND,
        }
    })
    .unwrap_or(ERR_INTERNAL_PANIC)
}

/// Logs a parameter for a run.
///
/// # Arguments
/// * `path` - Null-terminated C string containing the path to the tracker
/// * `run_id` - Null-terminated C string containing the run ID
/// * `key` - Null-terminated C string containing the parameter name
/// * `value` - Null-terminated C string containing the parameter value
///
/// # Returns
/// * `1` (ERR_SUCCESS) - Parameter logged successfully
/// * `0` (ERR_GENERIC) - Generic error
/// * `-1` (ERR_DB_NOT_FOUND) - Tracker not found
/// * `-2` (ERR_INVALID_PATH) - Invalid arguments
/// * `-5` (ERR_KEY_NOT_FOUND) - Run not found
/// * `-100` (ERR_INTERNAL_PANIC) - Internal panic occurred
///
/// _Requirements: 8.1_
#[no_mangle]
pub extern "C" fn SYNA_exp_log_param(
    path: *const c_char,
    run_id: *const c_char,
    key: *const c_char,
    value: *const c_char,
) -> i32 {
    std::panic::catch_unwind(|| {
        if path.is_null() || run_id.is_null() || key.is_null() || value.is_null() {
            return ERR_INVALID_PATH;
        }

        let path_str = match unsafe { CStr::from_ptr(path) }.to_str() {
            Ok(s) => s,
            Err(_) => return ERR_INVALID_PATH,
        };

        let run_id_str = match unsafe { CStr::from_ptr(run_id) }.to_str() {
            Ok(s) => s,
            Err(_) => return ERR_INVALID_PATH,
        };

        let key_str = match unsafe { CStr::from_ptr(key) }.to_str() {
            Ok(s) => s,
            Err(_) => return ERR_INVALID_PATH,
        };

        let value_str = match unsafe { CStr::from_ptr(value) }.to_str() {
            Ok(s) => s,
            Err(_) => return ERR_INVALID_PATH,
        };

        let mut reg = EXPERIMENT_REGISTRY.lock();
        match reg.get_mut(path_str) {
            Some(tracker) => match tracker.log_param(run_id_str, key_str, value_str) {
                Ok(_) => ERR_SUCCESS,
                Err(crate::error::SynaError::RunNotFound(_)) => ERR_KEY_NOT_FOUND,
                Err(crate::error::SynaError::RunAlreadyEnded(_)) => ERR_GENERIC,
                Err(_) => ERR_GENERIC,
            },
            None => crate::error::ERR_DB_NOT_FOUND,
        }
    })
    .unwrap_or(ERR_INTERNAL_PANIC)
}

/// Logs a metric value for a run.
///
/// # Arguments
/// * `path` - Null-terminated C string containing the path to the tracker
/// * `run_id` - Null-terminated C string containing the run ID
/// * `key` - Null-terminated C string containing the metric name
/// * `value` - The metric value (f64)
/// * `step` - Step number (use -1 for auto-generated timestamp)
///
/// # Returns
/// * `1` (ERR_SUCCESS) - Metric logged successfully
/// * `0` (ERR_GENERIC) - Generic error
/// * `-1` (ERR_DB_NOT_FOUND) - Tracker not found
/// * `-2` (ERR_INVALID_PATH) - Invalid arguments
/// * `-5` (ERR_KEY_NOT_FOUND) - Run not found
/// * `-100` (ERR_INTERNAL_PANIC) - Internal panic occurred
///
/// _Requirements: 8.1_
#[no_mangle]
pub extern "C" fn SYNA_exp_log_metric(
    path: *const c_char,
    run_id: *const c_char,
    key: *const c_char,
    value: f64,
    step: i64,
) -> i32 {
    std::panic::catch_unwind(|| {
        if path.is_null() || run_id.is_null() || key.is_null() {
            return ERR_INVALID_PATH;
        }

        let path_str = match unsafe { CStr::from_ptr(path) }.to_str() {
            Ok(s) => s,
            Err(_) => return ERR_INVALID_PATH,
        };

        let run_id_str = match unsafe { CStr::from_ptr(run_id) }.to_str() {
            Ok(s) => s,
            Err(_) => return ERR_INVALID_PATH,
        };

        let key_str = match unsafe { CStr::from_ptr(key) }.to_str() {
            Ok(s) => s,
            Err(_) => return ERR_INVALID_PATH,
        };

        let step_opt = if step < 0 { None } else { Some(step as u64) };

        let mut reg = EXPERIMENT_REGISTRY.lock();
        match reg.get_mut(path_str) {
            Some(tracker) => match tracker.log_metric(run_id_str, key_str, value, step_opt) {
                Ok(_) => ERR_SUCCESS,
                Err(crate::error::SynaError::RunNotFound(_)) => ERR_KEY_NOT_FOUND,
                Err(crate::error::SynaError::RunAlreadyEnded(_)) => ERR_GENERIC,
                Err(_) => ERR_GENERIC,
            },
            None => crate::error::ERR_DB_NOT_FOUND,
        }
    })
    .unwrap_or(ERR_INTERNAL_PANIC)
}

/// Logs an artifact for a run.
///
/// # Arguments
/// * `path` - Null-terminated C string containing the path to the tracker
/// * `run_id` - Null-terminated C string containing the run ID
/// * `name` - Null-terminated C string containing the artifact name
/// * `data` - Pointer to the artifact data
/// * `data_len` - Length of the artifact data
///
/// # Returns
/// * `1` (ERR_SUCCESS) - Artifact logged successfully
/// * `0` (ERR_GENERIC) - Generic error
/// * `-1` (ERR_DB_NOT_FOUND) - Tracker not found
/// * `-2` (ERR_INVALID_PATH) - Invalid arguments
/// * `-5` (ERR_KEY_NOT_FOUND) - Run not found
/// * `-100` (ERR_INTERNAL_PANIC) - Internal panic occurred
///
/// _Requirements: 8.1_
#[no_mangle]
pub extern "C" fn SYNA_exp_log_artifact(
    path: *const c_char,
    run_id: *const c_char,
    name: *const c_char,
    data: *const u8,
    data_len: usize,
) -> i32 {
    std::panic::catch_unwind(|| {
        if path.is_null() || run_id.is_null() || name.is_null() {
            return ERR_INVALID_PATH;
        }
        if data.is_null() && data_len > 0 {
            return ERR_INVALID_PATH;
        }

        let path_str = match unsafe { CStr::from_ptr(path) }.to_str() {
            Ok(s) => s,
            Err(_) => return ERR_INVALID_PATH,
        };

        let run_id_str = match unsafe { CStr::from_ptr(run_id) }.to_str() {
            Ok(s) => s,
            Err(_) => return ERR_INVALID_PATH,
        };

        let name_str = match unsafe { CStr::from_ptr(name) }.to_str() {
            Ok(s) => s,
            Err(_) => return ERR_INVALID_PATH,
        };

        let artifact_data = if data_len == 0 {
            &[]
        } else {
            unsafe { std::slice::from_raw_parts(data, data_len) }
        };

        let mut reg = EXPERIMENT_REGISTRY.lock();
        match reg.get_mut(path_str) {
            Some(tracker) => match tracker.log_artifact(run_id_str, name_str, artifact_data) {
                Ok(_) => ERR_SUCCESS,
                Err(crate::error::SynaError::RunNotFound(_)) => ERR_KEY_NOT_FOUND,
                Err(crate::error::SynaError::RunAlreadyEnded(_)) => ERR_GENERIC,
                Err(_) => ERR_GENERIC,
            },
            None => crate::error::ERR_DB_NOT_FOUND,
        }
    })
    .unwrap_or(ERR_INTERNAL_PANIC)
}

/// Ends a run with the given status.
///
/// # Arguments
/// * `path` - Null-terminated C string containing the path to the tracker
/// * `run_id` - Null-terminated C string containing the run ID
/// * `status` - Status: 0=Running, 1=Completed, 2=Failed, 3=Killed
///
/// # Returns
/// * `1` (ERR_SUCCESS) - Run ended successfully
/// * `0` (ERR_GENERIC) - Generic error (e.g., run already ended)
/// * `-1` (ERR_DB_NOT_FOUND) - Tracker not found
/// * `-2` (ERR_INVALID_PATH) - Invalid arguments
/// * `-5` (ERR_KEY_NOT_FOUND) - Run not found
/// * `-100` (ERR_INTERNAL_PANIC) - Internal panic occurred
///
/// _Requirements: 8.1_
#[no_mangle]
pub extern "C" fn SYNA_exp_end_run(path: *const c_char, run_id: *const c_char, status: i32) -> i32 {
    std::panic::catch_unwind(|| {
        if path.is_null() || run_id.is_null() {
            return ERR_INVALID_PATH;
        }

        let path_str = match unsafe { CStr::from_ptr(path) }.to_str() {
            Ok(s) => s,
            Err(_) => return ERR_INVALID_PATH,
        };

        let run_id_str = match unsafe { CStr::from_ptr(run_id) }.to_str() {
            Ok(s) => s,
            Err(_) => return ERR_INVALID_PATH,
        };

        let run_status = match status {
            0 => RunStatus::Running,
            1 => RunStatus::Completed,
            2 => RunStatus::Failed,
            3 => RunStatus::Killed,
            _ => RunStatus::Completed,
        };

        let mut reg = EXPERIMENT_REGISTRY.lock();
        match reg.get_mut(path_str) {
            Some(tracker) => match tracker.end_run(run_id_str, run_status) {
                Ok(_) => ERR_SUCCESS,
                Err(crate::error::SynaError::RunNotFound(_)) => ERR_KEY_NOT_FOUND,
                Err(crate::error::SynaError::RunAlreadyEnded(_)) => ERR_GENERIC,
                Err(_) => ERR_GENERIC,
            },
            None => crate::error::ERR_DB_NOT_FOUND,
        }
    })
    .unwrap_or(ERR_INTERNAL_PANIC)
}

// =============================================================================
// MmapVectorStore FFI Functions (Ultra-High-Throughput)
// =============================================================================

use crate::mmap_vector::{MmapVectorConfig, MmapVectorStore};

/// Thread-safe global registry for managing open MmapVectorStore instances.
static MMAP_VECTOR_REGISTRY: Lazy<Mutex<HashMap<String, MmapVectorStore>>> =
    Lazy::new(|| Mutex::new(HashMap::new()));

/// Creates or opens a memory-mapped vector store at the given path.
///
/// This is an alternative to `SYNA_vector_store_new()` that uses memory-mapped I/O
/// for ultra-high-throughput writes (500K-1M vectors/sec).
///
/// # Arguments
/// * `path` - Null-terminated C string containing the path to the mmap file
/// * `dimensions` - Number of dimensions (64-8192)
/// * `metric` - Distance metric: 0=Cosine, 1=Euclidean, 2=DotProduct
/// * `initial_capacity` - Pre-allocated capacity in number of vectors
///
/// # Returns
/// * `1` (ERR_SUCCESS) - Store opened successfully
/// * `0` (ERR_GENERIC) - Generic error during open
/// * `-2` (ERR_INVALID_PATH) - Path is null or invalid UTF-8
/// * `-100` (ERR_INTERNAL_PANIC) - Internal panic occurred
#[no_mangle]
pub extern "C" fn SYNA_mmap_vector_store_new(
    path: *const c_char,
    dimensions: u16,
    metric: i32,
    initial_capacity: usize,
) -> i32 {
    std::panic::catch_unwind(|| {
        if path.is_null() {
            return ERR_INVALID_PATH;
        }

        let path_str = match unsafe { CStr::from_ptr(path) }.to_str() {
            Ok(s) => s,
            Err(_) => return ERR_INVALID_PATH,
        };

        let distance_metric = match metric {
            0 => crate::distance::DistanceMetric::Cosine,
            1 => crate::distance::DistanceMetric::Euclidean,
            2 => crate::distance::DistanceMetric::DotProduct,
            _ => crate::distance::DistanceMetric::Cosine,
        };

        let config = MmapVectorConfig {
            dimensions,
            metric: distance_metric,
            initial_capacity,
            ..Default::default()
        };

        match MmapVectorStore::new(path_str, config) {
            Ok(store) => {
                let mut reg = MMAP_VECTOR_REGISTRY.lock();
                reg.insert(path_str.to_string(), store);
                ERR_SUCCESS
            }
            Err(_) => ERR_GENERIC,
        }
    })
    .unwrap_or(ERR_INTERNAL_PANIC)
}

/// Inserts a vector into the mmap vector store.
///
/// This is an ultra-fast operation (no syscalls, just memcpy).
///
/// # Arguments
/// * `path` - Null-terminated C string containing the path to the store
/// * `key` - Null-terminated C string containing the vector key
/// * `vector` - Pointer to the vector data (f32 array)
/// * `dimensions` - Number of dimensions in the vector
///
/// # Returns
/// * `1` (ERR_SUCCESS) - Vector inserted successfully
/// * `0` (ERR_GENERIC) - Generic error
/// * `-1` (ERR_DB_NOT_FOUND) - Store not found
/// * `-2` (ERR_INVALID_PATH) - Invalid arguments
/// * `-6` (ERR_TYPE_MISMATCH) - Dimension mismatch
/// * `-100` (ERR_INTERNAL_PANIC) - Internal panic occurred
#[no_mangle]
pub extern "C" fn SYNA_mmap_vector_store_insert(
    path: *const c_char,
    key: *const c_char,
    vector: *const f32,
    dimensions: u16,
) -> i32 {
    std::panic::catch_unwind(|| {
        if path.is_null() || key.is_null() || vector.is_null() {
            return ERR_INVALID_PATH;
        }

        let path_str = match unsafe { CStr::from_ptr(path) }.to_str() {
            Ok(s) => s,
            Err(_) => return ERR_INVALID_PATH,
        };

        let key_str = match unsafe { CStr::from_ptr(key) }.to_str() {
            Ok(s) => s,
            Err(_) => return ERR_INVALID_PATH,
        };

        let vec_slice = unsafe { std::slice::from_raw_parts(vector, dimensions as usize) };

        let mut reg = MMAP_VECTOR_REGISTRY.lock();
        match reg.get_mut(path_str) {
            Some(store) => match store.insert(key_str, vec_slice) {
                Ok(_) => ERR_SUCCESS,
                Err(crate::error::SynaError::DimensionMismatch { .. }) => ERR_TYPE_MISMATCH,
                Err(_) => ERR_GENERIC,
            },
            None => crate::error::ERR_DB_NOT_FOUND,
        }
    })
    .unwrap_or(ERR_INTERNAL_PANIC)
}

/// Inserts multiple vectors in a batch (maximum throughput).
///
/// This achieves 500K-1M vectors/sec by writing directly to memory.
///
/// # Arguments
/// * `path` - Null-terminated C string containing the path to the store
/// * `keys` - Array of null-terminated C strings (vector keys)
/// * `vectors` - Contiguous array of vector data (count * dimensions floats)
/// * `dimensions` - Number of dimensions per vector
/// * `count` - Number of vectors to insert
///
/// # Returns
/// * Non-negative value - Number of vectors inserted
/// * `-1` (ERR_DB_NOT_FOUND) - Store not found
/// * `-2` (ERR_INVALID_PATH) - Invalid arguments
/// * `-100` (ERR_INTERNAL_PANIC) - Internal panic occurred
#[no_mangle]
pub extern "C" fn SYNA_mmap_vector_store_insert_batch(
    path: *const c_char,
    keys: *const *const c_char,
    vectors: *const f32,
    dimensions: u16,
    count: usize,
) -> i32 {
    std::panic::catch_unwind(|| {
        if path.is_null() || keys.is_null() || vectors.is_null() || count == 0 {
            return ERR_INVALID_PATH;
        }

        let path_str = match unsafe { CStr::from_ptr(path) }.to_str() {
            Ok(s) => s,
            Err(_) => return ERR_INVALID_PATH,
        };

        // Convert keys
        let key_ptrs = unsafe { std::slice::from_raw_parts(keys, count) };
        let mut key_strings: Vec<String> = Vec::with_capacity(count);
        for &key_ptr in key_ptrs {
            if key_ptr.is_null() {
                return ERR_INVALID_PATH;
            }
            match unsafe { CStr::from_ptr(key_ptr) }.to_str() {
                Ok(s) => key_strings.push(s.to_string()),
                Err(_) => return ERR_INVALID_PATH,
            }
        }
        let key_refs: Vec<&str> = key_strings.iter().map(|s| s.as_str()).collect();

        // Convert vectors
        let dims = dimensions as usize;
        let all_vectors = unsafe { std::slice::from_raw_parts(vectors, count * dims) };
        let vec_refs: Vec<&[f32]> = (0..count)
            .map(|i| &all_vectors[i * dims..(i + 1) * dims])
            .collect();

        let mut reg = MMAP_VECTOR_REGISTRY.lock();
        match reg.get_mut(path_str) {
            Some(store) => match store.insert_batch(&key_refs, &vec_refs) {
                Ok(inserted) => inserted as i32,
                Err(_) => ERR_GENERIC,
            },
            None => crate::error::ERR_DB_NOT_FOUND,
        }
    })
    .unwrap_or(ERR_INTERNAL_PANIC)
}

/// Searches for the k nearest neighbors in the mmap vector store.
///
/// # Arguments
/// * `path` - Null-terminated C string containing the path to the store
/// * `query` - Pointer to the query vector (f32 array)
/// * `dimensions` - Number of dimensions in the query
/// * `k` - Number of results to return
/// * `out_json` - Pointer to write the JSON results string
/// * `out_len` - Pointer to write the JSON string length
///
/// # Returns
/// * Non-negative value - Number of results found
/// * `-1` (ERR_DB_NOT_FOUND) - Store not found
/// * `-2` (ERR_INVALID_PATH) - Invalid arguments
/// * `-6` (ERR_TYPE_MISMATCH) - Dimension mismatch
/// * `-100` (ERR_INTERNAL_PANIC) - Internal panic occurred
#[no_mangle]
pub extern "C" fn SYNA_mmap_vector_store_search(
    path: *const c_char,
    query: *const f32,
    dimensions: u16,
    k: usize,
    out_json: *mut *mut c_char,
    out_len: *mut usize,
) -> i32 {
    std::panic::catch_unwind(|| {
        if path.is_null() || query.is_null() || out_json.is_null() || out_len.is_null() {
            return ERR_INVALID_PATH;
        }

        let path_str = match unsafe { CStr::from_ptr(path) }.to_str() {
            Ok(s) => s,
            Err(_) => return ERR_INVALID_PATH,
        };

        let query_slice = unsafe { std::slice::from_raw_parts(query, dimensions as usize) };

        let reg = MMAP_VECTOR_REGISTRY.lock();
        match reg.get(path_str) {
            Some(store) => match store.search(query_slice, k) {
                Ok(results) => {
                    let count = results.len() as i32;

                    // Convert results to JSON
                    let json_results: Vec<serde_json::Value> = results
                        .iter()
                        .map(|r| {
                            serde_json::json!({
                                "key": r.key,
                                "score": r.score,
                            })
                        })
                        .collect();

                    let json =
                        serde_json::to_string(&json_results).unwrap_or_else(|_| "[]".to_string());

                    unsafe { *out_len = json.len() };
                    match CString::new(json) {
                        Ok(c_string) => {
                            unsafe { *out_json = c_string.into_raw() };
                            count
                        }
                        Err(_) => ERR_GENERIC,
                    }
                }
                Err(crate::error::SynaError::DimensionMismatch { .. }) => ERR_TYPE_MISMATCH,
                Err(_) => ERR_GENERIC,
            },
            None => crate::error::ERR_DB_NOT_FOUND,
        }
    })
    .unwrap_or(ERR_INTERNAL_PANIC)
}

/// Builds the HNSW index for the mmap vector store.
///
/// # Arguments
/// * `path` - Null-terminated C string containing the path to the store
///
/// # Returns
/// * `1` (ERR_SUCCESS) - Index built successfully
/// * `0` (ERR_GENERIC) - Generic error
/// * `-1` (ERR_DB_NOT_FOUND) - Store not found
/// * `-2` (ERR_INVALID_PATH) - Invalid path
/// * `-100` (ERR_INTERNAL_PANIC) - Internal panic occurred
#[no_mangle]
pub extern "C" fn SYNA_mmap_vector_store_build_index(path: *const c_char) -> i32 {
    std::panic::catch_unwind(|| {
        if path.is_null() {
            return ERR_INVALID_PATH;
        }

        let path_str = match unsafe { CStr::from_ptr(path) }.to_str() {
            Ok(s) => s,
            Err(_) => return ERR_INVALID_PATH,
        };

        let mut reg = MMAP_VECTOR_REGISTRY.lock();
        match reg.get_mut(path_str) {
            Some(store) => match store.build_index() {
                Ok(_) => ERR_SUCCESS,
                Err(_) => ERR_GENERIC,
            },
            None => crate::error::ERR_DB_NOT_FOUND,
        }
    })
    .unwrap_or(ERR_INTERNAL_PANIC)
}

/// Flushes the mmap vector store to disk.
///
/// # Arguments
/// * `path` - Null-terminated C string containing the path to the store
///
/// # Returns
/// * `1` (ERR_SUCCESS) - Flushed successfully
/// * `0` (ERR_GENERIC) - Generic error
/// * `-1` (ERR_DB_NOT_FOUND) - Store not found
/// * `-2` (ERR_INVALID_PATH) - Invalid path
/// * `-100` (ERR_INTERNAL_PANIC) - Internal panic occurred
#[no_mangle]
pub extern "C" fn SYNA_mmap_vector_store_flush(path: *const c_char) -> i32 {
    std::panic::catch_unwind(|| {
        if path.is_null() {
            return ERR_INVALID_PATH;
        }

        let path_str = match unsafe { CStr::from_ptr(path) }.to_str() {
            Ok(s) => s,
            Err(_) => return ERR_INVALID_PATH,
        };

        let mut reg = MMAP_VECTOR_REGISTRY.lock();
        match reg.get_mut(path_str) {
            Some(store) => match store.flush() {
                Ok(_) => ERR_SUCCESS,
                Err(_) => ERR_GENERIC,
            },
            None => crate::error::ERR_DB_NOT_FOUND,
        }
    })
    .unwrap_or(ERR_INTERNAL_PANIC)
}

/// Closes the mmap vector store and removes it from the registry.
///
/// # Arguments
/// * `path` - Null-terminated C string containing the path to the store
///
/// # Returns
/// * `1` (ERR_SUCCESS) - Closed successfully
/// * `-1` (ERR_DB_NOT_FOUND) - Store not found
/// * `-2` (ERR_INVALID_PATH) - Invalid path
/// * `-100` (ERR_INTERNAL_PANIC) - Internal panic occurred
#[no_mangle]
pub extern "C" fn SYNA_mmap_vector_store_close(path: *const c_char) -> i32 {
    std::panic::catch_unwind(|| {
        if path.is_null() {
            return ERR_INVALID_PATH;
        }

        let path_str = match unsafe { CStr::from_ptr(path) }.to_str() {
            Ok(s) => s,
            Err(_) => return ERR_INVALID_PATH,
        };

        let mut reg = MMAP_VECTOR_REGISTRY.lock();
        match reg.remove(path_str) {
            Some(_store) => {
                // Store is dropped here, which triggers checkpoint
                ERR_SUCCESS
            }
            None => crate::error::ERR_DB_NOT_FOUND,
        }
    })
    .unwrap_or(ERR_INTERNAL_PANIC)
}

/// Returns the number of vectors in the mmap vector store.
///
/// # Arguments
/// * `path` - Null-terminated C string containing the path to the store
///
/// # Returns
/// * Non-negative value - Number of vectors
/// * `-1` (ERR_DB_NOT_FOUND) - Store not found
/// * `-2` (ERR_INVALID_PATH) - Invalid path
/// * `-100` (ERR_INTERNAL_PANIC) - Internal panic occurred
#[no_mangle]
pub extern "C" fn SYNA_mmap_vector_store_len(path: *const c_char) -> i64 {
    std::panic::catch_unwind(|| {
        if path.is_null() {
            return ERR_INVALID_PATH as i64;
        }

        let path_str = match unsafe { CStr::from_ptr(path) }.to_str() {
            Ok(s) => s,
            Err(_) => return ERR_INVALID_PATH as i64,
        };

        let reg = MMAP_VECTOR_REGISTRY.lock();
        match reg.get(path_str) {
            Some(store) => store.len() as i64,
            None => crate::error::ERR_DB_NOT_FOUND as i64,
        }
    })
    .unwrap_or(ERR_INTERNAL_PANIC as i64)
}

// =============================================================================
// Gravity Well Index (GWI) FFI Functions
// =============================================================================

use crate::gwi::{GravityWellIndex, GwiConfig};

/// Thread-safe global registry for managing open GravityWellIndex instances.
static GWI_REGISTRY: Lazy<Mutex<HashMap<String, GravityWellIndex>>> =
    Lazy::new(|| Mutex::new(HashMap::new()));

/// Create a new Gravity Well Index
///
/// # Arguments
/// * `path` - Path to the index file
/// * `dimensions` - Vector dimensions (64-8192)
/// * `branching_factor` - Branching factor at each level (default: 16)
/// * `num_levels` - Number of hierarchy levels (default: 3)
///
/// # Returns
/// * `1` (ERR_SUCCESS) - Index created successfully
/// * `-2` (ERR_INVALID_PATH) - Invalid path
/// * `-100` (ERR_INTERNAL_PANIC) - Internal panic occurred
#[no_mangle]
pub extern "C" fn SYNA_gwi_new(
    path: *const c_char,
    dimensions: u16,
    branching_factor: u16,
    num_levels: u8,
    initial_capacity: usize,
) -> i32 {
    std::panic::catch_unwind(|| {
        if path.is_null() {
            return ERR_INVALID_PATH;
        }

        let path_str = match unsafe { CStr::from_ptr(path) }.to_str() {
            Ok(s) => s,
            Err(_) => return ERR_INVALID_PATH,
        };

        let config = GwiConfig {
            dimensions,
            branching_factor: if branching_factor == 0 {
                16
            } else {
                branching_factor
            },
            num_levels: if num_levels == 0 { 3 } else { num_levels },
            initial_capacity: if initial_capacity == 0 {
                10_000
            } else {
                initial_capacity
            },
            ..Default::default()
        };

        match GravityWellIndex::new(path_str, config) {
            Ok(index) => {
                let mut reg = GWI_REGISTRY.lock();
                reg.insert(path_str.to_string(), index);
                ERR_SUCCESS
            }
            Err(_) => ERR_GENERIC,
        }
    })
    .unwrap_or(ERR_INTERNAL_PANIC)
}

/// Open an existing Gravity Well Index
///
/// # Arguments
/// * `path` - Path to the existing index file
///
/// # Returns
/// * `1` (ERR_SUCCESS) - Index opened successfully
/// * `-2` (ERR_INVALID_PATH) - Invalid path or file doesn't exist
/// * `-100` (ERR_INTERNAL_PANIC) - Internal panic occurred
#[no_mangle]
pub extern "C" fn SYNA_gwi_open(path: *const c_char) -> i32 {
    std::panic::catch_unwind(|| {
        if path.is_null() {
            return ERR_INVALID_PATH;
        }

        let path_str = match unsafe { CStr::from_ptr(path) }.to_str() {
            Ok(s) => s,
            Err(_) => return ERR_INVALID_PATH,
        };

        match GravityWellIndex::open(path_str) {
            Ok(index) => {
                let mut reg = GWI_REGISTRY.lock();
                reg.insert(path_str.to_string(), index);
                ERR_SUCCESS
            }
            Err(_) => ERR_INVALID_PATH,
        }
    })
    .unwrap_or(ERR_INTERNAL_PANIC)
}

/// Initialize GWI attractors from sample vectors
///
/// # Arguments
/// * `path` - Path to the index file
/// * `vectors` - Pointer to contiguous f32 vector data
/// * `num_vectors` - Number of sample vectors
/// * `dimensions` - Dimensions per vector
///
/// # Returns
/// * `1` (ERR_SUCCESS) - Attractors initialized
/// * `-1` (ERR_DB_NOT_FOUND) - Index not found
/// * `-2` (ERR_INVALID_PATH) - Invalid path
/// * `-100` (ERR_INTERNAL_PANIC) - Internal panic occurred
#[no_mangle]
pub extern "C" fn SYNA_gwi_initialize(
    path: *const c_char,
    vectors: *const f32,
    num_vectors: usize,
    dimensions: u16,
) -> i32 {
    std::panic::catch_unwind(|| {
        if path.is_null() || vectors.is_null() {
            return ERR_INVALID_PATH;
        }

        let path_str = match unsafe { CStr::from_ptr(path) }.to_str() {
            Ok(s) => s,
            Err(_) => return ERR_INVALID_PATH,
        };

        let total_floats = num_vectors * dimensions as usize;
        let data_slice = unsafe { std::slice::from_raw_parts(vectors, total_floats) };

        let sample_vectors: Vec<&[f32]> = data_slice.chunks(dimensions as usize).collect();

        let mut reg = GWI_REGISTRY.lock();
        match reg.get_mut(path_str) {
            Some(index) => match index.initialize_attractors(&sample_vectors) {
                Ok(()) => ERR_SUCCESS,
                Err(_) => ERR_GENERIC,
            },
            None => crate::error::ERR_DB_NOT_FOUND,
        }
    })
    .unwrap_or(ERR_INTERNAL_PANIC)
}

/// Insert a vector into the GWI
///
/// # Arguments
/// * `path` - Path to the index file
/// * `key` - Null-terminated key string
/// * `vector` - Pointer to f32 vector data
/// * `dimensions` - Vector dimensions
///
/// # Returns
/// * `1` (ERR_SUCCESS) - Vector inserted
/// * `-1` (ERR_DB_NOT_FOUND) - Index not found
/// * `-2` (ERR_INVALID_PATH) - Invalid path/key
/// * `-100` (ERR_INTERNAL_PANIC) - Internal panic occurred
#[no_mangle]
pub extern "C" fn SYNA_gwi_insert(
    path: *const c_char,
    key: *const c_char,
    vector: *const f32,
    dimensions: u16,
) -> i32 {
    std::panic::catch_unwind(|| {
        if path.is_null() || key.is_null() || vector.is_null() {
            return ERR_INVALID_PATH;
        }

        let path_str = match unsafe { CStr::from_ptr(path) }.to_str() {
            Ok(s) => s,
            Err(_) => return ERR_INVALID_PATH,
        };

        let key_str = match unsafe { CStr::from_ptr(key) }.to_str() {
            Ok(s) => s,
            Err(_) => return ERR_INVALID_PATH,
        };

        let vector_slice = unsafe { std::slice::from_raw_parts(vector, dimensions as usize) };

        let mut reg = GWI_REGISTRY.lock();
        match reg.get_mut(path_str) {
            Some(index) => match index.insert(key_str, vector_slice) {
                Ok(()) => ERR_SUCCESS,
                Err(_) => ERR_GENERIC,
            },
            None => crate::error::ERR_DB_NOT_FOUND,
        }
    })
    .unwrap_or(ERR_INTERNAL_PANIC)
}

/// Batch insert vectors into the GWI
///
/// # Arguments
/// * `path` - Path to the index file
/// * `keys` - Array of null-terminated key strings
/// * `vectors` - Pointer to contiguous f32 vector data
/// * `dimensions` - Dimensions per vector
/// * `count` - Number of vectors to insert
///
/// # Returns
/// * Non-negative - Number of vectors inserted
/// * `-1` (ERR_DB_NOT_FOUND) - Index not found
/// * `-2` (ERR_INVALID_PATH) - Invalid path
/// * `-100` (ERR_INTERNAL_PANIC) - Internal panic occurred
#[no_mangle]
pub extern "C" fn SYNA_gwi_insert_batch(
    path: *const c_char,
    keys: *const *const c_char,
    vectors: *const f32,
    dimensions: u16,
    count: usize,
) -> i32 {
    std::panic::catch_unwind(|| {
        if path.is_null() || keys.is_null() || (vectors.is_null() && count > 0) {
            return ERR_INVALID_PATH;
        }

        let path_str = match unsafe { CStr::from_ptr(path) }.to_str() {
            Ok(s) => s,
            Err(_) => return ERR_INVALID_PATH,
        };

        let keys_slice = unsafe { std::slice::from_raw_parts(keys, count) };
        let mut key_strings: Vec<&str> = Vec::with_capacity(count);
        for key_ptr in keys_slice {
            if key_ptr.is_null() {
                return ERR_INVALID_PATH;
            }
            match unsafe { CStr::from_ptr(*key_ptr) }.to_str() {
                Ok(s) => key_strings.push(s),
                Err(_) => return ERR_INVALID_PATH,
            }
        }

        let total_floats = count * dimensions as usize;
        let data_slice = unsafe { std::slice::from_raw_parts(vectors, total_floats) };
        let vector_refs: Vec<&[f32]> = data_slice.chunks(dimensions as usize).collect();

        let mut reg = GWI_REGISTRY.lock();
        match reg.get_mut(path_str) {
            Some(index) => match index.insert_batch(&key_strings, &vector_refs) {
                Ok(n) => n as i32,
                Err(_) => ERR_GENERIC,
            },
            None => crate::error::ERR_DB_NOT_FOUND,
        }
    })
    .unwrap_or(ERR_INTERNAL_PANIC)
}

/// Search for k nearest neighbors in the GWI
///
/// # Arguments
/// * `path` - Path to the index file
/// * `query` - Pointer to f32 query vector
/// * `dimensions` - Query vector dimensions
/// * `k` - Number of neighbors to return
/// * `out_json` - Pointer to write JSON result string
///
/// # Returns
/// * Non-negative - Number of results found
/// * `-1` (ERR_DB_NOT_FOUND) - Index not found
/// * `-2` (ERR_INVALID_PATH) - Invalid path
/// * `-100` (ERR_INTERNAL_PANIC) - Internal panic occurred
#[no_mangle]
pub extern "C" fn SYNA_gwi_search(
    path: *const c_char,
    query: *const f32,
    dimensions: u16,
    k: usize,
    out_json: *mut *mut c_char,
) -> i32 {
    // Default nprobe
    SYNA_gwi_search_nprobe(path, query, dimensions, k, 3, out_json)
}

/// Search for k nearest neighbors with custom nprobe
///
/// Higher nprobe = better recall but slower search.
/// - nprobe=3: Fast, ~5-15% recall
/// - nprobe=10: Balanced, ~30-50% recall
/// - nprobe=30: High quality, ~70-90% recall
/// - nprobe=100: Near-exact, ~95%+ recall
///
/// # Arguments
/// * `path` - Path to the index file
/// * `query` - Query vector
/// * `dimensions` - Number of dimensions
/// * `k` - Number of results to return
/// * `nprobe` - Number of clusters to probe
/// * `out_json` - Output JSON string with results
///
/// # Returns
/// * Number of results on success
/// * `-1` (ERR_DB_NOT_FOUND) - Index not found
/// * `-2` (ERR_INVALID_PATH) - Invalid path
/// * `-100` (ERR_INTERNAL_PANIC) - Internal panic occurred
#[no_mangle]
pub extern "C" fn SYNA_gwi_search_nprobe(
    path: *const c_char,
    query: *const f32,
    dimensions: u16,
    k: usize,
    nprobe: usize,
    out_json: *mut *mut c_char,
) -> i32 {
    std::panic::catch_unwind(|| {
        if path.is_null() || query.is_null() || out_json.is_null() {
            return ERR_INVALID_PATH;
        }

        let path_str = match unsafe { CStr::from_ptr(path) }.to_str() {
            Ok(s) => s,
            Err(_) => return ERR_INVALID_PATH,
        };

        let query_slice = unsafe { std::slice::from_raw_parts(query, dimensions as usize) };

        let reg = GWI_REGISTRY.lock();
        match reg.get(path_str) {
            Some(index) => match index.search_with_nprobe(query_slice, k, nprobe) {
                Ok(results) => {
                    let json_results: Vec<serde_json::Value> = results
                        .iter()
                        .map(|r| {
                            serde_json::json!({
                                "key": r.key,
                                "score": r.score,
                            })
                        })
                        .collect();

                    let json_str = serde_json::to_string(&json_results).unwrap_or_default();
                    let c_str = CString::new(json_str).unwrap_or_default();
                    unsafe {
                        *out_json = c_str.into_raw();
                    }
                    results.len() as i32
                }
                Err(_) => ERR_GENERIC,
            },
            None => crate::error::ERR_DB_NOT_FOUND,
        }
    })
    .unwrap_or(ERR_INTERNAL_PANIC)
}

/// Flush GWI changes to disk
///
/// # Arguments
/// * `path` - Path to the index file
///
/// # Returns
/// * `1` (ERR_SUCCESS) - Flushed successfully
/// * `-1` (ERR_DB_NOT_FOUND) - Index not found
/// * `-2` (ERR_INVALID_PATH) - Invalid path
/// * `-100` (ERR_INTERNAL_PANIC) - Internal panic occurred
#[no_mangle]
pub extern "C" fn SYNA_gwi_flush(path: *const c_char) -> i32 {
    std::panic::catch_unwind(|| {
        if path.is_null() {
            return ERR_INVALID_PATH;
        }

        let path_str = match unsafe { CStr::from_ptr(path) }.to_str() {
            Ok(s) => s,
            Err(_) => return ERR_INVALID_PATH,
        };

        let reg = GWI_REGISTRY.lock();
        match reg.get(path_str) {
            Some(index) => match index.flush() {
                Ok(()) => ERR_SUCCESS,
                Err(_) => ERR_GENERIC,
            },
            None => crate::error::ERR_DB_NOT_FOUND,
        }
    })
    .unwrap_or(ERR_INTERNAL_PANIC)
}

/// Close a GWI and remove from registry
///
/// # Arguments
/// * `path` - Path to the index file
///
/// # Returns
/// * `1` (ERR_SUCCESS) - Closed successfully
/// * `-1` (ERR_DB_NOT_FOUND) - Index not found
/// * `-2` (ERR_INVALID_PATH) - Invalid path
/// * `-100` (ERR_INTERNAL_PANIC) - Internal panic occurred
#[no_mangle]
pub extern "C" fn SYNA_gwi_close(path: *const c_char) -> i32 {
    std::panic::catch_unwind(|| {
        if path.is_null() {
            return ERR_INVALID_PATH;
        }

        let path_str = match unsafe { CStr::from_ptr(path) }.to_str() {
            Ok(s) => s,
            Err(_) => return ERR_INVALID_PATH,
        };

        let mut reg = GWI_REGISTRY.lock();
        match reg.remove(path_str) {
            Some(mut index) => {
                let _ = index.close();
                ERR_SUCCESS
            }
            None => crate::error::ERR_DB_NOT_FOUND,
        }
    })
    .unwrap_or(ERR_INTERNAL_PANIC)
}

/// Get number of vectors in the GWI
///
/// # Arguments
/// * `path` - Path to the index file
///
/// # Returns
/// * Non-negative - Number of vectors
/// * `-1` (ERR_DB_NOT_FOUND) - Index not found
/// * `-2` (ERR_INVALID_PATH) - Invalid path
/// * `-100` (ERR_INTERNAL_PANIC) - Internal panic occurred
#[no_mangle]
pub extern "C" fn SYNA_gwi_len(path: *const c_char) -> i64 {
    std::panic::catch_unwind(|| {
        if path.is_null() {
            return ERR_INVALID_PATH as i64;
        }

        let path_str = match unsafe { CStr::from_ptr(path) }.to_str() {
            Ok(s) => s,
            Err(_) => return ERR_INVALID_PATH as i64,
        };

        let reg = GWI_REGISTRY.lock();
        match reg.get(path_str) {
            Some(index) => index.len() as i64,
            None => crate::error::ERR_DB_NOT_FOUND as i64,
        }
    })
    .unwrap_or(ERR_INTERNAL_PANIC as i64)
}

// =============================================================================
// Cascade Index FFI Functions
// =============================================================================

use crate::cascade::{CascadeConfig, CascadeIndex};

/// Global registry for Cascade Index instances
static CASCADE_REGISTRY: Lazy<Mutex<HashMap<String, CascadeIndex>>> =
    Lazy::new(|| Mutex::new(HashMap::new()));

/// Creates a new Cascade Index.
///
/// # Arguments
/// * `path` - Path to the index file
/// * `dimensions` - Vector dimensions (64-8192)
///
/// # Returns
/// * `1` (ERR_SUCCESS) - Index created successfully
/// * `-2` (ERR_INVALID_PATH) - Invalid path
/// * `-100` (ERR_INTERNAL_PANIC) - Internal panic
#[no_mangle]
pub extern "C" fn SYNA_cascade_new(path: *const c_char, dimensions: u16) -> i32 {
    std::panic::catch_unwind(|| {
        if path.is_null() {
            return ERR_INVALID_PATH;
        }

        let c_str = unsafe { CStr::from_ptr(path) };
        let path_str = match c_str.to_str() {
            Ok(s) => s,
            Err(_) => return ERR_INVALID_PATH,
        };

        let config = CascadeConfig {
            dimensions,
            ..Default::default()
        };

        match CascadeIndex::new(path_str, config) {
            Ok(index) => {
                let mut registry = CASCADE_REGISTRY.lock();
                registry.insert(path_str.to_string(), index);
                ERR_SUCCESS
            }
            Err(_) => ERR_GENERIC,
        }
    })
    .unwrap_or(ERR_INTERNAL_PANIC)
}

/// Inserts a vector into the Cascade Index.
///
/// # Arguments
/// * `path` - Path to the index
/// * `key` - Key for the vector
/// * `vector` - Pointer to vector data
/// * `dimensions` - Vector dimensions
///
/// # Returns
/// * `1` (ERR_SUCCESS) - Vector inserted
/// * `-2` (ERR_INVALID_PATH) - Invalid path
/// * `-100` (ERR_INTERNAL_PANIC) - Internal panic
#[no_mangle]
pub extern "C" fn SYNA_cascade_insert(
    path: *const c_char,
    key: *const c_char,
    vector: *const f32,
    dimensions: u16,
) -> i32 {
    std::panic::catch_unwind(|| {
        if path.is_null() || key.is_null() || vector.is_null() {
            return ERR_INVALID_PATH;
        }

        let path_str = match unsafe { CStr::from_ptr(path) }.to_str() {
            Ok(s) => s,
            Err(_) => return ERR_INVALID_PATH,
        };

        let key_str = match unsafe { CStr::from_ptr(key) }.to_str() {
            Ok(s) => s,
            Err(_) => return ERR_INVALID_PATH,
        };

        let vec_slice = unsafe { std::slice::from_raw_parts(vector, dimensions as usize) };

        let mut registry = CASCADE_REGISTRY.lock();
        if let Some(index) = registry.get_mut(path_str) {
            match index.insert(key_str, vec_slice) {
                Ok(_) => ERR_SUCCESS,
                Err(_) => ERR_GENERIC,
            }
        } else {
            ERR_GENERIC
        }
    })
    .unwrap_or(ERR_INTERNAL_PANIC)
}

/// Inserts multiple vectors into the Cascade Index.
///
/// # Arguments
/// * `path` - Path to the index
/// * `keys` - Array of key pointers
/// * `vectors` - Pointer to flattened vector data
/// * `dimensions` - Vector dimensions
/// * `count` - Number of vectors
///
/// # Returns
/// * `1` (ERR_SUCCESS) - Vectors inserted
/// * `-2` (ERR_INVALID_PATH) - Invalid path
/// * `-100` (ERR_INTERNAL_PANIC) - Internal panic
#[no_mangle]
pub extern "C" fn SYNA_cascade_insert_batch(
    path: *const c_char,
    keys: *const *const c_char,
    vectors: *const f32,
    dimensions: u16,
    count: usize,
) -> i32 {
    std::panic::catch_unwind(|| {
        if path.is_null() || keys.is_null() || vectors.is_null() || count == 0 {
            return ERR_INVALID_PATH;
        }

        let path_str = match unsafe { CStr::from_ptr(path) }.to_str() {
            Ok(s) => s,
            Err(_) => return ERR_INVALID_PATH,
        };

        let dims = dimensions as usize;
        let mut registry = CASCADE_REGISTRY.lock();

        if let Some(index) = registry.get_mut(path_str) {
            for i in 0..count {
                let key_ptr = unsafe { *keys.add(i) };
                if key_ptr.is_null() {
                    continue;
                }

                let key_str = match unsafe { CStr::from_ptr(key_ptr) }.to_str() {
                    Ok(s) => s,
                    Err(_) => continue,
                };

                let vec_start = i * dims;
                let vec_slice = unsafe { std::slice::from_raw_parts(vectors.add(vec_start), dims) };

                if index.insert(key_str, vec_slice).is_err() {
                    return ERR_GENERIC;
                }
            }
            ERR_SUCCESS
        } else {
            ERR_GENERIC
        }
    })
    .unwrap_or(ERR_INTERNAL_PANIC)
}

/// Searches the Cascade Index for nearest neighbors.
///
/// # Arguments
/// * `path` - Path to the index
/// * `query` - Query vector
/// * `dimensions` - Vector dimensions
/// * `k` - Number of results
/// * `out_json` - Output JSON string pointer
///
/// # Returns
/// * `1` (ERR_SUCCESS) - Search completed
/// * `-2` (ERR_INVALID_PATH) - Invalid path
/// * `-100` (ERR_INTERNAL_PANIC) - Internal panic
#[no_mangle]
pub extern "C" fn SYNA_cascade_search(
    path: *const c_char,
    query: *const f32,
    dimensions: u16,
    k: usize,
    out_json: *mut *mut c_char,
) -> i32 {
    // Use good defaults matching CascadeConfig::default()
    SYNA_cascade_search_params(path, query, dimensions, k, 16, 80, out_json)
}

/// Searches with custom parameters.
#[no_mangle]
pub extern "C" fn SYNA_cascade_search_params(
    path: *const c_char,
    query: *const f32,
    dimensions: u16,
    k: usize,
    num_probes: usize,
    ef_search: usize,
    out_json: *mut *mut c_char,
) -> i32 {
    std::panic::catch_unwind(|| {
        if path.is_null() || query.is_null() || out_json.is_null() {
            return ERR_INVALID_PATH;
        }

        let path_str = match unsafe { CStr::from_ptr(path) }.to_str() {
            Ok(s) => s,
            Err(_) => return ERR_INVALID_PATH,
        };

        let query_slice = unsafe { std::slice::from_raw_parts(query, dimensions as usize) };

        let registry = CASCADE_REGISTRY.lock();
        if let Some(index) = registry.get(path_str) {
            match index.search_with_params(query_slice, k, num_probes, ef_search) {
                Ok(results) => {
                    let json_results: Vec<serde_json::Value> = results
                        .iter()
                        .map(|r| {
                            serde_json::json!({
                                "key": r.key,
                                "score": r.score
                            })
                        })
                        .collect();

                    let json_str = serde_json::to_string(&json_results).unwrap_or_default();
                    let c_string = std::ffi::CString::new(json_str).unwrap_or_default();
                    unsafe {
                        *out_json = c_string.into_raw();
                    }
                    ERR_SUCCESS
                }
                Err(_) => ERR_GENERIC,
            }
        } else {
            ERR_GENERIC
        }
    })
    .unwrap_or(ERR_INTERNAL_PANIC)
}

/// Flushes the Cascade Index to disk.
#[no_mangle]
pub extern "C" fn SYNA_cascade_flush(path: *const c_char) -> i32 {
    std::panic::catch_unwind(|| {
        if path.is_null() {
            return ERR_INVALID_PATH;
        }

        let path_str = match unsafe { CStr::from_ptr(path) }.to_str() {
            Ok(s) => s,
            Err(_) => return ERR_INVALID_PATH,
        };

        let registry = CASCADE_REGISTRY.lock();
        if let Some(index) = registry.get(path_str) {
            match index.flush() {
                Ok(_) => ERR_SUCCESS,
                Err(_) => ERR_GENERIC,
            }
        } else {
            ERR_GENERIC
        }
    })
    .unwrap_or(ERR_INTERNAL_PANIC)
}

/// Closes the Cascade Index.
#[no_mangle]
pub extern "C" fn SYNA_cascade_close(path: *const c_char) -> i32 {
    std::panic::catch_unwind(|| {
        if path.is_null() {
            return ERR_INVALID_PATH;
        }

        let path_str = match unsafe { CStr::from_ptr(path) }.to_str() {
            Ok(s) => s,
            Err(_) => return ERR_INVALID_PATH,
        };

        let mut registry = CASCADE_REGISTRY.lock();
        if registry.remove(path_str).is_some() {
            ERR_SUCCESS
        } else {
            ERR_GENERIC
        }
    })
    .unwrap_or(ERR_INTERNAL_PANIC)
}

/// Returns the number of vectors in the Cascade Index.
#[no_mangle]
pub extern "C" fn SYNA_cascade_len(path: *const c_char) -> i64 {
    std::panic::catch_unwind(|| {
        if path.is_null() {
            return -1;
        }

        let path_str = match unsafe { CStr::from_ptr(path) }.to_str() {
            Ok(s) => s,
            Err(_) => return -1,
        };

        let registry = CASCADE_REGISTRY.lock();
        if let Some(index) = registry.get(path_str) {
            index.len() as i64
        } else {
            -1
        }
    })
    .unwrap_or(-1)
}