diaryx_core 0.10.0

Core library for Diaryx - a tool to manage markdown files with YAML frontmatter
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
//! Workspace operations module.
//!
//! This module provides functionality for working with Diaryx workspaces:
//! - Tree traversal and building
//! - File operations (move, rename, delete)
//! - Index management (contents, part_of relationships)
//!
//! # Module Structure
//!
//! - `types` - Core data types (IndexFrontmatter, IndexFile, TreeNode)
//!
//! # Async-first Design
//!
//! This module uses `AsyncFileSystem` for all filesystem operations.
//! For synchronous contexts (CLI, tests), wrap a sync filesystem with
//! `SyncToAsyncFs` and use `futures_lite::future::block_on()`.

mod types;

// Re-export types for backwards compatibility
pub use types::{IndexFile, IndexFrontmatter, TreeNode, format_tree_node};

use std::collections::HashSet;
use std::path::{Path, PathBuf};

use serde_yaml::Value;

use crate::config::Config;
use crate::error::{DiaryxError, Result};
use crate::fs::AsyncFileSystem;

/// Workspace operations (async-first).
///
/// All methods are async and use `AsyncFileSystem` for filesystem access.
pub struct Workspace<FS: AsyncFileSystem> {
    fs: FS,
}

impl<FS: AsyncFileSystem> Workspace<FS> {
    /// Create a new workspace
    pub fn new(fs: FS) -> Self {
        Self { fs }
    }

    /// Get a reference to the underlying filesystem
    pub fn fs_ref(&self) -> &FS {
        &self.fs
    }

    /// Parse a markdown file and extract index frontmatter
    pub async fn parse_index(&self, path: &Path) -> Result<IndexFile> {
        let content = self
            .fs
            .read_to_string(path)
            .await
            .map_err(|e| DiaryxError::FileRead {
                path: path.to_path_buf(),
                source: e,
            })?;

        // Check if content starts with frontmatter delimiter
        if !content.starts_with("---\n") && !content.starts_with("---\r\n") {
            return Err(DiaryxError::NoFrontmatter(path.to_path_buf()));
        }

        // Find the closing delimiter
        let rest = &content[4..]; // Skip first "---\n"
        let end_idx = rest
            .find("\n---\n")
            .or_else(|| rest.find("\n---\r\n"))
            .ok_or_else(|| DiaryxError::NoFrontmatter(path.to_path_buf()))?;

        let frontmatter_str = &rest[..end_idx];
        let body = &rest[end_idx + 5..]; // Skip "\n---\n"

        let frontmatter: IndexFrontmatter =
            serde_yaml::from_str(frontmatter_str).map_err(|e| DiaryxError::YamlParse {
                path: path.to_path_buf(),
                message: e.to_string(),
            })?;

        Ok(IndexFile {
            path: path.to_path_buf(),
            frontmatter,
            body: body.to_string(),
        })
    }

    /// Check if a file is an index file (has contents property)
    pub async fn is_index_file(&self, path: &Path) -> bool {
        if path.extension().is_none_or(|ext| ext != "md") {
            return false;
        }

        self.parse_index(path)
            .await
            .map(|idx| idx.frontmatter.is_index())
            .unwrap_or(false)
    }

    /// Check if a file is a root index (has contents but no part_of)
    pub async fn is_root_index(&self, path: &Path) -> bool {
        self.parse_index(path)
            .await
            .map(|idx| idx.frontmatter.is_root())
            .unwrap_or(false)
    }

    /// Find a root index in the given directory
    pub async fn find_root_index_in_dir(&self, dir: &Path) -> Result<Option<PathBuf>> {
        let md_files = self
            .fs
            .list_md_files(dir)
            .await
            .map_err(|e| DiaryxError::FileRead {
                path: dir.to_path_buf(),
                source: e,
            })?;

        for file in md_files {
            if self.is_root_index(&file).await {
                return Ok(Some(file));
            }
        }

        Ok(None)
    }

    /// Find any index file in the given directory (has `contents` property)
    /// Prefers root indexes over non-root indexes
    pub async fn find_any_index_in_dir(&self, dir: &Path) -> Result<Option<PathBuf>> {
        let md_files = self
            .fs
            .list_md_files(dir)
            .await
            .map_err(|e| DiaryxError::FileRead {
                path: dir.to_path_buf(),
                source: e,
            })?;

        let mut found_index: Option<PathBuf> = None;

        for file in md_files {
            if let Ok(index) = self.parse_index(&file).await
                && index.frontmatter.is_index()
            {
                // Prefer root index if found
                if index.frontmatter.is_root() {
                    return Ok(Some(file));
                }
                // Otherwise remember the first index we find
                if found_index.is_none() {
                    found_index = Some(file);
                }
            }
        }

        Ok(found_index)
    }

    /// Collect all files reachable from an index via `contents` traversal
    /// Returns a list of all files including the index itself and all nested contents
    pub async fn collect_workspace_files(&self, index_path: &Path) -> Result<Vec<PathBuf>> {
        let mut files = Vec::new();
        let mut visited = HashSet::new();
        self.collect_workspace_files_recursive(index_path, &mut files, &mut visited)
            .await?;
        files.sort();
        Ok(files)
    }

    /// Recursive helper for collecting workspace files
    async fn collect_workspace_files_recursive(
        &self,
        path: &Path,
        files: &mut Vec<PathBuf>,
        visited: &mut HashSet<PathBuf>,
    ) -> Result<()> {
        // Canonicalize to handle relative paths consistently
        let canonical = path.canonicalize().unwrap_or_else(|_| path.to_path_buf());

        // Avoid cycles
        if visited.contains(&canonical) {
            return Ok(());
        }
        visited.insert(canonical.clone());

        // Add this file to the list
        files.push(path.to_path_buf());

        // If this is an index file, recurse into its contents
        if let Ok(index) = self.parse_index(path).await
            && index.frontmatter.is_index()
        {
            for child_path_str in index.frontmatter.contents_list() {
                let child_path = index.resolve_path(child_path_str);

                // Only include if the file exists
                if self.fs.exists(&child_path).await {
                    Box::pin(self.collect_workspace_files_recursive(&child_path, files, visited))
                        .await?;
                }
            }
        }

        Ok(())
    }

    /// Detect the workspace root from the current directory
    /// Searches current directory for a root index file
    pub async fn detect_workspace(&self, start_dir: &Path) -> Result<Option<PathBuf>> {
        // Look for root index in start directory
        if let Some(root) = self.find_root_index_in_dir(start_dir).await? {
            return Ok(Some(root));
        }

        Ok(None)
    }

    /// Resolve workspace: check current dir, then fall back to config default
    pub async fn resolve_workspace(&self, current_dir: &Path, config: &Config) -> Result<PathBuf> {
        // First, try to detect workspace in current directory
        if let Some(root) = self.detect_workspace(current_dir).await? {
            return Ok(root);
        }

        // Fall back to config's default_workspace and look for root index there
        if let Some(root) = self
            .find_root_index_in_dir(&config.default_workspace)
            .await?
        {
            return Ok(root);
        }

        // If no root index exists in default_workspace, return the expected README.md path
        // (it may need to be created)
        Ok(config.default_workspace.join("README.md"))
    }

