kimun_core 0.2.19

Core library for the Kimün notes application
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
pub mod filename;
pub mod saved_searches;
use std::{
    fmt::Display,
    hash::Hash,
    path::{Path, PathBuf},
    str::FromStr,
    sync::LazyLock,
    time::UNIX_EPOCH,
};

use ignore::{WalkBuilder, WalkParallel};
use log::warn;
use regex::Regex;
use serde::{de::Visitor, Deserialize, Serialize};
use twox_hash::XxHash64;

use super::{error::FSError, DirectoryDetails, NoteDetails};

use super::utilities::path_to_string;

/// The vault-internal path separator. Always `/`, independent of the host OS:
/// a [`VaultPath`] is logical and portable, and is only translated to native
/// OS separators when resolved to a real on-disk location.
pub const PATH_SEPARATOR: char = '/';
const NOTE_EXTENSION: &str = ".md";

/// Appends the note extension to `name` if it is not already present, without
/// sanitizing the rest of the string. Unlike [`VaultPath::note_path_from`] this
/// leaves wildcards and other non-path characters intact, so search patterns
/// (e.g. `proj*`) keep their meaning. Use it only for building match patterns,
/// never for constructing real vault paths.
pub fn with_note_extension<S: AsRef<str>>(name: S) -> String {
    let name = name.as_ref();
    if name.ends_with(NOTE_EXTENSION) {
        name.to_string()
    } else {
        format!("{name}{NOTE_EXTENSION}")
    }
}

static RX_INCREMENT_SUFFIX: LazyLock<Regex> =
    LazyLock::new(|| Regex::new(r"_(?P<number>[0-9]+)$").unwrap());

#[derive(Debug, Clone, PartialEq, Eq, Hash)]
pub(crate) struct VaultEntry {
    pub path: VaultPath,
    pub path_string: String,
    pub data: EntryData,
}

impl AsRef<str> for VaultEntry {
    fn as_ref(&self) -> &str {
        self.path_string.as_ref()
    }
}

#[derive(Debug, Clone, PartialEq, Eq, Hash)]
pub(crate) enum EntryData {
    Note(NoteEntryData),
    Directory(DirectoryEntryData),
    Attachment,
}

/// Lightweight metadata for an indexed note: enough to detect changes without
/// reading the note's contents. Produced from filesystem metadata as the vault
/// is walked.
#[derive(Debug, Clone, PartialEq, Eq, Hash, serde::Serialize)]
pub struct NoteEntryData {
    /// The note's vault path, stored flattened (no `.`/`..` components).
    pub path: VaultPath,
    /// File size in bytes. Cheap first-pass signal that a note changed.
    pub size: u64,
    /// Last-modified time, in whole seconds since the Unix epoch.
    pub modified_secs: u64,
}

impl NoteEntryData {
    #[cfg(test)]
    pub async fn load_details<P: AsRef<Path>>(
        &self,
        workspace_path: P,
        path: &VaultPath,
    ) -> Result<NoteDetails, FSError> {
        let content = load_note(workspace_path, path).await?;
        Ok(NoteDetails::new(path, content))
    }

    /// Reads the file at `os_path` directly (no case-insensitive resolution).
    /// Use when the real on-disk path is already known (e.g. from the walker).
    pub(crate) fn load_details_from_os_path(&self, os_path: &Path) -> Result<NoteDetails, FSError> {
        let bytes = std::fs::read(os_path)?;
        let text = String::from_utf8(bytes)?;
        Ok(NoteDetails::new(&self.path, text))
    }

    async fn from_os_path(path: &VaultPath, file_path: &Path) -> Result<NoteEntryData, FSError> {
        let metadata = tokio::fs::metadata(file_path).await?;
        Ok(Self::from_metadata(path, &metadata))
    }

    fn from_metadata(path: &VaultPath, metadata: &std::fs::Metadata) -> NoteEntryData {
        let size = metadata.len();
        let modified_secs = metadata
            .modified()
            .map(|t| t.duration_since(UNIX_EPOCH).unwrap().as_secs())
            .unwrap_or(0);
        NoteEntryData {
            path: path.flatten(),
            size,
            modified_secs,
        }
    }
}

/// Metadata for an indexed directory. A directory carries no content of its
/// own, so its vault path is all that needs tracking.
#[derive(Debug, Clone, PartialEq, Eq, Hash)]
pub struct DirectoryEntryData {
    /// The directory's vault path.
    pub path: VaultPath,
}
impl DirectoryEntryData {
    /// Builds the public [`DirectoryDetails`] view of this directory entry.
    pub fn get_details<P: AsRef<Path>>(&self) -> DirectoryDetails {
        DirectoryDetails {
            path: self.path.clone(),
        }
    }
}

#[cfg(test)]
#[derive(Debug, Clone)]
pub(crate) enum VaultEntryDetails {
    Note(NoteDetails),
    #[allow(dead_code)]
    Directory(DirectoryDetails),
    None,
}

#[cfg(test)]
impl VaultEntryDetails {
    pub fn get_title(&mut self) -> String {
        match self {
            VaultEntryDetails::Note(note_details) => note_details.get_title(),
            VaultEntryDetails::Directory(_) => String::new(),
            VaultEntryDetails::None => String::new(),
        }
    }
}

impl VaultEntry {
    #[cfg(test)]
    pub async fn new<P: AsRef<Path>>(workspace_path: P, path: VaultPath) -> Result<Self, FSError> {
        let os_path = resolve_path_on_disk(&workspace_path, &path).await;
        let metadata = tokio::fs::metadata(&os_path)
            .await
            .map_err(|e| Self::map_metadata_err(e, &os_path))?;
        Self::assemble(path, &metadata)
    }

    #[cfg(test)]
    pub async fn from_path<P: AsRef<Path>, F: AsRef<Path>>(
        workspace_path: P,
        full_path: F,
    ) -> Result<Self, FSError> {
        let note_path = VaultPath::from_path(&workspace_path, &full_path)?;
        let os_path = full_path.as_ref();
        let metadata = tokio::fs::metadata(os_path)
            .await
            .map_err(|e| Self::map_metadata_err(e, os_path))?;
        Self::assemble(note_path, &metadata)
    }

    /// Sync sibling of `from_path`. Used by the parallel-walker visitor where
    /// the OS path is already known and the calling thread is synchronous.
    pub(crate) fn from_path_sync<P: AsRef<Path>, F: AsRef<Path>>(
        workspace_path: P,
        full_path: F,
    ) -> Result<Self, FSError> {
        let note_path = VaultPath::from_path(&workspace_path, &full_path)?;
        let os_path = full_path.as_ref();
        let metadata =
            std::fs::metadata(os_path).map_err(|e| Self::map_metadata_err(e, os_path))?;
        Self::assemble(note_path, &metadata)
    }

    fn map_metadata_err(e: std::io::Error, os_path: &Path) -> FSError {
        match e.kind() {
            std::io::ErrorKind::NotFound => FSError::NoFileOrDirectoryFound {
                path: path_to_string(os_path),
            },
            _ => FSError::ReadFileError(e),
        }
    }

    fn assemble(path: VaultPath, metadata: &std::fs::Metadata) -> Result<Self, FSError> {
        let data = if metadata.is_dir() {
            EntryData::Directory(DirectoryEntryData { path: path.clone() })
        } else if path.is_note() {
            EntryData::Note(NoteEntryData::from_metadata(&path, metadata))
        } else {
            EntryData::Attachment
        };
        let path_string = path.to_string();
        Ok(VaultEntry {
            path,
            path_string,
            data,
        })
    }
}

impl Display for VaultEntry {
    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
        match &self.data {
            EntryData::Note(_details) => write!(f, "[NOT] {}", self.path),
            EntryData::Directory(_details) => write!(f, "[DIR] {}", self.path),
            EntryData::Attachment => write!(f, "[ATT]"),
        }
    }
}

pub(crate) fn hash_text<S: AsRef<str>>(text: S) -> u64 {
    XxHash64::oneshot(42, text.as_ref().as_bytes())
}

/// Resolves a VaultPath to the real PathBuf on disk by matching each component
/// case-insensitively. When a component doesn't exist on disk yet, the stored
/// (lowercase) name is used for the remainder of the path.
///
/// Fast path: stored paths are always lowercase, so `vault_path.to_pathbuf` is
/// the canonical form. We try it directly first; only fall back to the
/// per-slice walk when something exists on disk under a different case
/// (legacy mixed-case files imported from outside Kimun).
pub(crate) async fn resolve_path_on_disk<P: AsRef<Path>>(
    workspace_path: P,
    vault_path: &VaultPath,
) -> PathBuf {
    let canonical = vault_path.to_pathbuf(&workspace_path);
    if matches!(tokio::fs::try_exists(&canonical).await, Ok(true)) {
        return canonical;
    }
    let mut current = workspace_path.as_ref().to_path_buf();
    for slice in &vault_path.flatten().slices {
        let name = slice.to_string();
        let real_name = async {
            let mut entries = tokio::fs::read_dir(&current).await.ok()?;
            while let Ok(Some(entry)) = entries.next_entry().await {
                if entry.file_name().to_string_lossy().to_lowercase() == name {
                    return Some(entry.file_name().to_string_lossy().into_owned());
                }
            }
            None
        }
        .await
        .unwrap_or(name);
        current = current.join(real_name);
    }
    current
}

/// Sync variant of `resolve_path_on_disk` for use in non-async contexts.
pub(crate) fn resolve_path_on_disk_sync<P: AsRef<Path>>(
    workspace_path: P,
    vault_path: &VaultPath,
) -> PathBuf {
    let canonical = vault_path.to_pathbuf(&workspace_path);
    if canonical.exists() {
        return canonical;
    }
    let mut current = workspace_path.as_ref().to_path_buf();
    for slice in &vault_path.flatten().slices {
        let name = slice.to_string();
        let real_name = std::fs::read_dir(&current)
            .ok()
            .and_then(|entries| {
                entries
                    .filter_map(|e| e.ok())
                    .find(|e| e.file_name().to_string_lossy().to_lowercase() == name)
                    .map(|e| e.file_name().to_string_lossy().into_owned())
            })
            .unwrap_or(name);
        current = current.join(real_name);
    }
    current
}

/// Walks the vault directory tree and returns a human-readable description of
/// every pair of entries that collide when lowercased (e.g. "note.md" vs "Note.md").
/// Returns an empty Vec if the vault is clean.
pub(crate) fn check_case_conflicts<P: AsRef<Path>>(workspace_path: P) -> Vec<String> {
    let root = workspace_path.as_ref();
    check_conflicts_in_dir(root, root)
}

