tngl 0.1.0

Repo-native TUI graph tool for code relationships
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
//! Round-trip-safe parser and writer for `graph.tngl`.
//!
//! The central invariant: `serialize(parse(input)?) == input` for any valid input.
//! This guarantees that hand-authored comments, blank lines, and whitespace alignment
//! are never disturbed by tooling.

use std::collections::HashSet;

use anyhow::{Context, Result, bail};

use crate::graph::model::{Edge, EdgeKind, Graph, Node};

// ---------------------------------------------------------------------------
// Document model
// ---------------------------------------------------------------------------

/// A single line from `graph.tngl`, classified and stored verbatim.
///
/// The raw string stored in each variant is the exact text of the line
/// (without the terminating `\n`). Serialising by joining with `\n` and
/// appending the original trailing-newline flag reproduces the original bytes.
#[derive(Debug, Clone, PartialEq, Eq)]
pub enum DocLine {
    /// A blank or whitespace-only line.
    Blank(String),
    /// A comment line (starts with `#` after trimming).
    Comment(String),
    /// A marker tag line (`[orphan]`, `[bundle]`, `[orphan bundle]`).
    Tag(String),
    /// A node declaration line (optionally indented for visual hierarchy).
    Node(String),
    /// An edge declaration (`->` or `--`, usually indented).
    Edge(String),
}

impl DocLine {
    /// The raw text of this line (no newline character).
    pub fn raw(&self) -> &str {
        match self {
            Self::Blank(s) | Self::Comment(s) | Self::Tag(s) | Self::Node(s) | Self::Edge(s) => s,
        }
    }

    /// The semantic path for a Node line, or `None`.
    pub fn node_path(&self) -> Option<&str> {
        if let Self::Node(s) = self {
            Some(s.trim())
        } else {
            None
        }
    }
}

/// The complete document model for a `graph.tngl` file.
///
/// Preserves every line verbatim so that `serialize(parse(input)?) == input`.
#[derive(Debug, Clone, PartialEq, Eq, Default)]
pub struct Document {
    pub lines: Vec<DocLine>,
    /// Whether the original input ended with a newline character.
    pub trailing_newline: bool,
}

/// Summary of lint fixes applied to a graph document.
#[derive(Debug, Default, Clone, Copy, PartialEq, Eq)]
pub struct LintReport {
    pub removed_floating_orphan_tags: usize,
    pub removed_extra_blank_lines: usize,
    pub normalized_tag_indentation: usize,
    pub normalized_edge_indentation: usize,
}

impl LintReport {
    pub fn changed(&self) -> bool {
        self.removed_floating_orphan_tags > 0
            || self.removed_extra_blank_lines > 0
            || self.normalized_tag_indentation > 0
            || self.normalized_edge_indentation > 0
    }
}

#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum OrphanMarkerKind {
    Orphan,
    OrphanSubtree,
}

// ---------------------------------------------------------------------------
// Parsing
// ---------------------------------------------------------------------------

/// Parse `graph.tngl` text into a `Document`.
///
/// Returns an error if any edge line is malformed. Unknown node references are
/// allowed — they are reported as dangling edges, not parse errors.
pub fn parse(input: &str) -> Result<Document> {
    let (raw_lines, trailing_newline) = split_lines_raw(input);

    let mut lines = Vec::with_capacity(raw_lines.len());

    for (line_num, raw) in raw_lines.into_iter().enumerate() {
        let trimmed = raw.trim();

        let doc_line = if trimmed.is_empty() {
            DocLine::Blank(raw)
        } else if trimmed.starts_with('#') {
            DocLine::Comment(raw)
        } else if is_tag_line(trimmed) {
            DocLine::Tag(raw)
        } else if is_edge_line(&raw) {
            // Validate immediately so callers get a clear error location.
            parse_edge_line(&raw)
                .with_context(|| format!("invalid edge at line {}", line_num + 1))?;
            DocLine::Edge(raw)
        } else if (raw.starts_with(' ') || raw.starts_with('\t')) && raw.trim_start().contains(':')
        {
            // Indented lines containing ':' are likely malformed edges.
            parse_edge_line(&raw)
                .with_context(|| format!("invalid edge at line {}", line_num + 1))?;
            unreachable!("parse_edge_line above always returns Err for malformed edges");
        } else {
            DocLine::Node(raw)
        };

        lines.push(doc_line);
    }

    Ok(Document {
        lines,
        trailing_newline,
    })
}

/// Serialise a `Document` back to text.
///
/// When applied to a parsed document this produces byte-identical output.
pub fn serialize(doc: &Document) -> String {
    if doc.lines.is_empty() {
        return String::new();
    }
    let mut out = doc
        .lines
        .iter()
        .map(DocLine::raw)
        .collect::<Vec<_>>()
        .join("\n");
    if doc.trailing_newline {
        out.push('\n');
    }
    out
}

// ---------------------------------------------------------------------------
// Semantic model conversion
// ---------------------------------------------------------------------------

/// Build a `Graph` from a `Document`.
///
/// The graph reflects the semantic content only; comments, blank lines and
/// whitespace formatting are not carried over.
pub fn to_graph(doc: &Document) -> Result<Graph> {
    let mut graph = Graph::new();
    let mut current_node: Option<String> = None;

    for (i, line) in doc.lines.iter().enumerate() {
        match line {
            DocLine::Blank(_) | DocLine::Comment(_) | DocLine::Tag(_) => {
                // No semantic effect; blank lines do not reset the current node
                // because `->` lines after a blank still belong to the same node.
            }
            DocLine::Node(raw) => {
                let path = raw.trim().to_string();
                if graph.contains(&path) {
                    bail!("duplicate node '{}' at line {}", path, i + 1);
                }
                graph.add_node(Node::new(path.clone()));
                current_node = Some(path);
            }
            DocLine::Edge(raw) => {
                let edge = parse_edge_line(raw)
                    .with_context(|| format!("invalid edge at line {}", i + 1))?;
                match current_node.as_deref() {
                    None => bail!("edge at line {} appears before any node declaration", i + 1),
                    Some(path) => {
                        graph
                            .get_mut(path)
                            .expect("current_node must be in graph")
                            .edges
                            .push(edge);
                    }
                }
            }
        }
    }

    Ok(graph)
}

/// Build a canonical `Document` from a `Graph`.
///
/// Produces clean, consistently formatted output. Does not preserve any
/// hand-authored formatting (use for fresh files only — `tngl init`).
pub fn from_graph(graph: &Graph) -> Document {
    let mut lines: Vec<DocLine> = Vec::new();

    for (idx, node) in graph.nodes.iter().enumerate() {
        if idx > 0 {
            lines.push(DocLine::Blank(String::new()));
        }
        lines.push(DocLine::Node(format_node_line(&node.path)));
        for edge in &node.edges {
            lines.push(DocLine::Edge(format_edge_line(edge)));
        }
    }

    Document {
        lines,
        trailing_newline: true,
    }
}

// ---------------------------------------------------------------------------
// Document mutation helpers (used by `tngl update`)
// ---------------------------------------------------------------------------

/// Insert a new orphan node into the document in hierarchical order.
pub fn add_node(doc: &mut Document, path: &str) {
    let indent = detect_indent_unit(doc);
    let node_line = DocLine::Node(format_node_line_with_indent(path, &indent));

    if let Some(insert_at) = find_insert_idx(doc, path) {
        let mut insert_at = insert_at;
        let mut suppress_leading_blank = false;

        if should_remove_edge_to_child_blank(doc, path, insert_at) {
            doc.lines.remove(insert_at - 1);
            insert_at -= 1;
            suppress_leading_blank = true;
        }

        let mut block: Vec<DocLine> = Vec::new();
        if !suppress_leading_blank
            && insert_at > 0
            && !matches!(doc.lines[insert_at - 1], DocLine::Blank(_))
        {
            block.push(DocLine::Blank(String::new()));
        }
        block.push(node_line);
        if insert_at < doc.lines.len() && !matches!(doc.lines[insert_at], DocLine::Blank(_)) {
            block.push(DocLine::Blank(String::new()));
        }
        doc.lines.splice(insert_at..insert_at, block);
    } else {
        if !doc.lines.is_empty() {
            doc.lines.push(DocLine::Blank(String::new()));
        }
        doc.lines.push(node_line);
    }
    doc.trailing_newline = true;
}

/// Remove a node and all its associated edge lines from the document.
///
/// Also removes any immediately preceding blank separator line so the document
/// stays clean. Returns `true` if the node was found and removed.
pub fn remove_node(doc: &mut Document, path: &str) -> bool {
    let Some((node_idx, end_idx)) = find_node_range(&doc.lines, path) else {
        return false;
    };

    let (tag_block_start, has_tag_block) = find_tag_block_start(doc, node_idx);

    if end_idx < doc.lines.len() {
        // There is another node after this one: remove this node's block and any
        // marker tags attached to it. Keep the separator before it.
        let delete_from = if has_tag_block {
            tag_block_start
        } else {
            node_idx
        };
        let mut delete_to = trailing_comment_block_start(&doc.lines, delete_from, end_idx);
        if let Some(next_tag_start) = attached_tag_block_start_before_node(&doc.lines, end_idx) {
            delete_to = delete_to.min(next_tag_start);
        }
        doc.lines.drain(delete_from..delete_to);
    } else {
        // Last node: remove attached marker tags plus a preceding separator blank.
        let base_from = if has_tag_block {
            tag_block_start
        } else {
            node_idx
        };
        let delete_from = if base_from > 0 && matches!(doc.lines[base_from - 1], DocLine::Blank(_))
        {
            base_from - 1
        } else {
            base_from
        };
        let delete_to = trailing_comment_block_start(&doc.lines, delete_from, end_idx);
        doc.lines.drain(delete_from..delete_to);
    }
    true
}