    /// Initialize a new workspace with a root index file
    pub async fn init_workspace(
        &self,
        dir: &Path,
        title: Option<&str>,
        description: Option<&str>,
    ) -> Result<PathBuf> {
        // Check if ANY root index already exists in this directory
        // (not just README.md - could be index.md or any other .md file)
        if let Ok(Some(existing_root)) = self.find_root_index_in_dir(dir).await {
            return Err(DiaryxError::WorkspaceAlreadyExists(existing_root));
        }

        let readme_path = dir.join("README.md");

        // Create directory if needed
        self.fs.create_dir_all(dir).await?;

        let display_title = title.unwrap_or_else(|| {
            dir.file_name()
                .and_then(|n| n.to_str())
                .unwrap_or("Workspace")
        });

        let desc = description.unwrap_or("A diaryx workspace");

        let content = format!(
            "---\ntitle: {}\ndescription: {}\ncontents: []\n---\n\n# {}\n\n{}\n",
            display_title, desc, display_title, desc
        );

        self.fs
            .create_new(&readme_path, &content)
            .await
            .map_err(|e| DiaryxError::FileWrite {
                path: readme_path.clone(),
                source: e,
            })?;

        Ok(readme_path)
    }

    /// Build a tree structure from the workspace hierarchy
    pub async fn build_tree(&self, root_path: &Path) -> Result<TreeNode> {
        self.build_tree_with_depth(root_path, None, &mut HashSet::new())
            .await
    }

    /// Build a tree structure with depth limit and cycle detection
    /// `max_depth` of None means unlimited, Some(0) means just the root node
    pub async fn build_tree_with_depth(
        &self,
        root_path: &Path,
        max_depth: Option<usize>,
        visited: &mut HashSet<PathBuf>,
    ) -> Result<TreeNode> {
        let index = self.parse_index(root_path).await?;

        // Canonicalize path for cycle detection
        let canonical = root_path
            .canonicalize()
            .unwrap_or_else(|_| root_path.to_path_buf());

        // Check for cycles
        if visited.contains(&canonical) {
            return Ok(TreeNode {
                name: format!(
                    "{} (cycle)",
                    root_path.file_name().unwrap_or_default().to_string_lossy()
                ),
                description: None,
                path: root_path.to_path_buf(),
                children: Vec::new(),
            });
        }
        visited.insert(canonical);

        let name = index
            .frontmatter
            .display_name()
            .map(String::from)
            .unwrap_or_else(|| {
                // Fall back to filename without extension
                root_path
                    .file_stem()
                    .and_then(|s| s.to_str())
                    .map(String::from)
                    .unwrap_or_else(|| root_path.display().to_string())
            });

        let mut children = Vec::new();
        let contents = index.frontmatter.contents_list();
        let child_count = contents.len();

        // Check if we've hit depth limit
        let at_depth_limit = max_depth.map(|d| d == 0).unwrap_or(false);

        if at_depth_limit && child_count > 0 {
            // Show truncation indicator
            children.push(TreeNode {
                name: format!("... ({} more)", child_count),
                description: None,
                path: root_path.to_path_buf(),
                children: Vec::new(),
            });
        } else {
            let next_depth = max_depth.map(|d| d.saturating_sub(1));

            for child_path_str in contents {
                let child_path = index.resolve_path(child_path_str);

                // Only include if the file exists
                if self.fs.exists(&child_path).await {
                    match Box::pin(self.build_tree_with_depth(&child_path, next_depth, visited))
                        .await
                    {
                        Ok(child_node) => children.push(child_node),
                        Err(_) => {
                            // If we can't parse a child, include it as a leaf with error indication
                            children.push(TreeNode {
                                name: format!("{} (error)", child_path_str),
                                description: None,
                                path: child_path,
                                children: Vec::new(),
                            });
                        }
                    }
                }
                // Ignore non-existent paths (as per spec: "ignore by default")
            }
        }

        Ok(TreeNode {
            name,
            description: index.frontmatter.description,
            path: root_path.to_path_buf(),
            children,
        })
    }

    /// Build a tree structure from the actual filesystem (for "Show All Files" mode)
    /// Unlike build_tree, this scans directories for actual files rather than following contents references
    pub async fn build_filesystem_tree(
        &self,
        root_dir: &Path,
        show_hidden: bool,
    ) -> Result<TreeNode> {
        self.build_filesystem_tree_with_depth(root_dir, show_hidden, None)
            .await
    }

    /// Build a filesystem tree with optional depth limiting for lazy loading
    pub async fn build_filesystem_tree_with_depth(
        &self,
        root_dir: &Path,
        show_hidden: bool,
        max_depth: Option<usize>,
    ) -> Result<TreeNode> {
        self.build_filesystem_tree_recursive(root_dir, show_hidden, max_depth)
            .await
    }

    async fn build_filesystem_tree_recursive(
        &self,
        dir: &Path,
        show_hidden: bool,
        max_depth: Option<usize>,
    ) -> Result<TreeNode> {
        // Get directory name for display
        let dir_name = dir
            .file_name()
            .map(|n| n.to_string_lossy().to_string())
            .unwrap_or_else(|| dir.to_string_lossy().to_string());

        // Try to find an index file in this directory to get title/description
        let (name, description, index_path) =
            if let Ok(Some(index)) = self.find_any_index_in_dir(dir).await {
                if let Ok(parsed) = self.parse_index(&index).await {
                    let title = parsed.frontmatter.title.unwrap_or_else(|| dir_name.clone());
                    (title, parsed.frontmatter.description, Some(index))
                } else {
                    (dir_name.clone(), None, Some(index))
                }
            } else {
                (dir_name.clone(), None, None)
            };

        // The path to use - if there's an index, use it; otherwise use the directory
        let node_path = index_path.unwrap_or_else(|| dir.to_path_buf());

        // Check if we've hit depth limit
        let at_depth_limit = max_depth.map(|d| d == 0).unwrap_or(false);

        // List all entries in this directory
        let mut children = Vec::new();
        if let Ok(entries) = self.fs.list_files(dir).await {
            let mut entries: Vec<_> = entries.into_iter().collect();
            entries.sort(); // Sort alphabetically

            // Filter out hidden files first to get accurate count
            let entries: Vec<_> = entries
                .into_iter()
                .filter(|entry| {
                    let file_name = entry
                        .file_name()
                        .map(|n| n.to_string_lossy().to_string())
                        .unwrap_or_default();
                    show_hidden || !file_name.starts_with('.')
                })
                .collect();

            // If at depth limit, show truncation indicator
            if at_depth_limit && !entries.is_empty() {
                children.push(TreeNode {
                    name: format!("... ({} more)", entries.len()),
                    description: None,
                    path: node_path.clone(),
                    children: Vec::new(),
                });
            } else {
                let next_depth = max_depth.map(|d| d.saturating_sub(1));

                for entry in entries {
                    let file_name = entry
                        .file_name()
                        .map(|n| n.to_string_lossy().to_string())
                        .unwrap_or_default();

                    if self.fs.is_dir(&entry).await {
                        // Recurse into subdirectory with decremented depth
                        if let Ok(child_tree) = Box::pin(self.build_filesystem_tree_recursive(
                            &entry,
                            show_hidden,
                            next_depth,
                        ))
                        .await
                        {
                            children.push(child_tree);
                        }
                    } else {
                        // It's a file - skip index files (already represented by parent dir)
                        if self.is_index_file(&entry).await {
                            continue;
                        }

                        // Get title from frontmatter if it's a markdown file
                        let (file_title, file_desc) =
                            if entry.extension().is_some_and(|e| e == "md") {
                                if let Ok(parsed) = self.parse_index(&entry).await {
                                    (
                                        parsed.frontmatter.title.unwrap_or(file_name.clone()),
                                        parsed.frontmatter.description,
                                    )
                                } else {
                                    (file_name.clone(), None)
                                }
                            } else {
                                (file_name.clone(), None)
                            };

                        children.push(TreeNode {
                            name: file_title,
                            description: file_desc,
                            path: entry,
                            children: Vec::new(),
                        });
                    }
                }
            }
        }

        Ok(TreeNode {
            name,
            description,
            path: node_path,
            children,
        })
    }

