agentvfs 0.1.6

Virtual filesystem CLI backed by embedded databases for AI agents
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
//! SQLite storage backend implementation.
//!
//! Uses WAL mode for concurrent reads with single writer.
//! Busy timeout handles write conflicts automatically.

use std::path::{Path, PathBuf};
use std::sync::Mutex;

use chrono::Utc;
use rusqlite::{params, Connection, OptionalExtension};

use crate::error::{Result, VfsError};
use crate::fs::{FileEntry, FileType};
use crate::storage::StorageBackend;

/// SQLite storage backend.
///
/// # Concurrency Model
///
/// - **Journal Mode**: WAL (Write-Ahead Logging)
/// - **Reads**: Concurrent, non-blocking
/// - **Writes**: Single writer at a time
/// - **Conflict Handling**: busy_timeout (5000ms default) - SQLite retries automatically
/// - **Transactions**: IMMEDIATE mode (acquire write lock at BEGIN)
pub struct SqliteBackend {
    conn: Mutex<Connection>,
    path: PathBuf,
}

impl SqliteBackend {
    /// Open or create a SQLite database at the given path.
    ///
    /// Initializes the database with the vfs schema if it's new.
    pub fn open(path: &Path) -> Result<Self> {
        let conn = Connection::open(path)?;

        // Configure SQLite for concurrent access
        conn.pragma_update(None, "journal_mode", "WAL")?;
        conn.pragma_update(None, "busy_timeout", 5000)?;
        conn.pragma_update(None, "synchronous", "NORMAL")?;
        conn.pragma_update(None, "foreign_keys", "ON")?;

        let backend = Self {
            conn: Mutex::new(conn),
            path: path.to_path_buf(),
        };

        // Initialize schema if needed
        backend.initialize_schema()?;

        Ok(backend)
    }

    /// Initialize the database schema.
    fn initialize_schema(&self) -> Result<()> {
        let conn = self.conn.lock().unwrap();

        // Check if schema exists
        let has_schema: bool = conn.query_row(
            "SELECT COUNT(*) > 0 FROM sqlite_master WHERE type='table' AND name='files'",
            [],
            |row| row.get(0),
        )?;

        if has_schema {
            // Check for schema migration
            drop(conn);
            return self.migrate_schema();
        }

        // Create schema
        conn.execute_batch(
            r#"
            -- File metadata
            CREATE TABLE files (
                id INTEGER PRIMARY KEY,
                parent_id INTEGER REFERENCES files(id) ON DELETE CASCADE,
                name TEXT NOT NULL,
                file_type INTEGER NOT NULL,
                content_hash BLOB,
                size INTEGER NOT NULL DEFAULT 0,
                created_at INTEGER NOT NULL,
                modified_at INTEGER NOT NULL,
                UNIQUE(parent_id, name)
            );

            CREATE INDEX idx_files_parent ON files(parent_id);
            CREATE INDEX idx_files_hash ON files(content_hash);

            -- Path lookup cache
            CREATE TABLE paths (
                path TEXT PRIMARY KEY,
                file_id INTEGER NOT NULL REFERENCES files(id) ON DELETE CASCADE
            );

            -- Content blobs (content-addressable storage)
            CREATE TABLE contents (
                hash BLOB PRIMARY KEY,
                data BLOB NOT NULL,
                size INTEGER NOT NULL,
                ref_count INTEGER NOT NULL DEFAULT 1
            );

            -- Vault settings
            CREATE TABLE settings (
                key TEXT PRIMARY KEY,
                value TEXT NOT NULL
            );

            -- Version history for files
            CREATE TABLE file_versions (
                id INTEGER PRIMARY KEY,
                file_id INTEGER NOT NULL REFERENCES files(id) ON DELETE CASCADE,
                version_number INTEGER NOT NULL,
                content_hash BLOB NOT NULL,
                size INTEGER NOT NULL,
                created_at INTEGER NOT NULL,
                UNIQUE(file_id, version_number)
            );

            CREATE INDEX idx_versions_file ON file_versions(file_id);
            CREATE INDEX idx_versions_created ON file_versions(created_at);

            -- Full-text search index
            CREATE VIRTUAL TABLE fts_content USING fts5(
                path,
                content,
                tokenize='porter unicode61'
            );

            -- Tags registry
            CREATE TABLE tags (
                id INTEGER PRIMARY KEY,
                name TEXT NOT NULL UNIQUE,
                created_at INTEGER NOT NULL
            );

            -- File-tag associations (many-to-many)
            CREATE TABLE file_tags (
                id INTEGER PRIMARY KEY,
                file_id INTEGER NOT NULL REFERENCES files(id) ON DELETE CASCADE,
                tag_id INTEGER NOT NULL REFERENCES tags(id) ON DELETE CASCADE,
                created_at INTEGER NOT NULL,
                UNIQUE(file_id, tag_id)
            );

            CREATE INDEX idx_file_tags_file ON file_tags(file_id);
            CREATE INDEX idx_file_tags_tag ON file_tags(tag_id);

            -- File metadata (key-value pairs)
            CREATE TABLE file_metadata (
                id INTEGER PRIMARY KEY,
                file_id INTEGER NOT NULL REFERENCES files(id) ON DELETE CASCADE,
                key TEXT NOT NULL,
                value TEXT NOT NULL,
                created_at INTEGER NOT NULL,
                modified_at INTEGER NOT NULL,
                UNIQUE(file_id, key)
            );

            CREATE INDEX idx_metadata_file ON file_metadata(file_id);
            CREATE INDEX idx_metadata_key ON file_metadata(key);

            -- Snapshots for vault state
            CREATE TABLE snapshots (
                id INTEGER PRIMARY KEY,
                name TEXT NOT NULL UNIQUE,
                created_at INTEGER NOT NULL,
                file_count INTEGER NOT NULL,
                total_size INTEGER NOT NULL,
                description TEXT
            );

            -- Snapshot file entries
            CREATE TABLE snapshot_files (
                id INTEGER PRIMARY KEY,
                snapshot_id INTEGER NOT NULL REFERENCES snapshots(id) ON DELETE CASCADE,
                path TEXT NOT NULL,
                file_type INTEGER NOT NULL,
                content_hash BLOB,
                size INTEGER NOT NULL,
                created_at INTEGER NOT NULL,
                modified_at INTEGER NOT NULL
            );

            CREATE INDEX idx_snapshot_files_snapshot ON snapshot_files(snapshot_id);

            -- Snapshot version history
            CREATE TABLE snapshot_versions (
                id INTEGER PRIMARY KEY,
                snapshot_id INTEGER NOT NULL REFERENCES snapshots(id) ON DELETE CASCADE,
                path TEXT NOT NULL,
                version_number INTEGER NOT NULL,
                content_hash BLOB NOT NULL,
                size INTEGER NOT NULL,
                created_at INTEGER NOT NULL,
                UNIQUE(snapshot_id, path, version_number)
            );

            CREATE INDEX idx_snapshot_versions_snapshot ON snapshot_versions(snapshot_id);

            -- Snapshot tag registry
            CREATE TABLE snapshot_tags (
                id INTEGER PRIMARY KEY,
                snapshot_id INTEGER NOT NULL REFERENCES snapshots(id) ON DELETE CASCADE,
                name TEXT NOT NULL,
                created_at INTEGER NOT NULL,
                UNIQUE(snapshot_id, name)
            );

            CREATE INDEX idx_snapshot_tags_snapshot ON snapshot_tags(snapshot_id);

            -- Snapshot file-tag associations
            CREATE TABLE snapshot_file_tags (
                id INTEGER PRIMARY KEY,
                snapshot_id INTEGER NOT NULL REFERENCES snapshots(id) ON DELETE CASCADE,
                path TEXT NOT NULL,
                tag_name TEXT NOT NULL,
                created_at INTEGER NOT NULL,
                UNIQUE(snapshot_id, path, tag_name)
            );

            CREATE INDEX idx_snapshot_file_tags_snapshot ON snapshot_file_tags(snapshot_id);

            -- Snapshot metadata
            CREATE TABLE snapshot_metadata (
                id INTEGER PRIMARY KEY,
                snapshot_id INTEGER NOT NULL REFERENCES snapshots(id) ON DELETE CASCADE,
                path TEXT NOT NULL,
                key TEXT NOT NULL,
                value TEXT NOT NULL,
                modified_at INTEGER NOT NULL,
                UNIQUE(snapshot_id, path, key)
            );

            CREATE INDEX idx_snapshot_metadata_snapshot ON snapshot_metadata(snapshot_id);

            -- Audit log for operations
            CREATE TABLE audit_log (
                id INTEGER PRIMARY KEY,
                timestamp INTEGER NOT NULL,
                operation TEXT NOT NULL,
                path TEXT,
                details TEXT
            );

            CREATE INDEX idx_audit_timestamp ON audit_log(timestamp);
            CREATE INDEX idx_audit_operation ON audit_log(operation);

            -- Initialize root directory (id=1)
            INSERT INTO files (id, parent_id, name, file_type, size, created_at, modified_at)
            VALUES (1, NULL, '', 1, 0, strftime('%s', 'now'), strftime('%s', 'now'));

            INSERT INTO paths (path, file_id) VALUES ('/', 1);

            INSERT INTO settings (key, value) VALUES
                ('schema_version', '5'),
                ('created_at', strftime('%s', 'now'));
            "#,
        )?;

        Ok(())
    }