/// Add an edge to an existing node in the document.
///
/// Inserts the edge line after the last existing edge of that node (before any
/// trailing blank lines). Returns an error if the source node is not found.
pub fn add_edge(doc: &mut Document, source: &str, edge: &Edge) -> Result<()> {
    let indent_unit = detect_indent_unit(doc);
    let (node_idx, end_idx) = find_node_range(&doc.lines, source)
        .ok_or_else(|| anyhow::anyhow!("node '{}' not found in document", source))?;
    let edge_indent = edge_indent_for_node(doc, node_idx, end_idx, &indent_unit);

    // Find the last Edge line within this node's range.
    let insert_after = doc.lines[node_idx + 1..end_idx]
        .iter()
        .rposition(|l| matches!(l, DocLine::Edge(_)))
        .map(|rel| node_idx + 1 + rel)
        .unwrap_or(node_idx);

    doc.lines.insert(
        insert_after + 1,
        DocLine::Edge(format_edge_line_with_indent(edge, &edge_indent)),
    );
    Ok(())
}

/// Remove a specific edge from a node.
///
/// Matches on target path. Returns `true` if the edge was found and removed.
pub fn remove_edge(doc: &mut Document, source: &str, target: &str) -> bool {
    let Some((node_idx, end_idx)) = find_node_range(&doc.lines, source) else {
        return false;
    };

    let range = &doc.lines[node_idx + 1..end_idx];
    let rel_pos = range.iter().position(|l| {
        if let DocLine::Edge(raw) = l {
            parse_edge_line(raw)
                .map(|e| e.target == target)
                .unwrap_or(false)
        } else {
            false
        }
    });

    if let Some(rel) = rel_pos {
        doc.lines.remove(node_idx + 1 + rel);
        true
    } else {
        false
    }
}

/// Reorder edge lines under every node by kind:
/// 1) undirected (`--`)
/// 2) outgoing (`->`)
/// 3) incoming (`<-`)
///
/// Non-edge lines (comments/blanks/tags) keep their original positions; only
/// edge lines are permuted across existing edge slots. Returns the number of
/// nodes whose edge order changed.
pub fn sort_edges_by_kind(doc: &mut Document) -> usize {
    let mut changed_nodes = 0usize;
    let mut i = 0usize;

    while i < doc.lines.len() {
        if !matches!(doc.lines[i], DocLine::Node(_)) {
            i += 1;
            continue;
        }

        let end_idx = doc.lines[i + 1..]
            .iter()
            .position(|l| matches!(l, DocLine::Node(_)))
            .map(|rel| i + 1 + rel)
            .unwrap_or(doc.lines.len());

        let mut edge_positions = Vec::new();
        let mut edge_lines = Vec::new();
        for idx in i + 1..end_idx {
            if let DocLine::Edge(raw) = &doc.lines[idx] {
                edge_positions.push(idx);
                edge_lines.push(raw.clone());
            }
        }

        if edge_lines.len() > 1 {
            let mut sorted = edge_lines.clone();
            sorted.sort_by_key(|raw| {
                parse_edge_line(raw)
                    .map(|e| edge_kind_rank(&e.kind))
                    .unwrap_or(usize::MAX)
            });

            if sorted != edge_lines {
                for (idx, raw) in edge_positions.iter().zip(sorted.into_iter()) {
                    doc.lines[*idx] = DocLine::Edge(raw);
                }
                changed_nodes += 1;
            }
        }

        i = end_idx;
    }

    changed_nodes
}

/// Replace the label of matching edge lines under `source`.
///
/// Matches by `(target, kind, old_label)` and updates to `new_label`.
/// Returns the number of edge lines changed.
pub fn replace_edge_label(
    doc: &mut Document,
    source: &str,
    target: &str,
    kind: EdgeKind,
    old_label: &str,
    new_label: &str,
) -> usize {
    let Some((node_idx, end_idx)) = find_node_range(&doc.lines, source) else {
        return 0;
    };

    let mut changed = 0;
    for idx in node_idx + 1..end_idx {
        let DocLine::Edge(raw) = &doc.lines[idx] else {
            continue;
        };
        let Ok(mut edge) = parse_edge_line(raw) else {
            continue;
        };
        if edge.target != target || edge.kind != kind || edge.label != old_label {
            continue;
        }
        edge.label = new_label.to_string();
        let leading_len = raw.len() - raw.trim_start().len();
        let indent = &raw[..leading_len];
        doc.lines[idx] = DocLine::Edge(format_edge_line_with_indent(&edge, indent));
        changed += 1;
    }
    changed
}

/// Remove all edge lines in the document that point **to** `target`.
///
/// Used by the `delete` strategy in `tngl update` to clean up incoming edges
/// when a node is removed. Returns the number of edge lines removed.
pub fn remove_edges_targeting(doc: &mut Document, target: &str) -> usize {
    let mut count = 0;
    let mut i = 0;
    while i < doc.lines.len() {
        let remove = if let DocLine::Edge(raw) = &doc.lines[i] {
            parse_edge_line(raw)
                .map(|e| e.target == target)
                .unwrap_or(false)
        } else {
            false
        };
        if remove {
            doc.lines.remove(i);
            count += 1;
        } else {
            i += 1;
        }
    }
    count
}

/// Mark a node as `[missing]` by prepending a comment above it.
///
/// Used by the `preserve` deletion strategy in `tngl update`.
pub fn mark_missing(doc: &mut Document, path: &str) -> bool {
    let Some((node_idx, _)) = find_node_range(&doc.lines, path) else {
        return false;
    };
    doc.lines
        .insert(node_idx, DocLine::Comment(format!("# [missing] {}", path)));
    true
}

/// Mark a node as an intentional orphan by ensuring `[orphan]` above it.
///
/// Returns `true` when changed, `false` if the node was not found or already
/// had the orphan semantics.
pub fn mark_orphan(doc: &mut Document, path: &str) -> bool {
    let Some((node_idx, _)) = find_node_range(&doc.lines, path) else {
        return false;
    };

    if let Some(tag_idx) = attached_tag_line_idx(doc, node_idx) {
        return ensure_tag_tokens_on_line(doc, tag_idx, &[TAG_ORPHAN]);
    }

    let node_raw = doc.lines[node_idx].raw();
    let tag = format!("{}[orphan]", leading_whitespace(node_raw));
    doc.lines.insert(node_idx, DocLine::Tag(tag));
    true
}

/// Mark a folder node as intentional orphan bundle by ensuring
/// `[orphan bundle]` above it.
///
/// Returns `true` when changed, `false` if the node was not found, is not a
/// folder node, or already had orphan-bundle semantics.
#[cfg(test)]
pub fn mark_orphan_subtree(doc: &mut Document, path: &str) -> bool {
    if !path.ends_with('/') {
        return false;
    }

    let Some((node_idx, _)) = find_node_range(&doc.lines, path) else {
        return false;
    };

    if let Some(tag_idx) = attached_tag_line_idx(doc, node_idx) {
        return ensure_tag_tokens_on_line(doc, tag_idx, &[TAG_ORPHAN, TAG_BUNDLE]);
    }

    let node_raw = doc.lines[node_idx].raw();
    let tag = format!("{}[orphan bundle]", leading_whitespace(node_raw));
    doc.lines.insert(node_idx, DocLine::Tag(tag));
    true
}

/// Mark a folder node as bundled by ensuring `[bundle]` above it.
///
/// Returns `true` when changed, `false` if the node was not found, is not a
/// folder node, or already had bundle semantics.
pub fn mark_link_subtree(doc: &mut Document, path: &str) -> bool {
    if !path.ends_with('/') {
        return false;
    }

    let Some((node_idx, _)) = find_node_range(&doc.lines, path) else {
        return false;
    };

    if let Some(tag_idx) = attached_tag_line_idx(doc, node_idx) {
        return ensure_tag_tokens_on_line(doc, tag_idx, &[TAG_BUNDLE]);
    }

    let node_raw = doc.lines[node_idx].raw();
    let tag = format!("{}[bundle]", leading_whitespace(node_raw));
    doc.lines.insert(node_idx, DocLine::Tag(tag));
    true
}

/// Remove an `[orphan]` marker directly attached to `path`.
pub fn unmark_orphan(doc: &mut Document, path: &str) -> bool {
    unmark_marker(doc, path, OrphanMarkerKind::Orphan)
}

/// Remove orphan-bundle semantics directly attached to `path`.
///
/// For `[orphan bundle]`, this removes only `orphan`, leaving `[bundle]`.
pub fn unmark_orphan_subtree(doc: &mut Document, path: &str) -> bool {
    unmark_marker(doc, path, OrphanMarkerKind::OrphanSubtree)
}

/// Remove bundle semantics directly attached to `path`.
///
/// For `[orphan bundle]`, this removes only `bundle`, leaving `[orphan]`.
pub fn unmark_link_subtree(doc: &mut Document, path: &str) -> bool {
    let Some((node_idx, _)) = find_node_range(&doc.lines, path) else {
        return false;
    };
    let Some(tag_idx) = attached_tag_line_idx(doc, node_idx) else {
        return false;
    };
    let raw = match &doc.lines[tag_idx] {
        DocLine::Tag(raw) => raw.clone(),
        _ => return false,
    };
    let Some(mut tokens) = parse_tag_tokens(raw.trim()) else {
        return false;
    };
    if !tokens.iter().any(|t| t == TAG_BUNDLE) {
        return false;
    }
    tokens.retain(|t| t != TAG_BUNDLE);
    let tokens = canonicalize_tag_tokens(tokens);
    if tokens.is_empty() {
        doc.lines.remove(tag_idx);
    } else {
        doc.lines[tag_idx] = DocLine::Tag(format!(
            "{}{}",
            leading_whitespace(&raw),
            format_tag_tokens(&tokens)
        ));
    }
    true
}