    /// Format tree for display (like the `tree` command)
    pub fn format_tree(&self, node: &TreeNode, prefix: &str) -> String {
        let mut result = String::new();

        // Add the current node (root has no connector)
        result.push_str(prefix);
        result.push_str(&node.name);

        // Add description if present
        if let Some(ref desc) = node.description {
            result.push_str(" - ");
            result.push_str(desc);
        }
        result.push('\n');

        // Add children
        let child_count = node.children.len();
        for (i, child) in node.children.iter().enumerate() {
            let is_last_child = i == child_count - 1;
            let connector = if is_last_child {
                "└── "
            } else {
                "├── "
            };
            let child_prefix = if is_last_child { "    " } else { "│   " };

            result.push_str(prefix);
            result.push_str(connector);
            result.push_str(&format_tree_node(
                child,
                &format!("{}{}", prefix, child_prefix),
            ));
        }

        result
    }

    /// Get workspace info as formatted string
    pub async fn workspace_info(&self, root_path: &Path) -> Result<String> {
        self.workspace_info_with_depth(root_path, None).await
    }

    /// Get workspace info as formatted string with depth limit
    /// `max_depth` of None means unlimited
    pub async fn workspace_info_with_depth(
        &self,
        root_path: &Path,
        max_depth: Option<usize>,
    ) -> Result<String> {
        let mut visited = HashSet::new();
        let tree = self
            .build_tree_with_depth(root_path, max_depth, &mut visited)
            .await?;
        Ok(self.format_tree(&tree, "").trim_end().to_string())
    }

    // ==================== Frontmatter Helper Methods ====================
    // These are internal helpers for manipulating frontmatter in workspace operations

    /// Get a frontmatter property from a file
    async fn get_frontmatter_property(&self, path: &Path, key: &str) -> Result<Option<Value>> {
        let content = match self.fs.read_to_string(path).await {
            Ok(c) => c,
            Err(e) if e.kind() == std::io::ErrorKind::NotFound => return Ok(None),
            Err(e) => {
                return Err(DiaryxError::FileRead {
                    path: path.to_path_buf(),
                    source: e,
                });
            }
        };

        if !content.starts_with("---\n") && !content.starts_with("---\r\n") {
            return Ok(None);
        }

        let rest = &content[4..];
        let end_idx = rest.find("\n---\n").or_else(|| rest.find("\n---\r\n"));

        if let Some(idx) = end_idx {
            let frontmatter_str = &rest[..idx];
            let frontmatter: indexmap::IndexMap<String, Value> =
                serde_yaml::from_str(frontmatter_str)?;
            Ok(frontmatter.get(key).cloned())
        } else {
            Ok(None)
        }
    }

    /// Set a frontmatter property in a file
    pub async fn set_frontmatter_property(
        &self,
        path: &Path,
        key: &str,
        value: Value,
    ) -> Result<()> {
        let content = match self.fs.read_to_string(path).await {
            Ok(c) => c,
            Err(e) if e.kind() == std::io::ErrorKind::NotFound => {
                // Create new file with just this property
                let mut frontmatter = indexmap::IndexMap::new();
                frontmatter.insert(key.to_string(), value);
                let yaml_str = serde_yaml::to_string(&frontmatter)?;
                let new_content = format!("---\n{}---\n", yaml_str);
                return self.fs.write_file(path, &new_content).await.map_err(|e| {
                    DiaryxError::FileWrite {
                        path: path.to_path_buf(),
                        source: e,
                    }
                });
            }
            Err(e) => {
                return Err(DiaryxError::FileRead {
                    path: path.to_path_buf(),
                    source: e,
                });
            }
        };

        let (mut frontmatter, body) = if content.starts_with("---\n")
            || content.starts_with("---\r\n")
        {
            let rest = &content[4..];
            if let Some(idx) = rest.find("\n---\n").or_else(|| rest.find("\n---\r\n")) {
                let frontmatter_str = &rest[..idx];
                let body = &rest[idx + 5..];
                let fm: indexmap::IndexMap<String, Value> = serde_yaml::from_str(frontmatter_str)?;
                (fm, body.to_string())
            } else {
                (indexmap::IndexMap::new(), content)
            }
        } else {
            (indexmap::IndexMap::new(), content)
        };

        frontmatter.insert(key.to_string(), value);
        let yaml_str = serde_yaml::to_string(&frontmatter)?;
        let new_content = format!("---\n{}---\n{}", yaml_str, body);

        self.fs
            .write_file(path, &new_content)
            .await
            .map_err(|e| DiaryxError::FileWrite {
                path: path.to_path_buf(),
                source: e,
            })
    }

    /// Remove a frontmatter property from a file
    async fn remove_frontmatter_property(&self, path: &Path, key: &str) -> Result<()> {
        let content = match self.fs.read_to_string(path).await {
            Ok(c) => c,
            Err(_) => return Ok(()), // File doesn't exist, nothing to remove
        };

        if !content.starts_with("---\n") && !content.starts_with("---\r\n") {
            return Ok(()); // No frontmatter
        }

        let rest = &content[4..];
        let end_idx = match rest.find("\n---\n").or_else(|| rest.find("\n---\r\n")) {
            Some(idx) => idx,
            None => return Ok(()), // Malformed frontmatter
        };

        let frontmatter_str = &rest[..end_idx];
        let body = &rest[end_idx + 5..];

        let mut frontmatter: indexmap::IndexMap<String, Value> =
            serde_yaml::from_str(frontmatter_str)?;
        frontmatter.shift_remove(key);

        let yaml_str = serde_yaml::to_string(&frontmatter)?;
        let new_content = format!("---\n{}---\n{}", yaml_str, body);

        self.fs
            .write_file(path, &new_content)
            .await
            .map_err(|e| DiaryxError::FileWrite {
                path: path.to_path_buf(),
                source: e,
            })
    }