fn check_conflicts_in_dir(workspace_root: &Path, dir: &Path) -> Vec<String> {
    let mut conflicts = Vec::new();
    let mut seen: std::collections::HashMap<String, std::ffi::OsString> =
        std::collections::HashMap::new();

    let entries = match std::fs::read_dir(dir) {
        Ok(e) => e,
        Err(_) => return conflicts,
    };

    let mut subdirs = Vec::new();
    for entry in entries.flatten() {
        let name = entry.file_name();
        let name_str = name.to_string_lossy().to_string();
        // skip hidden entries, consistent with the vault's filter_files behaviour
        if name_str.starts_with('.') {
            continue;
        }
        let lower = name_str.to_lowercase();
        if let Some(existing) = seen.get(&lower) {
            let rel = dir.strip_prefix(workspace_root).unwrap_or(dir);
            let rel_str = rel.to_string_lossy();
            let location = if rel_str.is_empty() {
                PATH_SEPARATOR.to_string()
            } else {
                format!("{}{}", PATH_SEPARATOR, rel_str)
            };
            conflicts.push(format!(
                "\"{}\" conflicts with \"{}\" in {}",
                name_str,
                existing.to_string_lossy(),
                location
            ));
        } else {
            seen.insert(lower, name);
        }
        // Use file_type() rather than is_dir() to avoid following symlinks,
        // which could cause unbounded recursion on symlink loops.
        if let Ok(ft) = entry.file_type() {
            if ft.is_dir() {
                subdirs.push(entry.path());
            }
        }
    }

    // Recurse into all subdirectories, including both sides of a conflicting pair,
    // so that deeper conflicts inside them are also surfaced.
    for subdir in subdirs {
        conflicts.extend(check_conflicts_in_dir(workspace_root, &subdir));
    }

    conflicts
}

/// Loads a note from disk, if the file doesn't exist, returns a FSError::NotePathNotFound
/// Returns the note's text. If you want the details, use NoteDetails::from_content
pub(crate) async fn load_note<P: AsRef<Path>>(
    workspace_path: P,
    path: &VaultPath,
) -> Result<String, FSError> {
    let os_path = resolve_path_on_disk(&workspace_path, path).await;
    match tokio::fs::read(&os_path).await {
        Ok(file) => {
            let text = String::from_utf8(file)?;
            Ok(text)
        }
        Err(e) => match e.kind() {
            std::io::ErrorKind::NotFound => Err(FSError::VaultPathNotFound {
                path: path.to_owned(),
            }),
            _ => Err(FSError::ReadFileError(e)),
        },
    }
}

/// Creates a new directory at `path`. Returns `FSError::AlreadyExists` if the
/// directory (or any case-insensitive variant) is already present.
pub(crate) async fn create_directory<P: AsRef<Path>>(
    workspace_path: P,
    path: &VaultPath,
) -> Result<DirectoryEntryData, FSError> {
    path.ensure_directory()?;

    let full_path = resolve_path_on_disk(&workspace_path, path).await;
    if let Some(parent) = full_path.parent() {
        tokio::fs::create_dir_all(parent).await?;
    }
    match tokio::fs::create_dir(&full_path).await {
        Ok(()) => Ok(DirectoryEntryData {
            path: path.to_owned(),
        }),
        Err(e) if e.kind() == std::io::ErrorKind::AlreadyExists => Err(FSError::AlreadyExists {
            path: path.to_owned(),
        }),
        Err(e) => Err(FSError::ReadFileError(e)),
    }
}

/// Writes raw bytes (e.g. an image attachment) at `path` under the workspace,
/// creating parent directories as needed. Unlike [`save_note`], does not require
/// the path to be a note file and bypasses the case-insensitive note resolver.
pub(crate) async fn save_attachment<P: AsRef<Path>>(
    workspace_path: P,
    path: &VaultPath,
    bytes: &[u8],
) -> Result<(), FSError> {
    let full_path = path.flatten().to_pathbuf(workspace_path);
    if let Some(parent) = full_path.parent() {
        tokio::fs::create_dir_all(parent).await?;
    }
    tokio::fs::write(&full_path, bytes).await?;
    Ok(())
}

pub(crate) async fn save_note<P: AsRef<Path>, S: AsRef<str>>(
    workspace_path: P,
    path: &VaultPath,
    text: S,
) -> Result<NoteEntryData, FSError> {
    path.ensure_note()?;
    // Resolve the full path case-insensitively so an existing `MyNote.md` is
    // written in place rather than creating a new lowercase `mynote.md` alongside it.
    let full_path = resolve_path_on_disk(&workspace_path, path).await;
    if let Some(base_path) = full_path.parent() {
        tokio::fs::create_dir_all(base_path).await?;
    }
    tokio::fs::write(&full_path, text.as_ref().as_bytes()).await?;

    let entry = NoteEntryData::from_os_path(path, &full_path).await?;
    Ok(entry)
}

/// Creates a new note at `path` exclusively. Returns `FSError::AlreadyExists` if
/// any file (case-insensitive) already occupies the resolved path.
pub(crate) async fn create_note_exclusive<P: AsRef<Path>, S: AsRef<str>>(
    workspace_path: P,
    path: &VaultPath,
    text: S,
) -> Result<NoteEntryData, FSError> {
    path.ensure_note()?;
    let full_path = resolve_path_on_disk(&workspace_path, path).await;
    if let Some(base_path) = full_path.parent() {
        tokio::fs::create_dir_all(base_path).await?;
    }
    let mut file = match tokio::fs::OpenOptions::new()
        .write(true)
        .create_new(true)
        .open(&full_path)
        .await
    {
        Ok(f) => f,
        Err(e) if e.kind() == std::io::ErrorKind::AlreadyExists => {
            return Err(FSError::AlreadyExists {
                path: path.to_owned(),
            });
        }
        Err(e) => return Err(FSError::ReadFileError(e)),
    };
    use tokio::io::AsyncWriteExt;
    file.write_all(text.as_ref().as_bytes()).await?;
    file.flush().await?;
    drop(file);

    NoteEntryData::from_os_path(path, &full_path).await
}

pub(crate) async fn rename_note<P: AsRef<Path>>(
    workspace_path: P,
    from: &VaultPath,
    to: &VaultPath,
) -> Result<(), FSError> {
    from.ensure_note()?;
    to.ensure_note()?;
    rename_path(workspace_path, from, to).await
}

pub(crate) async fn rename_directory<P: AsRef<Path>>(
    workspace_path: P,
    from: &VaultPath,
    to: &VaultPath,
) -> Result<(), FSError> {
    from.ensure_directory()?;
    to.ensure_directory()?;
    rename_path(workspace_path, from, to).await
}

/// Resolves both endpoints, ensures the destination's parent directory exists,
/// and renames atomically. Returns `FSError::AlreadyExists` if the destination
/// is occupied (the OS rename would silently overwrite on Linux otherwise).
async fn rename_path<P: AsRef<Path>>(
    workspace_path: P,
    from: &VaultPath,
    to: &VaultPath,
) -> Result<(), FSError> {
    let full_from_path = resolve_path_on_disk(&workspace_path, from).await;
    let (to_parent, to_name) = to.get_parent_path();
    let to_base = resolve_path_on_disk(&workspace_path, &to_parent).await;
    let full_to_path = to_base.join(&to_name);

    if matches!(tokio::fs::try_exists(&full_to_path).await, Ok(true)) {
        return Err(FSError::AlreadyExists {
            path: to.to_owned(),
        });
    }

    match tokio::fs::metadata(&to_base).await {
        Ok(m) if m.is_dir() => {}
        _ => {
            tokio::fs::create_dir_all(&to_base).await?;
        }
    }
    tokio::fs::rename(full_from_path, full_to_path).await?;
    Ok(())
}
/// How long automated-edit backups are retained before the lazy purge reclaims
/// them. Counted in whole days against the UTC backup date.
const BACKUP_RETENTION_DAYS: i64 = 30;

/// The last `(backups_root, date)` purged in this process. The sweep is
/// de-duplicated against this so it runs at most once per vault per UTC day
/// rather than on every backup write — a single hub-note rename can back up
/// thousands of victims in a row, and each would otherwise re-scan the root.
static LAST_PURGE: std::sync::LazyLock<
    std::sync::Mutex<Option<(std::path::PathBuf, chrono::NaiveDate)>>,
> = std::sync::LazyLock::new(|| std::sync::Mutex::new(None));

/// Best-effort sweep of the backups root: removes every `<YYYY-MM-DD>` directory
/// whose date is older than [`BACKUP_RETENTION_DAYS`]. Runs at most once per
/// backups root per UTC day per process (see [`LAST_PURGE`]). Never fails the
/// caller — backups are housekeeping, and a purge error must not block (and
/// thereby abort) the edit that triggered it.
async fn purge_old_backups(backups_root: &Path) {
    let today = chrono::Utc::now().date_naive();
    // Skip if we already swept this root today (in this process). The marker is
    // only stamped AFTER a successful sweep below, so a transient failure (e.g.
    // the dir not existing yet, or a read error) is retried on the next backup.
    if LAST_PURGE
        .lock()
        .unwrap()
        .as_ref()
        .is_some_and(|(root, day)| root == backups_root && *day == today)
    {
        return;
    }
    let cutoff = today - chrono::Duration::days(BACKUP_RETENTION_DAYS);
    let mut entries = match tokio::fs::read_dir(backups_root).await {
        Ok(e) => e,
        Err(_) => return,
    };
    while let Ok(Some(entry)) = entries.next_entry().await {
        let name = entry.file_name();
        if let Ok(date) = chrono::NaiveDate::parse_from_str(&name.to_string_lossy(), "%Y-%m-%d") {
            if date < cutoff {
                let _ = tokio::fs::remove_dir_all(entry.path()).await;
            }
        }
    }
    *LAST_PURGE.lock().unwrap() = Some((backups_root.to_path_buf(), today));
}

/// Atomically reserves a free backup destination: tries the mirrored name first,
/// then time-and-counter-suffixed variants, each via `create_new` so two writers
/// racing on the same note get distinct files and no pre-image is ever clobbered.
/// Returns the reserved (now-empty) path for the caller to copy into.
async fn reserve_backup_dest(base: &Path) -> Result<std::path::PathBuf, FSError> {
    let mut candidate = base.to_path_buf();
    let mut attempt: u32 = 0;
    loop {
        match tokio::fs::OpenOptions::new()
            .write(true)
            .create_new(true)
            .open(&candidate)
            .await
        {
            Ok(_) => return Ok(candidate),
            Err(e) if e.kind() == std::io::ErrorKind::AlreadyExists => {
                let ts = chrono::Utc::now().format("%H%M%S%6f");
                let mut name = base.file_name().unwrap_or_default().to_os_string();
                name.push(format!(".{ts}.{attempt}"));
                candidate = base.with_file_name(name);
                attempt = attempt.wrapping_add(1);
            }
            Err(e) => return Err(FSError::ReadFileError(e)),
        }
    }
}