/// Return explicitly tagged orphan markers as `(path, marker_kind)`.
pub fn explicit_orphan_markers(doc: &Document) -> Vec<(String, OrphanMarkerKind)> {
    let mut markers = Vec::new();

    for (idx, line) in doc.lines.iter().enumerate() {
        let DocLine::Tag(raw) = line else {
            continue;
        };
        let trimmed = raw.trim();
        let kind = if is_orphan_tag(trimmed) {
            OrphanMarkerKind::Orphan
        } else if is_orphan_subtree_tag(trimmed) {
            OrphanMarkerKind::OrphanSubtree
        } else {
            continue;
        };

        let Some(target_idx) = tag_target_node_idx(doc, idx) else {
            continue;
        };
        let path = doc.lines[target_idx]
            .node_path()
            .expect("target_idx guaranteed to be node");

        if matches!(kind, OrphanMarkerKind::OrphanSubtree) && !path.ends_with('/') {
            continue;
        }

        markers.push((path.to_string(), kind));
    }

    markers
}

/// Return folder roots explicitly tagged with `[bundle]`.
pub fn explicit_link_subtree_markers(doc: &Document) -> Vec<String> {
    let mut roots = Vec::new();
    for (idx, line) in doc.lines.iter().enumerate() {
        let DocLine::Tag(raw) = line else {
            continue;
        };
        if !is_link_subtree_tag(raw.trim()) {
            continue;
        }
        let Some(target_idx) = tag_target_node_idx(doc, idx) else {
            continue;
        };
        let path = doc.lines[target_idx]
            .node_path()
            .expect("target_idx guaranteed to be node");
        if path.ends_with('/') {
            roots.push(path.to_string());
        }
    }
    roots
}

/// Convert an attached `[bundle]` marker to `[orphan bundle]`.
///
/// Returns `true` if converted, `false` if no matching marker was attached.
pub fn convert_link_subtree_to_orphan_subtree(doc: &mut Document, path: &str) -> bool {
    add_tokens_to_matching_marker(doc, path, is_link_subtree_tag, &[TAG_ORPHAN, TAG_BUNDLE])
}

/// Convert an attached `[orphan]` marker to `[orphan bundle]`.
///
/// Returns `true` if converted, `false` if no matching marker was attached.
#[cfg(test)]
pub fn convert_orphan_to_orphan_subtree(doc: &mut Document, path: &str) -> bool {
    add_tokens_to_matching_marker(doc, path, is_orphan_tag, &[TAG_ORPHAN, TAG_BUNDLE])
}

/// Lint and normalize marker tags in-place.
///
/// Currently removes floating marker tags (`[orphan]`, `[bundle]`,
/// `[orphan bundle]`) that are not directly associated with a following node
/// block, removes invalid subtree tags that point to non-folder nodes, and
/// collapses repeated blank-line runs to single separators. Also normalizes tag
/// and edge indentation to match the hierarchy.
pub fn lint(doc: &mut Document) -> LintReport {
    let mut report = LintReport::default();
    let mut i = 0;
    while i < doc.lines.len() {
        let is_tag = matches!(doc.lines[i], DocLine::Tag(_));
        if !is_tag {
            i += 1;
            continue;
        }

        if tag_target_node_idx(doc, i).is_none() {
            doc.lines.remove(i);
            report.removed_floating_orphan_tags += 1;
            continue;
        }

        if let DocLine::Tag(raw) = &doc.lines[i] {
            let trimmed = raw.trim();
            let Some(mut tokens) = parse_tag_tokens(trimmed) else {
                i += 1;
                continue;
            };
            let target_idx = tag_target_node_idx(doc, i).expect("checked above");
            let target_path = doc.lines[target_idx]
                .node_path()
                .expect("target_idx guaranteed to be node");

            // `bundle` only applies to folders; strip it for non-folder targets.
            if !target_path.ends_with('/') {
                tokens.retain(|t| t != TAG_BUNDLE);
            }

            let normalized = canonicalize_tag_tokens(tokens);
            if normalized.is_empty() {
                doc.lines.remove(i);
                report.removed_floating_orphan_tags += 1;
                continue;
            }

            let desired = format!(
                "{}{}",
                leading_whitespace(raw),
                format_tag_tokens(&normalized)
            );
            if *raw != desired {
                doc.lines[i] = DocLine::Tag(desired);
            }
        }

        i += 1;
    }

    let indent_unit = detect_indent_unit(doc);
    report.normalized_tag_indentation = normalize_tag_indentation(doc);
    report.normalized_edge_indentation = normalize_edge_indentation(doc, &indent_unit);
    report.removed_extra_blank_lines = collapse_consecutive_blank_lines(doc);
    trim_leading_and_trailing_blanks(doc);

    report
}

/// Return node paths marked as intentional orphans from marker tags.
///
/// Preferred format:
/// - `[orphan]` immediately above a node
/// - `[orphan bundle]` above a folder node (applies to folder + descendants)
pub fn intentional_orphans(doc: &Document) -> HashSet<String> {
    let mut marked = HashSet::new();
    let subtree_roots: Vec<String> = intentional_orphan_subtree_roots(doc).into_iter().collect();
    let node_paths: Vec<String> = doc
        .lines
        .iter()
        .filter_map(|line| line.node_path().map(String::from))
        .collect();

    for (idx, line) in doc.lines.iter().enumerate() {
        let DocLine::Tag(raw) = line else {
            continue;
        };

        let trimmed = raw.trim();
        if let Some(target_idx) = tag_target_node_idx(doc, idx) {
            let next_path = doc.lines[target_idx]
                .node_path()
                .expect("target_idx guaranteed to be node");
            if is_orphan_tag(trimmed) {
                marked.insert(next_path.to_string());
            }
        }
    }

    for root in subtree_roots {
        for path in &node_paths {
            if is_in_subtree(path, &root) {
                marked.insert(path.clone());
            }
        }
    }

    marked
}

/// Return folder roots tagged with `[orphan bundle]`.
pub fn intentional_orphan_subtree_roots(doc: &Document) -> HashSet<String> {
    let mut roots = HashSet::new();
    for (idx, line) in doc.lines.iter().enumerate() {
        let DocLine::Tag(raw) = line else {
            continue;
        };
        if !is_orphan_subtree_tag(raw.trim()) {
            continue;
        }
        let Some(target_idx) = tag_target_node_idx(doc, idx) else {
            continue;
        };
        let path = doc.lines[target_idx]
            .node_path()
            .expect("target_idx guaranteed to be node");
        if path.ends_with('/') {
            roots.insert(path.to_string());
        }
    }
    roots
}

/// Return folder roots tagged for subtree collapse.
///
/// Includes both:
/// - `[orphan bundle]` (intentional orphan semantics + collapse)
/// - `[bundle]` (linked-folder semantics + collapse)
pub fn collapsed_subtree_roots(doc: &Document) -> HashSet<String> {
    let mut roots = HashSet::new();
    for (idx, line) in doc.lines.iter().enumerate() {
        let DocLine::Tag(raw) = line else {
            continue;
        };
        let trimmed = raw.trim();
        if !is_orphan_subtree_tag(trimmed) && !is_link_subtree_tag(trimmed) {
            continue;
        }
        let Some(target_idx) = tag_target_node_idx(doc, idx) else {
            continue;
        };
        let path = doc.lines[target_idx]
            .node_path()
            .expect("target_idx guaranteed to be node");
        if path.ends_with('/') {
            roots.insert(path.to_string());
        }
    }
    roots
}

// ---------------------------------------------------------------------------
// Private helpers
// ---------------------------------------------------------------------------

/// Split input into raw lines (without line terminators), plus a trailing-newline flag.
///
/// Splitting on `\n` and preserving any `\r` within lines ensures that CRLF
/// files are handled transparently: joining with `\n` reproduces the original.
fn split_lines_raw(input: &str) -> (Vec<String>, bool) {
    if input.is_empty() {
        return (Vec::new(), false);
    }

    let trailing_newline = input.ends_with('\n');
    // Remove the final `\n` before splitting so we don't get a spurious empty
    // last element in the Vec.
    let body = if trailing_newline {
        &input[..input.len() - 1]
    } else {
        input
    };
    let lines = body.split('\n').map(String::from).collect();
    (lines, trailing_newline)
}

fn is_edge_line(raw: &str) -> bool {
    let trimmed = raw.trim_start();
    trimmed.starts_with("->") || trimmed.starts_with("<-") || trimmed.starts_with("--")
}