    /// Migrate schema from older versions.
    fn migrate_schema(&self) -> Result<()> {
        let conn = self.conn.lock().unwrap();

        // Get current schema version
        let version: String = conn
            .query_row(
                "SELECT value FROM settings WHERE key = 'schema_version'",
                [],
                |row| row.get(0),
            )
            .unwrap_or_else(|_| "1".to_string());

        let version_num: u32 = version.parse().unwrap_or(1);

        if version_num >= 5 {
            return Ok(());
        }

        // Migrate from v3 to v4: Add snapshots, snapshot_files, audit_log tables
        if version_num < 4 {
            conn.execute_batch(
                r#"
                -- Snapshots for vault state
                CREATE TABLE IF NOT EXISTS snapshots (
                    id INTEGER PRIMARY KEY,
                    name TEXT NOT NULL UNIQUE,
                    created_at INTEGER NOT NULL,
                    file_count INTEGER NOT NULL,
                    total_size INTEGER NOT NULL,
                    description TEXT
                );

                -- Snapshot file entries
                CREATE TABLE IF NOT EXISTS snapshot_files (
                    id INTEGER PRIMARY KEY,
                    snapshot_id INTEGER NOT NULL REFERENCES snapshots(id) ON DELETE CASCADE,
                    path TEXT NOT NULL,
                    file_type INTEGER NOT NULL,
                    content_hash BLOB,
                    size INTEGER NOT NULL,
                    created_at INTEGER NOT NULL,
                    modified_at INTEGER NOT NULL
                );

                CREATE INDEX IF NOT EXISTS idx_snapshot_files_snapshot ON snapshot_files(snapshot_id);

                -- Audit log for operations
                CREATE TABLE IF NOT EXISTS audit_log (
                    id INTEGER PRIMARY KEY,
                    timestamp INTEGER NOT NULL,
                    operation TEXT NOT NULL,
                    path TEXT,
                    details TEXT
                );

                CREATE INDEX IF NOT EXISTS idx_audit_timestamp ON audit_log(timestamp);
                CREATE INDEX IF NOT EXISTS idx_audit_operation ON audit_log(operation);

                -- Update schema version
                UPDATE settings SET value = '4' WHERE key = 'schema_version';
                "#,
            )?;
        }

        // Migrate from v4 to v5: Add snapshot state tables for versions, tags, and metadata
        if version_num < 5 {
            conn.execute_batch(
                r#"
                CREATE TABLE IF NOT EXISTS snapshot_versions (
                    id INTEGER PRIMARY KEY,
                    snapshot_id INTEGER NOT NULL REFERENCES snapshots(id) ON DELETE CASCADE,
                    path TEXT NOT NULL,
                    version_number INTEGER NOT NULL,
                    content_hash BLOB NOT NULL,
                    size INTEGER NOT NULL,
                    created_at INTEGER NOT NULL,
                    UNIQUE(snapshot_id, path, version_number)
                );

                CREATE INDEX IF NOT EXISTS idx_snapshot_versions_snapshot ON snapshot_versions(snapshot_id);

                CREATE TABLE IF NOT EXISTS snapshot_tags (
                    id INTEGER PRIMARY KEY,
                    snapshot_id INTEGER NOT NULL REFERENCES snapshots(id) ON DELETE CASCADE,
                    name TEXT NOT NULL,
                    created_at INTEGER NOT NULL,
                    UNIQUE(snapshot_id, name)
                );

                CREATE INDEX IF NOT EXISTS idx_snapshot_tags_snapshot ON snapshot_tags(snapshot_id);

                CREATE TABLE IF NOT EXISTS snapshot_file_tags (
                    id INTEGER PRIMARY KEY,
                    snapshot_id INTEGER NOT NULL REFERENCES snapshots(id) ON DELETE CASCADE,
                    path TEXT NOT NULL,
                    tag_name TEXT NOT NULL,
                    created_at INTEGER NOT NULL,
                    UNIQUE(snapshot_id, path, tag_name)
                );

                CREATE INDEX IF NOT EXISTS idx_snapshot_file_tags_snapshot ON snapshot_file_tags(snapshot_id);

                CREATE TABLE IF NOT EXISTS snapshot_metadata (
                    id INTEGER PRIMARY KEY,
                    snapshot_id INTEGER NOT NULL REFERENCES snapshots(id) ON DELETE CASCADE,
                    path TEXT NOT NULL,
                    key TEXT NOT NULL,
                    value TEXT NOT NULL,
                    modified_at INTEGER NOT NULL,
                    UNIQUE(snapshot_id, path, key)
                );

                CREATE INDEX IF NOT EXISTS idx_snapshot_metadata_snapshot ON snapshot_metadata(snapshot_id);

                UPDATE settings SET value = '5' WHERE key = 'schema_version';
                "#,
            )?;
        }

        Ok(())
    }

    // ==================== File Operations ====================

    /// Get a file entry by path.
    pub fn get_entry_by_path(&self, path: &str) -> Result<FileEntry> {
        let conn = self.conn.lock().unwrap();

        let file_id: i64 = conn
            .query_row("SELECT file_id FROM paths WHERE path = ?", [path], |row| {
                row.get(0)
            })
            .optional()?
            .ok_or_else(|| VfsError::NotFound(PathBuf::from(path)))?;

        self.get_entry_by_id_locked(&conn, file_id)
    }

    /// Get a file entry by ID.
    pub fn get_entry_by_id(&self, id: i64) -> Result<FileEntry> {
        let conn = self.conn.lock().unwrap();
        self.get_entry_by_id_locked(&conn, id)
    }

    fn get_entry_by_id_locked(&self, conn: &Connection, id: i64) -> Result<FileEntry> {
        conn.query_row(
            "SELECT id, parent_id, name, file_type, content_hash, size, created_at, modified_at
             FROM files WHERE id = ?",
            [id],
            |row| {
                Ok(FileEntry {
                    id: row.get(0)?,
                    parent_id: row.get(1)?,
                    name: row.get(2)?,
                    file_type: FileType::from_i64(row.get(3)?).unwrap_or(FileType::File),
                    content_hash: row
                        .get::<_, Option<Vec<u8>>>(4)?
                        .and_then(|v| v.try_into().ok()),
                    size: row.get::<_, i64>(5)? as u64,
                    created_at: chrono::DateTime::from_timestamp(row.get(6)?, 0)
                        .unwrap_or_else(Utc::now),
                    modified_at: chrono::DateTime::from_timestamp(row.get(7)?, 0)
                        .unwrap_or_else(Utc::now),
                })
            },
        )
        .map_err(|e| match e {
            rusqlite::Error::QueryReturnedNoRows => {
                VfsError::Internal(format!("file entry not found: id={}", id))
            }
            e => e.into(),
        })
    }

    /// List children of a directory.
    pub fn list_children(&self, parent_id: i64) -> Result<Vec<FileEntry>> {
        let conn = self.conn.lock().unwrap();

        let mut stmt = conn.prepare(
            "SELECT id, parent_id, name, file_type, content_hash, size, created_at, modified_at
             FROM files WHERE parent_id = ? ORDER BY file_type DESC, name",
        )?;

        let entries = stmt
            .query_map([parent_id], |row| {
                Ok(FileEntry {
                    id: row.get(0)?,
                    parent_id: row.get(1)?,
                    name: row.get(2)?,
                    file_type: FileType::from_i64(row.get(3)?).unwrap_or(FileType::File),
                    content_hash: row
                        .get::<_, Option<Vec<u8>>>(4)?
                        .and_then(|v| v.try_into().ok()),
                    size: row.get::<_, i64>(5)? as u64,
                    created_at: chrono::DateTime::from_timestamp(row.get(6)?, 0)
                        .unwrap_or_else(Utc::now),
                    modified_at: chrono::DateTime::from_timestamp(row.get(7)?, 0)
                        .unwrap_or_else(Utc::now),
                })
            })?
            .collect::<std::result::Result<Vec<_>, _>>()?;

        Ok(entries)
    }

    /// Read file content by hash.
    pub fn read_content(&self, hash: &[u8; 32]) -> Result<Vec<u8>> {
        let conn = self.conn.lock().unwrap();

        conn.query_row(
            "SELECT data FROM contents WHERE hash = ?",
            [hash.as_slice()],
            |row| row.get(0),
        )
        .map_err(|e| match e {
            rusqlite::Error::QueryReturnedNoRows => {
                VfsError::Internal("content not found".to_string())
            }
            e => e.into(),
        })
    }

    /// Write file content and get its hash.
    pub fn write_content(&self, data: &[u8]) -> Result<[u8; 32]> {
        use sha2::{Digest, Sha256};

        let mut hasher = Sha256::new();
        hasher.update(data);
        let hash: [u8; 32] = hasher.finalize().into();

        let conn = self.conn.lock().unwrap();
        let size = data.len() as i64;

        conn.execute(
            "INSERT OR IGNORE INTO contents (hash, data, size, ref_count) VALUES (?, ?, ?, 1)",
            params![hash.as_slice(), data, size],
        )?;

        Ok(hash)
    }

    /// Create a file entry.
    pub fn create_file(
        &self,
        parent_id: i64,
        name: &str,
        content_hash: &[u8; 32],
        size: u64,
        path: &str,
    ) -> Result<i64> {
        let conn = self.conn.lock().unwrap();
        let now = Utc::now().timestamp();

        conn.execute(
            "INSERT INTO files (parent_id, name, file_type, content_hash, size, created_at, modified_at)
             VALUES (?, ?, ?, ?, ?, ?, ?)",
            params![
                parent_id,
                name,
                FileType::File.to_i64(),
                content_hash.as_slice(),
                size as i64,
                now,
                now
            ],
        )?;

        let file_id = conn.last_insert_rowid();

        conn.execute(
            "INSERT INTO paths (path, file_id) VALUES (?, ?)",
            params![path, file_id],
        )?;

        Ok(file_id)
    }

    /// Update a file's content.
    pub fn update_file(&self, file_id: i64, content_hash: &[u8; 32], size: u64) -> Result<()> {
        let conn = self.conn.lock().unwrap();
        let now = Utc::now().timestamp();

        conn.execute(
            "UPDATE files SET content_hash = ?, size = ?, modified_at = ? WHERE id = ?",
            params![content_hash.as_slice(), size as i64, now, file_id],
        )?;

        Ok(())
    }

    /// Create a directory entry.
    pub fn create_directory(&self, parent_id: i64, name: &str, path: &str) -> Result<i64> {
        let conn = self.conn.lock().unwrap();
        let now = Utc::now().timestamp();

        conn.execute(
            "INSERT INTO files (parent_id, name, file_type, size, created_at, modified_at)
             VALUES (?, ?, ?, 0, ?, ?)",
            params![parent_id, name, FileType::Directory.to_i64(), now, now],
        )?;

        let dir_id = conn.last_insert_rowid();

        conn.execute(
            "INSERT INTO paths (path, file_id) VALUES (?, ?)",
            params![path, dir_id],
        )?;

        Ok(dir_id)
    }

    /// Check if a name exists under a parent.
    pub fn name_exists(&self, parent_id: i64, name: &str) -> Result<bool> {
        let conn = self.conn.lock().unwrap();

        let exists: bool = conn
            .query_row(
                "SELECT 1 FROM files WHERE parent_id = ? AND name = ?",
                params![parent_id, name],
                |_| Ok(true),
            )
            .optional()?
            .unwrap_or(false);

        Ok(exists)
    }

    /// Get file ID by parent and name.
    pub fn get_file_id(&self, parent_id: i64, name: &str) -> Result<Option<i64>> {
        let conn = self.conn.lock().unwrap();

        conn.query_row(
            "SELECT id FROM files WHERE parent_id = ? AND name = ?",
            params![parent_id, name],
            |row| row.get(0),
        )
        .optional()
        .map_err(|e| e.into())
    }

    /// Delete a file or directory entry.
    pub fn delete_entry(&self, id: i64, path: &str) -> Result<()> {
        let conn = self.conn.lock().unwrap();

        // Delete paths (including children)
        conn.execute(
            "DELETE FROM paths WHERE path = ? OR path LIKE ?",
            params![path, format!("{}/%", path)],
        )?;

        // Delete file entry (CASCADE handles children)
        conn.execute("DELETE FROM files WHERE id = ?", [id])?;

        Ok(())
    }

    /// Check if a directory has children.
    pub fn has_children(&self, id: i64) -> Result<bool> {
        let conn = self.conn.lock().unwrap();

        let has: bool = conn
            .query_row(
                "SELECT 1 FROM files WHERE parent_id = ? LIMIT 1",
                [id],
                |_| Ok(true),
            )
            .optional()?
            .unwrap_or(false);

        Ok(has)
    }