/// Copies the current on-disk content of the note at `path` into a hidden, dated
/// backup directory inside the vault, before the note is overwritten or deleted.
/// The backup lives at `<workspace>/.kimun/backups/<YYYY-MM-DD>/<note>` — the
/// note's on-disk path mirrored under the (UTC) date. The destination is claimed
/// atomically (see [`reserve_backup_dest`]); a repeat edit on the same day gets a
/// time-suffixed sibling, and concurrent writers never overwrite each other's
/// pre-image. Returns `Ok(())` without writing when the source note does not
/// exist (nothing to back up). `.kimun` is hidden, so the indexer's walker skips
/// it and backups never appear in search.
pub(crate) async fn backup_note<P: AsRef<Path>>(
    workspace_path: P,
    path: &VaultPath,
) -> Result<(), FSError> {
    let workspace_path = workspace_path.as_ref();
    let src = resolve_path_on_disk(workspace_path, path).await;
    // Fail closed: only skip the backup when the source is genuinely absent.
    // A probe error (FS unhealthy) must abort the edit, not silently proceed
    // without a pre-image.
    match tokio::fs::try_exists(&src).await {
        Ok(true) => {}
        Ok(false) => return Ok(()),
        Err(e) => return Err(FSError::ReadFileError(e)),
    }

    let rel = src
        .strip_prefix(workspace_path)
        .map_err(|_| FSError::InvalidPath {
            path: src.to_string_lossy().into_owned(),
            message: "note path escapes the workspace".to_string(),
        })?;
    let backups_root = workspace_path.join(".kimun").join("backups");
    purge_old_backups(&backups_root).await;
    let date = chrono::Utc::now().format("%Y-%m-%d").to_string();
    let base = backups_root.join(date).join(rel);
    if let Some(parent) = base.parent() {
        tokio::fs::create_dir_all(parent).await?;
    }
    // Reserve a unique name, then stream the source into it — no full read into
    // memory, and the reserved name can't be clobbered by a concurrent backup.
    let dest = reserve_backup_dest(&base).await?;
    tokio::fs::copy(&src, &dest).await?;
    Ok(())
}

pub(crate) async fn delete_note<P: AsRef<Path>>(
    workspace_path: P,
    path: &VaultPath,
) -> Result<(), FSError> {
    let full_path = resolve_path_on_disk(&workspace_path, path).await;
    tokio::fs::remove_file(full_path).await?;
    Ok(())
}

/// Create `dir` and all missing parents. No-op if it already exists.
pub(crate) fn ensure_dir(dir: &Path) -> Result<(), FSError> {
    std::fs::create_dir_all(dir).map_err(FSError::ReadFileError)
}

/// Returns true if anything (file or directory) exists at the resolved
/// disk path for `path`. Cheaper than `load_note` when the contents are
/// not needed.
pub(crate) async fn path_exists<P: AsRef<Path>>(
    workspace_path: P,
    path: &VaultPath,
) -> Result<bool, FSError> {
    let full_path = resolve_path_on_disk(&workspace_path, path).await;
    Ok(tokio::fs::try_exists(&full_path).await?)
}

pub(crate) async fn delete_directory<P: AsRef<Path>>(
    workspace_path: P,
    path: &VaultPath,
) -> Result<(), FSError> {
    let full_path = resolve_path_on_disk(&workspace_path, path).await;
    tokio::fs::remove_dir_all(full_path).await?;
    Ok(())
}

/// A logical, vault-internal path to a note or directory.
///
/// `VaultPath` is the core's single currency for everything inside a vault: it
/// never refers to a location outside the workspace, and it is portable across
/// Windows, macOS, and Linux. Components are sanitized and lowercased on
/// construction (see [`VaultPath::new`]) so that only characters valid on all
/// three filesystems survive and equality is effectively case-insensitive. The
/// separator is always [`PATH_SEPARATOR`] (`/`); translation to native OS paths
/// happens only at the filesystem boundary in `nfs`.
///
/// A path may be absolute (rooted at the vault root, rendered with a leading
/// `/`) or relative, and may contain `.`/`..` components until [`flatten`]ed.
///
/// [`flatten`]: VaultPath::flatten
#[derive(Debug, Clone, PartialEq, Eq, Hash, PartialOrd, Ord)]
pub struct VaultPath {
    absolute: bool,
    slices: Vec<VaultPathSlice>,
}

impl FromStr for VaultPath {
    type Err = FSError;

    fn from_str(s: &str) -> Result<Self, Self::Err> {
        Self::from_string(s)
    }
}

impl TryFrom<String> for VaultPath {
    type Error = FSError;

    fn try_from(value: String) -> Result<Self, Self::Error> {
        Self::from_string(value)
    }
}

impl From<&VaultPath> for VaultPath {
    fn from(value: &VaultPath) -> Self {
        value.to_owned()
    }
}

impl TryFrom<&str> for VaultPath {
    type Error = FSError;
    fn try_from(value: &str) -> Result<Self, Self::Error> {
        VaultPath::from_string(value)
    }
}

impl TryFrom<&String> for VaultPath {
    type Error = FSError;

    fn try_from(value: &String) -> Result<Self, Self::Error> {
        VaultPath::from_string(value)
    }
}

impl Serialize for VaultPath {
    fn serialize<S>(&self, serializer: S) -> Result<S::Ok, S::Error>
    where
        S: serde::Serializer,
    {
        let string = self.to_string();
        serializer.serialize_str(string.as_ref())
    }
}

struct DeserializeVaultPathVisitor;
impl Visitor<'_> for DeserializeVaultPathVisitor {
    type Value = VaultPath;

    fn expecting(&self, formatter: &mut std::fmt::Formatter) -> std::fmt::Result {
        formatter.write_str("A valid path with `/` separators, no need of starting `/`")
    }
    fn visit_str<E>(self, value: &str) -> Result<Self::Value, E> {
        let path = VaultPath::new(value);
        Ok(path)
    }
}

impl<'de> Deserialize<'de> for VaultPath {
    fn deserialize<D>(deserializer: D) -> Result<Self, D::Error>
    where
        D: serde::Deserializer<'de>,
    {
        deserializer.deserialize_str(DeserializeVaultPathVisitor)
    }
}

impl VaultPath {
    /// Creates a new vault path, for every invalid character
    /// it gets replaced to an underscore `_`. If you want to validate
    /// the path first, either use the `VaultPath::From` trait or use
    /// `VaultPath::is_valid()`
    pub fn new<S: AsRef<str>>(path: S) -> Self {
        let mut slices = vec![];
        let absolute = path.as_ref().starts_with(PATH_SEPARATOR);
        path.as_ref()
            .split(PATH_SEPARATOR)
            .filter(|p| !p.is_empty()) // We remove the empty ones,
            // so `//` are treated as `/`
            .for_each(|slice| {
                slices.push(VaultPathSlice::new(slice));
            });
        Self { absolute, slices }
    }

    fn from_string<S: AsRef<str>>(value: S) -> Result<Self, FSError> {
        let path = value.as_ref();
        if Self::is_valid(path) {
            Ok(Self::new(path))
        } else {
            Err(FSError::InvalidPath {
                path: path.to_string(),
                message: "path contains invalid characters".to_string(),
            })
        }
    }

    /// Returns `true` if `path` is already a clean vault path needing no
    /// sanitization: every component is valid on all three target filesystems
    /// and there are no doubled separators. Use this to validate caller-supplied
    /// strings up front; [`VaultPath::new`] will instead silently repair them.
    ///
    /// ```
    /// use kimun_core::nfs::VaultPath;
    /// assert!(VaultPath::is_valid("/projects/notes.md"));
    /// assert!(!VaultPath::is_valid("bad?name"));
    /// ```
    pub fn is_valid<S: AsRef<str>>(path: S) -> bool {
        // path can only start with one slash `/`
        if path
            .as_ref()
            .starts_with(format!("{}{}", PATH_SEPARATOR, PATH_SEPARATOR).as_str())
        {
            return false;
        }
        !path
            .as_ref()
            .split(PATH_SEPARATOR)
            .any(|s| !VaultPathSlice::is_valid(s))
    }

    /// Builds a sanitized note path from `path`, ensuring it ends with the note
    /// extension. A trailing separator is dropped before the extension is added,
    /// so `notes/` becomes `notes.md`. Unlike [`with_note_extension`], the rest
    /// of the string is sanitized through [`VaultPath::new`], so this is the
    /// correct constructor for real note paths (not search patterns).
    ///
    /// ```
    /// use kimun_core::nfs::VaultPath;
    /// assert_eq!(VaultPath::note_path_from("projects/todo").to_string(), "projects/todo.md");
    /// assert_eq!(VaultPath::note_path_from("readme.md").to_string(), "readme.md");
    /// ```
    pub fn note_path_from<S: AsRef<str>>(path: S) -> Self {
        let path = path.as_ref();
        let path_clean = path.strip_suffix(PATH_SEPARATOR).unwrap_or(path);
        let p = if !path_clean.ends_with(NOTE_EXTENSION) {
            [path_clean, NOTE_EXTENSION].concat()
        } else {
            path_clean.to_owned()
        };
        VaultPath::new(p)
    }

    /// The vault root: an absolute path with no components, rendered as `/`.
    ///
    /// ```
    /// use kimun_core::nfs::VaultPath;
    /// assert_eq!(VaultPath::root().to_string(), "/");
    /// ```
    pub fn root() -> Self {
        Self {
            absolute: true,
            slices: vec![],
        }
    }

    /// The empty relative path: no components and not absolute, rendered as the
    /// empty string. Distinct from [`root`](VaultPath::root), which is absolute.
    ///
    /// ```
    /// use kimun_core::nfs::VaultPath;
    /// assert_eq!(VaultPath::empty().to_string(), "");
    /// ```
    pub fn empty() -> Self {
        Self {
            absolute: false,
            slices: vec![],
        }
    }

    /// Returns `true` when the path has no components, i.e. it is either the
    /// vault root or the empty path.
    pub fn is_root_or_empty(&self) -> bool {
        self.slices.is_empty()
    }

    /// Returns a variant of this path with its final component's name
    /// incremented to avoid a collision. A numeric `_N` suffix is added or bumped
    /// (e.g. `note.md` → `note_0.md`, `note_0.md` → `note_1.md`), preserving the
    /// note extension. Used to pick a fresh name when the desired one is taken.
    pub fn get_name_on_conflict(&self) -> VaultPath {
        let mut slices = self.slices.clone();
        match slices.pop() {
            Some(slice) => {
                if let VaultPathSlice::PathSlice(name) = slice {
                    let new_name = if let Some(name) = name.strip_suffix(NOTE_EXTENSION) {
                        format!("{}{}", Self::increment(name), NOTE_EXTENSION)
                    } else {
                        Self::increment(name)
                    };
                    slices.push(VaultPathSlice::new(new_name));
                    VaultPath {
                        absolute: self.absolute,
                        slices,
                    }
                } else {
                    VaultPath::new("0")
                }
            }
            None => VaultPath::new("0"),
        }
    }

    /// Returns the final component's name with the note extension stripped — the
    /// note's display title as derived from its filename. For directories (no
    /// extension) this is just the directory name. Compare [`get_name`], which
    /// keeps the extension.
    ///
    /// [`get_name`]: VaultPath::get_name
    ///
    /// ```
    /// use kimun_core::nfs::VaultPath;
    /// assert_eq!(VaultPath::new("/projects/todo.md").get_clean_name(), "todo");
    /// ```
    pub fn get_clean_name(&self) -> String {
        let name = self.get_name();
        if let Some(name) = name.strip_suffix(NOTE_EXTENSION) {
            name.to_string()
        } else {
            name
        }
    }

    /// Returns the full vault path as a string with the note extension stripped.
    /// E.g. `/projects/rust-notes.md` → `/projects/rust-notes`
    /// If the path does not end with the note extension, returns it unchanged.
    pub fn to_bare_string(&self) -> String {
        let s = self.to_string();
        s.strip_suffix(NOTE_EXTENSION)
            .map(|bare| bare.to_owned())
            .unwrap_or(s)
    }