fn unmark_marker(doc: &mut Document, path: &str, kind: OrphanMarkerKind) -> bool {
    let Some((node_idx, _)) = find_node_range(&doc.lines, path) else {
        return false;
    };

    let Some(tag_idx) = attached_tag_line_idx(doc, node_idx) else {
        return false;
    };

    let raw = match &doc.lines[tag_idx] {
        DocLine::Tag(raw) => raw.clone(),
        _ => return false,
    };
    let trimmed = raw.trim();
    let matches = match kind {
        OrphanMarkerKind::Orphan => is_orphan_tag(trimmed),
        OrphanMarkerKind::OrphanSubtree => is_orphan_subtree_tag(trimmed),
    };
    if !matches {
        return false;
    }

    let Some(mut tokens) = parse_tag_tokens(trimmed) else {
        return false;
    };
    tokens.retain(|t| t != TAG_ORPHAN);
    let tokens = canonicalize_tag_tokens(tokens);
    if tokens.is_empty() {
        doc.lines.remove(tag_idx);
    } else {
        doc.lines[tag_idx] = DocLine::Tag(format!(
            "{}{}",
            leading_whitespace(&raw),
            format_tag_tokens(&tokens)
        ));
    }
    true
}

fn add_tokens_to_matching_marker(
    doc: &mut Document,
    path: &str,
    matcher: fn(&str) -> bool,
    tokens: &[&str],
) -> bool {
    let Some((node_idx, _)) = find_node_range(&doc.lines, path) else {
        return false;
    };
    let Some(tag_idx) = attached_tag_line_idx(doc, node_idx) else {
        return false;
    };

    let raw = match &doc.lines[tag_idx] {
        DocLine::Tag(raw) => raw.clone(),
        _ => return false,
    };
    if !matcher(raw.trim()) {
        return false;
    }
    let _ = ensure_tag_tokens_on_line(doc, tag_idx, tokens);
    // A successful conversion is considered handled even if already normalized.
    true
}

fn find_tag_block_start(doc: &Document, node_idx: usize) -> (usize, bool) {
    let mut i = node_idx;
    let mut tag_start = node_idx;
    let mut has_tag = false;

    while i > 0 {
        match &doc.lines[i - 1] {
            DocLine::Tag(_) => {
                has_tag = true;
                tag_start = i - 1;
                i -= 1;
            }
            DocLine::Blank(_) => {
                i -= 1;
            }
            _ => break,
        }
    }

    (tag_start, has_tag)
}

fn trailing_comment_block_start(lines: &[DocLine], from: usize, to: usize) -> usize {
    let mut i = to;
    let mut saw_comment = false;
    while i > from {
        match &lines[i - 1] {
            DocLine::Blank(_) => i -= 1,
            DocLine::Comment(_) => {
                saw_comment = true;
                i -= 1;
            }
            _ => break,
        }
    }
    if saw_comment { i } else { to }
}

fn attached_tag_block_start_before_node(lines: &[DocLine], node_idx: usize) -> Option<usize> {
    let mut i = node_idx;
    let mut saw_tag = false;

    while i > 0 {
        match &lines[i - 1] {
            DocLine::Blank(_) | DocLine::Comment(_) => i -= 1,
            DocLine::Tag(_) => {
                saw_tag = true;
                i -= 1;
            }
            _ => break,
        }
    }

    if saw_tag { Some(i) } else { None }
}

const TAG_ORPHAN: &str = "orphan";
const TAG_BUNDLE: &str = "bundle";

fn is_tag_line(trimmed: &str) -> bool {
    parse_tag_tokens(trimmed).is_some()
}

fn is_orphan_tag(trimmed: &str) -> bool {
    tag_has_token(trimmed, TAG_ORPHAN) && !tag_has_token(trimmed, TAG_BUNDLE)
}

fn is_orphan_subtree_tag(trimmed: &str) -> bool {
    tag_has_token(trimmed, TAG_ORPHAN) && tag_has_token(trimmed, TAG_BUNDLE)
}

fn is_link_subtree_tag(trimmed: &str) -> bool {
    tag_has_token(trimmed, TAG_BUNDLE) && !tag_has_token(trimmed, TAG_ORPHAN)
}

fn tag_has_token(trimmed: &str, needle: &str) -> bool {
    parse_tag_tokens(trimmed)
        .map(|tokens| tokens.iter().any(|t| t == needle))
        .unwrap_or(false)
}

fn parse_tag_tokens(trimmed: &str) -> Option<Vec<String>> {
    let inner = trimmed.strip_prefix('[')?.strip_suffix(']')?.trim();
    if inner.is_empty() {
        return None;
    }
    Some(inner.split_whitespace().map(|t| t.to_string()).collect())
}

fn canonicalize_tag_tokens(tokens: Vec<String>) -> Vec<String> {
    let mut deduped: Vec<String> = Vec::new();
    let mut seen = HashSet::new();
    for token in tokens {
        if seen.insert(token.clone()) {
            deduped.push(token);
        }
    }

    let has_orphan = deduped.iter().any(|t| t == TAG_ORPHAN);
    let has_bundle = deduped.iter().any(|t| t == TAG_BUNDLE);

    let mut out: Vec<String> = Vec::new();
    if has_orphan {
        out.push(TAG_ORPHAN.to_string());
    }
    if has_bundle {
        out.push(TAG_BUNDLE.to_string());
    }
    for token in deduped {
        if token != TAG_ORPHAN && token != TAG_BUNDLE {
            out.push(token);
        }
    }
    out
}

fn format_tag_tokens(tokens: &[String]) -> String {
    format!("[{}]", tokens.join(" "))
}

fn attached_tag_line_idx(doc: &Document, node_idx: usize) -> Option<usize> {
    for i in (0..node_idx).rev() {
        match &doc.lines[i] {
            DocLine::Blank(_) | DocLine::Comment(_) => continue,
            DocLine::Tag(_) => return Some(i),
            DocLine::Node(_) | DocLine::Edge(_) => return None,
        }
    }
    None
}

fn ensure_tag_tokens_on_line(doc: &mut Document, tag_idx: usize, required: &[&str]) -> bool {
    let raw = match &doc.lines[tag_idx] {
        DocLine::Tag(raw) => raw.clone(),
        _ => return false,
    };
    let Some(mut tokens) = parse_tag_tokens(raw.trim()) else {
        return false;
    };
    let before = canonicalize_tag_tokens(tokens.clone());
    for token in required {
        if !tokens.iter().any(|existing| existing == token) {
            tokens.push((*token).to_string());
        }
    }
    let after = canonicalize_tag_tokens(tokens);
    if after == before {
        return false;
    }
    doc.lines[tag_idx] = DocLine::Tag(format!(
        "{}{}",
        leading_whitespace(&raw),
        format_tag_tokens(&after)
    ));
    true
}

fn is_in_subtree(path: &str, root: &str) -> bool {
    if root.ends_with('/') {
        path == root || path.starts_with(root)
    } else {
        path == root
    }
}

fn tag_target_node_idx(doc: &Document, tag_idx: usize) -> Option<usize> {
    let mut i = tag_idx + 1;
    while i < doc.lines.len() {
        match &doc.lines[i] {
            DocLine::Blank(_) | DocLine::Comment(_) => i += 1,
            DocLine::Node(_) => return Some(i),
            DocLine::Tag(_) | DocLine::Edge(_) => return None,
        }
    }
    None
}

fn trim_leading_and_trailing_blanks(doc: &mut Document) {
    while matches!(doc.lines.first(), Some(DocLine::Blank(_))) {
        doc.lines.remove(0);
    }
    while matches!(doc.lines.last(), Some(DocLine::Blank(_))) {
        doc.lines.pop();
    }
}

fn normalize_tag_indentation(doc: &mut Document) -> usize {
    let mut changed = 0usize;
    for i in 0..doc.lines.len() {
        let DocLine::Tag(raw) = &doc.lines[i] else {
            continue;
        };
        let Some(target_idx) = tag_target_node_idx(doc, i) else {
            continue;
        };
        let node_indent = leading_whitespace(doc.lines[target_idx].raw());
        let desired = format!("{}{}", node_indent, raw.trim());
        if *raw != desired {
            doc.lines[i] = DocLine::Tag(desired);
            changed += 1;
        }
    }
    changed
}

fn normalize_edge_indentation(doc: &mut Document, indent_unit: &str) -> usize {
    let mut changed = 0usize;
    let mut current_node_indent = String::new();
    let mut have_node = false;

    for i in 0..doc.lines.len() {
        match &doc.lines[i] {
            DocLine::Node(raw) => {
                current_node_indent = leading_whitespace(raw).to_string();
                have_node = true;
            }
            DocLine::Edge(raw) if have_node => {
                let desired = format!("{}{}", current_node_indent, indent_unit);
                let normalized = format!("{}{}", desired, raw.trim_start());
                if *raw != normalized {
                    doc.lines[i] = DocLine::Edge(normalized);
                    changed += 1;
                }
            }
            _ => {}
        }
    }

    changed
}

fn collapse_consecutive_blank_lines(doc: &mut Document) -> usize {
    let mut removed = 0usize;
    let mut i = 1usize;
    while i < doc.lines.len() {
        if matches!(doc.lines[i - 1], DocLine::Blank(_))
            && matches!(doc.lines[i], DocLine::Blank(_))
        {
            doc.lines.remove(i);
            removed += 1;
        } else {
            i += 1;
        }
    }
    removed
}