    /// Normalize a path string by stripping leading "./" prefix
    fn normalize_contents_path(path: &str) -> &str {
        path.strip_prefix("./").unwrap_or(path)
    }

    /// Add an entry to an index's contents list
    pub async fn add_to_index_contents(&self, index_path: &Path, entry: &str) -> Result<bool> {
        // Normalize the entry path (strip leading ./)
        let normalized_entry = Self::normalize_contents_path(entry);

        match self.get_frontmatter_property(index_path, "contents").await {
            Ok(Some(Value::Sequence(mut items))) => {
                // Check if entry already exists (comparing normalized forms)
                let already_exists = items.iter().any(|item| {
                    if let Some(s) = item.as_str() {
                        Self::normalize_contents_path(s) == normalized_entry
                    } else {
                        false
                    }
                });

                if !already_exists {
                    items.push(Value::String(normalized_entry.to_string()));
                    // Sort contents for consistent ordering
                    items.sort_by(|a, b| {
                        let a_str = a.as_str().unwrap_or("");
                        let b_str = b.as_str().unwrap_or("");
                        a_str.cmp(b_str)
                    });
                    self.set_frontmatter_property(index_path, "contents", Value::Sequence(items))
                        .await?;
                    return Ok(true);
                }
                Ok(false)
            }
            Ok(None) => {
                // Create contents with just this entry (normalized)
                let items = vec![Value::String(normalized_entry.to_string())];
                self.set_frontmatter_property(index_path, "contents", Value::Sequence(items))
                    .await?;
                Ok(true)
            }
            _ => {
                // Contents exists but isn't a sequence, or error reading - skip
                Ok(false)
            }
        }
    }

    /// Remove an entry from an index's contents list
    async fn remove_from_index_contents(&self, index_path: &Path, entry: &str) -> Result<bool> {
        // Normalize the entry path for comparison
        let normalized_entry = Self::normalize_contents_path(entry);

        match self.get_frontmatter_property(index_path, "contents").await {
            Ok(Some(Value::Sequence(mut items))) => {
                let before_len = items.len();
                // Remove entries that match when normalized
                items.retain(|item| {
                    if let Some(s) = item.as_str() {
                        Self::normalize_contents_path(s) != normalized_entry
                    } else {
                        true
                    }
                });

                if items.len() != before_len {
                    // Sort contents for consistent ordering
                    items.sort_by(|a, b| {
                        let a_str = a.as_str().unwrap_or("");
                        let b_str = b.as_str().unwrap_or("");
                        a_str.cmp(b_str)
                    });
                    self.set_frontmatter_property(index_path, "contents", Value::Sequence(items))
                        .await?;
                    return Ok(true);
                }
                Ok(false)
            }
            Ok(None) | Ok(Some(_)) => {
                // No contents property or not a sequence - nothing to remove
                Ok(false)
            }
            Err(_) => {
                // Error reading - skip
                Ok(false)
            }
        }
    }

    // ==================== Entry Management Methods ====================

    /// Attach an entry to a parent index, creating bidirectional links.
    ///
    /// This method:
    /// - Adds the entry to the parent index's `contents` list (relative to parent's directory)
    /// - Sets the entry's `part_of` property to point to the parent index (relative to entry)
    ///
    /// Both paths must exist.
    pub async fn attach_entry_to_parent(
        &self,
        entry_path: &Path,
        parent_index_path: &Path,
    ) -> Result<()> {
        use crate::path_utils::{
            relative_path_from_dir_to_target, relative_path_from_file_to_target,
        };

        // Validate both paths exist
        if !self.fs.exists(entry_path).await {
            return Err(DiaryxError::FileRead {
                path: entry_path.to_path_buf(),
                source: std::io::Error::new(std::io::ErrorKind::NotFound, "Entry does not exist"),
            });
        }
        if !self.fs.exists(parent_index_path).await {
            return Err(DiaryxError::FileRead {
                path: parent_index_path.to_path_buf(),
                source: std::io::Error::new(
                    std::io::ErrorKind::NotFound,
                    "Parent index does not exist",
                ),
            });
        }

        // Calculate relative path from parent's directory to entry
        let parent_dir = parent_index_path.parent().unwrap_or_else(|| Path::new(""));
        let child_rel = relative_path_from_dir_to_target(parent_dir, entry_path);

        // Add entry to parent's contents
        self.add_to_index_contents(parent_index_path, &child_rel)
            .await?;

        // Calculate relative path from entry to parent index
        let parent_rel = relative_path_from_file_to_target(entry_path, parent_index_path);

        // Set entry's part_of
        self.set_frontmatter_property(entry_path, "part_of", Value::String(parent_rel))
            .await?;

        Ok(())
    }

    /// Move/rename an entry while updating workspace index references.
    ///
    /// This method:
    /// - Moves the file from `from_path` to `to_path`
    /// - Removes the entry from old parent's `contents` (if parent index exists)
    /// - Adds the entry to new parent's `contents` (if parent index exists)
    /// - Updates the moved file's `part_of` to point to new parent index
    ///
    /// Returns `Ok(())` if successful. Does nothing if source equals destination.
    pub async fn move_entry(&self, from_path: &Path, to_path: &Path) -> Result<()> {
        use crate::path_utils::relative_path_from_file_to_target;

        // No-op if same path
        if from_path == to_path {
            return Ok(());
        }

        // Get filenames and parent directories before moving
        let old_parent = from_path.parent().ok_or_else(|| DiaryxError::InvalidPath {
            path: from_path.to_path_buf(),
            message: "No parent directory for source path".to_string(),
        })?;
        let old_file_name = from_path
            .file_name()
            .and_then(|n| n.to_str())
            .ok_or_else(|| DiaryxError::InvalidPath {
                path: from_path.to_path_buf(),
                message: "Invalid source file name".to_string(),
            })?
            .to_string();

        let new_parent = to_path.parent().ok_or_else(|| DiaryxError::InvalidPath {
            path: to_path.to_path_buf(),
            message: "No parent directory for destination path".to_string(),
        })?;
        let new_file_name = to_path
            .file_name()
            .and_then(|n| n.to_str())
            .ok_or_else(|| DiaryxError::InvalidPath {
                path: to_path.to_path_buf(),
                message: "Invalid destination file name".to_string(),
            })?
            .to_string();

        // Move the file
        self.fs
            .move_file(from_path, to_path)
            .await
            .map_err(|e| DiaryxError::FileWrite {
                path: to_path.to_path_buf(),
                source: e,
            })?;

        // Remove from old parent's contents (if old parent has an index)
        if let Ok(Some(old_index_path)) = self.find_any_index_in_dir(old_parent).await {
            let _ = self
                .remove_from_index_contents(&old_index_path, &old_file_name)
                .await;
        }

        // Add to new parent's contents and update part_of (if new parent has an index)
        if let Ok(Some(new_index_path)) = self.find_any_index_in_dir(new_parent).await {
            let _ = self
                .add_to_index_contents(&new_index_path, &new_file_name)
                .await;

            // Update moved entry's part_of
            let rel_part_of = relative_path_from_file_to_target(to_path, &new_index_path);
            let _ = self
                .set_frontmatter_property(to_path, "part_of", Value::String(rel_part_of))
                .await;
        }

        Ok(())
    }