    /// Move/rename a file entry.
    pub fn move_entry(
        &self,
        id: i64,
        new_parent_id: i64,
        new_name: &str,
        old_path: &str,
        new_path: &str,
    ) -> Result<()> {
        let conn = self.conn.lock().unwrap();
        let now = Utc::now().timestamp();

        // Update file entry
        conn.execute(
            "UPDATE files SET parent_id = ?, name = ?, modified_at = ? WHERE id = ?",
            params![new_parent_id, new_name, now, id],
        )?;

        // Delete old paths
        conn.execute(
            "DELETE FROM paths WHERE path = ? OR path LIKE ?",
            params![old_path, format!("{}/%", old_path)],
        )?;

        // Insert new path
        conn.execute(
            "INSERT INTO paths (path, file_id) VALUES (?, ?)",
            params![new_path, id],
        )?;

        Ok(())
    }

    /// Rebuild paths for children after a move.
    pub fn rebuild_child_paths(&self, parent_id: i64, parent_path: &str) -> Result<()> {
        let children = self.list_children(parent_id)?;
        let conn = self.conn.lock().unwrap();
        let mut directories = Vec::new();

        for child in &children {
            let child_path = if parent_path == "/" {
                format!("/{}", child.name)
            } else {
                format!("{}/{}", parent_path, child.name)
            };

            conn.execute(
                "INSERT OR REPLACE INTO paths (path, file_id) VALUES (?, ?)",
                params![&child_path, child.id],
            )?;

            if child.is_dir() {
                directories.push((child.id, child_path));
            }
        }

        drop(conn);

        for (child_id, child_path) in directories {
            self.rebuild_child_paths(child_id, &child_path)?;
        }

        Ok(())
    }

    /// Increment reference count for content.
    pub fn increment_content_ref(&self, hash: &[u8; 32]) -> Result<()> {
        let conn = self.conn.lock().unwrap();

        conn.execute(
            "UPDATE contents SET ref_count = ref_count + 1 WHERE hash = ?",
            [hash.as_slice()],
        )?;

        Ok(())
    }

    /// Copy file entry (shares content).
    pub fn copy_file(
        &self,
        src: &FileEntry,
        new_parent_id: i64,
        new_name: &str,
        new_path: &str,
    ) -> Result<i64> {
        let conn = self.conn.lock().unwrap();
        let now = Utc::now().timestamp();

        let hash_slice: Option<&[u8]> = src.content_hash.as_ref().map(|h| h.as_slice());
        conn.execute(
            "INSERT INTO files (parent_id, name, file_type, content_hash, size, created_at, modified_at)
             VALUES (?, ?, ?, ?, ?, ?, ?)",
            params![
                new_parent_id,
                new_name,
                FileType::File.to_i64(),
                hash_slice,
                src.size as i64,
                now,
                now
            ],
        )?;

        let file_id = conn.last_insert_rowid();

        conn.execute(
            "INSERT INTO paths (path, file_id) VALUES (?, ?)",
            params![new_path, file_id],
        )?;

        // Increment ref count
        if let Some(ref hash) = src.content_hash {
            let hash_ref: &[u8] = hash.as_slice();
            conn.execute(
                "UPDATE contents SET ref_count = ref_count + 1 WHERE hash = ?",
                [hash_ref],
            )?;
        }

        Ok(file_id)
    }

    /// Get setting value.
    pub fn get_setting(&self, key: &str) -> Result<Option<String>> {
        let conn = self.conn.lock().unwrap();

        conn.query_row("SELECT value FROM settings WHERE key = ?", [key], |row| {
            row.get(0)
        })
        .optional()
        .map_err(|e| e.into())
    }

    // ==================== Version Operations ====================

    /// Create a version snapshot of the current file state.
    pub fn create_version(&self, file_id: i64, content_hash: &[u8; 32], size: u64) -> Result<u64> {
        let conn = self.conn.lock().unwrap();
        let now = Utc::now().timestamp();

        // Get next version number
        let next_version: u64 = conn.query_row(
            "SELECT COALESCE(MAX(version_number), 0) + 1 FROM file_versions WHERE file_id = ?",
            [file_id],
            |row| row.get(0),
        )?;

        conn.execute(
            "INSERT INTO file_versions (file_id, version_number, content_hash, size, created_at)
             VALUES (?, ?, ?, ?, ?)",
            params![
                file_id,
                next_version as i64,
                content_hash.as_slice(),
                size as i64,
                now
            ],
        )?;

        Ok(next_version)
    }

    /// Get all versions of a file.
    pub fn get_file_versions(&self, file_id: i64) -> Result<Vec<crate::fs::FileVersion>> {
        let conn = self.conn.lock().unwrap();

        let mut stmt = conn.prepare(
            "SELECT id, file_id, version_number, content_hash, size, created_at
             FROM file_versions WHERE file_id = ? ORDER BY version_number DESC",
        )?;

        let versions = stmt
            .query_map([file_id], |row| {
                Ok(crate::fs::FileVersion {
                    id: row.get(0)?,
                    file_id: row.get(1)?,
                    version_number: row.get::<_, i64>(2)? as u64,
                    content_hash: row.get::<_, Vec<u8>>(3)?.try_into().unwrap_or([0u8; 32]),
                    size: row.get::<_, i64>(4)? as u64,
                    created_at: chrono::DateTime::from_timestamp(row.get(5)?, 0)
                        .unwrap_or_else(Utc::now),
                })
            })?
            .collect::<std::result::Result<Vec<_>, _>>()?;

        Ok(versions)
    }

    /// Get a specific version of a file.
    pub fn get_version(&self, file_id: i64, version_num: u64) -> Result<crate::fs::FileVersion> {
        let conn = self.conn.lock().unwrap();

        conn.query_row(
            "SELECT id, file_id, version_number, content_hash, size, created_at
             FROM file_versions WHERE file_id = ? AND version_number = ?",
            params![file_id, version_num as i64],
            |row| {
                Ok(crate::fs::FileVersion {
                    id: row.get(0)?,
                    file_id: row.get(1)?,
                    version_number: row.get::<_, i64>(2)? as u64,
                    content_hash: row.get::<_, Vec<u8>>(3)?.try_into().unwrap_or([0u8; 32]),
                    size: row.get::<_, i64>(4)? as u64,
                    created_at: chrono::DateTime::from_timestamp(row.get(5)?, 0)
                        .unwrap_or_else(Utc::now),
                })
            },
        )
        .map_err(|e| match e {
            rusqlite::Error::QueryReturnedNoRows => {
                VfsError::NotFound(PathBuf::from(format!("version {} not found", version_num)))
            }
            e => e.into(),
        })
    }

    /// Get the content of a specific version.
    pub fn get_version_content(&self, file_id: i64, version_num: u64) -> Result<Vec<u8>> {
        let version = self.get_version(file_id, version_num)?;
        self.read_content(&version.content_hash)
    }

    /// Get the latest version number for a file (0 if no versions).
    pub fn get_latest_version_number(&self, file_id: i64) -> Result<u64> {
        let conn = self.conn.lock().unwrap();

        let version: i64 = conn.query_row(
            "SELECT COALESCE(MAX(version_number), 0) FROM file_versions WHERE file_id = ?",
            [file_id],
            |row| row.get(0),
        )?;

        Ok(version as u64)
    }

    // ==================== Search Operations ====================

    /// Index a file for full-text search.
    pub fn index_file(&self, file_id: i64, path: &str, content: &str) -> Result<()> {
        let conn = self.conn.lock().unwrap();

        // Delete existing index entry if any
        conn.execute("DELETE FROM fts_content WHERE rowid = ?", [file_id])?;

        // Insert new index entry
        conn.execute(
            "INSERT INTO fts_content (rowid, path, content) VALUES (?, ?, ?)",
            params![file_id, path, content],
        )?;

        Ok(())
    }

    /// Remove a file from the search index.
    pub fn remove_from_index(&self, file_id: i64) -> Result<()> {
        let conn = self.conn.lock().unwrap();

        conn.execute("DELETE FROM fts_content WHERE rowid = ?", [file_id])?;

        Ok(())
    }

    /// Rebuild a single file's search index entry from stored content.
    pub fn sync_file_index(&self, file_id: i64, path: &str) -> Result<()> {
        let conn = self.conn.lock().unwrap();

        conn.execute("DELETE FROM fts_content WHERE rowid = ?", [file_id])?;

        let data: Option<Vec<u8>> = conn
            .query_row(
                "SELECT c.data
                 FROM files f
                 JOIN contents c ON c.hash = f.content_hash
                 WHERE f.id = ? AND f.file_type = 0",
                [file_id],
                |row| row.get(0),
            )
            .optional()?;

        if let Some(data) = data {
            if let Ok(content) = String::from_utf8(data) {
                conn.execute(
                    "INSERT INTO fts_content (rowid, path, content) VALUES (?, ?, ?)",
                    params![file_id, path, content],
                )?;
            }
        }

        Ok(())
    }

    // ==================== Atomic Operations ====================
    /// Atomic file write: stores content, creates or updates file entry,
    /// versions the previous state, and updates the search index in a single
    /// SQLite transaction.
    pub fn write_file_atomic(
        &self,
        parent_id: i64,
        name: &str,
        content: &[u8],
        path: &str,
    ) -> Result<i64> {
        use sha2::{Digest, Sha256};

        let mut hasher = Sha256::new();
        hasher.update(content);
        let hash: [u8; 32] = hasher.finalize().into();
        let size = content.len() as u64;

        let conn = self.conn.lock().unwrap();
        let now = Utc::now().timestamp();

        conn.execute("BEGIN IMMEDIATE", [])?;

        let result = (|| -> Result<i64> {
            // Store content (idempotent)
            conn.execute(
                "INSERT OR IGNORE INTO contents (hash, data, size, ref_count) VALUES (?, ?, ?, 1)",
                params![hash.as_slice(), content, size as i64],
            )?;

            // Check if file already exists
            let existing_id: Option<i64> = conn
                .query_row(
                    "SELECT id FROM files WHERE parent_id = ? AND name = ?",
                    params![parent_id, name],
                    |row| row.get(0),
                )
                .optional()?;

            let file_id = if let Some(id) = existing_id {
                // Snapshot current state into a version
                let current_hash: Option<Vec<u8>> = conn
                    .query_row(
                        "SELECT content_hash FROM files WHERE id = ?",
                        [id],
                        |row| row.get(0),
                    )
                    .optional()?;

                if let Some(h) = current_hash {
                    let next_version: i64 = conn.query_row(
                        "SELECT COALESCE(MAX(version_number), 0) + 1 FROM file_versions WHERE file_id = ?",
                        [id],
                        |row| row.get(0),
                    )?;

                    conn.execute(
                        "INSERT INTO file_versions (file_id, version_number, content_hash, size, created_at)
                         VALUES (?, ?, ?, ?, ?)",
                        params![id, next_version, h.as_slice(), size as i64, now],
                    )?;
                }

                // Update existing file
                conn.execute(
                    "UPDATE files SET content_hash = ?, size = ?, modified_at = ? WHERE id = ?",
                    params![hash.as_slice(), size as i64, now, id],
                )?;

                id
            } else {
                // Create new file entry
                conn.execute(
                    "INSERT INTO files (parent_id, name, file_type, content_hash, size, created_at, modified_at)
                     VALUES (?, ?, ?, ?, ?, ?, ?)",
                    params![parent_id, name, FileType::File.to_i64(), hash.as_slice(), size as i64, now, now],
                )?;

                let file_id = conn.last_insert_rowid();

                conn.execute(
                    "INSERT INTO paths (path, file_id) VALUES (?, ?)",
                    params![path, file_id],
                )?;

                // Create initial version
                conn.execute(
                    "INSERT INTO file_versions (file_id, version_number, content_hash, size, created_at)
                     VALUES (?, 1, ?, ?, ?)",
                    params![file_id, hash.as_slice(), size as i64, now],
                )?;

                file_id
            };

            // Update FTS index: always delete old entry, then re-insert if valid UTF-8
            conn.execute("DELETE FROM fts_content WHERE rowid = ?", [file_id])?;
            if let Ok(text) = String::from_utf8(content.to_vec()) {
                conn.execute(
                    "INSERT INTO fts_content (rowid, path, content) VALUES (?, ?, ?)",
                    params![file_id, path, text],
                )?;
            }

            Ok(file_id)
        })();

        match result {
            Ok(id) => {
                conn.execute("COMMIT", [])?;
                Ok(id)
            }
            Err(e) => {
                let _ = conn.execute("ROLLBACK", []);
                Err(e)
            }
        }
    }