/// Parse the semantic content of an edge line.
///
/// Expected form (after stripping optional leading whitespace):
/// `-> <target> : <label>`, `<- <target> : <label>`, or `-- <target> : <label>`
fn parse_edge_line(raw: &str) -> Result<Edge> {
    let trimmed = raw.trim();

    let (kind, rest) = if let Some(r) = trimmed.strip_prefix("->") {
        (EdgeKind::Directed, r)
    } else if let Some(r) = trimmed.strip_prefix("<-") {
        (EdgeKind::Incoming, r)
    } else if let Some(r) = trimmed.strip_prefix("--") {
        (EdgeKind::Undirected, r)
    } else {
        bail!(
            "edge must start with '->', '<-', or '--', got: {:?}",
            trimmed
        );
    };

    let rest = rest.trim_start();

    let colon_pos = rest
        .find(':')
        .ok_or_else(|| anyhow::anyhow!("edge missing ':' separator: {:?}", raw))?;

    let target = rest[..colon_pos].trim().to_string();
    let label = rest[colon_pos + 1..].trim().to_string();

    if target.is_empty() {
        bail!("edge has empty target path: {:?}", raw);
    }

    Ok(Edge {
        target,
        kind,
        label,
    })
}

fn leading_whitespace(raw: &str) -> &str {
    let len = raw.len() - raw.trim_start_matches([' ', '\t']).len();
    &raw[..len]
}

/// Format an `Edge` as a canonical edge line (4-space indent, no extra padding).
fn format_edge_line(edge: &Edge) -> String {
    format_edge_line_with_indent(edge, DEFAULT_INDENT_UNIT)
}

fn format_edge_line_with_indent(edge: &Edge, indent: &str) -> String {
    let arrow = match edge.kind {
        EdgeKind::Directed => "->",
        EdgeKind::Incoming => "<-",
        EdgeKind::Undirected => "--",
    };
    if edge.label.is_empty() {
        format!("{indent}{} {} :", arrow, edge.target)
    } else {
        format!("{indent}{} {} : {}", arrow, edge.target, edge.label)
    }
}

fn format_node_line(path: &str) -> String {
    format_node_line_with_indent(path, DEFAULT_INDENT_UNIT)
}

fn edge_kind_rank(kind: &EdgeKind) -> usize {
    match kind {
        EdgeKind::Undirected => 0,
        EdgeKind::Directed => 1,
        EdgeKind::Incoming => 2,
    }
}

fn format_node_line_with_indent(path: &str, indent: &str) -> String {
    let depth = path_depth(path);
    format!("{}{}", indent.repeat(depth), path)
}

const DEFAULT_INDENT_UNIT: &str = "    ";

fn detect_indent_unit(doc: &Document) -> String {
    let mut space_gcd: Option<usize> = None;

    for line in &doc.lines {
        let raw = match line {
            DocLine::Node(s) | DocLine::Edge(s) => s.as_str(),
            _ => continue,
        };

        let leading_len = raw.len() - raw.trim_start_matches([' ', '\t']).len();
        if leading_len == 0 {
            continue;
        }
        let leading = &raw[..leading_len];
        if leading.contains('\t') {
            return "\t".to_string();
        }
        if leading.bytes().all(|b| b == b' ') {
            space_gcd = Some(space_gcd.map_or(leading.len(), |g| gcd(g, leading.len())));
        }
    }

    " ".repeat(space_gcd.unwrap_or(DEFAULT_INDENT_UNIT.len()).max(1))
}

fn edge_indent_for_node(
    doc: &Document,
    node_idx: usize,
    end_idx: usize,
    indent_unit: &str,
) -> String {
    for idx in node_idx + 1..end_idx {
        if let DocLine::Edge(raw) = &doc.lines[idx] {
            return leading_whitespace(raw).to_string();
        }
    }
    let node_indent = leading_whitespace(doc.lines[node_idx].raw());
    format!("{}{}", node_indent, indent_unit)
}

fn gcd(mut a: usize, mut b: usize) -> usize {
    while b != 0 {
        let r = a % b;
        a = b;
        b = r;
    }
    a
}

fn path_depth(path: &str) -> usize {
    path.trim_end_matches('/')
        .split('/')
        .filter(|segment| !segment.is_empty())
        .count()
        .saturating_sub(1)
}

/// Return `(node_line_idx, end_idx)` for the node with the given path.
///
/// `end_idx` is the exclusive upper bound of lines that "belong" to this node
/// (i.e. everything up to but not including the next Node line, or end of Vec).
fn find_node_range(lines: &[DocLine], path: &str) -> Option<(usize, usize)> {
    let node_idx = lines.iter().position(|l| l.node_path() == Some(path))?;

    let end_idx = lines[node_idx + 1..]
        .iter()
        .position(|l| matches!(l, DocLine::Node(_)))
        .map(|rel| node_idx + 1 + rel)
        .unwrap_or(lines.len());

    Some((node_idx, end_idx))
}

fn find_insert_idx(doc: &Document, path: &str) -> Option<usize> {
    doc.lines
        .iter()
        .enumerate()
        .find_map(|(idx, line)| match line.node_path() {
            Some(existing) if compare_hierarchical_paths(path, existing).is_lt() => Some(idx),
            _ => None,
        })
}

fn should_remove_edge_to_child_blank(doc: &Document, path: &str, insert_at: usize) -> bool {
    if insert_at < 2 {
        return false;
    }
    if !matches!(doc.lines[insert_at - 1], DocLine::Blank(_)) {
        return false;
    }
    if !matches!(doc.lines[insert_at - 2], DocLine::Edge(_)) {
        return false;
    }

    // Only collapse this blank when the insertion is for a descendant of the
    // nearest previous node (i.e. inserting child nodes under a folder that
    // currently ends with one or more edge lines).
    let parent = doc.lines[..insert_at]
        .iter()
        .rev()
        .find_map(DocLine::node_path);
    let Some(parent) = parent else {
        return false;
    };
    parent.ends_with('/') && path != parent && path.starts_with(parent)
}

fn compare_hierarchical_paths(a: &str, b: &str) -> std::cmp::Ordering {
    use std::cmp::Ordering;

    let (a_comps, a_is_dir) = path_components(a);
    let (b_comps, b_is_dir) = path_components(b);
    let min_len = a_comps.len().min(b_comps.len());

    for i in 0..min_len {
        if a_comps[i] == b_comps[i] {
            continue;
        }
        let a_kind = component_kind(i, a_comps.len(), a_is_dir);
        let b_kind = component_kind(i, b_comps.len(), b_is_dir);
        if a_kind != b_kind {
            return a_kind.cmp(&b_kind);
        }
        return a_comps[i].cmp(b_comps[i]);
    }

    match a_comps.len().cmp(&b_comps.len()) {
        Ordering::Equal => a_is_dir.cmp(&b_is_dir).reverse(),
        other => other,
    }
}

fn path_components(path: &str) -> (Vec<&str>, bool) {
    let is_dir = path.ends_with('/');
    let trimmed = path.trim_end_matches('/');
    let comps = if trimmed.is_empty() {
        Vec::new()
    } else {
        trimmed.split('/').collect()
    };
    (comps, is_dir)
}

fn component_kind(idx: usize, len: usize, is_dir: bool) -> u8 {
    if idx < len.saturating_sub(1) || is_dir {
        0
    } else {
        1
    }
}