    /// Delete an entry while updating workspace index references.
    ///
    /// This method:
    /// - Fails if the entry is an index with non-empty `contents` (has children)
    /// - Removes the entry from parent's `contents` (if parent index exists)
    /// - Deletes the file
    ///
    /// For index files with directories, only the file is deleted (not the directory).
    pub async fn delete_entry(&self, path: &Path) -> Result<()> {
        // Check if this is an index file with children
        if let Ok(index) = self.parse_index(path).await {
            let contents = index.frontmatter.contents_list();
            if !contents.is_empty() {
                return Err(DiaryxError::InvalidPath {
                    path: path.to_path_buf(),
                    message: format!(
                        "Cannot delete index with {} children. Delete children first.",
                        contents.len()
                    ),
                });
            }
        }

        // Get the filename and parent directory
        let parent = path.parent().ok_or_else(|| DiaryxError::InvalidPath {
            path: path.to_path_buf(),
            message: "No parent directory".to_string(),
        })?;
        let file_name = path
            .file_name()
            .and_then(|n| n.to_str())
            .ok_or_else(|| DiaryxError::InvalidPath {
                path: path.to_path_buf(),
                message: "Invalid file name".to_string(),
            })?
            .to_string();

        // Remove from parent's contents (if parent has an index)
        if let Ok(Some(index_path)) = self.find_any_index_in_dir(parent).await {
            let _ = self
                .remove_from_index_contents(&index_path, &file_name)
                .await;
        }

        // Delete the file
        self.fs
            .delete_file(path)
            .await
            .map_err(|e| DiaryxError::FileWrite {
                path: path.to_path_buf(),
                source: e,
            })?;

        Ok(())
    }

    /// Generate a unique filename for a new child entry in the given directory.
    ///
    /// Returns filenames like "new-entry.md", "new-entry-1.md", "new-entry-2.md", etc.
    pub async fn generate_unique_child_name(&self, parent_dir: &Path) -> String {
        let base_name = "new-entry";
        let mut candidate = format!("{}.md", base_name);
        let mut counter = 1;

        while self.fs.exists(&parent_dir.join(&candidate)).await {
            candidate = format!("{}-{}.md", base_name, counter);
            counter += 1;
        }

        candidate
    }

    /// Create a new child entry under a parent index.
    ///
    /// This method:
    /// - Generates a unique filename if not provided
    /// - Creates the child file with basic frontmatter
    /// - Adds the child to the parent's `contents`
    /// - Sets the child's `part_of` to point to the parent
    ///
    /// Returns the path to the new child entry.
    pub async fn create_child_entry(
        &self,
        parent_index_path: &Path,
        title: Option<&str>,
    ) -> Result<PathBuf> {
        use crate::path_utils::relative_path_from_file_to_target;

        // Parse parent - if it's a leaf (not an index), convert it to an index first
        let effective_parent = if let Ok(parent_index) = self.parse_index(parent_index_path).await {
            if parent_index.frontmatter.is_index() {
                parent_index_path.to_path_buf()
            } else {
                // Parent is a leaf file - convert to index first
                self.convert_to_index(parent_index_path).await?
            }
        } else {
            // Parent doesn't exist or couldn't be parsed - try to convert anyway
            // (convert_to_index will fail with a proper error if file doesn't exist)
            return Err(DiaryxError::FileRead {
                path: parent_index_path.to_path_buf(),
                source: std::io::Error::new(std::io::ErrorKind::NotFound, "Parent file not found"),
            });
        };

        // Determine parent directory (from effective parent, which may have moved)
        let parent_dir = effective_parent
            .parent()
            .ok_or_else(|| DiaryxError::InvalidPath {
                path: effective_parent.clone(),
                message: "Parent index has no directory".to_string(),
            })?;

        // Generate unique filename
        let child_filename = self.generate_unique_child_name(parent_dir).await;
        let child_path = parent_dir.join(&child_filename);

        // Calculate relative path from child to parent
        let parent_rel = relative_path_from_file_to_target(&child_path, &effective_parent);

        // Create child file with frontmatter
        let display_title = title.unwrap_or("New Entry");
        let content = format!(
            "---\ntitle: {}\npart_of: {}\n---\n\n# {}\n\n",
            display_title, parent_rel, display_title
        );

        self.fs
            .create_new(&child_path, &content)
            .await
            .map_err(|e| DiaryxError::FileWrite {
                path: child_path.clone(),
                source: e,
            })?;

        // Add to parent's contents
        self.add_to_index_contents(&effective_parent, &child_filename)
            .await?;

        Ok(child_path)
    }