    /// Atomic directory creation: checks for duplicates and creates the
    /// directory entry + path in a single SQLite transaction.
    pub fn create_directory_atomic(
        &self,
        parent_id: i64,
        name: &str,
        path: &str,
    ) -> Result<i64> {
        let conn = self.conn.lock().unwrap();
        let now = Utc::now().timestamp();

        conn.execute("BEGIN IMMEDIATE", [])?;

        let result = (|| -> Result<i64> {
            let exists: bool = conn
                .query_row(
                    "SELECT 1 FROM files WHERE parent_id = ? AND name = ?",
                    params![parent_id, name],
                    |_| Ok(true),
                )
                .optional()?
                .unwrap_or(false);

            if exists {
                return Err(VfsError::AlreadyExists(PathBuf::from(path)));
            }

            conn.execute(
                "INSERT INTO files (parent_id, name, file_type, size, created_at, modified_at)
                 VALUES (?, ?, ?, 0, ?, ?)",
                params![parent_id, name, FileType::Directory.to_i64(), now, now],
            )?;

            let dir_id = conn.last_insert_rowid();

            conn.execute(
                "INSERT INTO paths (path, file_id) VALUES (?, ?)",
                params![path, dir_id],
            )?;

            Ok(dir_id)
        })();

        match result {
            Ok(id) => {
                conn.execute("COMMIT", [])?;
                Ok(id)
            }
            Err(e) => {
                let _ = conn.execute("ROLLBACK", []);
                Err(e)
            }
        }
    }

    /// Atomic delete: removes paths and the file entry (with CASCADE) in a
    /// single SQLite transaction.
    pub fn delete_entry_atomic(&self, id: i64, path: &str) -> Result<()> {
        let conn = self.conn.lock().unwrap();

        conn.execute("BEGIN IMMEDIATE", [])?;

        let result = (|| -> Result<()> {
            conn.execute(
                "DELETE FROM paths WHERE path = ? OR path LIKE ?",
                params![path, format!("{}/%", path)],
            )?;

            conn.execute("DELETE FROM files WHERE id = ?", [id])?;

            Ok(())
        })();

        match result {
            Ok(()) => {
                conn.execute("COMMIT", [])?;
                Ok(())
            }
            Err(e) => {
                let _ = conn.execute("ROLLBACK", []);
                Err(e)
            }
        }
    }

    /// Atomic move: updates the file entry, swaps paths, and rebuilds child
    /// paths inside a single SQLite transaction.
    pub fn move_entry_atomic(
        &self,
        id: i64,
        new_parent_id: i64,
        new_name: &str,
        old_path: &str,
        new_path: &str,
    ) -> Result<()> {
        let conn = self.conn.lock().unwrap();
        let now = Utc::now().timestamp();

        conn.execute("BEGIN IMMEDIATE", [])?;

        let result = (|| -> Result<()> {
            // Update file entry
            conn.execute(
                "UPDATE files SET parent_id = ?, name = ?, modified_at = ? WHERE id = ?",
                params![new_parent_id, new_name, now, id],
            )?;

            // Delete old paths
            conn.execute(
                "DELETE FROM paths WHERE path = ? OR path LIKE ?",
                params![old_path, format!("{}/%", old_path)],
            )?;

            // Insert new path for the moved entry itself
            conn.execute(
                "INSERT INTO paths (path, file_id) VALUES (?, ?)",
                params![new_path, id],
            )?;

            // If directory, rebuild all descendant paths
            let is_dir: bool = conn
                .query_row(
                    "SELECT file_type = 1 FROM files WHERE id = ?",
                    [id],
                    |row| row.get::<_, bool>(0),
                )
                .optional()?
                .unwrap_or(false);

            if is_dir {
                Self::rebuild_child_paths_locked(&conn, id, new_path)?;
            }

            Ok(())
        })();

        match result {
            Ok(()) => {
                conn.execute("COMMIT", [])?;
                Ok(())
            }
            Err(e) => {
                let _ = conn.execute("ROLLBACK", []);
                Err(e)
            }
        }
    }

    /// Recursive helper for rebuilding child paths while already holding the
    /// connection lock (used inside a transaction).
    fn rebuild_child_paths_locked(
        conn: &Connection,
        parent_id: i64,
        parent_path: &str,
    ) -> Result<()> {
        let mut stmt = conn.prepare(
            "SELECT id, name, file_type FROM files WHERE parent_id = ? ORDER BY name",
        )?;

        let children: Vec<(i64, String, bool)> = stmt
            .query_map([parent_id], |row| {
                let id: i64 = row.get(0)?;
                let name: String = row.get(1)?;
                let file_type: i64 = row.get(2)?;
                Ok((id, name, file_type == 1))
            })?
            .collect::<std::result::Result<Vec<_>, _>>()?;

        drop(stmt);

        for (child_id, child_name, is_dir) in children {
            let child_path = if parent_path == "/" {
                format!("/{}", child_name)
            } else {
                format!("{}/{}", parent_path, child_name)
            };

            conn.execute(
                "INSERT OR REPLACE INTO paths (path, file_id) VALUES (?, ?)",
                params![&child_path, child_id],
            )?;

            if is_dir {
                Self::rebuild_child_paths_locked(conn, child_id, &child_path)?;
            }
        }

        Ok(())
    }

    /// Atomic copy: inserts the new file entry, its path, and increments the
    /// content reference count in a single SQLite transaction.
    pub fn copy_file_atomic(
        &self,
        src: &FileEntry,
        new_parent_id: i64,
        new_name: &str,
        new_path: &str,
    ) -> Result<i64> {
        let conn = self.conn.lock().unwrap();
        let now = Utc::now().timestamp();

        conn.execute("BEGIN IMMEDIATE", [])?;

        let result = (|| -> Result<i64> {
            let hash_slice: Option<&[u8]> = src.content_hash.as_ref().map(|h| h.as_slice());

            conn.execute(
                "INSERT INTO files (parent_id, name, file_type, content_hash, size, created_at, modified_at)
                 VALUES (?, ?, ?, ?, ?, ?, ?)",
                params![
                    new_parent_id,
                    new_name,
                    FileType::File.to_i64(),
                    hash_slice,
                    src.size as i64,
                    now,
                    now
                ],
            )?;

            let file_id = conn.last_insert_rowid();

            conn.execute(
                "INSERT INTO paths (path, file_id) VALUES (?, ?)",
                params![new_path, file_id],
            )?;

            if let Some(ref hash) = src.content_hash {
                conn.execute(
                    "UPDATE contents SET ref_count = ref_count + 1 WHERE hash = ?",
                    [hash.as_slice()],
                )?;
            }

            Ok(file_id)
        })();

        match result {
            Ok(id) => {
                conn.execute("COMMIT", [])?;
                Ok(id)
            }
            Err(e) => {
                let _ = conn.execute("ROLLBACK", []);
                Err(e)
            }
        }
    }

    /// Search content using FTS5.
    pub fn search_content(
        &self,
        query: &str,
        limit: usize,
    ) -> Result<Vec<crate::fs::SearchResult>> {
        let conn = self.conn.lock().unwrap();

        let mut stmt = conn.prepare(
            "SELECT rowid, path, snippet(fts_content, 1, '>>>>', '<<<<', '...', 32) as snippet,
                    rank
             FROM fts_content
             WHERE fts_content MATCH ?
             ORDER BY rank
             LIMIT ?",
        )?;

        let results = stmt
            .query_map(params![query, limit as i64], |row| {
                Ok(crate::fs::SearchResult {
                    file_id: row.get(0)?,
                    path: row.get(1)?,
                    snippet: row.get(2)?,
                    rank: row.get(3)?,
                })
            })?
            .collect::<std::result::Result<Vec<_>, _>>()?;

        Ok(results)
    }

    /// Rebuild the entire search index.
    pub fn rebuild_search_index(&self) -> Result<u64> {
        let conn = self.conn.lock().unwrap();

        // Clear existing index
        conn.execute("DELETE FROM fts_content", [])?;

        // Get all files with content
        let mut stmt = conn.prepare(
            "SELECT f.id, p.path, c.data
             FROM files f
             JOIN paths p ON p.file_id = f.id
             JOIN contents c ON c.hash = f.content_hash
             WHERE f.file_type = 0", // Files only
        )?;

        let mut indexed = 0u64;
        let mut rows = stmt.query([])?;
        while let Some(row) = rows.next()? {
            let file_id: i64 = row.get(0)?;
            let path: String = row.get(1)?;
            let data: Vec<u8> = row.get(2)?;

            if let Ok(content) = String::from_utf8(data) {
                conn.execute(
                    "INSERT INTO fts_content (rowid, path, content) VALUES (?, ?, ?)",
                    params![file_id, path, content],
                )?;
                indexed += 1;
            }
        }

        Ok(indexed)
    }

    // ==================== Tag Operations ====================

    /// Create a new tag.
    pub fn create_tag(&self, name: &str) -> Result<i64> {
        let conn = self.conn.lock().unwrap();
        let now = Utc::now().timestamp();

        conn.execute(
            "INSERT INTO tags (name, created_at) VALUES (?, ?)",
            params![name, now],
        )?;

        Ok(conn.last_insert_rowid())
    }