    /// Returns the full vault path as a string, ensuring it ends with the note extension.
    /// E.g. `/projects/rust-notes` → `/projects/rust-notes.md`
    /// If the path already ends with the extension, returns it unchanged.
    pub fn to_string_with_ext(&self) -> String {
        with_note_extension(self.to_string())
    }

    fn increment<S: AsRef<str>>(name: S) -> String {
        let name = name.as_ref();
        let (n, suffix_num) = if let Some(caps) = RX_INCREMENT_SUFFIX.captures(name) {
            let suffix = &caps["number"];
            let n = name
                .strip_suffix(&format!("_{}", suffix))
                .map_or_else(|| name.to_string(), |s| s.to_string());
            (n, suffix.parse::<u64>().map_or_else(|_e| 0, |n| n + 1))
        } else {
            (name.to_string(), 0)
        };
        format!("{}_{}", n, suffix_num)
    }

    /// Returns the path's components as plain strings, after [`flatten`]ing
    /// (so no `.`/`..` entries remain). Useful for walking the path level by
    /// level.
    ///
    /// [`flatten`]: VaultPath::flatten
    ///
    /// ```
    /// use kimun_core::nfs::VaultPath;
    /// assert_eq!(VaultPath::new("/a/b/c.md").get_slices(), vec!["a", "b", "c.md"]);
    /// ```
    pub fn get_slices(&self) -> Vec<String> {
        self.flatten()
            .slices
            .iter()
            .map(|slice| slice.to_string())
            .collect()
    }

    /// Joins this path onto `workspace_path` to produce the canonical on-disk
    /// `PathBuf`, mapping `/` to native separators and [`flatten`]ing first.
    ///
    /// This is the *canonical* (lowercase) location only; it does not perform
    /// case-insensitive resolution, so an existing file stored under a different
    /// case will not be found. Use the `nfs` resolver for that.
    ///
    /// [`flatten`]: VaultPath::flatten
    pub fn to_pathbuf<P: AsRef<Path>>(&self, workspace_path: P) -> PathBuf {
        let mut path = workspace_path.as_ref().to_path_buf();
        for p in &self.flatten().slices {
            let slice = p.to_string();
            path = path.join(&slice);
        }
        path
    }

    /// Returns a full path without any relative slices
    /// If it tries to go up beyond the current path, drops a warning
    pub fn flatten(&self) -> VaultPath {
        let mut slices = vec![];
        for slice in &self.slices {
            match slice {
                VaultPathSlice::PathSlice(_name) => slices.push(slice.clone()),
                VaultPathSlice::Up => {
                    if slices.pop().is_none() {
                        warn!("Trying to move a directory up from root")
                    }
                }
                VaultPathSlice::Current => {}
            }
        }
        VaultPath {
            absolute: self.absolute,
            slices,
        }
    }

    /// Returns the last part of the path slices
    /// if it is a note, will return the note filename, if it is a directory, will return the directory name
    pub fn get_name(&self) -> String {
        self.flatten().slices.last().map_or_else(String::new, |s| {
            if let VaultPathSlice::PathSlice(name) = s {
                name.to_owned()
            } else {
                String::new()
            }
        })
    }

    /// Returns the path of `self` written relative to a note file's *directory*.
    ///
    /// Markdown engines resolve relative links against the containing folder,
    /// not the note file itself. Linking from `/notes/journal/today.md` to
    /// `/assets/img.png` therefore produces `../../assets/img.png` (two `..`s
    /// — for `journal/` and `notes/`), not three. This wraps
    /// [`Self::get_relative_to`] using the note's parent path so callers get the
    /// markdown-correct result.
    pub fn relative_link_from_note(&self, note_path: &VaultPath) -> VaultPath {
        let (parent, _) = note_path.flatten().get_parent_path();
        self.flatten().get_relative_to(&parent)
    }

    /// Resolve `self` as a link target written inside `note_path`.
    ///
    /// Inverse of [`Self::relative_link_from_note`]: markdown links resolve against
    /// the *directory* containing the note, so a `../work/anton.md` target in
    /// `/journal/today.md` resolves to `/work/anton.md` (flattened, absolute).
    /// Absolute targets are returned flattened as-is. A bare filename with no
    /// directory part (e.g. `anton.md`) is returned unchanged so callers can
    /// fall back to a vault-wide name lookup (wiki-style links).
    pub fn resolve_link_in_note(&self, note_path: &VaultPath) -> VaultPath {
        if self.is_note_file() {
            return self.clone();
        }
        let (parent, _) = note_path.flatten().get_parent_path();
        parent.append(self).flatten().absolute()
    }

    /// Expresses this path relative to `reference_path`, walking up with `..`
    /// for each component of the reference not shared with this path, then down
    /// into this path's remaining components. The result is always relative.
    ///
    /// Note `reference_path` is treated as a directory: every one of its trailing
    /// components becomes a `..`. To build a markdown link relative to a note
    /// *file*, use [`relative_link_from_note`], which accounts for the note's own
    /// filename.
    ///
    /// [`relative_link_from_note`]: VaultPath::relative_link_from_note
    ///
    /// ```
    /// use kimun_core::nfs::VaultPath;
    /// let from = VaultPath::new("/main/path/first");
    /// let target = VaultPath::new("/main/second");
    /// assert_eq!(target.get_relative_to(&from).to_string(), "../../second");
    /// ```
    pub fn get_relative_to(&self, reference_path: &VaultPath) -> VaultPath {
        let mut slices = vec![];
        let ref_slices = reference_path.slices.clone();
        let mut position = 0;
        for (pos, slice) in self.slices.iter().enumerate() {
            position = pos;
            if let Some(reference) = ref_slices.get(pos) {
                if !slice.eq(reference) {
                    break;
                }
            } else {
                break;
            }
        }
        ref_slices.iter().skip(position).for_each(|_| {
            slices.push(VaultPathSlice::Up);
        });
        self.slices.iter().skip(position).for_each(|slice| {
            slices.push(slice.to_owned());
        });

        VaultPath {
            absolute: false,
            slices,
        }
    }

    /// Converts a real on-disk path back into an absolute vault path by
    /// stripping the `workspace_path` prefix. Returns `FSError::InvalidPath` if
    /// `full_path` does not live inside the workspace. Each OS component is run
    /// through [`VaultPath::new`], so the result is sanitized and lowercased.
    pub fn from_path<P: AsRef<Path>, F: AsRef<Path>>(
        workspace_path: P,
        full_path: F,
    ) -> Result<Self, FSError> {
        let fp = full_path.as_ref();
        let relative = fp
            .strip_prefix(&workspace_path)
            .map_err(|_e| FSError::InvalidPath {
                path: path_to_string(&full_path),
                message: format!(
                    "The path provided is not a path belonging to the workspace: {}",
                    path_to_string(workspace_path)
                ),
            })?;
        let mut path_list = vec![PATH_SEPARATOR.to_string()];
        relative.components().for_each(|component| {
            let os_str = component.as_os_str();
            let slice = match os_str.to_str() {
                Some(comp) => comp.to_owned(),
                None => os_str.to_string_lossy().to_string(),
            };
            path_list.push(slice);
        });
        let pl = path_list.join(PATH_SEPARATOR.to_string().as_str());

        Ok(VaultPath::new(pl).absolute())
    }

    /// Returns `true` if this path is a *bare* note filename: a single,
    /// relative component ending in the note extension, with no directory part
    /// (e.g. `anton.md`). Such paths are the signal for a vault-wide, wiki-style
    /// name lookup rather than a directory-scoped path match.
    ///
    /// ```
    /// use kimun_core::nfs::VaultPath;
    /// assert!(VaultPath::new("anton.md").is_note_file());
    /// assert!(!VaultPath::new("/work/anton.md").is_note_file());
    /// ```
    pub fn is_note_file(&self) -> bool {
        match self.slices.last() {
            Some(path_slice) => path_slice.is_note() && self.slices.len() == 1 && !self.absolute,
            None => false,
        }
    }

    /// Returns `true` if this path points at a note, i.e. its final component
    /// ends with the note extension. Unlike [`is_note_file`], the path may have
    /// any number of directory components.
    ///
    /// [`is_note_file`]: VaultPath::is_note_file
    pub fn is_note(&self) -> bool {
        match self.slices.last() {
            Some(path_slice) => path_slice.is_note(),
            None => false,
        }
    }

    /// Returns Ok if the path looks like a note path; otherwise an `InvalidPath` error.
    pub fn ensure_note(&self) -> Result<(), FSError> {
        if self.is_note() {
            Ok(())
        } else {
            Err(FSError::InvalidPath {
                path: self.to_string(),
                message: "The path is not a note".to_string(),
            })
        }
    }

    /// Returns Ok if the path does not have a note extension; otherwise an `InvalidPath` error.
    pub fn ensure_directory(&self) -> Result<(), FSError> {
        if self.is_note() {
            Err(FSError::InvalidPath {
                path: self.to_string(),
                message: "The path is not a directory".to_string(),
            })
        } else {
            Ok(())
        }
    }

    /// Returns `true` if this path is relative (not rooted at the vault root).
    pub fn is_relative(&self) -> bool {
        !self.absolute
    }

    /// Returns `true` if this path is absolute (rooted at the vault root).
    pub fn is_absolute(&self) -> bool {
        self.absolute
    }

    /// Marks this path absolute in place.
    pub fn to_absolute(&mut self) {
        self.absolute = true;
    }

    /// Consumes the path and returns it marked absolute (builder-style sibling
    /// of [`to_absolute`](VaultPath::to_absolute)).
    pub fn absolute(mut self) -> Self {
        self.absolute = true;
        self
    }

    /// Marks this path relative in place.
    pub fn to_relative(&mut self) {
        self.absolute = false;
    }

    /// Splits the path into its parent path and the final component's name.
    /// The parent keeps this path's absoluteness; the name is the empty string
    /// when the path has no components.
    ///
    /// ```
    /// use kimun_core::nfs::VaultPath;
    /// let (parent, name) = VaultPath::new("/a/b/c.md").get_parent_path();
    /// assert_eq!(parent.to_string(), "/a/b");
    /// assert_eq!(name, "c.md");
    /// ```
    pub fn get_parent_path(&self) -> (VaultPath, String) {
        let mut new_path = self.slices.clone();
        let current = new_path
            .pop()
            .map_or_else(|| "".to_string(), |s| s.to_string());

        (
            Self {
                absolute: self.absolute,
                slices: new_path,
            },
            current,
        )
    }

    /// Appends `path` to this one. If `path` is absolute it wins outright and is
    /// returned as-is; otherwise its components are concatenated onto this path,
    /// keeping this path's absoluteness. The result is not flattened, so any
    /// `..` in `path` survives until [`flatten`] is called.
    ///
    /// [`flatten`]: VaultPath::flatten
    ///
    /// ```
    /// use kimun_core::nfs::VaultPath;
    /// let base = VaultPath::new("/main/path");
    /// let rel = VaultPath::new("sub/note.md");
    /// assert_eq!(base.append(&rel).to_string(), "/main/path/sub/note.md");
    /// ```
    pub fn append(&self, path: &VaultPath) -> VaultPath {
        if !path.is_relative() {
            // Absolute paths are absolute
            path.to_owned()
        } else {
            let mut slices = self.slices.clone();
            let mut other_slices = path.slices.clone();
            slices.append(&mut other_slices);
            VaultPath {
                absolute: self.absolute,
                slices,
            }
        }
    }