    /// Rename an entry file by giving it a new filename.
    ///
    /// This method handles both leaf files and index files:
    /// - Leaf files: renames the file directly and updates parent `contents`
    /// - Index files: renames the containing directory AND the file itself, updates grandparent `contents`
    ///
    /// Returns the new path to the renamed file.
    pub async fn rename_entry(&self, path: &Path, new_filename: &str) -> Result<PathBuf> {
        let is_index = self.is_index_file(path).await;

        if is_index {
            // For index files, we rename the containing directory AND the file
            let current_dir = path.parent().ok_or_else(|| DiaryxError::InvalidPath {
                path: path.to_path_buf(),
                message: "Index file has no parent directory".to_string(),
            })?;

            let parent_of_dir = current_dir
                .parent()
                .ok_or_else(|| DiaryxError::InvalidPath {
                    path: path.to_path_buf(),
                    message: "Directory has no parent".to_string(),
                })?;

            // Get new directory name from the filename (strip .md extension)
            let new_dir_name = new_filename.trim_end_matches(".md");
            let new_dir_path = parent_of_dir.join(new_dir_name);
            // New file will be named {dirname}.md
            let new_file_path = new_dir_path.join(new_filename);

            // Don't rename if same path
            if new_dir_path == current_dir {
                return Ok(path.to_path_buf());
            }

            // Check if target directory already exists
            if self.fs.exists(&new_dir_path).await {
                return Err(DiaryxError::InvalidPath {
                    path: new_dir_path,
                    message: "Target directory already exists".to_string(),
                });
            }

            // Create new directory
            self.fs.create_dir_all(&new_dir_path).await?;

            // Move all files from old directory to new directory and track children
            let mut children_paths: Vec<PathBuf> = Vec::new();
            if let Ok(files) = self.fs.list_files(current_dir).await {
                for file in files {
                    let file_name = file.file_name().unwrap_or_default();
                    let new_path = new_dir_path.join(file_name);

                    // If this is the index file itself, use the new filename
                    if file == path {
                        self.fs.move_file(&file, &new_file_path).await?;
                    } else {
                        self.fs.move_file(&file, &new_path).await?;
                        children_paths.push(new_path);
                    }
                }
            }

            // Update all children's part_of to point to new index
            for child_path in &children_paths {
                use crate::path_utils::relative_path_from_file_to_target;
                let new_part_of = relative_path_from_file_to_target(child_path, &new_file_path);
                let _ = self
                    .set_frontmatter_property(child_path, "part_of", Value::String(new_part_of))
                    .await;
            }

            // Update grandparent's contents if it exists
            if let Ok(Some(grandparent_index)) = self.find_any_index_in_dir(parent_of_dir).await {
                let old_dir_name = current_dir
                    .file_name()
                    .and_then(|n| n.to_str())
                    .unwrap_or_default();

                // Calculate relative paths for old and new entries
                let old_rel = format!("{}/{}.md", old_dir_name, old_dir_name);
                let new_rel = format!("{}/{}", new_dir_name, new_filename);

                let _ = self
                    .remove_from_index_contents(&grandparent_index, &old_rel)
                    .await;
                let _ = self
                    .add_to_index_contents(&grandparent_index, &new_rel)
                    .await;
            }

            Ok(new_file_path)
        } else {
            // For leaf files, simple rename within the same directory
            let parent = path.parent().ok_or_else(|| DiaryxError::InvalidPath {
                path: path.to_path_buf(),
                message: "File has no parent directory".to_string(),
            })?;

            let old_filename = path
                .file_name()
                .and_then(|n| n.to_str())
                .ok_or_else(|| DiaryxError::InvalidPath {
                    path: path.to_path_buf(),
                    message: "Invalid file name".to_string(),
                })?
                .to_string();

            let new_path = parent.join(new_filename);

            // Don't rename if same path
            if new_path == path {
                return Ok(path.to_path_buf());
            }

            // Check if target already exists
            if self.fs.exists(&new_path).await {
                return Err(DiaryxError::InvalidPath {
                    path: new_path,
                    message: "Target file already exists".to_string(),
                });
            }

            // Move the file
            self.fs.move_file(path, &new_path).await?;

            // Update parent's contents if it exists
            if let Ok(Some(parent_index)) = self.find_any_index_in_dir(parent).await {
                let _ = self
                    .remove_from_index_contents(&parent_index, &old_filename)
                    .await;
                let _ = self
                    .add_to_index_contents(&parent_index, new_filename)
                    .await;
            }

            Ok(new_path)
        }
    }

    /// Duplicate an entry, creating a copy with a unique name.
    ///
    /// This method:
    /// - For leaf files: copies the file with a "-copy" suffix (or "-copy-N" if exists)
    /// - For index files: copies the entire directory structure recursively
    /// - Updates the copy's `part_of` to point to the same parent
    /// - Adds the copy to the parent's `contents`
    ///
    /// Returns the path to the new duplicated entry.
    pub async fn duplicate_entry(&self, source_path: &Path) -> Result<PathBuf> {
        use crate::path_utils::relative_path_from_file_to_target;

        let is_index = self.is_index_file(source_path).await;

        if is_index {
            // For index files, we duplicate the entire directory
            let source_dir = source_path
                .parent()
                .ok_or_else(|| DiaryxError::InvalidPath {
                    path: source_path.to_path_buf(),
                    message: "Index file has no parent directory".to_string(),
                })?;

            let parent_of_dir = source_dir
                .parent()
                .ok_or_else(|| DiaryxError::InvalidPath {
                    path: source_path.to_path_buf(),
                    message: "Directory has no parent".to_string(),
                })?;

            // Get source directory name and generate unique copy name
            let source_dir_name =
                source_dir
                    .file_name()
                    .and_then(|n| n.to_str())
                    .ok_or_else(|| DiaryxError::InvalidPath {
                        path: source_path.to_path_buf(),
                        message: "Invalid directory name".to_string(),
                    })?;

            let new_dir_name = self
                .generate_unique_copy_name(parent_of_dir, source_dir_name, false)
                .await;
            let new_dir_path = parent_of_dir.join(&new_dir_name);
            let new_index_path = new_dir_path.join(format!("{}.md", new_dir_name));

            // Create new directory
            self.fs.create_dir_all(&new_dir_path).await?;

            // Copy all files from source directory to new directory
            if let Ok(files) = self.fs.list_files(source_dir).await {
                for file in files {
                    let file_name = file
                        .file_name()
                        .and_then(|n| n.to_str())
                        .unwrap_or_default();

                    // For the index file, use the new directory name
                    let new_path = if file == source_path {
                        new_index_path.clone()
                    } else {
                        new_dir_path.join(file_name)
                    };

                    // Copy file content
                    let content =
                        self.fs
                            .read_to_string(&file)
                            .await
                            .map_err(|e| DiaryxError::FileRead {
                                path: file.clone(),
                                source: e,
                            })?;
                    self.fs.write_file(&new_path, &content).await.map_err(|e| {
                        DiaryxError::FileWrite {
                            path: new_path.clone(),
                            source: e,
                        }
                    })?;

                    // Update part_of for child files to point to new index
                    if new_path != new_index_path {
                        let new_part_of =
                            relative_path_from_file_to_target(&new_path, &new_index_path);
                        let _ = self
                            .set_frontmatter_property(
                                &new_path,
                                "part_of",
                                Value::String(new_part_of),
                            )
                            .await;
                    }
                }
            }

            // Update the copied index's part_of to point to grandparent (same as source)
            if let Ok(Some(grandparent_index)) = self.find_any_index_in_dir(parent_of_dir).await {
                let new_part_of =
                    relative_path_from_file_to_target(&new_index_path, &grandparent_index);
                let _ = self
                    .set_frontmatter_property(
                        &new_index_path,
                        "part_of",
                        Value::String(new_part_of),
                    )
                    .await;

                // Add to grandparent's contents
                let rel_path = format!("{}/{}.md", new_dir_name, new_dir_name);
                let _ = self
                    .add_to_index_contents(&grandparent_index, &rel_path)
                    .await;
            }

            Ok(new_index_path)
        } else {
            // For leaf files, simple copy in same directory
            let parent = source_path
                .parent()
                .ok_or_else(|| DiaryxError::InvalidPath {
                    path: source_path.to_path_buf(),
                    message: "File has no parent directory".to_string(),
                })?;

            let source_filename = source_path
                .file_name()
                .and_then(|n| n.to_str())
                .ok_or_else(|| DiaryxError::InvalidPath {
                    path: source_path.to_path_buf(),
                    message: "Invalid file name".to_string(),
                })?;

            // Generate unique copy name
            let new_filename = self
                .generate_unique_copy_name(parent, source_filename, true)
                .await;
            let new_path = parent.join(&new_filename);

            // Copy file content
            let content =
                self.fs
                    .read_to_string(source_path)
                    .await
                    .map_err(|e| DiaryxError::FileRead {
                        path: source_path.to_path_buf(),
                        source: e,
                    })?;
            self.fs
                .write_file(&new_path, &content)
                .await
                .map_err(|e| DiaryxError::FileWrite {
                    path: new_path.clone(),
                    source: e,
                })?;

            // Update parent's contents if it exists
            if let Ok(Some(parent_index)) = self.find_any_index_in_dir(parent).await {
                // Update part_of to point to parent
                let new_part_of = relative_path_from_file_to_target(&new_path, &parent_index);
                let _ = self
                    .set_frontmatter_property(&new_path, "part_of", Value::String(new_part_of))
                    .await;

                // Add to parent's contents
                let _ = self
                    .add_to_index_contents(&parent_index, &new_filename)
                    .await;
            }

            Ok(new_path)
        }
    }