    /// Delete a tag (and all associations).
    pub fn delete_tag(&self, tag_id: i64) -> Result<()> {
        let conn = self.conn.lock().unwrap();

        conn.execute("DELETE FROM tags WHERE id = ?", [tag_id])?;

        Ok(())
    }

    /// Rename a tag.
    pub fn rename_tag(&self, tag_id: i64, new_name: &str) -> Result<()> {
        let conn = self.conn.lock().unwrap();

        conn.execute(
            "UPDATE tags SET name = ? WHERE id = ?",
            params![new_name, tag_id],
        )?;

        Ok(())
    }

    /// List all tags in the vault.
    pub fn list_tags(&self) -> Result<Vec<crate::fs::Tag>> {
        let conn = self.conn.lock().unwrap();

        let mut stmt = conn.prepare("SELECT id, name, created_at FROM tags ORDER BY name")?;

        let tags = stmt
            .query_map([], |row| {
                Ok(crate::fs::Tag {
                    id: row.get(0)?,
                    name: row.get(1)?,
                    created_at: chrono::DateTime::from_timestamp(row.get(2)?, 0)
                        .unwrap_or_else(Utc::now),
                })
            })?
            .collect::<std::result::Result<Vec<_>, _>>()?;

        Ok(tags)
    }

    /// Get a tag by name.
    pub fn get_tag_by_name(&self, name: &str) -> Result<Option<crate::fs::Tag>> {
        let conn = self.conn.lock().unwrap();

        conn.query_row(
            "SELECT id, name, created_at FROM tags WHERE name = ?",
            [name],
            |row| {
                Ok(crate::fs::Tag {
                    id: row.get(0)?,
                    name: row.get(1)?,
                    created_at: chrono::DateTime::from_timestamp(row.get(2)?, 0)
                        .unwrap_or_else(Utc::now),
                })
            },
        )
        .optional()
        .map_err(|e| e.into())
    }

    /// Add a tag to a file.
    pub fn add_tag_to_file(&self, file_id: i64, tag_id: i64) -> Result<()> {
        let conn = self.conn.lock().unwrap();
        let now = Utc::now().timestamp();

        conn.execute(
            "INSERT OR IGNORE INTO file_tags (file_id, tag_id, created_at) VALUES (?, ?, ?)",
            params![file_id, tag_id, now],
        )?;

        Ok(())
    }

    /// Remove a tag from a file.
    pub fn remove_tag_from_file(&self, file_id: i64, tag_id: i64) -> Result<()> {
        let conn = self.conn.lock().unwrap();

        conn.execute(
            "DELETE FROM file_tags WHERE file_id = ? AND tag_id = ?",
            params![file_id, tag_id],
        )?;

        Ok(())
    }

    /// Get all tags for a file.
    pub fn get_file_tags(&self, file_id: i64) -> Result<Vec<crate::fs::Tag>> {
        let conn = self.conn.lock().unwrap();

        let mut stmt = conn.prepare(
            "SELECT t.id, t.name, t.created_at
             FROM tags t
             JOIN file_tags ft ON ft.tag_id = t.id
             WHERE ft.file_id = ?
             ORDER BY t.name",
        )?;

        let tags = stmt
            .query_map([file_id], |row| {
                Ok(crate::fs::Tag {
                    id: row.get(0)?,
                    name: row.get(1)?,
                    created_at: chrono::DateTime::from_timestamp(row.get(2)?, 0)
                        .unwrap_or_else(Utc::now),
                })
            })?
            .collect::<std::result::Result<Vec<_>, _>>()?;

        Ok(tags)
    }

    /// Get all file IDs that have a specific tag.
    pub fn get_files_with_tag(&self, tag_id: i64) -> Result<Vec<i64>> {
        let conn = self.conn.lock().unwrap();

        let mut stmt = conn.prepare("SELECT file_id FROM file_tags WHERE tag_id = ?")?;

        let file_ids = stmt
            .query_map([tag_id], |row| row.get(0))?
            .collect::<std::result::Result<Vec<_>, _>>()?;

        Ok(file_ids)
    }

    /// Get or create a tag by name.
    pub fn get_or_create_tag(&self, name: &str) -> Result<i64> {
        if let Some(tag) = self.get_tag_by_name(name)? {
            Ok(tag.id)
        } else {
            self.create_tag(name)
        }
    }

    // ==================== Metadata Operations ====================

    /// Set metadata on a file (insert or update).
    pub fn set_metadata(&self, file_id: i64, key: &str, value: &str) -> Result<()> {
        let conn = self.conn.lock().unwrap();
        let now = Utc::now().timestamp();

        conn.execute(
            "INSERT INTO file_metadata (file_id, key, value, created_at, modified_at)
             VALUES (?, ?, ?, ?, ?)
             ON CONFLICT(file_id, key) DO UPDATE SET value = ?, modified_at = ?",
            params![file_id, key, value, now, now, value, now],
        )?;

        Ok(())
    }

    /// Get a single metadata value.
    pub fn get_metadata(&self, file_id: i64, key: &str) -> Result<Option<String>> {
        let conn = self.conn.lock().unwrap();

        conn.query_row(
            "SELECT value FROM file_metadata WHERE file_id = ? AND key = ?",
            params![file_id, key],
            |row| row.get(0),
        )
        .optional()
        .map_err(|e| e.into())
    }

    /// Get all metadata for a file.
    pub fn get_all_metadata(&self, file_id: i64) -> Result<Vec<crate::fs::Metadata>> {
        let conn = self.conn.lock().unwrap();

        let mut stmt = conn.prepare(
            "SELECT key, value, modified_at FROM file_metadata WHERE file_id = ? ORDER BY key",
        )?;

        let metadata = stmt
            .query_map([file_id], |row| {
                Ok(crate::fs::Metadata {
                    key: row.get(0)?,
                    value: row.get(1)?,
                    modified_at: chrono::DateTime::from_timestamp(row.get(2)?, 0)
                        .unwrap_or_else(Utc::now),
                })
            })?
            .collect::<std::result::Result<Vec<_>, _>>()?;

        Ok(metadata)
    }

    /// Delete a metadata key from a file.
    pub fn delete_metadata(&self, file_id: i64, key: &str) -> Result<()> {
        let conn = self.conn.lock().unwrap();

        conn.execute(
            "DELETE FROM file_metadata WHERE file_id = ? AND key = ?",
            params![file_id, key],
        )?;

        Ok(())
    }

    /// Get all file IDs that have a specific metadata key-value pair.
    pub fn get_files_with_metadata(&self, key: &str, value: &str) -> Result<Vec<i64>> {
        let conn = self.conn.lock().unwrap();

        let mut stmt =
            conn.prepare("SELECT file_id FROM file_metadata WHERE key = ? AND value = ?")?;

        let file_ids = stmt
            .query_map(params![key, value], |row| row.get(0))?
            .collect::<std::result::Result<Vec<_>, _>>()?;

        Ok(file_ids)
    }

    // ==================== Maintenance Operations ====================

    /// Get vault storage statistics.
    pub fn get_vault_stats(&self) -> Result<VaultStats> {
        let conn = self.conn.lock().unwrap();

        // Count files (type 0)
        let files: u64 = conn.query_row(
            "SELECT COUNT(*) FROM files WHERE file_type = 0",
            [],
            |row| row.get(0),
        )?;

        // Count directories (type 1, excluding root)
        let directories: u64 = conn.query_row(
            "SELECT COUNT(*) FROM files WHERE file_type = 1 AND id != 1",
            [],
            |row| row.get(0),
        )?;

        // Count total versions
        let total_versions: u64 =
            conn.query_row("SELECT COUNT(*) FROM file_versions", [], |row| row.get(0))?;

        // Count content blobs and total size
        let (content_blobs, total_size_bytes): (u64, u64) = conn.query_row(
            "SELECT COUNT(*), COALESCE(SUM(size), 0) FROM contents",
            [],
            |row| Ok((row.get(0)?, row.get(1)?)),
        )?;

        // Find orphaned blobs (content with ref_count = 0)
        let (orphaned_blobs, orphaned_bytes): (u64, u64) = conn.query_row(
            "SELECT COUNT(*), COALESCE(SUM(size), 0) FROM contents WHERE ref_count = 0",
            [],
            |row| Ok((row.get(0)?, row.get(1)?)),
        )?;

        Ok(VaultStats {
            files,
            directories,
            total_versions,
            content_blobs,
            total_size_bytes,
            orphaned_blobs,
            orphaned_bytes,
        })
    }

    // ==================== Prune Operations ====================

    /// Delete old versions, keeping N most recent.
    pub fn prune_versions_keep(&self, file_id: i64, keep: u64) -> Result<u64> {
        let conn = self.conn.lock().unwrap();

        // First get the version numbers to keep
        let mut stmt = conn.prepare(
            "SELECT version_number FROM file_versions
             WHERE file_id = ?
             ORDER BY version_number DESC
             LIMIT ?",
        )?;

        let versions_to_keep: Vec<i64> = stmt
            .query_map(params![file_id, keep as i64], |row| row.get(0))?
            .collect::<std::result::Result<Vec<_>, _>>()?;

        if versions_to_keep.is_empty() {
            return Ok(0);
        }

        // Delete versions not in the keep list
        let placeholders = versions_to_keep
            .iter()
            .map(|_| "?")
            .collect::<Vec<_>>()
            .join(",");
        let sql = format!(
            "DELETE FROM file_versions WHERE file_id = ? AND version_number NOT IN ({})",
            placeholders
        );

        let mut stmt = conn.prepare(&sql)?;

        // Build params: file_id followed by version numbers
        let mut params_vec: Vec<Box<dyn rusqlite::ToSql>> = vec![Box::new(file_id)];
        for v in &versions_to_keep {
            params_vec.push(Box::new(*v));
        }

        let refs: Vec<&dyn rusqlite::ToSql> = params_vec.iter().map(|b| b.as_ref()).collect();
        let deleted = stmt.execute(refs.as_slice())?;

        Ok(deleted as u64)
    }

    /// Delete versions older than a timestamp.
    pub fn prune_versions_older_than(&self, file_id: i64, timestamp: i64) -> Result<u64> {
        let conn = self.conn.lock().unwrap();

        let deleted = conn.execute(
            "DELETE FROM file_versions WHERE file_id = ? AND created_at < ?",
            params![file_id, timestamp],
        )?;

        Ok(deleted as u64)
    }

    /// Prune all files in vault.
    pub fn prune_all_versions(
        &self,
        keep: Option<u64>,
        older_than: Option<i64>,
    ) -> Result<PruneStats> {
        let conn = self.conn.lock().unwrap();

        // Get all file IDs with versions
        let mut stmt = conn.prepare("SELECT DISTINCT file_id FROM file_versions")?;

        let file_ids: Vec<i64> = stmt
            .query_map([], |row| row.get(0))?
            .collect::<std::result::Result<Vec<_>, _>>()?;

        drop(stmt);
        drop(conn);

        let mut total_deleted = 0u64;
        let mut files_processed = 0u64;

        for file_id in file_ids {
            let deleted = if let Some(k) = keep {
                self.prune_versions_keep(file_id, k)?
            } else if let Some(ts) = older_than {
                self.prune_versions_older_than(file_id, ts)?
            } else {
                0
            };

            if deleted > 0 {
                files_processed += 1;
                total_deleted += deleted;
            }
        }

        Ok(PruneStats {
            files_processed,
            versions_deleted: total_deleted,
        })
    }