    /// Compares two paths by components only, ignoring whether each is absolute
    /// or relative. So `/a/b` is "like" `a/b`.
    ///
    /// ```
    /// use kimun_core::nfs::VaultPath;
    /// assert!(VaultPath::new("/a/b").is_like(&VaultPath::new("a/b")));
    /// ```
    pub fn is_like(&self, other: &VaultPath) -> bool {
        self.slices.eq(&other.slices)
    }
}

impl Display for VaultPath {
    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
        if self.absolute {
            write!(f, "{}", PATH_SEPARATOR)?;
        }
        write!(
            f,
            "{}",
            self.slices
                .iter()
                .map(|s| s.to_string())
                .collect::<Vec<String>>()
                .join(&PATH_SEPARATOR.to_string())
        )
    }
}

#[derive(Debug, Clone, PartialEq, Eq, Hash, PartialOrd, Ord)]
enum VaultPathSlice {
    PathSlice(String),
    Up,
    Current,
}

impl VaultPathSlice {
    fn new<S: AsRef<str>>(slice: S) -> Self {
        // Replace runs of leading dots so "..foo" becomes "__foo".
        let slice = if filename::RX_PATH_NAME.is_match(slice.as_ref()) {
            slice.as_ref().replace(".", "_")
        } else {
            slice.as_ref().to_string()
        };
        if slice.eq("..") {
            VaultPathSlice::Up
        } else if slice.eq(".") {
            VaultPathSlice::Current
        } else {
            // Replace invalid chars, lowercase, strip leading/trailing spaces and
            // trailing dots (Windows silently strips them, causing silent collisions).
            let sanitized = filename::RX_PATH_CHARS
                .replace_all(&slice, "_")
                .to_lowercase();
            let sanitized = sanitized.trim().trim_end_matches('.').to_string();
            // Prefix Windows reserved device names so they don't map to device handles.
            let final_slice = if filename::RX_WIN_RESERVED.is_match(&sanitized) {
                format!("_{}", sanitized)
            } else {
                sanitized
            };

            VaultPathSlice::PathSlice(final_slice)
        }
    }

    fn is_valid<S: AsRef<str>>(slice: S) -> bool {
        let slice = slice.as_ref();
        if slice == "." || slice == ".." {
            return true;
        }
        !filename::RX_PATH_CHARS.is_match(slice)
            && !filename::RX_PATH_NAME.is_match(slice)
            && !filename::RX_WIN_RESERVED.is_match(slice)
            && !slice.ends_with('.')
            && !slice.starts_with(' ')
            && !slice.ends_with(' ')
    }

    fn is_note(&self) -> bool {
        match self {
            VaultPathSlice::PathSlice(name) => name.ends_with(NOTE_EXTENSION),
            _ => false,
        }
    }
}

impl Display for VaultPathSlice {
    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
        match self {
            VaultPathSlice::PathSlice(name) => write!(f, "{}", name),
            VaultPathSlice::Up => write!(f, ".."),
            VaultPathSlice::Current => write!(f, "."),
        }
    }
}

fn filter_files(dir: &ignore::DirEntry) -> bool {
    // Prune dotfile / dot-directory entries (e.g. the hidden `.kimun` backups
    // dir) so they never enter the index. `path().starts_with(".")` does NOT
    // work here — the walker root is an absolute path, so an entry's path never
    // begins with "."; check the entry's own name instead. The `ignore` crate's
    // default hidden filter also covers these, but excluding them explicitly
    // keeps the walk correct even if that default is ever disabled.
    dir.file_name()
        .to_str()
        .map(|name| !name.starts_with('.'))
        .unwrap_or(true)
}

pub(crate) fn list_directories<P: AsRef<Path>>(
    base_path: P,
    path: &VaultPath,
    recursive: bool,
) -> Result<Vec<super::DirectoryDetails>, FSError> {
    let base_path = base_path.as_ref();
    let os_path = resolve_path_on_disk_sync(base_path, path);
    let walker = WalkBuilder::new(&os_path)
        .max_depth(if recursive { None } else { Some(1) })
        .filter_entry(filter_files)
        .build();

    let mut dirs = Vec::new();
    for entry in walker.flatten() {
        let entry_path = entry.path();
        if entry_path.is_dir() && entry_path != os_path {
            let vault_path = VaultPath::from_path(base_path, entry_path)?;
            dirs.push(super::DirectoryDetails { path: vault_path });
        }
    }
    Ok(dirs)
}

pub(crate) fn get_file_walker<P: AsRef<Path>>(
    base_path: P,
    path: &VaultPath,
    recurse: bool,
) -> WalkParallel {
    let w = WalkBuilder::new(resolve_path_on_disk_sync(base_path, path))
        .max_depth(if recurse { None } else { Some(1) })
        .filter_entry(filter_files)
        // .threads(0)
        .build_parallel();

    w
}

#[cfg(test)]
mod tests {
    use std::path::{Path, PathBuf};

    use super::{save_attachment, with_note_extension};

    #[test]
    fn with_note_extension_appends_when_missing() {
        assert_eq!(with_note_extension("projects"), "projects.md");
    }

    #[test]
    fn with_note_extension_keeps_when_present() {
        assert_eq!(with_note_extension("projects.md"), "projects.md");
    }

    #[test]
    fn with_note_extension_preserves_wildcards_and_path() {
        // Unlike VaultPath, this does not sanitize `*` so search wildcards survive.
        assert_eq!(with_note_extension("work/proj*"), "work/proj*.md");
    }

    /// Returns true if the filesystem at `dir` is case-sensitive.
    /// Used to skip "no duplicate lowercase entry" assertions on macOS and other
    /// platforms that use a case-insensitive filesystem by default.
    fn is_case_sensitive_fs(dir: &Path) -> bool {
        // Write a probe file with a known uppercase name, then check whether the
        // lowercase variant resolves to the same entry or is absent.
        let upper = dir.join("__CaseSensitivityProbe__");
        std::fs::write(&upper, "").unwrap();
        let result = !dir.join("__casesensitivityprobe__").exists();
        std::fs::remove_file(&upper).unwrap();
        result
    }

    use crate::{
        error::FSError,
        nfs::{
            create_directory, delete_directory, delete_note, rename_directory, rename_note,
            save_note, DirectoryEntryData, EntryData, VaultEntry, VaultEntryDetails,
        },
        utilities::path_to_string,
        DirectoryDetails, NoteDetails,
    };

    use super::{load_note, VaultPath, VaultPathSlice};

    // --- cross-platform character validation tests ---

    #[test]
    fn control_chars_are_invalid() {
        // Control characters U+0001–U+001F must be rejected (Windows forbids them)
        assert!(!VaultPath::is_valid("note\x01name"));
        assert!(!VaultPath::is_valid("dir\x1fname"));
    }

    #[test]
    fn control_chars_are_sanitized_in_new() {
        let path = VaultPath::new("note\x07name");
        assert_eq!("note_name", path.to_string());
    }

    #[test]
    fn windows_reserved_names_are_invalid() {
        // Windows device names must be rejected regardless of extension or case
        for name in &["CON", "PRN", "AUX", "NUL", "COM1", "COM9", "LPT1", "LPT9"] {
            assert!(!VaultPath::is_valid(name), "{name} should be invalid");
            assert!(
                !VaultPath::is_valid(format!("{name}.md")),
                "{name}.md should be invalid"
            );
        }
        // Lower-case variants too
        assert!(!VaultPath::is_valid("con.md"));
        assert!(!VaultPath::is_valid("nul"));
    }

    #[test]
    fn windows_reserved_names_are_sanitized_in_new() {
        // VaultPath::new should prefix reserved names with '_' so they don't map to
        // Windows device handles. The name is already lowercased by this point.
        let path = VaultPath::new("con.md");
        assert_eq!("_con.md", path.to_string());

        let path = VaultPath::new("nul");
        assert_eq!("_nul", path.to_string());

        let path = VaultPath::new("COM1.md");
        assert_eq!("_com1.md", path.to_string());
    }

    #[test]
    fn trailing_dot_is_invalid() {
        // Windows silently strips trailing dots from filenames
        assert!(!VaultPath::is_valid("notes."));
        assert!(!VaultPath::is_valid("dir./sub"));
    }

    #[test]
    fn trailing_dot_is_sanitized_in_new() {
        let path = VaultPath::new("notes./sub");
        // trailing dot stripped from directory component
        assert_eq!("notes/sub", path.to_string());
    }

    #[test]
    fn leading_or_trailing_spaces_are_invalid() {
        assert!(!VaultPath::is_valid(" note"));
        assert!(!VaultPath::is_valid("note "));
        assert!(!VaultPath::is_valid(" dir /sub"));
    }

    #[test]
    fn leading_and_trailing_spaces_are_sanitized_in_new() {
        let path = VaultPath::new(" note ");
        assert_eq!("note", path.to_string());
    }

    #[test]
    fn should_print_correctly() {
        let path_with_root = "/some/path";
        let path_without_root = "another/one";

        let path1 = VaultPath::new(path_with_root);
        let path2 = VaultPath::new(path_without_root);

        assert_eq!("/some/path".to_string(), path1.to_string());
        assert_eq!("another/one".to_string(), path2.to_string());
    }

    #[test]
    fn test_valid_path() {
        let path = "/some/path.md";
        assert!(VaultPath::is_valid(path));
    }

    #[test]
    fn test_rel_path() {
        let path = VaultPath::new("../some/path.md");
        assert_eq!("../some/path.md", path.to_string());
        assert!(path.is_relative());
    }

    #[test]
    fn join_two_paths() {
        let path1 = VaultPath::new("main/path");
        let path2 = VaultPath::new("sub/path");
        let joined = path1.append(&path2);
        assert_eq!("main/path/sub/path".to_string(), joined.to_string());
    }

    #[test]
    fn join_two_paths_with_relative() {
        let path1 = VaultPath::new("/main/path");
        let path2 = VaultPath::new("../sub/path");
        let joined = path1.append(&path2).flatten();
        assert_eq!("/main/sub/path".to_string(), joined.to_string());
    }

    #[test]
    fn path_with_up_dir_end() {
        let path = VaultPath::new("/main/path/..");
        assert_eq!("/main".to_string(), path.flatten().to_string());
    }

    #[test]
    fn from_current_path() {
        let path = VaultPath::new("./path/subpath");
        assert!(!path.flatten().absolute);
        assert_eq!("path/subpath", path.flatten().to_string());
    }

    #[test]
    fn only_dots_three_or_more_not_allowed_in_path() {
        let path = "/some/.../path";
        assert!(!VaultPath::is_valid(path));

        let vault_path = VaultPath::new(path);
        assert_eq!("/some/___/path", vault_path.to_string());
    }

    #[test]
    fn get_relative_to() {
        let path1 = VaultPath::new("/main/path/first");
        let path2 = VaultPath::new("/main/second");
        let rel = path2.get_relative_to(&path1);

        assert_eq!("../../second".to_string(), rel.to_string());
    }