// ---------------------------------------------------------------------------
// Tests
// ---------------------------------------------------------------------------

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

    // -----------------------------------------------------------------------
    // Round-trip tests — the core invariant
    // -----------------------------------------------------------------------

    fn rt(input: &str) {
        let doc = parse(input).expect("parse failed");
        let output = serialize(&doc);
        assert_eq!(output, input, "round-trip failed");
    }

    #[test]
    fn roundtrip_empty() {
        rt("");
    }

    #[test]
    fn roundtrip_single_orphan_with_newline() {
        rt("src/main.rs\n");
    }

    #[test]
    fn roundtrip_single_orphan_no_trailing_newline() {
        rt("src/main.rs");
    }

    #[test]
    fn roundtrip_directed_edge_with_label() {
        rt("src/main.rs\n    -> src/auth/ : bootstraps authentication\n");
    }

    #[test]
    fn roundtrip_directed_edge_empty_label() {
        rt("src/main.rs\n    -> src/auth/ :\n");
    }

    #[test]
    fn roundtrip_undirected_edge() {
        rt("src/auth/\n    -- docs/auth.md : documented by\n");
    }

    #[test]
    fn roundtrip_incoming_edge() {
        rt("src/auth/\n    <- src/main.rs : bootstrapped by\n");
    }

    #[test]
    fn roundtrip_multiple_nodes() {
        rt("src/main.rs\n    -> src/auth/ : bootstraps\n\nsrc/auth/\n    -> src/db/ : queries\n");
    }

    #[test]
    fn roundtrip_comments_preserved() {
        rt(
            "# This is a comment\n\nsrc/main.rs\n    -> src/auth/ : foo\n\n# Another comment\nsrc/auth/\n",
        );
    }

    #[test]
    fn roundtrip_blank_lines_preserved() {
        rt("\n\nsrc/main.rs\n\n\nsrc/auth/\n");
    }

    #[test]
    fn roundtrip_tab_indent() {
        rt("src/main.rs\n\t-> src/auth/ : foo\n");
    }

    #[test]
    fn roundtrip_indented_node() {
        rt("src/\n    src/main.rs\n");
    }

    #[test]
    fn roundtrip_orphan_tags() {
        rt("[orphan]\na.rs\n\n[orphan bundle]\nsrc/\n");
    }

    #[test]
    fn roundtrip_link_subtree_tag() {
        rt("[bundle]\nsrc/\n");
    }

    #[test]
    fn roundtrip_preserves_whitespace_aligned_edges() {
        // Hand-authored alignment — must be preserved verbatim.
        rt(
            "src/main.rs\n    -> src/auth/        : bootstraps authentication\n    -> config.toml      : reads secrets\n    -- docs/arch.md     : documented by\n",
        );
    }

    #[test]
    fn roundtrip_folder_node() {
        rt("src/auth/\n");
    }

    #[test]
    fn roundtrip_orphan_after_edges() {
        rt("src/main.rs\n    -> src/auth/ : foo\n\ndocs/arch.md\n\nREADME.md\n");
    }

    #[test]
    fn roundtrip_indented_comment_preserved() {
        // An indented comment is stored verbatim as a Comment line.
        rt("src/main.rs\n    # not an edge\n    -> src/auth/ : foo\n");
    }

    #[test]
    fn roundtrip_spec_example() {
        let input = "# This is a comment\n\nsrc/main.rs\n    -> src/auth/        : bootstraps authentication\n    -> config.toml      : reads secrets\n    -- docs/arch.md     : documented by\n\nsrc/auth/\n    -> src/db/          : queries user table\n    -> src/models/      : uses User model\n\ndocs/arch.md\n\nREADME.md\n";
        rt(input);
    }

    // -----------------------------------------------------------------------
    // Semantic extraction: to_graph
    // -----------------------------------------------------------------------

    #[test]
    fn to_graph_single_orphan() {
        let input = "src/main.rs\n";
        let doc = parse(input).unwrap();
        let graph = to_graph(&doc).unwrap();
        assert_eq!(graph.nodes.len(), 1);
        assert_eq!(graph.nodes[0].path, "src/main.rs");
        assert!(graph.nodes[0].is_orphan());
    }

    #[test]
    fn to_graph_directed_edge() {
        let input = "src/main.rs\n    -> src/auth/ : bootstraps\n";
        let doc = parse(input).unwrap();
        let graph = to_graph(&doc).unwrap();
        assert_eq!(graph.nodes[0].edges.len(), 1);
        let e = &graph.nodes[0].edges[0];
        assert_eq!(e.target, "src/auth/");
        assert_eq!(e.kind, EdgeKind::Directed);
        assert_eq!(e.label, "bootstraps");
    }

    #[test]
    fn to_graph_undirected_edge() {
        let input = "src/auth/\n    -- docs/auth.md : documented by\n";
        let doc = parse(input).unwrap();
        let graph = to_graph(&doc).unwrap();
        assert_eq!(graph.nodes[0].edges[0].kind, EdgeKind::Undirected);
        assert_eq!(graph.nodes[0].edges[0].label, "documented by");
    }

    #[test]
    fn to_graph_incoming_edge() {
        let input = "src/auth/\n    <- src/main.rs : bootstrapped by\n";
        let doc = parse(input).unwrap();
        let graph = to_graph(&doc).unwrap();
        assert_eq!(graph.nodes[0].edges[0].kind, EdgeKind::Incoming);
        assert_eq!(graph.nodes[0].edges[0].target, "src/main.rs");
    }

    #[test]
    fn to_graph_empty_label() {
        let input = "src/main.rs\n    -> src/auth/ :\n";
        let doc = parse(input).unwrap();
        let graph = to_graph(&doc).unwrap();
        assert_eq!(graph.nodes[0].edges[0].label, "");
    }

    #[test]
    fn to_graph_multiple_nodes_and_edges() {
        let input = "src/main.rs\n    -> src/auth/ : foo\n\nsrc/auth/\n    -> src/db/ : bar\n\ndocs/arch.md\n";
        let doc = parse(input).unwrap();
        let graph = to_graph(&doc).unwrap();
        assert_eq!(graph.nodes.len(), 3);
        assert_eq!(graph.nodes[0].edges.len(), 1);
        assert_eq!(graph.nodes[1].edges.len(), 1);
        assert!(graph.nodes[2].is_orphan());
    }

    #[test]
    fn to_graph_comments_and_blanks_ignored() {
        let input = "# comment\n\n[orphan]\nsrc/main.rs\n    -> src/auth/ : foo\n\n# another\n";
        let doc = parse(input).unwrap();
        let graph = to_graph(&doc).unwrap();
        assert_eq!(graph.nodes.len(), 1);
        assert_eq!(graph.nodes[0].edges.len(), 1);
    }

    #[test]
    fn to_graph_edge_after_blank_belongs_to_node() {
        // Blank lines between a node and its edges are allowed (blanks ignored semantically).
        let input = "src/main.rs\n\n    -> src/auth/ : foo\n";
        let doc = parse(input).unwrap();
        let graph = to_graph(&doc).unwrap();
        assert_eq!(graph.nodes[0].edges.len(), 1);
    }

    #[test]
    fn to_graph_preserves_node_order() {
        let input = "b.rs\na.rs\nc.rs\n";
        let doc = parse(input).unwrap();
        let graph = to_graph(&doc).unwrap();
        assert_eq!(graph.nodes[0].path, "b.rs");
        assert_eq!(graph.nodes[1].path, "a.rs");
        assert_eq!(graph.nodes[2].path, "c.rs");
    }

    #[test]
    fn to_graph_parses_indented_nodes() {
        let input = "src/\n    src/main.rs\n";
        let doc = parse(input).unwrap();
        let graph = to_graph(&doc).unwrap();
        assert_eq!(graph.nodes.len(), 2);
        assert_eq!(graph.nodes[1].path, "src/main.rs");
    }

    // -----------------------------------------------------------------------
    // Error cases
    // -----------------------------------------------------------------------

    #[test]
    fn error_duplicate_node() {
        let input = "src/main.rs\nsrc/main.rs\n";
        let doc = parse(input).unwrap();
        assert!(to_graph(&doc).is_err());
    }

    #[test]
    fn error_edge_before_any_node() {
        // parse succeeds (we validate edge syntax at parse time),
        // but to_graph should fail.
        let input = "    -> src/auth/ : foo\n";
        let doc = parse(input).unwrap();
        assert!(to_graph(&doc).is_err());
    }

    #[test]
    fn error_edge_missing_colon() {
        let input = "src/main.rs\n    -> src/auth/\n";
        assert!(parse(input).is_err());
    }

    #[test]
    fn error_edge_missing_target() {
        let input = "src/main.rs\n    -> :\n";
        assert!(parse(input).is_err());
    }

    #[test]
    fn error_edge_bad_arrow() {
        let input = "src/main.rs\n    => src/auth/ : foo\n";
        assert!(parse(input).is_err());
    }

    // -----------------------------------------------------------------------
    // from_graph
    // -----------------------------------------------------------------------

    #[test]
    fn from_graph_empty() {
        let graph = Graph::new();
        let doc = from_graph(&graph);
        assert!(doc.lines.is_empty());
        assert_eq!(serialize(&doc), "");
    }

    #[test]
    fn from_graph_single_orphan() {
        let mut graph = Graph::new();
        graph.add_node(Node::new("src/main.rs"));
        let doc = from_graph(&graph);
        assert_eq!(serialize(&doc), "    src/main.rs\n");
    }

    #[test]
    fn from_graph_with_edges() {
        let mut graph = Graph::new();
        let mut node = Node::new("src/main.rs");
        node.edges.push(Edge {
            target: "src/auth/".into(),
            kind: EdgeKind::Directed,
            label: "bootstraps".into(),
        });
        graph.add_node(node);
        let out = serialize(&from_graph(&graph));
        assert!(out.contains("src/main.rs\n"));
        assert!(out.contains("    -> src/auth/ : bootstraps"));
    }

    #[test]
    fn from_graph_empty_label_edge() {
        let mut graph = Graph::new();
        let mut node = Node::new("src/main.rs");
        node.edges.push(Edge {
            target: "src/auth/".into(),
            kind: EdgeKind::Directed,
            label: String::new(),
        });
        graph.add_node(node);
        let out = serialize(&from_graph(&graph));
        assert!(out.contains("    -> src/auth/ :"));
    }

    #[test]
    fn from_graph_separates_nodes_with_blank_line() {
        let mut graph = Graph::new();
        graph.add_node(Node::new("a.rs"));
        graph.add_node(Node::new("b.rs"));
        let out = serialize(&from_graph(&graph));
        assert_eq!(out, "a.rs\n\nb.rs\n");
    }

    // -----------------------------------------------------------------------
    // Document mutation: add_node
    // -----------------------------------------------------------------------

    #[test]
    fn add_node_to_empty_doc() {
        let mut doc = Document::default();
        add_node(&mut doc, "src/main.rs");
        assert_eq!(serialize(&doc), "    src/main.rs\n");
    }

    #[test]
    fn add_node_appends_with_blank_separator() {
        let mut doc = parse("a.rs\n").unwrap();
        add_node(&mut doc, "b.rs");
        assert_eq!(serialize(&doc), "a.rs\n\nb.rs\n");
    }

    #[test]
    fn add_node_inserts_by_hierarchy_before_root_file() {
        let mut doc = parse("src/\n\nroot.rs\n").unwrap();
        add_node(&mut doc, "src/new/");
        assert_eq!(serialize(&doc), "src/\n\n    src/new/\n\nroot.rs\n");
    }

    #[test]
    fn add_node_under_folder_with_edges_avoids_extra_blank_before_first_child() {
        let mut doc = parse("src/\n    <- consumer.rs : used by\n\nconsumer.rs\n").unwrap();
        add_node(&mut doc, "src/new.rs");
        let out = serialize(&doc);
        assert!(
            out.contains("src/\n    <- consumer.rs : used by\n    src/new.rs\n\nconsumer.rs\n")
        );
    }

    #[test]
    fn intentional_orphans_marker_and_subtree() {
        let doc = parse(
            "\
[orphan]
simple.rs

[orphan bundle]
src/
    src/lib.rs
    src/sub/
        src/sub/leaf.rs
",
        )
        .unwrap();
        let marked = intentional_orphans(&doc);
        assert!(marked.contains("simple.rs"));
        assert!(marked.contains("src/"));
        assert!(marked.contains("src/lib.rs"));
        assert!(marked.contains("src/sub/"));
        assert!(marked.contains("src/sub/leaf.rs"));
    }

    #[test]
    fn intentional_orphans_ignores_floating_tags() {
        let doc = parse(
            "\
[orphan]

[orphan]
a.rs
",
        )
        .unwrap();
        let marked = intentional_orphans(&doc);
        assert_eq!(marked.len(), 1);
        assert!(marked.contains("a.rs"));
    }

    #[test]
    fn mark_orphan_inserts_simple_marker() {
        let mut doc = parse("a.rs\n").unwrap();
        assert!(mark_orphan(&mut doc, "a.rs"));
        assert_eq!(serialize(&doc), "[orphan]\na.rs\n");
    }

    #[test]
    fn mark_orphan_no_duplicate() {
        let mut doc = parse("[orphan]\na.rs\n").unwrap();
        assert!(!mark_orphan(&mut doc, "a.rs"));
        assert_eq!(serialize(&doc), "[orphan]\na.rs\n");
    }

    #[test]
    fn mark_orphan_aligns_with_nested_node_indent() {
        let mut doc = parse("src/\n\n    src/main.rs\n").unwrap();
        assert!(mark_orphan(&mut doc, "src/main.rs"));
        assert_eq!(serialize(&doc), "src/\n\n    [orphan]\n    src/main.rs\n");
    }

    #[test]
    fn mark_orphan_subtree_inserts_marker() {
        let mut doc = parse("src/\n").unwrap();
        assert!(mark_orphan_subtree(&mut doc, "src/"));
        assert_eq!(serialize(&doc), "[orphan bundle]\nsrc/\n");
    }

    #[test]
    fn mark_orphan_subtree_rejects_file_nodes() {
        let mut doc = parse("a.rs\n").unwrap();
        assert!(!mark_orphan_subtree(&mut doc, "a.rs"));
        assert_eq!(serialize(&doc), "a.rs\n");
    }

    #[test]
    fn mark_orphan_subtree_aligns_with_nested_node_indent() {
        let mut doc = parse("src/\n\n    src/sub/\n").unwrap();
        assert!(mark_orphan_subtree(&mut doc, "src/sub/"));
        assert_eq!(
            serialize(&doc),
            "src/\n\n    [orphan bundle]\n    src/sub/\n"
        );
    }

    #[test]
    fn mark_link_subtree_inserts_marker() {
        let mut doc = parse("src/\n").unwrap();
        assert!(mark_link_subtree(&mut doc, "src/"));
        assert_eq!(serialize(&doc), "[bundle]\nsrc/\n");
    }

    #[test]
    fn explicit_orphan_markers_detects_both_tag_types() {
        let doc = parse("[orphan]\na.rs\n\n[orphan bundle]\nsrc/\n").unwrap();
        let markers = explicit_orphan_markers(&doc);
        assert_eq!(markers.len(), 2);
        assert_eq!(markers[0], ("a.rs".to_string(), OrphanMarkerKind::Orphan));
        assert_eq!(
            markers[1],
            ("src/".to_string(), OrphanMarkerKind::OrphanSubtree)
        );
    }

    #[test]
    fn explicit_link_subtree_markers_detects_folder_roots() {
        let doc = parse("[bundle]\nsrc/\n\n[orphan bundle]\nother/\n").unwrap();
        let roots = explicit_link_subtree_markers(&doc);
        assert_eq!(roots, vec!["src/".to_string()]);
    }

    #[test]
    fn unmark_orphan_removes_marker_only() {
        let mut doc = parse("[orphan]\na.rs\n").unwrap();
        assert!(unmark_orphan(&mut doc, "a.rs"));
        assert_eq!(serialize(&doc), "a.rs\n");
    }

    #[test]
    fn unmark_link_subtree_removes_bundle_and_keeps_orphan() {
        let mut doc = parse("[orphan bundle]\nsrc/\n").unwrap();
        assert!(unmark_link_subtree(&mut doc, "src/"));
        assert_eq!(serialize(&doc), "[orphan]\nsrc/\n");
    }

    #[test]
    fn unmark_orphan_subtree_removes_orphan_and_keeps_bundle() {
        let mut doc = parse("[orphan bundle]\nsrc/\n").unwrap();
        assert!(unmark_orphan_subtree(&mut doc, "src/"));
        assert_eq!(serialize(&doc), "[bundle]\nsrc/\n");
    }

    #[test]
    fn convert_link_subtree_to_orphan_subtree_rewrites_marker() {
        let mut doc = parse("[bundle]\nsrc/\n").unwrap();
        assert!(convert_link_subtree_to_orphan_subtree(&mut doc, "src/"));
        assert_eq!(serialize(&doc), "[orphan bundle]\nsrc/\n");
    }

    #[test]
    fn convert_link_subtree_to_orphan_subtree_preserves_indent() {
        let mut doc = parse("src/\n\n    [bundle]\n    src/html/\n").unwrap();
        assert!(convert_link_subtree_to_orphan_subtree(
            &mut doc,
            "src/html/"
        ));
        assert_eq!(
            serialize(&doc),
            "src/\n\n    [orphan bundle]\n    src/html/\n"
        );
    }

    #[test]
    fn convert_orphan_to_orphan_subtree_rewrites_marker() {
        let mut doc = parse("[orphan]\nsrc/\n").unwrap();
        assert!(convert_orphan_to_orphan_subtree(&mut doc, "src/"));
        assert_eq!(serialize(&doc), "[orphan bundle]\nsrc/\n");
    }

    #[test]
    fn lint_removes_floating_orphan_tags() {
        let mut doc = parse(
            "\
[orphan]

[orphan bundle]
# comment

a.rs
",
        )
        .unwrap();
        let report = lint(&mut doc);
        assert_eq!(report.removed_floating_orphan_tags, 1);
        assert_eq!(serialize(&doc), "[orphan]\n# comment\n\na.rs\n");
    }

    #[test]
    fn lint_removes_invalid_link_subtree_tag_on_file() {
        let mut doc = parse("[bundle]\na.rs\n").unwrap();
        let report = lint(&mut doc);
        assert_eq!(report.removed_floating_orphan_tags, 1);
        assert_eq!(serialize(&doc), "a.rs\n");
    }

    #[test]
    fn lint_keeps_orphan_subtree_on_empty_folder() {
        let mut doc = parse("[orphan bundle]\nempty/\n").unwrap();
        let report = lint(&mut doc);
        assert_eq!(report.removed_floating_orphan_tags, 0);
        assert_eq!(report.removed_extra_blank_lines, 0);
        assert_eq!(serialize(&doc), "[orphan bundle]\nempty/\n");
    }

    #[test]
    fn lint_collapses_consecutive_blank_lines() {
        let mut doc = parse("a.rs\n\n\nb.rs\n\n\nc.rs\n").unwrap();
        let report = lint(&mut doc);
        assert_eq!(report.removed_floating_orphan_tags, 0);
        assert_eq!(report.removed_extra_blank_lines, 2);
        assert_eq!(serialize(&doc), "a.rs\n\nb.rs\n\nc.rs\n");
    }

    #[test]
    fn lint_normalizes_tag_and_edge_indentation_to_node_depth() {
        let mut doc =
            parse("src/\n\n[orphan]\n    src/main.rs\n    -> README.md : documents\n").unwrap();
        let report = lint(&mut doc);
        assert_eq!(report.normalized_tag_indentation, 1);
        assert_eq!(report.normalized_edge_indentation, 1);
        assert_eq!(
            serialize(&doc),
            "src/\n\n    [orphan]\n    src/main.rs\n        -> README.md : documents\n"
        );
    }

    // -----------------------------------------------------------------------
    // Document mutation: remove_node
    // -----------------------------------------------------------------------

    #[test]
    fn remove_node_present() {
        let mut doc = parse("a.rs\n\nb.rs\n    -> a.rs : foo\n\nc.rs\n").unwrap();
        let removed = remove_node(&mut doc, "b.rs");
        assert!(removed);
        let out = serialize(&doc);
        assert!(!out.contains("b.rs"));
        assert!(out.contains("a.rs\n"));
        assert!(out.contains("c.rs\n"));
    }

    #[test]
    fn remove_node_not_present() {
        let mut doc = parse("a.rs\n").unwrap();
        assert!(!remove_node(&mut doc, "z.rs"));
    }

    #[test]
    fn remove_middle_node_preserves_separator_spacing() {
        let mut doc = parse("a/\n\n    a/file.rs\n\n    b/\n").unwrap();
        assert!(remove_node(&mut doc, "a/file.rs"));
        assert_eq!(serialize(&doc), "a/\n\n    b/\n");
    }

    #[test]
    fn remove_middle_node_preserves_following_tagged_block() {
        let mut doc = parse(
            "[orphan bundle]\na/\n\n    a/file.rs\n\n    [orphan bundle]\n    b/\n\n        b/file.rs\n",
        )
        .unwrap();
        assert!(remove_node(&mut doc, "a/file.rs"));
        let out = serialize(&doc);
        assert!(out.contains("    [orphan bundle]\n    b/\n"));
    }

    #[test]
    fn remove_node_also_removes_attached_orphan_tag() {
        let mut doc = parse("[orphan]\nnode.rs\n\nnext.rs\n").unwrap();
        assert!(remove_node(&mut doc, "node.rs"));
        assert_eq!(serialize(&doc), "next.rs\n");
    }

    #[test]
    fn remove_last_tagged_node_removes_separator_blank() {
        let mut doc = parse("prev.rs\n\n[orphan]\nnode.rs\n").unwrap();
        assert!(remove_node(&mut doc, "node.rs"));
        assert_eq!(serialize(&doc), "prev.rs\n");
    }

    #[test]
    fn remove_node_only_node() {
        let mut doc = parse("a.rs\n").unwrap();
        remove_node(&mut doc, "a.rs");
        assert_eq!(serialize(&doc), "");
    }

    // -----------------------------------------------------------------------
    // Document mutation: add_edge
    // -----------------------------------------------------------------------

    #[test]
    fn add_edge_to_orphan() {
        let mut doc = parse("src/main.rs\n").unwrap();
        let edge = Edge {
            target: "src/auth/".into(),
            kind: EdgeKind::Directed,
            label: "bootstraps".into(),
        };
        add_edge(&mut doc, "src/main.rs", &edge).unwrap();
        let out = serialize(&doc);
        assert_eq!(out, "src/main.rs\n    -> src/auth/ : bootstraps\n");
    }

    #[test]
    fn add_edge_appends_after_existing() {
        let mut doc = parse("src/main.rs\n    -> src/auth/ : foo\n").unwrap();
        let edge = Edge {
            target: "config.toml".into(),
            kind: EdgeKind::Directed,
            label: "reads".into(),
        };
        add_edge(&mut doc, "src/main.rs", &edge).unwrap();
        let out = serialize(&doc);
        assert_eq!(
            out,
            "src/main.rs\n    -> src/auth/ : foo\n    -> config.toml : reads\n"
        );
    }

    #[test]
    fn add_edge_does_not_affect_other_nodes() {
        let mut doc = parse("a.rs\n\nb.rs\n    -> a.rs : foo\n").unwrap();
        let edge = Edge {
            target: "c.rs".into(),
            kind: EdgeKind::Undirected,
            label: String::new(),
        };
        add_edge(&mut doc, "a.rs", &edge).unwrap();
        let out = serialize(&doc);
        // a.rs gets the new edge, b.rs's edges are unchanged
        assert!(out.starts_with("a.rs\n    -- c.rs :\n\nb.rs\n    -> a.rs : foo\n"));
    }

    #[test]
    fn add_edge_node_not_found() {
        let mut doc = parse("a.rs\n").unwrap();
        let edge = Edge {
            target: "b.rs".into(),
            kind: EdgeKind::Directed,
            label: String::new(),
        };
        assert!(add_edge(&mut doc, "z.rs", &edge).is_err());
    }

    #[test]
    fn add_node_respects_existing_two_space_indent() {
        let mut doc = parse("src/\n\n  src/main.rs\n").unwrap();
        add_node(&mut doc, "src/new.rs");
        let out = serialize(&doc);
        assert!(out.contains("  src/new.rs\n"));
        assert!(!out.contains("    src/new.rs\n"));
    }

    #[test]
    fn add_edge_respects_existing_tab_indent() {
        let mut doc = parse("src/main.rs\n\t-> src/auth/ : bootstraps\n").unwrap();
        let edge = Edge {
            target: "src/db/".into(),
            kind: EdgeKind::Directed,
            label: "queries".into(),
        };
        add_edge(&mut doc, "src/main.rs", &edge).unwrap();
        let out = serialize(&doc);
        assert!(out.contains("\t-> src/db/ : queries\n"));
        assert!(!out.contains("    -> src/db/ : queries\n"));
    }

    #[test]
    fn add_edge_under_nested_node_uses_nested_indent() {
        let mut doc = parse("src/\n\n    src/main.rs\n").unwrap();
        let edge = Edge {
            target: "README.md".into(),
            kind: EdgeKind::Directed,
            label: "documents".into(),
        };
        add_edge(&mut doc, "src/main.rs", &edge).unwrap();
        assert!(serialize(&doc).contains("    src/main.rs\n        -> README.md : documents\n"));
    }

    #[test]
    fn sort_edges_by_kind_orders_undir_then_out_then_in() {
        let mut doc = parse(
            "a.rs\n    <- d.rs : in\n    -> b.rs : out\n    -- c.rs : undirected\n\nb.rs\n\nc.rs\n\nd.rs\n",
        )
        .unwrap();
        let changed = sort_edges_by_kind(&mut doc);
        assert_eq!(changed, 1);
        assert!(
            serialize(&doc)
                .contains("a.rs\n    -- c.rs : undirected\n    -> b.rs : out\n    <- d.rs : in\n")
        );
    }

    #[test]
    fn intentional_orphan_subtree_roots_returns_folder_roots_only() {
        let doc = parse(
            "\
[orphan bundle]
src/
    src/lib.rs

[orphan]
other.rs
",
        )
        .unwrap();
        let roots = intentional_orphan_subtree_roots(&doc);
        assert_eq!(roots.len(), 1);
        assert!(roots.contains("src/"));
        assert!(!roots.contains("other.rs"));
    }

    #[test]
    fn collapsed_subtree_roots_includes_link_subtree() {
        let doc = parse(
            "\
[bundle]
linked/

[orphan bundle]
orphaned/
",
        )
        .unwrap();
        let roots = collapsed_subtree_roots(&doc);
        assert!(roots.contains("linked/"));
        assert!(roots.contains("orphaned/"));
    }

    // -----------------------------------------------------------------------
    // Document mutation: remove_edge
    // -----------------------------------------------------------------------

    #[test]
    fn remove_edge_present() {
        let mut doc =
            parse("src/main.rs\n    -> src/auth/ : foo\n    -> config.toml : bar\n").unwrap();
        let removed = remove_edge(&mut doc, "src/main.rs", "src/auth/");
        assert!(removed);
        let out = serialize(&doc);
        assert!(!out.contains("src/auth/"));
        assert!(out.contains("config.toml"));
    }

    #[test]
    fn remove_edge_not_present() {
        let mut doc = parse("src/main.rs\n    -> src/auth/ : foo\n").unwrap();
        assert!(!remove_edge(&mut doc, "src/main.rs", "nonexistent"));
    }

    #[test]
    fn replace_edge_label_updates_matching_edge_only() {
        let mut doc = parse("a.rs\n    -> b.rs : old\n    -> c.rs : keep\n").unwrap();
        let changed =
            replace_edge_label(&mut doc, "a.rs", "b.rs", EdgeKind::Directed, "old", "new");
        assert_eq!(changed, 1);
        let out = serialize(&doc);
        assert!(out.contains("-> b.rs : new"));
        assert!(out.contains("-> c.rs : keep"));
    }

    #[test]
    fn replace_edge_label_preserves_tab_indent() {
        let mut doc = parse("a.rs\n\t<- b.rs : old\n").unwrap();
        let changed =
            replace_edge_label(&mut doc, "a.rs", "b.rs", EdgeKind::Incoming, "old", "new");
        assert_eq!(changed, 1);
        assert_eq!(serialize(&doc), "a.rs\n\t<- b.rs : new\n");
    }

    // -----------------------------------------------------------------------
    // Document mutation: mark_missing
    // -----------------------------------------------------------------------

    #[test]
    fn mark_missing_inserts_comment() {
        let mut doc = parse("src/main.rs\n").unwrap();
        assert!(mark_missing(&mut doc, "src/main.rs"));
        let out = serialize(&doc);
        assert!(out.contains("# [missing] src/main.rs"));
    }

    // -----------------------------------------------------------------------
    // Document mutation: remove_edges_targeting
    // -----------------------------------------------------------------------

    #[test]
    fn remove_edges_targeting_basic() {
        let mut doc = parse("a.rs\n    -> b.rs : foo\n\nb.rs\n    -> a.rs : bar\n").unwrap();
        let count = remove_edges_targeting(&mut doc, "b.rs");
        assert_eq!(count, 1);
        let out = serialize(&doc);
        // The edge from a.rs -> b.rs is gone; b.rs node and its edges remain.
        assert!(!out.contains("-> b.rs"));
        assert!(out.contains("b.rs\n"));
        assert!(out.contains("-> a.rs : bar"));
    }

    #[test]
    fn remove_edges_targeting_multiple_sources() {
        let mut doc =
            parse("a.rs\n    -> c.rs : foo\n\nb.rs\n    -> c.rs : bar\n\nc.rs\n").unwrap();
        let count = remove_edges_targeting(&mut doc, "c.rs");
        assert_eq!(count, 2);
        let out = serialize(&doc);
        assert!(!out.contains("-> c.rs"));
        assert!(out.contains("c.rs\n"));
    }

    #[test]
    fn remove_edges_targeting_none() {
        let mut doc = parse("a.rs\n    -> b.rs : foo\n").unwrap();
        let count = remove_edges_targeting(&mut doc, "nonexistent");
        assert_eq!(count, 0);
    }

    // -----------------------------------------------------------------------
    // Edge cases and special paths
    // -----------------------------------------------------------------------

    #[test]
    fn crlf_roundtrip() {
        // Simulates a file with CRLF line endings.
        let input = "src/main.rs\r\n    -> src/auth/ : foo\r\n";
        let doc = parse(input).unwrap();
        assert_eq!(serialize(&doc), input);
    }

    #[test]
    fn node_path_with_spaces_in_name() {
        // Paths with spaces are valid on some filesystems.
        rt("src/my file.rs\n    -> src/other file.rs : foo\n");
    }

    #[test]
    fn multiple_blank_lines_preserved() {
        rt("a.rs\n\n\n\nb.rs\n");
    }
}