    /// Count versions that would be pruned with --keep N.
    pub fn count_versions_to_prune_keep(&self, file_id: i64, keep: u64) -> Result<u64> {
        let conn = self.conn.lock().unwrap();

        let total: u64 = conn.query_row(
            "SELECT COUNT(*) FROM file_versions WHERE file_id = ?",
            [file_id],
            |row| row.get(0),
        )?;

        Ok(total.saturating_sub(keep))
    }

    /// Count versions that would be pruned with --older-than.
    pub fn count_versions_to_prune_older(&self, file_id: i64, timestamp: i64) -> Result<u64> {
        let conn = self.conn.lock().unwrap();

        let count: u64 = conn.query_row(
            "SELECT COUNT(*) FROM file_versions WHERE file_id = ? AND created_at < ?",
            params![file_id, timestamp],
            |row| row.get(0),
        )?;

        Ok(count)
    }

    // ==================== Garbage Collection Operations ====================

    /// Recalculate all content reference counts.
    pub fn recalculate_ref_counts(&self) -> Result<u64> {
        let conn = self.conn.lock().unwrap();

        // Update ref_count based on actual references from files and file_versions
        conn.execute(
            "UPDATE contents SET ref_count = (
                SELECT COUNT(*) FROM files WHERE files.content_hash = contents.hash
            ) + (
                SELECT COUNT(*) FROM file_versions WHERE file_versions.content_hash = contents.hash
            ) + (
                SELECT COUNT(*) FROM snapshot_files WHERE snapshot_files.content_hash = contents.hash
            ) + (
                SELECT COUNT(*) FROM snapshot_versions WHERE snapshot_versions.content_hash = contents.hash
            )",
            [],
        )?;

        // Return count of blobs with ref_count = 0
        let orphans: u64 = conn.query_row(
            "SELECT COUNT(*) FROM contents WHERE ref_count = 0",
            [],
            |row| row.get(0),
        )?;