    #[test]
    fn get_relative_to_less_deep() {
        let path1 = VaultPath::new("/main/second");
        let path2 = VaultPath::new("/main/path/first");
        let rel = path2.get_relative_to(&path1);

        assert_eq!("../path/first".to_string(), rel.to_string());
    }

    #[test]
    fn get_relative_to_same() {
        let path1 = VaultPath::new("/main/second");
        let path2 = VaultPath::new("/main/second/sub/deep");
        let rel = path2.get_relative_to(&path1);

        assert_eq!("sub/deep".to_string(), rel.to_string());
    }

    #[test]
    fn relative_link_from_note_uses_parent_dir() {
        let note = VaultPath::new("/notes/journal/today.md");
        let asset = VaultPath::new("/assets/img.png");
        assert_eq!(
            "../../assets/img.png",
            asset.relative_link_from_note(&note).to_string()
        );
    }

    #[test]
    fn relative_link_from_root_note_to_assets() {
        let note = VaultPath::new("/note.md");
        let asset = VaultPath::new("/assets/img.png");
        assert_eq!(
            "assets/img.png",
            asset.relative_link_from_note(&note).to_string()
        );
    }

    #[test]
    fn relative_link_to_sibling_dir() {
        let note = VaultPath::new("/notes/today.md");
        let asset = VaultPath::new("/notes/assets/img.png");
        assert_eq!(
            "assets/img.png",
            asset.relative_link_from_note(&note).to_string()
        );
    }

    #[test]
    fn resolve_link_in_note_walks_up_and_lowercases() {
        let note = VaultPath::new("/journal/2026-03-01.md");
        let target = VaultPath::note_path_from("../Work/People/anton.md");
        assert_eq!(
            "/work/people/anton.md",
            target.resolve_link_in_note(&note).to_string()
        );
    }

    #[test]
    fn resolve_link_in_note_keeps_bare_name_for_name_lookup() {
        let note = VaultPath::new("/journal/2026-03-01.md");
        let target = VaultPath::note_path_from("anton.md");
        // Bare name unchanged (relative, single slice) so open_or_search does a
        // vault-wide name lookup rather than a directory-scoped path match.
        let resolved = target.resolve_link_in_note(&note);
        assert_eq!("anton.md", resolved.to_string());
        assert!(resolved.is_note_file());
    }

    #[test]
    fn resolve_link_in_note_absolute_target_unchanged() {
        let note = VaultPath::new("/journal/2026-03-01.md");
        let target = VaultPath::note_path_from("/work/people/anton.md");
        assert_eq!(
            "/work/people/anton.md",
            target.resolve_link_in_note(&note).to_string()
        );
    }

    #[test]
    fn resolve_link_in_note_sibling_subdir() {
        let note = VaultPath::new("/journal/2026-03-01.md");
        let target = VaultPath::note_path_from("attachments/notes.md");
        assert_eq!(
            "/journal/attachments/notes.md",
            target.resolve_link_in_note(&note).to_string()
        );
    }

    #[test]
    fn get_root() {
        let vault_path = VaultPath::root();
        assert_eq!("/".to_string(), vault_path.to_string());

        let root_path = VaultPath::new("/");
        assert_eq!(root_path, vault_path);
    }

    #[test]
    fn get_empty() {
        let vault_path = VaultPath::empty();
        assert_eq!("".to_string(), vault_path.to_string());

        let root_path = VaultPath::new("");
        assert_eq!(root_path, vault_path);
    }

    #[test]
    fn should_tell_if_its_note() {
        let path = "/some/../path.md";
        assert!(VaultPath::new(path).is_note());
    }

    #[test]
    fn paths_should_flatten_correctly() {
        let path = "some/path/../hola";
        assert!(VaultPath::is_valid(path));

        let vault_path = VaultPath::from_string(path).unwrap();
        let vault_path = vault_path.flatten();

        assert_eq!("some/hola".to_string(), vault_path.to_string());
    }

    #[test]
    fn test_file_should_not_look_like_url() {
        let valid = VaultPath::is_valid("http://example.com");

        assert!(!valid);
    }

    #[tokio::test]
    async fn test_file_not_exists() {
        let path = VaultPath::new("don't exist");
        let res = load_note(std::env::current_dir().unwrap(), &path).await;

        let result = if let Err(e) = res {
            matches!(e, FSError::VaultPathNotFound { path: _ })
        } else {
            false
        };

        assert!(result);
    }

    #[test]
    fn test_slice_char_replace() {
        let slice_str = "Some?unvalid:Chars?";
        let slice = VaultPathSlice::new(slice_str);

        assert_eq!("some_unvalid_chars_", slice.to_string());
        if let VaultPathSlice::PathSlice(name) = slice {
            assert_eq!("some_unvalid_chars_", name);
        }
    }

    #[test]
    fn test_path_create_from_string() {
        let path = "this/is/five/level/path";
        let path = VaultPath::new(path);

        assert_eq!(5, path.slices.len());
        assert_eq!("this", path.slices[0].to_string());
        assert_eq!("is", path.slices[1].to_string());
        assert_eq!("five", path.slices[2].to_string());
        assert_eq!("level", path.slices[3].to_string());
        assert_eq!("path", path.slices[4].to_string());
    }

    #[test]
    fn test_path_with_unvalid_chars() {
        let path = "t*his/i+s/caca?/";
        let path = VaultPath::new(path);

        assert_eq!(3, path.slices.len());
        assert_eq!("t_his", path.slices[0].to_string());
        assert_eq!("i+s", path.slices[1].to_string());
        assert_eq!("caca_", path.slices[2].to_string());
    }

    #[test]
    fn test_to_path_buf() {
        let workspace_path = PathBuf::from("workspace");
        let sep = std::path::MAIN_SEPARATOR_STR;

        let path = "/some/subpath";
        let path = VaultPath::new(path);
        let path_buf = path.to_pathbuf(&workspace_path);

        let path_string = path_to_string(path_buf);
        let expected_path_str = format!("workspace{sep}some{sep}subpath");
        assert_eq!(expected_path_str, path_string);
    }

    #[test]
    fn test_path_check_valid() {
        let path = PathBuf::from("/some/valid/path/workspace/note.md");
        let workspace = PathBuf::from("/some/valid/path");

        let entry = VaultPath::from_path(&workspace, &path).unwrap();

        assert_eq!("/workspace/note.md", entry.to_string());
    }

    #[tokio::test]
    async fn create_a_note() {
        use tempfile::TempDir;

        let temp_dir = TempDir::new().unwrap();
        let workspace_path = temp_dir.path();
        let note_path = VaultPath::new("note.md");
        let note_text = "this is an empty note".to_string();

        let res = save_note(workspace_path, &note_path, &note_text).await;
        if let Err(e) = &res {
            panic!("Error saving note: {e}")
        }

        let note = load_note(workspace_path, &note_path).await;
        if let Err(e) = &note {
            panic!("Error loading note: {e}")
        }
        assert_eq!(note.unwrap(), note_text);

        let del_res = delete_note(workspace_path, &note_path).await;
        if let Err(e) = &del_res {
            panic!("Error deleting note: {e}")
        }
        assert!(load_note(workspace_path, &note_path).await.is_err());
    }

    #[tokio::test]
    async fn move_a_note() {
        use tempfile::TempDir;

        let temp_dir = TempDir::new().unwrap();
        let workspace_path = temp_dir.path();
        let note_path = VaultPath::new("note.md");
        let dest_note_path = VaultPath::new("directory/moved_note.md");
        let note_text = "this is an empty note".to_string();

        let res = save_note(workspace_path, &note_path, &note_text).await;
        if let Err(e) = &res {
            panic!("Error saving note: {e}")
        }
        let note = load_note(workspace_path, &note_path).await;
        if let Err(e) = &note {
            panic!("Error loading note: {e}")
        }
        assert_eq!(note.as_ref().unwrap().to_owned(), note_text);

        let ren_res = rename_note(workspace_path, &note_path, &dest_note_path).await;
        if let Err(e) = &ren_res {
            panic!("Error renaming note: {e}")
        }
        let moved_note = load_note(workspace_path, &dest_note_path).await;
        if let Err(e) = &moved_note {
            panic!("Error loading note: {e}")
        }
        assert_eq!(note.unwrap(), moved_note.unwrap());
        assert!(load_note(workspace_path, &note_path).await.is_err());

        let del_res = delete_note(workspace_path, &dest_note_path).await;
        if let Err(e) = &del_res {
            panic!("Error deleting note: {e}")
        }
        assert!(load_note(workspace_path, &dest_note_path).await.is_err());

        let del_res = delete_directory(workspace_path, &dest_note_path.get_parent_path().0).await;
        if let Err(e) = &del_res {
            panic!("Error deleting directory: {e}")
        }
    }

    #[tokio::test]
    async fn move_a_directory() -> Result<(), FSError> {
        use tempfile::TempDir;

        let temp_dir = TempDir::new().unwrap();
        let workspace_path = temp_dir.path();
        let from_note_dir = VaultPath::new("old_dir");
        let from_note_path = from_note_dir.append(&VaultPath::new("note.md"));
        let dest_note_dir = VaultPath::new("new_dir/two_levels");
        let dest_note_path = dest_note_dir.append(&VaultPath::new("note.md"));
        let note_text = "this is an empty note".to_string();

        save_note(workspace_path, &from_note_path, &note_text).await?;
        let note = load_note(workspace_path, &from_note_path).await?;
        assert_eq!(note, note_text);

        rename_directory(workspace_path, &from_note_dir, &dest_note_dir).await?;
        let moved_note = load_note(workspace_path, &dest_note_path).await?;
        assert_eq!(note, moved_note);
        assert!(load_note(workspace_path, &from_note_dir).await.is_err());

        delete_note(workspace_path, &dest_note_path).await?;
        assert!(load_note(workspace_path, &dest_note_path).await.is_err());

        let first_level = dest_note_path.get_parent_path().0;
        let second_level = first_level.get_parent_path().0;
        delete_directory(workspace_path, &first_level).await?;
        delete_directory(workspace_path, &second_level).await?;

        Ok(())
    }

    // Additional comprehensive tests for NFS module

    #[tokio::test]
    async fn test_vault_entry_new_with_directory() {
        use tempfile::TempDir;

        let temp_dir = TempDir::new().unwrap();
        let workspace_path = temp_dir.path();
        let dir_path = VaultPath::new("test_directory");

        // Create directory first
        tokio::fs::create_dir_all(workspace_path.join("test_directory"))
            .await
            .ok();

        let result = VaultEntry::new(workspace_path, dir_path.clone()).await;
        assert!(result.is_ok());

        let entry = result.unwrap();
        assert_eq!(entry.path, dir_path);
        assert_eq!(entry.path_string, dir_path.to_string());

        match entry.data {
            EntryData::Directory(dir_data) => {
                assert_eq!(dir_data.path, dir_path);
            }
            _ => panic!("Expected Directory entry data"),
        }

        // Cleanup
        tokio::fs::remove_dir_all(workspace_path.join("test_directory"))
            .await
            .ok();
    }