    /// Generate a unique copy name for a file or directory.
    ///
    /// For files: "name.md" → "name-copy.md", "name-copy-2.md", etc.
    /// For directories: "name" → "name-copy", "name-copy-2", etc.
    async fn generate_unique_copy_name(
        &self,
        parent_dir: &Path,
        original_name: &str,
        is_file: bool,
    ) -> String {
        let (base_name, extension) = if is_file {
            // Strip .md extension for files
            let base = original_name.trim_end_matches(".md");
            (base.to_string(), ".md".to_string())
        } else {
            (original_name.to_string(), String::new())
        };

        // Try "name-copy" first
        let mut candidate = format!("{}-copy{}", base_name, extension);
        let mut counter = 2;

        while self.fs.exists(&parent_dir.join(&candidate)).await {
            candidate = format!("{}-copy-{}{}", base_name, counter, extension);
            counter += 1;
        }

        candidate
    }

    /// Convert a leaf file into an index file with a directory.
    ///
    /// This method:
    /// - Creates a directory with the same name as the file (without .md)
    /// - Moves the file into the directory as `{dirname}.md`
    /// - Adds empty `contents` property to the file
    ///
    /// Example: `journal/my-note.md` → `journal/my-note/my-note.md`
    ///
    /// Returns the new path to the index file.
    pub async fn convert_to_index(&self, path: &Path) -> Result<PathBuf> {
        // Check if already an index
        if self.is_index_file(path).await {
            return Err(DiaryxError::InvalidPath {
                path: path.to_path_buf(),
                message: "File is already an index".to_string(),
            });
        }

        let parent = path.parent().ok_or_else(|| DiaryxError::InvalidPath {
            path: path.to_path_buf(),
            message: "File has no parent directory".to_string(),
        })?;

        let file_stem =
            path.file_stem()
                .and_then(|s| s.to_str())
                .ok_or_else(|| DiaryxError::InvalidPath {
                    path: path.to_path_buf(),
                    message: "Invalid file name".to_string(),
                })?;

        let old_filename = path
            .file_name()
            .and_then(|n| n.to_str())
            .ok_or_else(|| DiaryxError::InvalidPath {
                path: path.to_path_buf(),
                message: "Invalid file name".to_string(),
            })?
            .to_string();

        // Create new directory and file paths
        let new_dir = parent.join(file_stem);
        let new_filename = format!("{}.md", file_stem);
        let new_path = new_dir.join(&new_filename);

        // Create directory
        self.fs.create_dir_all(&new_dir).await?;

        // Move file into directory
        self.fs.move_file(path, &new_path).await?;

        // Add contents property
        self.set_frontmatter_property(&new_path, "contents", Value::Sequence(vec![]))
            .await?;

        // Update part_of path since file moved one level deeper
        if let Ok(Some(Value::String(old_part_of))) =
            self.get_frontmatter_property(&new_path, "part_of").await
        {
            use crate::path_utils::{normalize_path, relative_path_from_file_to_target};

            // Resolve the old relative path to absolute (from the original location)
            let target_path = normalize_path(&parent.join(&old_part_of));

            // Calculate new relative path from the new location
            let new_part_of = relative_path_from_file_to_target(&new_path, &target_path);

            let _ = self
                .set_frontmatter_property(&new_path, "part_of", Value::String(new_part_of))
                .await;
        }

        // Update parent's contents to point to new location
        if let Ok(Some(parent_index)) = self.find_any_index_in_dir(parent).await {
            let _ = self
                .remove_from_index_contents(&parent_index, &old_filename)
                .await;
            let new_rel = format!("{}/{}", file_stem, new_filename);
            let _ = self.add_to_index_contents(&parent_index, &new_rel).await;
        }

        Ok(new_path)
    }

    /// Convert an empty index file back to a leaf file.
    ///
    /// This method:
    /// - Fails if the index has non-empty `contents`
    /// - Moves `dir/{name}.md` → `parent/dir.md`
    /// - Removes the now-empty directory
    /// - Removes the `contents` property
    ///
    /// Example: `journal/my-note/my-note.md` → `journal/my-note.md`
    ///
    /// Returns the new path to the leaf file.
    pub async fn convert_to_leaf(&self, path: &Path) -> Result<PathBuf> {
        // Check if this is an index with empty contents
        let index = self.parse_index(path).await?;
        let contents = index.frontmatter.contents_list();
        if !contents.is_empty() {
            return Err(DiaryxError::InvalidPath {
                path: path.to_path_buf(),
                message: format!(
                    "Cannot convert index with {} children to leaf",
                    contents.len()
                ),
            });
        }

        let current_dir = path.parent().ok_or_else(|| DiaryxError::InvalidPath {
            path: path.to_path_buf(),
            message: "File has no parent directory".to_string(),
        })?;

        let parent_of_dir = current_dir
            .parent()
            .ok_or_else(|| DiaryxError::InvalidPath {
                path: path.to_path_buf(),
                message: "Directory has no parent".to_string(),
            })?;

        let dir_name = current_dir
            .file_name()
            .and_then(|n| n.to_str())
            .ok_or_else(|| DiaryxError::InvalidPath {
                path: current_dir.to_path_buf(),
                message: "Invalid directory name".to_string(),
            })?;

        let new_filename = format!("{}.md", dir_name);
        let new_path = parent_of_dir.join(&new_filename);

        // Check if target already exists
        if self.fs.exists(&new_path).await {
            return Err(DiaryxError::InvalidPath {
                path: new_path,
                message: "Target file already exists".to_string(),
            });
        }

        // Move file out of directory
        self.fs.move_file(path, &new_path).await?;

        // Remove contents property
        let _ = self
            .remove_frontmatter_property(&new_path, "contents")
            .await;

        // Update part_of path since file moved one level up
        if let Ok(Some(Value::String(old_part_of))) =
            self.get_frontmatter_property(&new_path, "part_of").await
        {
            use crate::path_utils::{normalize_path, relative_path_from_file_to_target};

            // Resolve the old relative path to absolute (from the original location)
            let target_path = normalize_path(&current_dir.join(&old_part_of));

            // Calculate new relative path from the new location
            let new_part_of = relative_path_from_file_to_target(&new_path, &target_path);

            let _ = self
                .set_frontmatter_property(&new_path, "part_of", Value::String(new_part_of))
                .await;
        }

        // Update grandparent's contents
        if let Ok(Some(grandparent_index)) = self.find_any_index_in_dir(parent_of_dir).await {
            let old_rel = format!("{}/{}.md", dir_name, dir_name);
            let _ = self
                .remove_from_index_contents(&grandparent_index, &old_rel)
                .await;
            let _ = self
                .add_to_index_contents(&grandparent_index, &new_filename)
                .await;
        }

        Ok(new_path)
    }