        Ok(orphans)
    }

    /// Find orphaned content blobs (ref_count = 0).
    pub fn find_orphaned_blobs(&self) -> Result<Vec<OrphanedBlob>> {
        let conn = self.conn.lock().unwrap();

        let mut stmt = conn.prepare("SELECT hash, size FROM contents WHERE ref_count = 0")?;

        let orphans = stmt
            .query_map([], |row| {
                let hash: Vec<u8> = row.get(0)?;
                Ok(OrphanedBlob {
                    hash: hash.try_into().unwrap_or([0u8; 32]),
                    size: row.get(1)?,
                })
            })?
            .collect::<std::result::Result<Vec<_>, _>>()?;

        Ok(orphans)
    }

    /// Delete orphaned content blobs.
    pub fn delete_orphaned_blobs(&self) -> Result<GcStats> {
        // First find what we're deleting for stats
        let orphans = self.find_orphaned_blobs()?;
        let orphans_found = orphans.len() as u64;
        let bytes_freed: u64 = orphans.iter().map(|o| o.size).sum();

        let conn = self.conn.lock().unwrap();

        let deleted = conn.execute("DELETE FROM contents WHERE ref_count = 0", [])?;

        Ok(GcStats {
            orphans_found,
            orphans_deleted: deleted as u64,
            bytes_freed,
        })
    }

    // ==================== Compaction Operations ====================

    /// Run VACUUM to reclaim space.
    pub fn vacuum(&self) -> Result<()> {
        let conn = self.conn.lock().unwrap();

        // Checkpoint WAL first
        conn.execute_batch("PRAGMA wal_checkpoint(TRUNCATE)")?;

        // Run VACUUM
        conn.execute_batch("VACUUM")?;

        // Optimize
        conn.execute_batch("PRAGMA optimize")?;

        Ok(())
    }

    /// Get database file size.
    pub fn get_db_size(&self) -> Result<u64> {
        let metadata = std::fs::metadata(&self.path)?;
        let mut size = metadata.len();

        // Also count WAL and SHM files
        let wal_path = self.path.with_extension("db-wal");
        if let Ok(m) = std::fs::metadata(&wal_path) {
            size += m.len();
        }

        let shm_path = self.path.with_extension("db-shm");
        if let Ok(m) = std::fs::metadata(&shm_path) {
            size += m.len();
        }

        Ok(size)
    }

    /// Get all file IDs (files only, not directories).
    pub fn get_all_file_ids(&self) -> Result<Vec<i64>> {
        let conn = self.conn.lock().unwrap();

        let mut stmt = conn.prepare("SELECT id FROM files WHERE file_type = 0")?;

        let ids = stmt
            .query_map([], |row| row.get(0))?
            .collect::<std::result::Result<Vec<_>, _>>()?;

        Ok(ids)
    }

    // ==================== Quota Operations ====================

    /// Get a quota setting value.
    pub fn get_quota(&self, key: &str) -> Result<Option<u64>> {
        let setting_key = format!("quota_{}", key);
        match self.get_setting(&setting_key)? {
            Some(val) => Ok(val.parse::<u64>().ok()),
            None => Ok(None),
        }
    }

    /// Set a quota setting value.
    pub fn set_quota(&self, key: &str, value: u64) -> Result<()> {
        let conn = self.conn.lock().unwrap();
        let setting_key = format!("quota_{}", key);

        conn.execute(
            "INSERT OR REPLACE INTO settings (key, value) VALUES (?, ?)",
            params![setting_key, value.to_string()],
        )?;

        Ok(())
    }

    /// Clear a quota setting.
    pub fn clear_quota(&self, key: &str) -> Result<()> {
        let conn = self.conn.lock().unwrap();
        let setting_key = format!("quota_{}", key);

        conn.execute("DELETE FROM settings WHERE key = ?", [setting_key])?;

        Ok(())
    }

    /// Check if a write operation is allowed under quota limits.
    pub fn check_quota(&self, new_size: u64, new_file_count: u64) -> Result<QuotaCheck> {
        let stats = self.get_vault_stats()?;

        let max_size_mb = self.get_quota("max_size_mb")?;
        let max_files = self.get_quota("max_files")?;
        let max_file_size_mb = self.get_quota("max_file_size_mb")?;

        let mut check = QuotaCheck {
            allowed: true,
            reason: None,
            current_size: stats.total_size_bytes,
            current_files: stats.files,
            max_size_mb,
            max_files,
            max_file_size_mb,
        };

        // Check max file size (only for single file operations)
        if new_file_count == 1 {
            if let Some(max_mb) = max_file_size_mb {
                let max_bytes = max_mb * 1024 * 1024;
                if new_size > max_bytes {
                    check.allowed = false;
                    check.reason = Some(format!(
                        "file size {} bytes exceeds limit of {} MB",
                        new_size, max_mb
                    ));
                    return Ok(check);
                }
            }
        }

        // Check max files
        if new_file_count > 0 {
            if let Some(max) = max_files {
                let new_total_files = stats.files + new_file_count;
                if new_total_files > max {
                    check.allowed = false;
                    check.reason = Some(format!(
                        "file count {} would exceed limit of {}",
                        new_total_files, max
                    ));
                    return Ok(check);
                }
            }
        }

        // Check max total size
        if let Some(max_mb) = max_size_mb {
            let max_bytes = max_mb * 1024 * 1024;
            let new_total = stats.total_size_bytes + new_size;
            if new_total > max_bytes {
                check.allowed = false;
                check.reason = Some(format!(
                    "total size {} bytes would exceed limit of {} MB",
                    new_total, max_mb
                ));
                return Ok(check);
            }
        }

        Ok(check)
    }

    /// Get all quota settings.
    pub fn get_all_quotas(&self) -> Result<QuotaSettings> {
        Ok(QuotaSettings {
            max_size_mb: self.get_quota("max_size_mb")?,
            max_files: self.get_quota("max_files")?,
            max_file_size_mb: self.get_quota("max_file_size_mb")?,
        })
    }

    // ==================== Audit Log Operations ====================

    /// Log an operation to the audit log.
    pub fn log_operation(&self, op: &str, path: Option<&str>, details: Option<&str>) -> Result<()> {
        let conn = self.conn.lock().unwrap();
        let now = Utc::now().timestamp();

        conn.execute(
            "INSERT INTO audit_log (timestamp, operation, path, details) VALUES (?, ?, ?, ?)",
            params![now, op, path, details],
        )?;

        // Check for auto-rotation
        let max_entries = self.get_audit_max_entries_locked(&conn)?;
        let count: u64 = conn.query_row("SELECT COUNT(*) FROM audit_log", [], |row| row.get(0))?;

        if count > max_entries {
            // Delete oldest 10%
            let to_delete = (max_entries / 10).max(1);
            conn.execute(
                "DELETE FROM audit_log WHERE id IN (
                    SELECT id FROM audit_log ORDER BY timestamp ASC LIMIT ?
                )",
                [to_delete as i64],
            )?;
        }

        Ok(())
    }

    fn get_audit_max_entries_locked(&self, conn: &Connection) -> Result<u64> {
        let result: std::result::Result<String, _> = conn.query_row(
            "SELECT value FROM settings WHERE key = 'audit_max_entries'",
            [],
            |row| row.get(0),
        );

        match result {
            Ok(val) => Ok(val.parse::<u64>().unwrap_or(10000)),
            Err(_) => Ok(10000),
        }
    }

    /// Get audit log entries.
    pub fn get_audit_log(&self, limit: usize, since: Option<i64>) -> Result<Vec<AuditEntry>> {
        let conn = self.conn.lock().unwrap();

        if let Some(ts) = since {
            let mut stmt = conn.prepare(
                "SELECT id, timestamp, operation, path, details
                 FROM audit_log
                 WHERE timestamp >= ?
                 ORDER BY timestamp DESC
                 LIMIT ?",
            )?;

            let entries = stmt
                .query_map(params![ts, limit as i64], |row| {
                    Ok(AuditEntry {
                        id: row.get(0)?,
                        timestamp: row.get(1)?,
                        operation: row.get(2)?,
                        path: row.get(3)?,
                        details: row.get(4)?,
                    })
                })?
                .collect::<std::result::Result<Vec<_>, _>>()?;

            Ok(entries)
        } else {
            let mut stmt = conn.prepare(
                "SELECT id, timestamp, operation, path, details
                 FROM audit_log
                 ORDER BY timestamp DESC
                 LIMIT ?",
            )?;

            let entries = stmt
                .query_map([limit as i64], |row| {
                    Ok(AuditEntry {
                        id: row.get(0)?,
                        timestamp: row.get(1)?,
                        operation: row.get(2)?,
                        path: row.get(3)?,
                        details: row.get(4)?,
                    })
                })?
                .collect::<std::result::Result<Vec<_>, _>>()?;

            Ok(entries)
        }
    }

    /// Clear audit log entries.
    pub fn clear_audit_log(&self, before: Option<i64>) -> Result<u64> {
        let conn = self.conn.lock().unwrap();

        let deleted = if let Some(ts) = before {
            conn.execute("DELETE FROM audit_log WHERE timestamp < ?", [ts])?
        } else {
            conn.execute("DELETE FROM audit_log", [])?
        };

        Ok(deleted as u64)
    }

    /// Get audit log entry count.
    pub fn get_audit_count(&self) -> Result<u64> {
        let conn = self.conn.lock().unwrap();

        let count: u64 = conn.query_row("SELECT COUNT(*) FROM audit_log", [], |row| row.get(0))?;

        Ok(count)
    }

    // ==================== Snapshot Operations ====================

    /// Save a snapshot of the current vault state.
    pub fn save_snapshot(&self, name: &str, description: Option<&str>) -> Result<SnapshotInfo> {
        let conn = self.conn.lock().unwrap();
        let now = Utc::now().timestamp();

        // Get current file stats
        let (file_count, total_size): (u64, u64) = conn.query_row(
            "SELECT COUNT(*), COALESCE(SUM(size), 0) FROM files WHERE file_type = 0",
            [],
            |row| Ok((row.get(0)?, row.get(1)?)),
        )?;

        // Create snapshot record
        conn.execute(
            "INSERT INTO snapshots (name, created_at, file_count, total_size, description)
             VALUES (?, ?, ?, ?, ?)",
            params![name, now, file_count as i64, total_size as i64, description],
        )?;

        let snapshot_id = conn.last_insert_rowid();

        // Copy all files and directories (except root)
        conn.execute(
            "INSERT INTO snapshot_files (snapshot_id, path, file_type, content_hash, size, created_at, modified_at)
             SELECT ?, p.path, f.file_type, f.content_hash, f.size, f.created_at, f.modified_at
             FROM files f
             JOIN paths p ON p.file_id = f.id
             WHERE f.id != 1",
            [snapshot_id],
        )?;

        conn.execute(
            "INSERT INTO snapshot_versions (snapshot_id, path, version_number, content_hash, size, created_at)
             SELECT ?, p.path, fv.version_number, fv.content_hash, fv.size, fv.created_at
             FROM file_versions fv
             JOIN files f ON f.id = fv.file_id
             JOIN paths p ON p.file_id = f.id",
            [snapshot_id],
        )?;

        conn.execute(
            "INSERT INTO snapshot_tags (snapshot_id, name, created_at)
             SELECT ?, name, created_at
             FROM tags",
            [snapshot_id],
        )?;

        conn.execute(
            "INSERT INTO snapshot_file_tags (snapshot_id, path, tag_name, created_at)
             SELECT ?, p.path, t.name, ft.created_at
             FROM file_tags ft
             JOIN files f ON f.id = ft.file_id
             JOIN paths p ON p.file_id = f.id
             JOIN tags t ON t.id = ft.tag_id",
            [snapshot_id],
        )?;

        conn.execute(
            "INSERT INTO snapshot_metadata (snapshot_id, path, key, value, modified_at)
             SELECT ?, p.path, fm.key, fm.value, fm.modified_at
             FROM file_metadata fm
             JOIN files f ON f.id = fm.file_id
             JOIN paths p ON p.file_id = f.id",
            [snapshot_id],
        )?;

        Ok(SnapshotInfo {
            id: snapshot_id,
            name: name.to_string(),
            created_at: now,
            file_count,
            total_size,
            description: description.map(|s| s.to_string()),
        })
    }

    /// List all snapshots.
    pub fn list_snapshots(&self) -> Result<Vec<SnapshotInfo>> {
        let conn = self.conn.lock().unwrap();

        let mut stmt = conn.prepare(
            "SELECT id, name, created_at, file_count, total_size, description
             FROM snapshots
             ORDER BY created_at DESC",
        )?;

        let snapshots = stmt
            .query_map([], |row| {
                Ok(SnapshotInfo {
                    id: row.get(0)?,
                    name: row.get(1)?,
                    created_at: row.get(2)?,
                    file_count: row.get::<_, i64>(3)? as u64,
                    total_size: row.get::<_, i64>(4)? as u64,
                    description: row.get(5)?,
                })
            })?
            .collect::<std::result::Result<Vec<_>, _>>()?;

        Ok(snapshots)
    }

    /// Get a snapshot by name.
    pub fn get_snapshot(&self, name: &str) -> Result<SnapshotInfo> {
        let conn = self.conn.lock().unwrap();

        conn.query_row(
            "SELECT id, name, created_at, file_count, total_size, description
             FROM snapshots WHERE name = ?",
            [name],
            |row| {
                Ok(SnapshotInfo {
                    id: row.get(0)?,
                    name: row.get(1)?,
                    created_at: row.get(2)?,
                    file_count: row.get::<_, i64>(3)? as u64,
                    total_size: row.get::<_, i64>(4)? as u64,
                    description: row.get(5)?,
                })
            },
        )
        .map_err(|e| match e {
            rusqlite::Error::QueryReturnedNoRows => {
                VfsError::NotFound(PathBuf::from(format!("snapshot: {}", name)))
            }
            e => e.into(),
        })
    }

    /// Restore vault to a snapshot state.
    pub fn restore_snapshot(&self, name: &str) -> Result<RestoreStats> {
        // Get snapshot info first
        let snapshot = self.get_snapshot(name)?;

        let conn = self.conn.lock().unwrap();

        // Delete all existing files and paths (except root)
        conn.execute("DELETE FROM paths WHERE path != '/'", [])?;
        conn.execute("DELETE FROM files WHERE id != 1", [])?;
        conn.execute("DELETE FROM tags", [])?;

        // Also clear FTS index
        conn.execute("DELETE FROM fts_content", [])?;

        // Get snapshot files
        let mut stmt = conn.prepare(
            "SELECT path, file_type, content_hash, size, created_at, modified_at
             FROM snapshot_files WHERE snapshot_id = ?",
        )?;

        let files: Vec<(String, i64, Option<Vec<u8>>, i64, i64, i64)> = stmt
            .query_map([snapshot.id], |row| {
                Ok((
                    row.get(0)?,
                    row.get(1)?,
                    row.get(2)?,
                    row.get(3)?,
                    row.get(4)?,
                    row.get(5)?,
                ))
            })?
            .collect::<std::result::Result<Vec<_>, _>>()?;

        drop(stmt);

        let mut files_restored = 0u64;
        let mut dirs_restored = 0u64;
        let mut files_to_index = Vec::new();

        // Sort by path depth (directories first, then files)
        let mut sorted_files = files.clone();
        sorted_files.sort_by(|a, b| {
            let depth_a = a.0.matches('/').count();
            let depth_b = b.0.matches('/').count();
            depth_a.cmp(&depth_b)
        });

        for (path, file_type, content_hash, size, created_at, modified_at) in sorted_files {
            // Parse path to get parent and name
            let path_parts: Vec<&str> = path.trim_matches('/').split('/').collect();
            let name = path_parts.last().unwrap_or(&"").to_string();

            // Get parent path
            let parent_path = if path_parts.len() <= 1 {
                "/".to_string()
            } else {
                format!("/{}", path_parts[..path_parts.len() - 1].join("/"))
            };

            // Get parent ID
            let parent_id: i64 = conn.query_row(
                "SELECT file_id FROM paths WHERE path = ?",
                [&parent_path],
                |row| row.get(0),
            )?;

            // Insert file entry
            conn.execute(
                "INSERT INTO files (parent_id, name, file_type, content_hash, size, created_at, modified_at)
                 VALUES (?, ?, ?, ?, ?, ?, ?)",
                params![parent_id, name, file_type, content_hash, size, created_at, modified_at],
            )?;

            let file_id = conn.last_insert_rowid();

            // Insert path entry
            conn.execute(
                "INSERT INTO paths (path, file_id) VALUES (?, ?)",
                params![path, file_id],
            )?;

            if file_type == 0 {
                files_restored += 1;
                files_to_index.push((file_id, path));
            } else {
                dirs_restored += 1;
            }
        }

        let mut tag_stmt = conn.prepare(
            "SELECT name, created_at
             FROM snapshot_tags
             WHERE snapshot_id = ?
             ORDER BY name",
        )?;

        let tags: Vec<(String, i64)> = tag_stmt
            .query_map([snapshot.id], |row| Ok((row.get(0)?, row.get(1)?)))?
            .collect::<std::result::Result<Vec<_>, _>>()?;
        drop(tag_stmt);

        for (name, created_at) in tags {
            conn.execute(
                "INSERT INTO tags (name, created_at) VALUES (?, ?)",
                params![name, created_at],
            )?;
        }

        let mut version_stmt = conn.prepare(
            "SELECT path, version_number, content_hash, size, created_at
             FROM snapshot_versions
             WHERE snapshot_id = ?
             ORDER BY path, version_number",
        )?;

        let versions: Vec<(String, i64, Vec<u8>, i64, i64)> = version_stmt
            .query_map([snapshot.id], |row| {
                Ok((
                    row.get(0)?,
                    row.get(1)?,
                    row.get(2)?,
                    row.get(3)?,
                    row.get(4)?,
                ))
            })?
            .collect::<std::result::Result<Vec<_>, _>>()?;
        drop(version_stmt);

        for (path, version_number, content_hash, size, created_at) in versions {
            let file_id: i64 =
                conn.query_row("SELECT file_id FROM paths WHERE path = ?", [&path], |row| {
                    row.get(0)
                })?;
            conn.execute(
                "INSERT INTO file_versions (file_id, version_number, content_hash, size, created_at)
                 VALUES (?, ?, ?, ?, ?)",
                params![file_id, version_number, content_hash, size, created_at],
            )?;
        }

        let mut metadata_stmt = conn.prepare(
            "SELECT path, key, value, modified_at
             FROM snapshot_metadata
             WHERE snapshot_id = ?
             ORDER BY path, key",
        )?;

        let metadata_rows: Vec<(String, String, String, i64)> = metadata_stmt
            .query_map([snapshot.id], |row| {
                Ok((row.get(0)?, row.get(1)?, row.get(2)?, row.get(3)?))
            })?
            .collect::<std::result::Result<Vec<_>, _>>()?;
        drop(metadata_stmt);

        for (path, key, value, modified_at) in metadata_rows {
            let file_id: i64 =
                conn.query_row("SELECT file_id FROM paths WHERE path = ?", [&path], |row| {
                    row.get(0)
                })?;
            conn.execute(
                "INSERT INTO file_metadata (file_id, key, value, created_at, modified_at)
                 VALUES (?, ?, ?, ?, ?)",
                params![file_id, key, value, modified_at, modified_at],
            )?;
        }

        let mut file_tag_stmt = conn.prepare(
            "SELECT path, tag_name, created_at
             FROM snapshot_file_tags
             WHERE snapshot_id = ?
             ORDER BY path, tag_name",
        )?;

        let file_tag_rows: Vec<(String, String, i64)> = file_tag_stmt
            .query_map([snapshot.id], |row| {
                Ok((row.get(0)?, row.get(1)?, row.get(2)?))
            })?
            .collect::<std::result::Result<Vec<_>, _>>()?;
        drop(file_tag_stmt);

        for (path, tag_name, created_at) in file_tag_rows {
            let file_id: i64 =
                conn.query_row("SELECT file_id FROM paths WHERE path = ?", [&path], |row| {
                    row.get(0)
                })?;
            let tag_id: i64 =
                conn.query_row("SELECT id FROM tags WHERE name = ?", [&tag_name], |row| {
                    row.get(0)
                })?;
            conn.execute(
                "INSERT INTO file_tags (file_id, tag_id, created_at) VALUES (?, ?, ?)",
                params![file_id, tag_id, created_at],
            )?;
        }

        drop(conn);

        for (file_id, path) in files_to_index {
            self.sync_file_index(file_id, &path)?;
        }

        Ok(RestoreStats {
            files_restored,
            dirs_restored,
        })
    }

    /// Delete a snapshot.
    pub fn delete_snapshot(&self, name: &str) -> Result<()> {
        let conn = self.conn.lock().unwrap();

        let deleted = conn.execute("DELETE FROM snapshots WHERE name = ?", [name])?;

        if deleted == 0 {
            return Err(VfsError::NotFound(PathBuf::from(format!(
                "snapshot: {}",
                name
            ))));
        }

        Ok(())
    }

    /// Set a setting value.
    pub fn set_setting(&self, key: &str, value: &str) -> Result<()> {
        let conn = self.conn.lock().unwrap();

        conn.execute(
            "INSERT OR REPLACE INTO settings (key, value) VALUES (?, ?)",
            params![key, value],
        )?;

        Ok(())
    }
}