    #[tokio::test]
    async fn test_vault_entry_new_with_note() {
        let workspace_path = Path::new("testdata");
        let note_path = VaultPath::new("test_note.md");
        let note_content = "# Test Note\n\nThis is a test.";

        // Create note first
        save_note(workspace_path, &note_path, note_content)
            .await
            .unwrap();

        let result = VaultEntry::new(workspace_path, note_path.clone()).await;
        assert!(result.is_ok());

        let entry = result.unwrap();
        assert_eq!(entry.path, note_path);

        match entry.data {
            EntryData::Note(note_data) => {
                assert_eq!(note_data.path, note_path);
                assert!(note_data.size > 0);
                assert!(note_data.modified_secs > 0);
            }
            _ => panic!("Expected Note entry data"),
        }

        // Cleanup
        delete_note(workspace_path, &note_path).await.ok();
    }

    #[tokio::test]
    async fn test_vault_entry_new_with_attachment() {
        let workspace_path = Path::new("testdata");
        let attachment_path = VaultPath::new("test.txt");

        // Create a text file (attachment)
        tokio::fs::create_dir_all(workspace_path).await.ok();
        tokio::fs::write(workspace_path.join("test.txt"), "test content")
            .await
            .unwrap();

        let result = VaultEntry::new(workspace_path, attachment_path.clone()).await;
        assert!(result.is_ok());

        let entry = result.unwrap();
        match entry.data {
            EntryData::Attachment => (),
            _ => panic!("Expected Attachment entry data"),
        }

        // Cleanup
        tokio::fs::remove_file(workspace_path.join("test.txt"))
            .await
            .ok();
    }

    #[tokio::test]
    async fn test_vault_entry_new_with_nonexistent_path() {
        let workspace_path = Path::new("testdata");
        let nonexistent_path = VaultPath::new("does_not_exist.md");

        let result = VaultEntry::new(workspace_path, nonexistent_path).await;
        assert!(result.is_err());

        match result.unwrap_err() {
            FSError::NoFileOrDirectoryFound { .. } => (),
            _ => panic!("Expected NoFileOrDirectoryFound error"),
        }
    }

    #[tokio::test]
    async fn test_vault_entry_from_path() {
        let workspace_path = Path::new("testdata");
        let note_path = VaultPath::new("from_path_test.md");
        let note_content = "Test content";

        // Create note
        save_note(workspace_path, &note_path, note_content)
            .await
            .unwrap();

        let full_path = workspace_path.join("from_path_test.md");
        let result = VaultEntry::from_path(workspace_path, &full_path).await;
        assert!(result.is_ok());

        let entry = result.unwrap();
        assert_eq!(entry.path, note_path.clone().absolute());

        // Cleanup
        delete_note(workspace_path, &note_path).await.ok();
    }

    #[tokio::test]
    async fn test_vault_entry_display() {
        let workspace_path = Path::new("testdata");
        let note_path = VaultPath::new("display_test.md");
        let dir_path = VaultPath::new("display_dir");
        let attachment_path = VaultPath::new("display.txt");

        // Test note display
        save_note(workspace_path, &note_path, "content")
            .await
            .unwrap();
        let note_entry = VaultEntry::new(workspace_path, note_path.clone())
            .await
            .unwrap();
        let note_display = format!("{}", note_entry);
        assert!(note_display.contains("[NOT]"));
        assert!(note_display.contains(&note_path.to_string()));

        // Test directory display
        tokio::fs::create_dir_all(workspace_path.join("display_dir"))
            .await
            .ok();
        let dir_entry = VaultEntry::new(workspace_path, dir_path.clone())
            .await
            .unwrap();
        let dir_display = format!("{}", dir_entry);
        assert!(dir_display.contains("[DIR]"));
        assert!(dir_display.contains(&dir_path.to_string()));

        // Test attachment display
        tokio::fs::write(workspace_path.join("display.txt"), "content")
            .await
            .ok();
        let attachment_entry = VaultEntry::new(workspace_path, attachment_path.clone())
            .await
            .unwrap();
        let attachment_display = format!("{}", attachment_entry);
        assert!(attachment_display.contains("[ATT]"));

        // Cleanup
        delete_note(workspace_path, &note_path).await.ok();
        tokio::fs::remove_dir_all(workspace_path.join("display_dir"))
            .await
            .ok();
        tokio::fs::remove_file(workspace_path.join("display.txt"))
            .await
            .ok();
    }

    #[tokio::test]
    async fn test_note_entry_data_load_details() {
        let workspace_path = Path::new("testdata");
        let note_path = VaultPath::new("details_test.md");
        let note_content = "# Test\n\nContent here";

        save_note(workspace_path, &note_path, note_content)
            .await
            .unwrap();
        let entry = VaultEntry::new(workspace_path, note_path.clone())
            .await
            .unwrap();

        if let EntryData::Note(note_data) = entry.data {
            let details_result = note_data.load_details(workspace_path, &note_path).await;
            assert!(details_result.is_ok());

            let details = details_result.unwrap();
            assert_eq!(details.path, note_path);
            assert_eq!(details.raw_text, note_content);
        } else {
            panic!("Expected Note entry data");
        }

        // Cleanup
        delete_note(workspace_path, &note_path).await.ok();
    }

    #[test]
    fn test_directory_entry_data_get_details() {
        let dir_path = VaultPath::new("test_dir");
        let dir_data = DirectoryEntryData {
            path: dir_path.clone(),
        };

        let details = dir_data.get_details::<PathBuf>();
        assert_eq!(details.path, dir_path);
    }

    #[test]
    fn test_vault_entry_details_get_title() {
        let note_path = VaultPath::new("test.md");
        let note_content = "# My Title\n\nContent";
        let note_details = NoteDetails::new(&note_path, note_content);

        let mut note_entry_details = VaultEntryDetails::Note(note_details);
        let title = note_entry_details.get_title();
        assert_eq!(title, "My Title");

        let dir_path = VaultPath::new("test_dir");
        let dir_details = DirectoryDetails { path: dir_path };
        let mut dir_entry_details = VaultEntryDetails::Directory(dir_details);
        let dir_title = dir_entry_details.get_title();
        assert_eq!(dir_title, "");

        let mut none_details = VaultEntryDetails::None;
        let none_title = none_details.get_title();
        assert_eq!(none_title, "");
    }

    #[test]
    fn test_hash_text() {
        use super::hash_text;

        let text1 = "Hello, world!";
        let text2 = "Hello, world!";
        let text3 = "Different text";

        let hash1 = hash_text(text1);
        let hash2 = hash_text(text2);
        let hash3 = hash_text(text3);

        assert_eq!(hash1, hash2);
        assert_ne!(hash1, hash3);
        assert!(hash1 > 0);
    }

    #[tokio::test]
    async fn test_create_directory_with_note_path() {
        let workspace_path = Path::new("testdata");
        let note_path = VaultPath::new("invalid.md");

        let result = create_directory(workspace_path, &note_path).await;
        assert!(result.is_err());

        match result.unwrap_err() {
            FSError::InvalidPath { message, .. } => {
                assert_eq!(message, "The path is not a directory");
            }
            _ => panic!("Expected InvalidPath error"),
        }
    }

    #[tokio::test]
    async fn save_attachment_writes_bytes_and_creates_parent_dirs() {
        use tempfile::TempDir;

        let temp_dir = TempDir::new().unwrap();
        let workspace = temp_dir.path();
        let path = VaultPath::new("/assets/img.png");
        let bytes = b"\x89PNG\r\n\x1a\n stub".to_vec();

        save_attachment(workspace, &path, &bytes).await.unwrap();

        let on_disk = workspace.join("assets").join("img.png");
        let read_back = tokio::fs::read(&on_disk).await.unwrap();
        assert_eq!(read_back, bytes);
    }

    #[tokio::test]
    async fn test_save_note_with_directory_path() {
        let workspace_path = Path::new("testdata");
        let dir_path = VaultPath::new("directory");
        let content = "test content";

        let result = save_note(workspace_path, &dir_path, content).await;
        assert!(result.is_err());

        match result.unwrap_err() {
            FSError::InvalidPath { message, .. } => {
                assert_eq!(message, "The path is not a note");
            }
            _ => panic!("Expected InvalidPath error"),
        }
    }

    #[tokio::test]
    async fn test_rename_note_with_invalid_paths() {
        let workspace_path = Path::new("testdata");
        let dir_path = VaultPath::new("directory");
        let note_path = VaultPath::new("note.md");

        // Test renaming from directory (should fail)
        let result = rename_note(workspace_path, &dir_path, &note_path).await;
        assert!(result.is_err());

        // Test renaming to directory (should fail)
        let result = rename_note(workspace_path, &note_path, &dir_path).await;
        assert!(result.is_err());
    }

    #[tokio::test]
    async fn test_rename_directory_with_invalid_paths() {
        let workspace_path = Path::new("testdata");
        let dir_path = VaultPath::new("directory");
        let note_path = VaultPath::new("note.md");

        // Test renaming from note (should fail)
        let result = rename_directory(workspace_path, &note_path, &dir_path).await;
        assert!(result.is_err());

        // Test renaming to note (should fail)
        let result = rename_directory(workspace_path, &dir_path, &note_path).await;
        assert!(result.is_err());
    }

    #[test]
    fn test_vault_path_serialization() {
        use serde_json;

        let path = VaultPath::new("/test/path.md");
        let serialized = serde_json::to_string(&path).unwrap();
        assert_eq!(serialized, "\"/test/path.md\"");

        let deserialized: VaultPath = serde_json::from_str(&serialized).unwrap();
        assert_eq!(deserialized, path);
    }

    #[test]
    fn test_vault_path_try_from() {
        let path_str = "/valid/path.md";
        let path_result: Result<VaultPath, FSError> = path_str.try_into();
        assert!(path_result.is_ok());

        let invalid_path_str = "/invalid:path.md";
        let invalid_result: Result<VaultPath, FSError> = invalid_path_str.try_into();
        assert!(invalid_result.is_err());
    }

    #[test]
    fn test_vault_path_from_str() {
        use std::str::FromStr;

        let path_str = "/test/path.md";
        let path = VaultPath::from_str(path_str).unwrap();
        assert_eq!(path.to_string(), path_str);

        let invalid_str = "/invalid:path.md";
        let result = VaultPath::from_str(invalid_str);
        assert!(result.is_err());
    }

    #[test]
    fn test_vault_path_note_path_from() {
        let path_without_extension = "test/note";
        let path_with_extension = "test/note.md";
        let path_with_trailing_slash = "test/note/";

        let note_path1 = VaultPath::note_path_from(path_without_extension);
        let note_path2 = VaultPath::note_path_from(path_with_extension);
        let note_path3 = VaultPath::note_path_from(path_with_trailing_slash);

        assert_eq!(note_path1.to_string(), "test/note.md");
        assert_eq!(note_path2.to_string(), "test/note.md");
        assert_eq!(note_path3.to_string(), "test/note.md");

        assert!(note_path1.is_note());
        assert!(note_path2.is_note());
        assert!(note_path3.is_note());
    }

    #[test]
    fn test_vault_path_get_name_on_conflict() {
        let note_path = VaultPath::new("test.md");
        let conflicted = note_path.get_name_on_conflict();
        assert_eq!(conflicted.to_string(), "test_0.md");

        let numbered_path = VaultPath::new("test_5.md");
        let conflicted_numbered = numbered_path.get_name_on_conflict();
        assert_eq!(conflicted_numbered.to_string(), "test_6.md");

        let dir_path = VaultPath::new("directory");
        let conflicted_dir = dir_path.get_name_on_conflict();
        assert_eq!(conflicted_dir.to_string(), "directory_0");

        let empty_path = VaultPath::empty();
        let conflicted_empty = empty_path.get_name_on_conflict();
        assert_eq!(conflicted_empty.to_string(), "0");
    }