    /// Attach an entry to a parent, converting the parent to an index if needed,
    /// and moving the entry file into the parent's directory.
    ///
    /// This is a higher-level operation that combines:
    /// 1. Convert parent to index if it's a leaf
    /// 2. Move entry into parent's directory
    /// 3. Create bidirectional links (contents and part_of)
    ///
    /// Returns the new path to the entry after any moves.
    pub async fn attach_and_move_entry_to_parent(
        &self,
        entry: &Path,
        parent: &Path,
    ) -> Result<PathBuf> {
        // Check if parent needs to be converted to index
        let parent_is_index = self.is_index_file(parent).await;

        let effective_parent = if parent_is_index {
            parent.to_path_buf()
        } else {
            // Convert parent to index first
            self.convert_to_index(parent).await?
        };

        // Get parent directory
        let parent_dir = effective_parent
            .parent()
            .ok_or_else(|| DiaryxError::InvalidPath {
                path: effective_parent.clone(),
                message: "Parent index has no directory".to_string(),
            })?;

        // Get entry filename
        let entry_filename =
            entry
                .file_name()
                .and_then(|n| n.to_str())
                .ok_or_else(|| DiaryxError::InvalidPath {
                    path: entry.to_path_buf(),
                    message: "Invalid entry filename".to_string(),
                })?;

        // Calculate new path for entry
        let new_entry_path = parent_dir.join(entry_filename);

        // Move entry if not already in parent directory
        if entry.parent() != Some(parent_dir) {
            self.move_entry(entry, &new_entry_path).await?;
        }

        // Attach entry to parent (creates bidirectional links)
        self.attach_entry_to_parent(&new_entry_path, &effective_parent)
            .await?;

        Ok(new_entry_path)
    }
}

#[cfg(test)]
mod tests {
    use super::*;
    use crate::fs::{FileSystem, InMemoryFileSystem, SyncToAsyncFs, block_on_test};

    type TestFs = SyncToAsyncFs<InMemoryFileSystem>;

    fn make_test_fs() -> TestFs {
        SyncToAsyncFs::new(InMemoryFileSystem::new())
    }

    #[test]
    fn test_index_frontmatter_is_root() {
        let root_fm = IndexFrontmatter {
            title: Some("Root".to_string()),
            description: None,
            contents: Some(vec![]),
            part_of: None,
            audience: None,
            attachments: None,
            extra: std::collections::HashMap::new(),
        };
        assert!(root_fm.is_root());
        assert!(root_fm.is_index());

        let non_root_fm = IndexFrontmatter {
            title: Some("Non-root".to_string()),
            description: None,
            contents: Some(vec![]),
            part_of: Some("../parent.md".to_string()),
            audience: None,
            attachments: None,
            extra: std::collections::HashMap::new(),
        };
        assert!(!non_root_fm.is_root());
        assert!(non_root_fm.is_index());
    }

    #[test]
    fn test_tree_node_formatting() {
        let tree = TreeNode {
            name: "Root".to_string(),
            description: Some("Root description".to_string()),
            path: PathBuf::from("root.md"),
            children: vec![
                TreeNode {
                    name: "Child 1".to_string(),
                    description: None,
                    path: PathBuf::from("child1.md"),
                    children: vec![],
                },
                TreeNode {
                    name: "Child 2".to_string(),
                    description: Some("Child desc".to_string()),
                    path: PathBuf::from("child2.md"),
                    children: vec![],
                },
            ],
        };

        let fs = make_test_fs();
        let ws = Workspace::new(fs);
        let output = ws.format_tree(&tree, "");

        assert!(output.contains("Root - Root description"));
        assert!(output.contains("Child 1"));
        assert!(output.contains("Child 2 - Child desc"));
    }

    #[test]
    fn test_parse_index() {
        let fs = InMemoryFileSystem::new();
        fs.write_file(
            Path::new("test.md"),
            "---\ntitle: Test\ncontents: []\n---\n\nBody content",
        )
        .unwrap();

        let async_fs = SyncToAsyncFs::new(fs);
        let ws = Workspace::new(async_fs);

        let result = block_on_test(ws.parse_index(Path::new("test.md")));
        assert!(result.is_ok());

        let index = result.unwrap();
        assert_eq!(index.frontmatter.title, Some("Test".to_string()));
        assert!(index.frontmatter.is_index());
        assert!(index.body.contains("Body content"));
    }

    #[test]
    fn test_is_index_file() {
        let fs = InMemoryFileSystem::new();
        fs.write_file(
            Path::new("index.md"),
            "---\ntitle: Index\ncontents: []\n---\n",
        )
        .unwrap();
        fs.write_file(Path::new("leaf.md"), "---\ntitle: Leaf\n---\n")
            .unwrap();

        let async_fs = SyncToAsyncFs::new(fs);
        let ws = Workspace::new(async_fs);

        assert!(block_on_test(ws.is_index_file(Path::new("index.md"))));
        assert!(!block_on_test(ws.is_index_file(Path::new("leaf.md"))));
        assert!(!block_on_test(
            ws.is_index_file(Path::new("nonexistent.md"))
        ));
    }

    #[test]
    fn test_is_root_index() {
        let fs = InMemoryFileSystem::new();
        fs.write_file(
            Path::new("root.md"),
            "---\ntitle: Root\ncontents: []\n---\n",
        )
        .unwrap();
        fs.write_file(
            Path::new("child.md"),
            "---\ntitle: Child\ncontents: []\npart_of: root.md\n---\n",
        )
        .unwrap();

        let async_fs = SyncToAsyncFs::new(fs);
        let ws = Workspace::new(async_fs);

        assert!(block_on_test(ws.is_root_index(Path::new("root.md"))));
        assert!(!block_on_test(ws.is_root_index(Path::new("child.md"))));
    }
}