/// Vault storage statistics.
#[derive(Debug, Clone, serde::Serialize)]
pub struct VaultStats {
    pub files: u64,
    pub directories: u64,
    pub total_versions: u64,
    pub content_blobs: u64,
    pub total_size_bytes: u64,
    pub orphaned_blobs: u64,
    pub orphaned_bytes: u64,
}

/// Prune operation statistics.
#[derive(Debug, Clone, serde::Serialize)]
pub struct PruneStats {
    pub files_processed: u64,
    pub versions_deleted: u64,
}

/// Information about an orphaned blob.
#[derive(Debug, Clone)]
pub struct OrphanedBlob {
    pub hash: [u8; 32],
    pub size: u64,
}

/// Garbage collection statistics.
#[derive(Debug, Clone, serde::Serialize)]
pub struct GcStats {
    pub orphans_found: u64,
    pub orphans_deleted: u64,
    pub bytes_freed: u64,
}

/// Quota check result.
#[derive(Debug, Clone, serde::Serialize)]
pub struct QuotaCheck {
    pub allowed: bool,
    pub reason: Option<String>,
    pub current_size: u64,
    pub current_files: u64,
    pub max_size_mb: Option<u64>,
    pub max_files: Option<u64>,
    pub max_file_size_mb: Option<u64>,
}

/// Quota settings.
#[derive(Debug, Clone, serde::Serialize)]
pub struct QuotaSettings {
    pub max_size_mb: Option<u64>,
    pub max_files: Option<u64>,
    pub max_file_size_mb: Option<u64>,
}

/// Audit log entry.
#[derive(Debug, Clone, serde::Serialize)]
pub struct AuditEntry {
    pub id: i64,
    pub timestamp: i64,
    pub operation: String,
    pub path: Option<String>,
    pub details: Option<String>,
}

/// Snapshot information.
#[derive(Debug, Clone, serde::Serialize)]
pub struct SnapshotInfo {
    pub id: i64,
    pub name: String,
    pub created_at: i64,
    pub file_count: u64,
    pub total_size: u64,
    pub description: Option<String>,
}

/// Restore operation statistics.
#[derive(Debug, Clone, serde::Serialize)]
pub struct RestoreStats {
    pub files_restored: u64,
    pub dirs_restored: u64,
}

impl StorageBackend for SqliteBackend {
    fn get(&self, collection: &str, key: &[u8]) -> Result<Option<Vec<u8>>> {
        let conn = self.conn.lock().unwrap();

        match collection {
            "paths" => {
                let key_str = String::from_utf8_lossy(key);
                conn.query_row(
                    "SELECT file_id FROM paths WHERE path = ?",
                    [key_str.as_ref()],
                    |row| {
                        let id: i64 = row.get(0)?;
                        Ok(id.to_be_bytes().to_vec())
                    },
                )
                .optional()
                .map_err(|e| e.into())
            }
            "contents" => conn
                .query_row("SELECT data FROM contents WHERE hash = ?", [key], |row| {
                    row.get(0)
                })
                .optional()
                .map_err(|e| e.into()),
            "settings" => {
                let key_str = String::from_utf8_lossy(key);
                conn.query_row(
                    "SELECT value FROM settings WHERE key = ?",
                    [key_str.as_ref()],
                    |row| {
                        let val: String = row.get(0)?;
                        Ok(val.into_bytes())
                    },
                )
                .optional()
                .map_err(|e| e.into())
            }
            _ => Err(VfsError::Internal(format!(
                "unknown collection: {}",
                collection
            ))),
        }
    }

    fn put(&self, collection: &str, key: &[u8], value: &[u8]) -> Result<()> {
        let conn = self.conn.lock().unwrap();

        match collection {
            "paths" => {
                let key_str = String::from_utf8_lossy(key);
                let file_id = i64::from_be_bytes(
                    value
                        .try_into()
                        .map_err(|_| VfsError::Internal("invalid value format".to_string()))?,
                );
                conn.execute(
                    "INSERT OR REPLACE INTO paths (path, file_id) VALUES (?, ?)",
                    params![key_str.as_ref(), file_id],
                )?;
            }
            "settings" => {
                let key_str = String::from_utf8_lossy(key);
                let val_str = String::from_utf8_lossy(value);
                conn.execute(
                    "INSERT OR REPLACE INTO settings (key, value) VALUES (?, ?)",
                    params![key_str.as_ref(), val_str.as_ref()],
                )?;
            }
            "contents" => {
                let size = value.len() as i64;
                conn.execute(
                    "INSERT OR IGNORE INTO contents (hash, data, size, ref_count) VALUES (?, ?, ?, 1)",
                    params![key, value, size],
                )?;
            }
            _ => {
                return Err(VfsError::Internal(format!(
                    "put not supported for collection: {}",
                    collection
                )))
            }
        }

        Ok(())
    }

    fn delete(&self, collection: &str, key: &[u8]) -> Result<()> {
        let conn = self.conn.lock().unwrap();

        match collection {
            "paths" => {
                let key_str = String::from_utf8_lossy(key);
                conn.execute("DELETE FROM paths WHERE path = ?", [key_str.as_ref()])?;
            }
            "settings" => {
                let key_str = String::from_utf8_lossy(key);
                conn.execute("DELETE FROM settings WHERE key = ?", [key_str.as_ref()])?;
            }
            "contents" => {
                conn.execute("DELETE FROM contents WHERE hash = ?", [key])?;
            }
            "files" => {
                let id = i64::from_be_bytes(
                    key.try_into()
                        .map_err(|_| VfsError::Internal("invalid key format".to_string()))?,
                );
                conn.execute("DELETE FROM files WHERE id = ?", [id])?;
            }
            _ => {
                return Err(VfsError::Internal(format!(
                    "unknown collection: {}",
                    collection
                )))
            }
        }

        Ok(())
    }

    fn exists(&self, collection: &str, key: &[u8]) -> Result<bool> {
        let conn = self.conn.lock().unwrap();

        match collection {
            "paths" => {
                let key_str = String::from_utf8_lossy(key);
                let exists = conn
                    .query_row(
                        "SELECT 1 FROM paths WHERE path = ?",
                        [key_str.as_ref()],
                        |_| Ok(true),
                    )
                    .optional()?
                    .unwrap_or(false);
                Ok(exists)
            }
            "contents" => {
                let exists = conn
                    .query_row("SELECT 1 FROM contents WHERE hash = ?", [key], |_| Ok(true))
                    .optional()?
                    .unwrap_or(false);
                Ok(exists)
            }
            _ => Err(VfsError::Internal(format!(
                "exists not supported for: {}",
                collection
            ))),
        }
    }

    fn scan_all(&self, collection: &str) -> Result<Vec<(Vec<u8>, Vec<u8>)>> {
        let conn = self.conn.lock().unwrap();
        let mut results = Vec::new();

        match collection {
            "paths" => {
                let mut stmt = conn.prepare("SELECT path, file_id FROM paths")?;
                let rows = stmt.query_map([], |row| {
                    let path: String = row.get(0)?;
                    let file_id: i64 = row.get(1)?;
                    Ok((path.into_bytes(), file_id.to_be_bytes().to_vec()))
                })?;
                for row in rows {
                    results.push(row?);
                }
            }
            "settings" => {
                let mut stmt = conn.prepare("SELECT key, value FROM settings")?;
                let rows = stmt.query_map([], |row| {
                    let key: String = row.get(0)?;
                    let value: String = row.get(1)?;
                    Ok((key.into_bytes(), value.into_bytes()))
                })?;
                for row in rows {
                    results.push(row?);
                }
            }
            _ => {
                return Err(VfsError::Internal(format!(
                    "scan_all not supported for: {}",
                    collection
                )))
            }
        }

        Ok(results)
    }

    fn scan_prefix(&self, collection: &str, prefix: &[u8]) -> Result<Vec<(Vec<u8>, Vec<u8>)>> {
        let conn = self.conn.lock().unwrap();
        let mut results = Vec::new();

        match collection {
            "paths" => {
                let prefix_str = String::from_utf8_lossy(prefix);
                let pattern = format!("{}%", prefix_str);
                let mut stmt = conn.prepare("SELECT path, file_id FROM paths WHERE path LIKE ?")?;
                let rows = stmt.query_map([&pattern], |row| {
                    let path: String = row.get(0)?;
                    let file_id: i64 = row.get(1)?;
                    Ok((path.into_bytes(), file_id.to_be_bytes().to_vec()))
                })?;
                for row in rows {
                    results.push(row?);
                }
            }
            _ => {
                return Err(VfsError::Internal(format!(
                    "scan_prefix not supported for: {}",
                    collection
                )))
            }
        }

        Ok(results)
    }

    fn sync(&self) -> Result<()> {
        let conn = self.conn.lock().unwrap();
        conn.execute_batch("PRAGMA wal_checkpoint(TRUNCATE)")?;
        Ok(())
    }

    fn path(&self) -> &Path {
        &self.path
    }
}