    #[test]
    fn test_vault_path_get_clean_name() {
        let note_path = VaultPath::new("/path/to/note.md");
        assert_eq!(note_path.get_clean_name(), "note");

        let dir_path = VaultPath::new("/path/to/directory");
        assert_eq!(dir_path.get_clean_name(), "directory");

        let root_path = VaultPath::root();
        assert_eq!(root_path.get_clean_name(), "");
    }

    #[test]
    fn test_vault_path_get_slices() {
        let path = VaultPath::new("/path/to/../file.md");
        let slices = path.get_slices();
        assert_eq!(slices, vec!["path", "file.md"]);
    }

    #[test]
    fn test_vault_path_is_like() {
        let path1 = VaultPath::new("/test/path.md");
        let path2 = VaultPath::new("test/path.md"); // relative version
        let path3 = VaultPath::new("/different/path.md");

        assert!(path1.is_like(&path2));
        assert!(!path1.is_like(&path3));
    }

    #[test]
    fn test_vault_path_slice_edge_cases() {
        // Test slice with dots
        let path_with_dots = VaultPath::new("...invalid");
        assert_eq!(path_with_dots.to_string(), "___invalid");

        // Test slice with invalid characters
        let path_with_invalid = VaultPath::new("test:file?.md");
        assert_eq!(path_with_invalid.to_string(), "test_file_.md");

        // Test current directory slice
        let path_with_current = VaultPath::new("./test");
        assert_eq!(path_with_current.flatten().to_string(), "test");

        // Test parent directory slice
        let path_with_parent = VaultPath::new("../test");
        assert_eq!(path_with_parent.to_string(), "../test");
    }

    #[test]
    fn test_vault_path_increment_function() {
        use super::VaultPath;

        // Test the increment functionality through get_name_on_conflict
        let base_name = VaultPath::new("test");
        let incremented = base_name.get_name_on_conflict();
        assert_eq!(incremented.to_string(), "test_0");

        let numbered_name = VaultPath::new("test_3");
        let incremented_numbered = numbered_name.get_name_on_conflict();
        assert_eq!(incremented_numbered.to_string(), "test_4");
    }

    #[test]
    fn vault_path_normalizes_to_lowercase() {
        // Paths are always stored lowercase regardless of input case
        let a = VaultPath::new("/Projects/Note.md");
        let b = VaultPath::new("/projects/note.md");
        assert_eq!(a, b);
        assert_eq!(a.to_string(), "/projects/note.md");
    }

    // ── Case-insensitive disk resolution tests ────────────────────────────────

    #[tokio::test]
    async fn resolve_finds_uppercase_directory() {
        let tmp = tempfile::TempDir::new().unwrap();
        tokio::fs::create_dir(tmp.path().join("Journal"))
            .await
            .unwrap();

        let result = super::resolve_path_on_disk(tmp.path(), &VaultPath::new("/journal")).await;
        assert_eq!(result, tmp.path().join("Journal"));
    }

    #[tokio::test]
    async fn resolve_finds_uppercase_file() {
        let tmp = tempfile::TempDir::new().unwrap();
        tokio::fs::create_dir(tmp.path().join("Projects"))
            .await
            .unwrap();
        tokio::fs::write(tmp.path().join("Projects").join("MyNote.md"), "hi")
            .await
            .unwrap();

        let result =
            super::resolve_path_on_disk(tmp.path(), &VaultPath::new("/projects/mynote.md")).await;
        assert_eq!(result, tmp.path().join("Projects").join("MyNote.md"));
    }

    #[tokio::test]
    async fn resolve_uses_lowercase_for_nonexistent_path() {
        let tmp = tempfile::TempDir::new().unwrap();

        let result =
            super::resolve_path_on_disk(tmp.path(), &VaultPath::new("/newdir/note.md")).await;
        assert_eq!(result, tmp.path().join("newdir").join("note.md"));
    }

    #[test]
    fn resolve_sync_finds_uppercase_directory() {
        let tmp = tempfile::TempDir::new().unwrap();
        std::fs::create_dir(tmp.path().join("Archive")).unwrap();

        let result = super::resolve_path_on_disk_sync(tmp.path(), &VaultPath::new("/archive"));
        assert_eq!(result, tmp.path().join("Archive"));
    }

    #[tokio::test]
    async fn load_note_finds_uppercase_file() {
        let tmp = tempfile::TempDir::new().unwrap();
        tokio::fs::create_dir(tmp.path().join("Journal"))
            .await
            .unwrap();
        tokio::fs::write(tmp.path().join("Journal").join("MyNote.md"), "# Hello")
            .await
            .unwrap();

        let text = super::load_note(tmp.path(), &VaultPath::new("/journal/mynote.md"))
            .await
            .unwrap();
        assert_eq!(text, "# Hello");
    }

    #[tokio::test]
    async fn save_note_writes_to_existing_uppercase_file() {
        let tmp = tempfile::TempDir::new().unwrap();
        tokio::fs::create_dir(tmp.path().join("Journal"))
            .await
            .unwrap();
        tokio::fs::write(tmp.path().join("Journal").join("MyNote.md"), "original")
            .await
            .unwrap();

        save_note(tmp.path(), &VaultPath::new("/journal/mynote.md"), "updated")
            .await
            .unwrap();

        // The uppercase file should be updated
        let content = tokio::fs::read_to_string(tmp.path().join("Journal").join("MyNote.md"))
            .await
            .unwrap();
        assert_eq!(content, "updated");

        // On case-sensitive filesystems: no duplicate lowercase entries should exist.
        // On case-insensitive filesystems (e.g. macOS default APFS), 'Journal' and
        // 'journal' are the same path so these assertions are not meaningful.
        if is_case_sensitive_fs(tmp.path()) {
            assert!(!tmp.path().join("Journal").join("mynote.md").exists());
            assert!(!tmp.path().join("journal").exists());
        }
    }

    #[tokio::test]
    async fn save_note_in_uppercase_parent_directory() {
        let tmp = tempfile::TempDir::new().unwrap();
        tokio::fs::create_dir(tmp.path().join("Projects"))
            .await
            .unwrap();

        save_note(tmp.path(), &VaultPath::new("/projects/new.md"), "content")
            .await
            .unwrap();

        // File should land inside the existing uppercase directory
        assert!(tmp.path().join("Projects").join("new.md").exists());
        // On case-sensitive filesystems: no duplicate lowercase directory should exist.
        if is_case_sensitive_fs(tmp.path()) {
            assert!(!tmp.path().join("projects").exists());
        }
    }

    #[tokio::test]
    async fn delete_note_removes_uppercase_file() {
        let tmp = tempfile::TempDir::new().unwrap();
        tokio::fs::create_dir(tmp.path().join("Journal"))
            .await
            .unwrap();
        let file = tmp.path().join("Journal").join("MyNote.md");
        tokio::fs::write(&file, "bye").await.unwrap();

        delete_note(tmp.path(), &VaultPath::new("/journal/mynote.md"))
            .await
            .unwrap();

        assert!(!file.exists());
    }

    #[tokio::test]
    async fn delete_directory_removes_uppercase_directory() {
        let tmp = tempfile::TempDir::new().unwrap();
        tokio::fs::create_dir(tmp.path().join("Archive"))
            .await
            .unwrap();
        tokio::fs::write(tmp.path().join("Archive").join("note.md"), "x")
            .await
            .unwrap();

        delete_directory(tmp.path(), &VaultPath::new("/archive"))
            .await
            .unwrap();

        assert!(!tmp.path().join("Archive").exists());
    }

    #[tokio::test]
    async fn rename_note_finds_uppercase_source() {
        let tmp = tempfile::TempDir::new().unwrap();
        tokio::fs::create_dir(tmp.path().join("Projects"))
            .await
            .unwrap();
        tokio::fs::write(tmp.path().join("Projects").join("MyNote.md"), "data")
            .await
            .unwrap();

        rename_note(
            tmp.path(),
            &VaultPath::new("/projects/mynote.md"),
            &VaultPath::new("/projects/renamed.md"),
        )
        .await
        .unwrap();

        assert!(tmp.path().join("Projects").join("renamed.md").exists());
        assert!(!tmp.path().join("Projects").join("MyNote.md").exists());
    }

    #[tokio::test]
    async fn rename_note_into_uppercase_parent() {
        let tmp = tempfile::TempDir::new().unwrap();
        tokio::fs::create_dir(tmp.path().join("Inbox"))
            .await
            .unwrap();
        tokio::fs::write(tmp.path().join("Inbox").join("note.md"), "data")
            .await
            .unwrap();
        tokio::fs::create_dir(tmp.path().join("Archive"))
            .await
            .unwrap();

        rename_note(
            tmp.path(),
            &VaultPath::new("/inbox/note.md"),
            &VaultPath::new("/archive/note.md"),
        )
        .await
        .unwrap();

        assert!(tmp.path().join("Archive").join("note.md").exists());
        // On case-sensitive filesystems: no duplicate lowercase directory should exist.
        if is_case_sensitive_fs(tmp.path()) {
            assert!(!tmp.path().join("archive").exists());
        }
    }

    #[tokio::test]
    async fn rename_directory_finds_uppercase_source() {
        let tmp = tempfile::TempDir::new().unwrap();
        tokio::fs::create_dir(tmp.path().join("OldName"))
            .await
            .unwrap();

        rename_directory(
            tmp.path(),
            &VaultPath::new("/oldname"),
            &VaultPath::new("/newname"),
        )
        .await
        .unwrap();

        assert!(tmp.path().join("newname").exists());
        assert!(!tmp.path().join("OldName").exists());
    }

    #[tokio::test]
    async fn vault_entry_from_path_uses_lowercase_vault_path() {
        let tmp = tempfile::TempDir::new().unwrap();
        tokio::fs::create_dir(tmp.path().join("Projects"))
            .await
            .unwrap();
        tokio::fs::write(tmp.path().join("Projects").join("MyNote.md"), "# Title")
            .await
            .unwrap();

        let entry =
            VaultEntry::from_path(tmp.path(), tmp.path().join("Projects").join("MyNote.md"))
                .await
                .unwrap();

        // VaultPath is always lowercase even though the disk file has uppercase
        assert_eq!(entry.path.to_string(), "/projects/mynote.md");
        assert!(matches!(entry.data, EntryData::Note(_)));
    }

    #[tokio::test]
    async fn vault_entry_new_finds_uppercase_file() {
        let tmp = tempfile::TempDir::new().unwrap();
        tokio::fs::create_dir(tmp.path().join("Projects"))
            .await
            .unwrap();
        tokio::fs::write(tmp.path().join("Projects").join("MyNote.md"), "# Title")
            .await
            .unwrap();

        let entry = VaultEntry::new(tmp.path(), VaultPath::new("/projects/mynote.md"))
            .await
            .unwrap();

        assert_eq!(entry.path.to_string(), "/projects/mynote.md");
        assert!(matches!(entry.data, EntryData::Note(_)));
    }
}