dotr-dear 2.0.1

A dotfiles manager as dear as a daughter.
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
1205
1206
1207
1208
1209
1210
1211
1212
1213
1214
1215
1216
1217
1218
1219
1220
1221
1222
1223
1224
1225
1226
1227
1228
1229
1230
1231
1232
1233
1234
1235
1236
1237
1238
1239
1240
1241
1242
1243
1244
1245
1246
1247
1248
1249
1250
1251
1252
1253
1254
1255
1256
1257
1258
1259
1260
1261
1262
1263
1264
1265
1266
1267
1268
1269
1270
1271
1272
1273
1274
1275
1276
1277
1278
1279
1280
1281
1282
1283
1284
1285
1286
1287
1288
1289
1290
1291
1292
1293
1294
1295
1296
1297
1298
1299
1300
1301
1302
1303
1304
1305
1306
1307
1308
1309
1310
1311
1312
1313
1314
1315
1316
1317
1318
1319
1320
1321
1322
1323
1324
1325
1326
1327
1328
1329
1330
1331
1332
1333
1334
1335
1336
1337
1338
1339
1340
1341
1342
1343
1344
1345
1346
1347
1348
1349
1350
1351
1352
1353
1354
1355
1356
1357
1358
1359
1360
1361
1362
1363
1364
1365
1366
1367
1368
1369
1370
1371
1372
1373
1374
1375
1376
1377
1378
1379
1380
1381
1382
1383
1384
1385
1386
1387
1388
1389
1390
1391
1392
1393
1394
1395
1396
1397
1398
1399
1400
1401
1402
1403
1404
1405
1406
1407
1408
1409
1410
1411
1412
1413
1414
1415
1416
1417
1418
1419
1420
1421
1422
1423
1424
1425
1426
1427
1428
1429
1430
1431
1432
1433
1434
1435
1436
1437
1438
1439
1440
1441
1442
1443
1444
1445
1446
1447
1448
1449
1450
1451
1452
1453
1454
1455
1456
1457
1458
1459
1460
1461
1462
1463
1464
1465
1466
1467
1468
1469
1470
1471
1472
1473
1474
1475
1476
1477
1478
1479
1480
1481
1482
1483
1484
1485
1486
1487
1488
1489
1490
1491
1492
1493
1494
1495
1496
1497
1498
1499
1500
1501
1502
1503
1504
1505
1506
1507
1508
1509
1510
1511
1512
1513
1514
1515
1516
1517
1518
1519
1520
1521
1522
1523
1524
1525
1526
1527
1528
1529
1530
1531
1532
1533
1534
1535
1536
1537
1538
1539
1540
1541
1542
1543
1544
1545
1546
1547
1548
1549
1550
1551
1552
1553
1554
1555
1556
1557
1558
1559
1560
1561
1562
1563
1564
1565
1566
1567
1568
1569
1570
1571
1572
1573
1574
1575
1576
1577
1578
1579
1580
1581
1582
1583
1584
1585
1586
1587
1588
1589
1590
1591
1592
1593
1594
1595
1596
1597
1598
1599
1600
1601
1602
1603
1604
1605
1606
1607
1608
1609
1610
1611
1612
1613
1614
1615
1616
1617
1618
1619
1620
1621
1622
1623
1624
1625
1626
1627
1628
1629
1630
1631
1632
1633
1634
1635
1636
1637
1638
1639
1640
1641
1642
1643
1644
1645
1646
1647
1648
1649
1650
1651
1652
1653
1654
1655
1656
1657
1658
1659
1660
1661
1662
1663
1664
1665
1666
1667
1668
1669
1670
1671
1672
1673
1674
1675
1676
1677
1678
1679
1680
1681
1682
1683
1684
1685
1686
1687
1688
1689
1690
1691
1692
1693
1694
1695
1696
1697
1698
1699
1700
1701
1702
1703
1704
1705
1706
1707
1708
1709
1710
1711
1712
1713
1714
1715
1716
1717
1718
1719
1720
1721
1722
1723
1724
1725
1726
1727
1728
1729
1730
1731
1732
1733
1734
1735
1736
1737
1738
1739
1740
1741
1742
1743
1744
1745
1746
1747
1748
1749
1750
1751
1752
1753
1754
1755
1756
1757
1758
1759
1760
1761
1762
1763
1764
1765
1766
1767
1768
1769
1770
1771
1772
1773
1774
1775
1776
1777
1778
1779
1780
1781
1782
1783
1784
1785
1786
1787
1788
1789
1790
1791
1792
1793
1794
1795
1796
1797
1798
1799
1800
1801
1802
1803
1804
1805
1806
1807
1808
1809
1810
1811
1812
1813
1814
1815
1816
1817
1818
1819
1820
1821
1822
1823
1824
1825
1826
1827
1828
1829
1830
1831
1832
1833
1834
1835
1836
1837
1838
1839
1840
1841
1842
1843
1844
1845
1846
1847
1848
1849
1850
1851
1852
1853
1854
1855
1856
1857
1858
1859
1860
1861
1862
1863
1864
1865
1866
1867
1868
1869
1870
1871
1872
1873
1874
1875
1876
1877
1878
1879
1880
1881
1882
1883
1884
1885
1886
1887
1888
1889
1890
1891
1892
1893
1894
1895
1896
1897
1898
1899
1900
1901
1902
1903
1904
1905
1906
1907
1908
1909
1910
1911
1912
1913
1914
1915
1916
1917
1918
1919
1920
1921
1922
1923
1924
1925
1926
1927
1928
1929
1930
1931
1932
1933
1934
1935
1936
1937
1938
1939
1940
1941
1942
1943
1944
1945
1946
1947
1948
1949
1950
1951
1952
1953
1954
1955
1956
1957
1958
1959
1960
1961
1962
1963
1964
1965
1966
1967
1968
1969
1970
1971
1972
1973
1974
1975
1976
1977
1978
1979
1980
1981
1982
1983
1984
1985
1986
1987
1988
1989
1990
1991
1992
1993
1994
1995
1996
1997
1998
1999
2000
2001
2002
2003
2004
2005
2006
2007
2008
2009
2010
2011
2012
2013
2014
2015
2016
2017
2018
2019
2020
2021
2022
2023
2024
2025
2026
2027
2028
2029
2030
2031
2032
2033
2034
2035
2036
2037
2038
2039
2040
2041
2042
2043
2044
2045
2046
2047
2048
2049
2050
2051
2052
2053
2054
2055
2056
2057
2058
2059
2060
2061
2062
2063
2064
2065
2066
2067
2068
2069
2070
2071
2072
2073
2074
2075
2076
2077
2078
2079
2080
2081
2082
2083
2084
2085
2086
2087
2088
2089
2090
2091
2092
2093
2094
2095
2096
2097
2098
2099
2100
2101
2102
2103
2104
2105
2106
2107
2108
2109
2110
2111
2112
2113
2114
2115
2116
2117
2118
2119
2120
2121
2122
2123
2124
2125
2126
2127
2128
2129
2130
2131
2132
2133
2134
2135
2136
2137
2138
2139
2140
2141
2142
2143
2144
2145
2146
2147
2148
2149
2150
2151
2152
2153
2154
2155
2156
2157
2158
2159
2160
2161
2162
2163
2164
2165
2166
2167
2168
2169
2170
2171
2172
2173
2174
2175
2176
2177
2178
2179
2180
2181
2182
2183
2184
2185
2186
2187
2188
2189
2190
2191
2192
2193
2194
2195
2196
2197
2198
2199
2200
2201
2202
2203
2204
2205
2206
2207
2208
2209
2210
2211
2212
2213
2214
2215
2216
2217
2218
2219
2220
2221
2222
2223
2224
2225
2226
2227
2228
2229
2230
2231
2232
2233
2234
2235
2236
2237
2238
2239
2240
2241
2242
2243
2244
2245
2246
2247
2248
2249
2250
2251
2252
2253
2254
2255
2256
2257
2258
2259
2260
2261
2262
2263
2264
2265
2266
2267
2268
2269
2270
2271
2272
2273
2274
2275
2276
2277
2278
2279
2280
2281
2282
2283
2284
2285
2286
2287
2288
2289
2290
2291
2292
2293
2294
2295
2296
2297
2298
2299
2300
2301
2302
2303
2304
2305
2306
2307
2308
2309
2310
2311
2312
2313
2314
2315
2316
2317
2318
2319
2320
2321
2322
2323
2324
2325
2326
2327
2328
2329
2330
2331
2332
2333
2334
2335
2336
2337
2338
2339
2340
2341
2342
2343
2344
2345
2346
2347
2348
2349
2350
2351
2352
2353
2354
2355
2356
2357
2358
2359
2360
2361
2362
2363
2364
2365
2366
2367
2368
2369
2370
2371
2372
2373
2374
2375
2376
2377
2378
2379
2380
2381
2382
2383
2384
2385
2386
2387
2388
2389
2390
2391
2392
2393
2394
2395
2396
2397
2398
2399
2400
2401
2402
2403
2404
2405
2406
2407
2408
2409
2410
2411
2412
2413
2414
2415
2416
2417
2418
2419
2420
2421
2422
2423
2424
2425
2426
2427
2428
2429
2430
2431
2432
2433
2434
2435
2436
2437
2438
2439
2440
2441
2442
2443
2444
2445
2446
2447
2448
2449
2450
2451
2452
2453
2454
2455
2456
2457
2458
2459
2460
2461
2462
2463
2464
2465
2466
2467
2468
2469
2470
2471
2472
2473
2474
2475
2476
2477
2478
2479
2480
2481
2482
2483
2484
2485
2486
2487
2488
2489
2490
2491
2492
2493
2494
2495
2496
2497
2498
2499
2500
2501
2502
2503
2504
2505
2506
2507
2508
2509
2510
2511
2512
2513
2514
2515
2516
2517
2518
2519
2520
2521
2522
2523
2524
2525
2526
2527
2528
2529
2530
2531
2532
2533
2534
2535
2536
2537
2538
2539
2540
2541
2542
2543
2544
2545
2546
2547
2548
2549
2550
2551
2552
2553
2554
2555
use std::{fs, path::PathBuf};

use dotr_dear::{
    cli::{
        Cli, Command, CompletionShell, CompletionsArgs, DeployArgs, ImportArgs, InitArgs,
        PrintVarsArgs, UpdateArgs, run_cli,
    },
    config::Config,
    package::Package,
    profile::Profile,
};

struct TestFixture {
    cwd: PathBuf,
}

impl TestFixture {
    fn new() -> Self {
        let temp_dir = std::env::temp_dir().join(format!("dotr_cli_test_{}", uuid::Uuid::new_v4()));
        fs::create_dir_all(&temp_dir).expect("Failed to create temp dir");
        Self { cwd: temp_dir }
    }

    fn get_cli(&self, command: Option<Command>) -> Cli {
        Cli {
            command,
            working_dir: Some(self.cwd.to_str().unwrap().to_string()),
        }
    }

    fn init(&self) {
        run_cli(self.get_cli(Some(Command::Init(InitArgs {})))).expect("Init failed");
    }

    fn get_config(&self) -> Config {
        Config::from_path(&self.cwd).expect("Failed to load config")
    }

    fn assert_file_exists(&self, path: &str, message: &str) {
        assert!(self.cwd.join(path).exists(), "{}", message);
    }

    fn assert_file_not_exists(&self, path: &str, message: &str) {
        assert!(!self.cwd.join(path).exists(), "{}", message);
    }

    fn write_file(&self, path: &str, content: &str) {
        let file_path = self.cwd.join(path);
        if let Some(parent) = file_path.parent() {
            fs::create_dir_all(parent).expect("Failed to create parent dir");
        }
        fs::write(file_path, content).expect("Failed to write file");
    }

    fn read_file(&self, path: &str) -> String {
        fs::read_to_string(self.cwd.join(path)).expect("Failed to read file")
    }
}

impl Drop for TestFixture {
    fn drop(&mut self) {
        fs::remove_dir_all(&self.cwd).ok();
    }
}

#[test]
fn test_init_creates_config() {
    let fixture = TestFixture::new();

    fixture.init();

    fixture.assert_file_exists("config.toml", "config.toml should be created");
    fixture.assert_file_exists("dotfiles", "dotfiles directory should be created");
    fixture.assert_file_exists(".gitignore", ".gitignore should be created");

    let gitignore = fixture.read_file(".gitignore");
    assert!(
        gitignore.contains(".uservariables.toml"),
        ".gitignore should contain .uservariables.toml"
    );
}

#[test]
fn test_init_idempotent() {
    let fixture = TestFixture::new();

    // First init
    fixture.init();
    let first_config = fixture.read_file("config.toml");

    // Second init should not change config
    fixture.init();
    let second_config = fixture.read_file("config.toml");

    assert_eq!(
        first_config, second_config,
        "Config should not change on second init"
    );
}

#[test]
fn test_init_writes_schema_directive() {
    let fixture = TestFixture::new();

    fixture.init();

    let config = fixture.read_file("config.toml");
    let first_line = config
        .lines()
        .next()
        .expect("config.toml should not be empty");
    assert_eq!(
        first_line,
        "#:schema https://raw.githubusercontent.com/uroybd/DotR/main/schema/config.schema.json",
        "First line should be the taplo #:schema directive for editor validation/autocomplete"
    );

    // A leading comment must not break normal parsing.
    let loaded = fixture.get_config();
    assert!(
        loaded.profiles.contains_key("default"),
        "Config should still parse correctly with the schema directive present"
    );
}

#[test]
fn test_schema_directive_persists_across_saves() {
    let fixture = TestFixture::new();
    fixture.init();

    // Any mutating command re-saves config.toml. `Config::save()` has no
    // way to preserve a leading comment through serde round-tripping, so
    // it must re-add the directive itself on every write, not just the
    // one from `init()`.
    let mut config = fixture.get_config();
    config
        .profiles
        .entry("default".to_string())
        .or_insert_with(|| Profile::new("default"));
    config.save(&fixture.cwd).expect("Failed to save config");

    let content = fixture.read_file("config.toml");
    let first_line = content
        .lines()
        .next()
        .expect("config.toml should not be empty");
    assert_eq!(
        first_line,
        "#:schema https://raw.githubusercontent.com/uroybd/DotR/main/schema/config.schema.json",
        "The schema directive must survive a normal save(), not just the initial init()"
    );
}

#[test]
fn test_completions_all_shells_succeed() {
    let fixture = TestFixture::new();

    for shell in [
        CompletionShell::Bash,
        CompletionShell::Zsh,
        CompletionShell::Fish,
        CompletionShell::Elvish,
        CompletionShell::PowerShell,
        CompletionShell::Nushell,
        CompletionShell::Carapace,
    ] {
        let result =
            run_cli(fixture.get_cli(Some(Command::Completions(CompletionsArgs { shell }))));
        assert!(
            result.is_ok(),
            "completions generation should succeed for {:?}",
            shell
        );
    }
}

#[test]
fn test_completions_include_nested_packages_and_profiles_subcommands() {
    let output = std::process::Command::new(env!("CARGO_BIN_EXE_dotr"))
        .args(["completions", "bash"])
        .output()
        .expect("Failed to run dotr completions bash");
    assert!(
        output.status.success(),
        "completions command should succeed"
    );
    let script = String::from_utf8(output.stdout).expect("Output should be valid UTF-8");

    // Top-level subcommand groups.
    assert!(script.contains("packages"), "Should mention packages");
    assert!(script.contains("profiles"), "Should mention profiles");

    // Nested `packages` subcommands.
    for sub in ["list", "import", "deploy", "update", "remove", "diff"] {
        assert!(
            script.contains(sub),
            "Bash completions should include 'packages {}'",
            sub
        );
    }

    // Nested `profiles` subcommands.
    for sub in ["add", "list", "remove"] {
        assert!(
            script.contains(sub),
            "Bash completions should include 'profiles {}'",
            sub
        );
    }
}

#[test]
fn test_completions_carapace_matches_source_spec_file() {
    let output = std::process::Command::new(env!("CARGO_BIN_EXE_dotr"))
        .args(["completions", "carapace"])
        .output()
        .expect("Failed to run dotr completions carapace");
    assert!(
        output.status.success(),
        "completions carapace command should succeed"
    );
    let generated = String::from_utf8(output.stdout).expect("Output should be valid UTF-8");

    let source = fs::read_to_string(concat!(
        env!("CARGO_MANIFEST_DIR"),
        "/completions/carapace/dotr.yaml"
    ))
    .expect("Failed to read completions/carapace/dotr.yaml");

    assert_eq!(
        generated, source,
        "`dotr completions carapace` must print exactly the checked-in spec file, \
since the two are expected to stay embedded/identical (see include_str! in cli/mod.rs)"
    );

    // Sanity-check it's the spec we expect, not an empty/truncated file.
    assert!(generated.contains("name: dotr"));
    assert!(generated.contains("$(dotr packages list --plain)"));
    assert!(generated.contains("$(dotr profiles list --plain)"));
}

#[test]
fn test_packages_and_profiles_list_plain_output_is_scriptable() {
    let fixture = TestFixture::new();
    let bin = env!("CARGO_BIN_EXE_dotr");
    let cwd = fixture.cwd.to_str().unwrap();

    let run = |args: &[&str]| {
        let output = std::process::Command::new(bin)
            .args(["-w", cwd])
            .args(args)
            .output()
            .unwrap_or_else(|e| panic!("Failed to run dotr {:?}: {}", args, e));
        assert!(
            output.status.success(),
            "dotr {:?} should succeed: {}",
            args,
            String::from_utf8_lossy(&output.stderr)
        );
        String::from_utf8(output.stdout).expect("Output should be valid UTF-8")
    };

    run(&["init"]);
    fixture.write_file("f1.txt", "one");
    fixture.write_file("f2.txt", "two");
    run(&["import", "f1.txt", "-n", "pkg-a"]);
    run(&["import", "f2.txt", "-n", "pkg-b"]);
    run(&["profiles", "add", "work"]);

    let packages_plain = run(&["packages", "list", "--plain"]);
    let mut package_lines: Vec<&str> = packages_plain.lines().collect();
    package_lines.sort();
    assert_eq!(
        package_lines,
        // Names get the usual `f_`/`d_` prefix and `-`-to-`_` sanitization.
        vec!["f_pkg_a", "f_pkg_b"],
        "packages list --plain should print exactly the package names, nothing else \
(no banner, no decoration)"
    );

    let profiles_plain = run(&["profiles", "list", "--plain"]);
    let mut profile_lines: Vec<&str> = profiles_plain.lines().collect();
    profile_lines.sort();
    assert_eq!(
        profile_lines,
        vec!["default", "work"],
        "profiles list --plain should print exactly the profile names, nothing else"
    );

    // --plain and --verbose are mutually exclusive.
    let conflict = std::process::Command::new(bin)
        .args(["-w", cwd, "packages", "list", "--plain", "--verbose"])
        .output()
        .expect("Failed to run dotr packages list --plain --verbose");
    assert!(
        !conflict.status.success(),
        "--plain and --verbose should conflict"
    );
}

#[test]
fn test_packages_list_plain_suppresses_banner_even_when_enabled() {
    let fixture = TestFixture::new();
    let bin = env!("CARGO_BIN_EXE_dotr");
    let cwd = fixture.cwd.to_str().unwrap();

    fixture.init();
    let mut config = fixture.get_config();
    config.banner = true;
    config.save(&fixture.cwd).expect("Failed to save config");

    let output = std::process::Command::new(bin)
        .args(["-w", cwd, "packages", "list", "--plain"])
        .output()
        .expect("Failed to run dotr packages list --plain");
    assert!(output.status.success());
    let stdout = String::from_utf8(output.stdout).expect("Output should be valid UTF-8");
    assert!(
        !stdout.contains('â–ˆ'),
        "--plain output must never include the banner, even when banner = true: {:?}",
        stdout
    );
}

#[test]
fn test_import_creates_package() {
    let fixture = TestFixture::new();

    fixture.init();
    fixture.write_file("test.conf", "test content");

    let _ = run_cli(fixture.get_cli(Some(Command::Import(ImportArgs {
        name: None,
        path: fixture.cwd.join("test.conf").to_str().unwrap().to_string(),
        profile: None,
        ..Default::default()
    }))));

    let config = fixture.get_config();
    assert!(
        config.packages.contains_key("f_test_conf"),
        "Package should be imported"
    );

    fixture.assert_file_exists("dotfiles/f_test.conf", "File should be copied to dotfiles");
}

#[test]
fn test_import_with_profile() {
    let fixture = TestFixture::new();

    fixture.init();
    fixture.write_file("work.conf", "work content");

    let _ = run_cli(fixture.get_cli(Some(Command::Import(ImportArgs {
        name: None,
        path: fixture.cwd.join("work.conf").to_str().unwrap().to_string(),
        profile: Some("work".to_string()),
        ..Default::default()
    }))));

    let config = fixture.get_config();
    let package = config
        .packages
        .get("f_work_conf")
        .expect("Package should exist");

    assert!(!package.skip, "Package should not be marked as skip");
    assert!(
        config.profiles.contains_key("work"),
        "Profile should be created"
    );

    let profile = config.profiles.get("work").unwrap();
    assert!(
        profile.dependencies.contains(&"f_work_conf".to_string()),
        "Profile should have package as dependency"
    );
}

#[test]
fn test_deploy_creates_files() {
    let fixture = TestFixture::new();

    fixture.init();
    fixture.write_file("dotfiles/f_test/config.txt", "test config");

    // Add package to config
    let mut config = fixture.get_config();

    let test_package = dotr_dear::package::Package {
        name: "f_test".to_string(),
        src: "dotfiles/f_test".to_string(),
        dest: fixture
            .cwd
            .join("deploy_dest")
            .to_str()
            .unwrap()
            .to_string(),
        ..Default::default()
    };

    config.packages.insert("f_test".to_string(), test_package);
    config
        .profiles
        .get_mut("default")
        .unwrap()
        .dependencies
        .push("f_test".to_string());
    config.save(&fixture.cwd).expect("Failed to save config");

    let _ = run_cli(fixture.get_cli(Some(Command::Deploy(DeployArgs::default()))));

    fixture.assert_file_exists("deploy_dest/config.txt", "Deployed file should exist");
}

#[test]
fn test_deploy_with_profile() {
    let fixture = TestFixture::new();

    fixture.init();
    fixture.write_file("dotfiles/f_app/app.conf", "app config");

    // Create package and profile
    let mut config = fixture.get_config();

    let mut package = dotr_dear::package::Package {
        name: "f_app".to_string(),
        src: "dotfiles/f_app".to_string(),
        dest: fixture
            .cwd
            .join("default_dest")
            .to_str()
            .unwrap()
            .to_string(),
        ..Default::default()
    };

    package.targets.insert(
        "work".to_string(),
        fixture.cwd.join("work_dest").to_str().unwrap().to_string(),
    );

    config.packages.insert("f_app".to_string(), package);
    config
        .profiles
        .get_mut("default")
        .unwrap()
        .dependencies
        .push("f_app".to_string());

    let profile = dotr_dear::profile::Profile {
        name: "work".to_string(),
        dependencies: vec!["f_app".to_string()],
        ..Default::default()
    };
    config.profiles.insert("work".to_string(), profile);
    config.save(&fixture.cwd).expect("Failed to save config");

    let _ = run_cli(fixture.get_cli(Some(Command::Deploy(DeployArgs {
        packages: None,
        profile: Some("work".to_string()),
        ignore_errors: false,
        clean: Some(false),
        dry_run: false,
        ..Default::default()
    }))));

    fixture.assert_file_exists(
        "work_dest/app.conf",
        "File should be deployed to profile target",
    );
}

#[test]
fn test_deploy_specific_packages() {
    let fixture = TestFixture::new();

    fixture.init();
    fixture.write_file("dotfiles/f_pkg1/file1.txt", "file 1");
    fixture.write_file("dotfiles/f_pkg2/file2.txt", "file 2");

    // Create two packages
    let mut config = fixture.get_config();

    let pkg1 = dotr_dear::package::Package {
        name: "f_pkg1".to_string(),
        src: "dotfiles/f_pkg1".to_string(),
        dest: fixture.cwd.join("dest1").to_str().unwrap().to_string(),
        ..Default::default()
    };

    let pkg2 = dotr_dear::package::Package {
        name: "f_pkg2".to_string(),
        src: "dotfiles/f_pkg2".to_string(),
        dest: fixture.cwd.join("dest2").to_str().unwrap().to_string(),
        ..Default::default()
    };

    config.packages.insert("f_pkg1".to_string(), pkg1);
    config
        .profiles
        .get_mut("default")
        .unwrap()
        .dependencies
        .push("f_pkg1".to_string());
    config.packages.insert("f_pkg2".to_string(), pkg2);
    config
        .profiles
        .get_mut("default")
        .unwrap()
        .dependencies
        .push("f_pkg2".to_string());
    config.save(&fixture.cwd).expect("Failed to save config");

    // Deploy only pkg1
    let _ = run_cli(fixture.get_cli(Some(Command::Deploy(DeployArgs {
        packages: Some(vec!["f_pkg1".to_string()]),
        profile: None,
        ignore_errors: false,
        clean: Some(false),
        dry_run: false,
        ..Default::default()
    }))));

    fixture.assert_file_exists("dest1/file1.txt", "pkg1 should be deployed");
    fixture.assert_file_not_exists("dest2/file2.txt", "pkg2 should not be deployed");
}

#[test]
fn test_update_backs_up_files() {
    let fixture = TestFixture::new();

    fixture.init();

    // Create a package
    let mut config = fixture.get_config();
    let pkg = dotr_dear::package::Package {
        name: "f_update".to_string(),
        src: "dotfiles/f_update".to_string(),
        dest: fixture
            .cwd
            .join("update_dest")
            .to_str()
            .unwrap()
            .to_string(),
        ..Default::default()
    };
    config.packages.insert("f_update".to_string(), pkg);
    config
        .profiles
        .get_mut("default")
        .unwrap()
        .dependencies
        .push("f_update".to_string());
    config.save(&fixture.cwd).expect("Failed to save config");

    // Create file at dest
    fixture.write_file("update_dest", "updated content");

    let _ = run_cli(fixture.get_cli(Some(Command::Update(UpdateArgs::default()))));

    fixture.assert_file_exists("dotfiles/f_update", "File should be backed up");
    let content = fixture.read_file("dotfiles/f_update");
    assert_eq!(content, "updated content", "Backed up content should match");
}

#[test]
fn test_print_vars_shows_variables() {
    let fixture = TestFixture::new();

    fixture.init();

    // Add some variables to config
    let mut config = fixture.get_config();
    config.variables.insert(
        "TEST_VAR".to_string(),
        toml::Value::String("test_value".to_string()),
    );
    config.save(&fixture.cwd).expect("Failed to save config");

    // This will print to stdout - we're just testing it doesn't panic
    run_cli(fixture.get_cli(Some(Command::PrintVars(PrintVarsArgs { profile: None }))))
        .expect("Print vars should succeed");
}

#[test]
fn test_print_vars_with_profile() {
    let fixture = TestFixture::new();

    fixture.init();

    // Create profile with variables
    let mut config = fixture.get_config();
    let mut profile = dotr_dear::profile::Profile::new("dev");
    profile.variables.insert(
        "PROFILE_VAR".to_string(),
        toml::Value::String("dev_value".to_string()),
    );
    config.profiles.insert("dev".to_string(), profile);
    config.save(&fixture.cwd).expect("Failed to save config");

    // This will print to stdout - we're just testing it doesn't panic
    let _ = run_cli(fixture.get_cli(Some(Command::PrintVars(PrintVarsArgs {
        profile: Some("dev".to_string()),
    }))));
}

#[test]
fn test_banner_display() {
    let fixture = TestFixture::new();

    fixture.init();

    // Banner is controlled by config
    let mut config = fixture.get_config();
    config.banner = true;
    config.save(&fixture.cwd).expect("Failed to save config");

    // Deploy command should show banner
    let _ = run_cli(fixture.get_cli(Some(Command::Deploy(DeployArgs::default()))));

    // Just testing it doesn't panic
}

#[test]
fn test_banner_disabled() {
    let fixture = TestFixture::new();

    fixture.init();

    // Disable banner
    let mut config = fixture.get_config();
    config.banner = false;
    config.save(&fixture.cwd).expect("Failed to save config");

    // Deploy command should not show banner
    let _ = run_cli(fixture.get_cli(Some(Command::Deploy(DeployArgs::default()))));

    // Just testing it doesn't panic
}

#[test]
fn test_working_dir_relative_path() {
    let fixture = TestFixture::new();

    // Create a subdirectory
    fs::create_dir_all(fixture.cwd.join("subdir")).expect("Failed to create subdir");

    let cli = Cli {
        command: Some(Command::Init(InitArgs {})),
        working_dir: Some(fixture.cwd.join("subdir").to_str().unwrap().to_string()),
    };

    run_cli(cli).expect("Init in subdir should succeed");

    fixture.assert_file_exists("subdir/config.toml", "Config should be created in subdir");
}

#[test]
fn test_skip_flag_prevents_deployment() {
    let fixture = TestFixture::new();

    fixture.init();
    fixture.write_file("dotfiles/f_skip/skip.txt", "skip content");

    // Create package with skip flag
    let mut config = fixture.get_config();
    let pkg = dotr_dear::package::Package {
        name: "f_skip".to_string(),
        src: "dotfiles/f_skip".to_string(),
        dest: fixture.cwd.join("skip_dest").to_str().unwrap().to_string(),
        skip: true,
        ..Default::default()
    };
    config.packages.insert("f_skip".to_string(), pkg);
    config
        .profiles
        .get_mut("default")
        .unwrap()
        .dependencies
        .push("f_skip".to_string());
    config.save(&fixture.cwd).expect("Failed to save config");

    // Deploy without profile (skip packages should not be deployed)
    let _ = run_cli(fixture.get_cli(Some(Command::Deploy(DeployArgs::default()))));

    fixture.assert_file_not_exists("skip_dest/skip.txt", "Skip package should not be deployed");
}

#[test]
fn test_profile_dependencies_deployment() {
    let fixture = TestFixture::new();

    fixture.init();
    fixture.write_file("dotfiles/f_dep1/dep1.txt", "dep1");
    fixture.write_file("dotfiles/f_dep2/dep2.txt", "dep2");

    // Create packages and profile
    let mut config = fixture.get_config();

    let pkg1 = dotr_dear::package::Package {
        name: "f_dep1".to_string(),
        src: "dotfiles/f_dep1".to_string(),
        dest: fixture.cwd.join("dep1_dest").to_str().unwrap().to_string(),
        ..Default::default()
    };

    let pkg2 = dotr_dear::package::Package {
        name: "f_dep2".to_string(),
        src: "dotfiles/f_dep2".to_string(),
        dest: fixture.cwd.join("dep2_dest").to_str().unwrap().to_string(),
        ..Default::default()
    };

    config.packages.insert("f_dep1".to_string(), pkg1);
    config
        .profiles
        .get_mut("default")
        .unwrap()
        .dependencies
        .push("f_dep1".to_string());
    config.packages.insert("f_dep2".to_string(), pkg2);
    config
        .profiles
        .get_mut("default")
        .unwrap()
        .dependencies
        .push("f_dep2".to_string());

    // Profile with only dep1 as dependency
    let profile = dotr_dear::profile::Profile {
        name: "minimal".to_string(),
        dependencies: vec!["f_dep1".to_string()],
        ..Default::default()
    };
    config.profiles.insert("minimal".to_string(), profile);
    config.save(&fixture.cwd).expect("Failed to save config");

    // Deploy with profile
    let _ = run_cli(fixture.get_cli(Some(Command::Deploy(DeployArgs {
        packages: None,
        profile: Some("minimal".to_string()),
        ignore_errors: false,
        clean: Some(false),
        dry_run: false,
        ..Default::default()
    }))));

    fixture.assert_file_exists(
        "dep1_dest/dep1.txt",
        "Profile dependency should be deployed",
    );
    fixture.assert_file_not_exists(
        "dep2_dest/dep2.txt",
        "Non-dependency should not be deployed",
    );
}

#[test]
fn test_no_command_shows_help_message() {
    let fixture = TestFixture::new();

    let cli = Cli {
        command: None,
        working_dir: Some(fixture.cwd.to_str().unwrap().to_string()),
    };

    let result = run_cli(cli);
    assert!(result.is_ok(), "No command should not error");
}

// ===== UNHAPPY PATH TESTS =====

#[test]
fn test_nonexistent_working_directory_fails() {
    let nonexistent = PathBuf::from("/this/path/does/not/exist/dotr_test");

    let cli = Cli {
        command: Some(Command::Deploy(DeployArgs::default())),
        working_dir: Some(nonexistent.to_str().unwrap().to_string()),
    };

    let result = run_cli(cli);
    assert!(result.is_err(), "Should fail with nonexistent directory");
    assert!(
        result.unwrap_err().to_string().contains("does not exist"),
        "Error should mention directory doesn't exist"
    );
}

#[test]
fn test_deploy_without_config_fails() {
    let fixture = TestFixture::new();

    let result = run_cli(fixture.get_cli(Some(Command::Deploy(DeployArgs::default()))));

    assert!(result.is_err(), "Deploy without config should fail");
    assert!(
        result
            .unwrap_err()
            .to_string()
            .contains("config.toml not found"),
        "Error should mention missing config"
    );
}

#[test]
fn test_import_nonexistent_file_fails() {
    let fixture = TestFixture::new();
    fixture.init();

    let result = run_cli(
        fixture.get_cli(Some(Command::Import(ImportArgs {
            name: None,
            path: fixture
                .cwd
                .join("does_not_exist.conf")
                .to_str()
                .unwrap()
                .to_string(),
            profile: None,
            ..Default::default()
        }))),
    );

    assert!(result.is_err(), "Import nonexistent file should fail");
    assert!(
        result.unwrap_err().to_string().contains("does not exist"),
        "Error should mention file doesn't exist"
    );
}

#[test]
fn test_deploy_with_invalid_profile_fails() {
    let fixture = TestFixture::new();
    fixture.init();

    let result = run_cli(fixture.get_cli(Some(Command::Deploy(DeployArgs {
        packages: None,
        profile: Some("nonexistent_profile".to_string()),
        ignore_errors: false,
        clean: Some(false),
        dry_run: false,
        ..Default::default()
    }))));

    assert!(result.is_err(), "Deploy with invalid profile should fail");
    assert!(
        result.unwrap_err().to_string().contains("not found"),
        "Error should mention profile not found"
    );
}

#[test]
fn test_update_with_invalid_profile_fails() {
    let fixture = TestFixture::new();
    fixture.init();

    let result = run_cli(fixture.get_cli(Some(Command::Update(UpdateArgs {
        packages: None,
        profile: Some("invalid_profile".to_string()),
        ignore_errors: false,
        clean: Some(false),
        dry_run: false,
    }))));

    assert!(result.is_err(), "Update with invalid profile should fail");
    assert!(
        result.unwrap_err().to_string().contains("not found"),
        "Error should mention profile not found"
    );
}

#[test]
fn test_print_vars_with_invalid_profile_fails() {
    let fixture = TestFixture::new();
    fixture.init();

    let result = run_cli(fixture.get_cli(Some(Command::PrintVars(PrintVarsArgs {
        profile: Some("missing_profile".to_string()),
    }))));

    assert!(
        result.is_err(),
        "PrintVars with invalid profile should fail"
    );
    assert!(
        result.unwrap_err().to_string().contains("not found"),
        "Error should mention profile not found"
    );
}

#[test]
fn test_deploy_nonexistent_package_fails() {
    let fixture = TestFixture::new();
    fixture.init();

    let result = run_cli(fixture.get_cli(Some(Command::Deploy(DeployArgs {
        packages: Some(vec!["nonexistent_package".to_string()]),
        profile: None,
        ignore_errors: false,
        clean: Some(false),
        dry_run: false,
        ..Default::default()
    }))));

    // Deploy should fail with error for nonexistent package
    assert!(
        result.is_err(),
        "Deploy with nonexistent package should error"
    );
    assert!(
        result.unwrap_err().to_string().contains("not found"),
        "Error should mention package not found"
    );
}

#[test]
fn test_update_nonexistent_package_fails() {
    let fixture = TestFixture::new();
    fixture.init();

    let result = run_cli(fixture.get_cli(Some(Command::Update(UpdateArgs {
        packages: Some(vec!["nonexistent_package".to_string()]),
        profile: None,
        ignore_errors: false,
        clean: Some(false),
        dry_run: false,
    }))));

    // Update should fail with error for nonexistent package
    assert!(
        result.is_err(),
        "Update with nonexistent package should error"
    );
    assert!(
        result.unwrap_err().to_string().contains("not found"),
        "Error should mention package not found"
    );
}

#[test]
fn test_invalid_toml_config_fails() {
    let fixture = TestFixture::new();
    fixture.init();

    // Corrupt the config file
    fixture.write_file("config.toml", "invalid toml {{{ syntax");

    let result = run_cli(fixture.get_cli(Some(Command::Deploy(DeployArgs::default()))));

    assert!(result.is_err(), "Invalid TOML config should fail");
}

#[test]
fn test_invalid_uservariables_toml_fails() {
    let fixture = TestFixture::new();
    fixture.init();

    // Create invalid .uservariables.toml
    fixture.write_file(".uservariables.toml", "bad toml [[[");

    // Use PrintVars which will definitely try to load context
    let result =
        run_cli(fixture.get_cli(Some(Command::PrintVars(PrintVarsArgs { profile: None }))));

    assert!(result.is_err(), "Invalid uservariables TOML should fail");
    let error_msg = result.unwrap_err().to_string();
    assert!(
        error_msg.contains("parse") || error_msg.contains("Failed to parse"),
        "Error should mention parsing failure, got: {}",
        error_msg
    );
}

#[test]
fn test_package_with_missing_dependency_fails() {
    let fixture = TestFixture::new();
    fixture.init();

    // Create package with nonexistent dependency
    let mut config = fixture.get_config();
    let pkg = dotr_dear::package::Package {
        name: "test_pkg".to_string(),
        src: "dotfiles/test_pkg".to_string(),
        dest: fixture.cwd.join("dest").to_str().unwrap().to_string(),
        dependencies: Some(vec!["nonexistent_dep".to_string()]),
        ..Default::default()
    };
    config.packages.insert("test_pkg".to_string(), pkg);
    config
        .profiles
        .get_mut("default")
        .unwrap()
        .dependencies
        .push("test_pkg".to_string());
    config.save(&fixture.cwd).expect("Failed to save config");

    let result = run_cli(fixture.get_cli(Some(Command::Deploy(DeployArgs {
        packages: Some(vec!["test_pkg".to_string()]),
        profile: None,
        ignore_errors: false,
        clean: Some(false),
        dry_run: false,
        ..Default::default()
    }))));

    assert!(
        result.is_err(),
        "Package with missing dependency should fail"
    );
    assert!(
        result.unwrap_err().to_string().contains("not found"),
        "Error should mention dependency not found"
    );
}

#[test]
fn test_deploy_missing_source_fails() {
    let fixture = TestFixture::new();
    fixture.init();

    // Create package but don't create source files
    let mut config = fixture.get_config();
    let pkg = dotr_dear::package::Package {
        name: "missing_src".to_string(),
        src: "dotfiles/missing_src".to_string(),
        dest: fixture.cwd.join("dest").to_str().unwrap().to_string(),
        ..Default::default()
    };
    config.packages.insert("missing_src".to_string(), pkg);
    config
        .profiles
        .get_mut("default")
        .unwrap()
        .dependencies
        .push("missing_src".to_string());
    config.save(&fixture.cwd).expect("Failed to save config");

    let result = run_cli(fixture.get_cli(Some(Command::Deploy(DeployArgs::default()))));

    // This might succeed as walkdir might not find any files, depending on implementation
    // If src directory doesn't exist, it should fail
    if let Err(e) = result {
        let error_msg = e.to_string();
        assert!(
            error_msg.contains("No such file") || error_msg.contains("does not exist"),
            "Error should mention missing source, got: {}",
            error_msg
        );
    }
}

#[test]
fn test_import_normalizes_home_path() {
    let fixture = TestFixture::new();
    fixture.init();

    // Create a test file in a subdirectory
    let test_dir = fixture.cwd.join("test_import");
    fs::create_dir_all(&test_dir).expect("Failed to create test dir");
    fs::write(test_dir.join("test.txt"), "content").expect("Failed to write test file");

    // Import the file
    let _ = run_cli(fixture.get_cli(Some(Command::Import(ImportArgs {
        name: None,
        path: test_dir.to_str().unwrap().to_string(),
        profile: None,
        ..Default::default()
    }))));

    let config = fixture.get_config();
    let package = config
        .packages
        .values()
        .next()
        .expect("Should have package");

    // Path should not have ~ since it's not in home directory
    assert!(
        !package.dest.starts_with('~'),
        "Non-home path should not use ~"
    );
}

#[test]
fn test_import_preserves_tilde_path() {
    // This test verifies that the normalize_home_path function preserves tilde notation
    // We test this at the utility level rather than end-to-end to avoid creating files in real home

    let path_with_tilde = "~/.config/nvim";
    let normalized = dotr_dear::utils::normalize_home_path(path_with_tilde);

    assert_eq!(
        normalized, path_with_tilde,
        "Tilde paths should be preserved as-is"
    );

    // Test with different tilde paths
    let paths = vec![
        "~/.bashrc",
        "~/.config/alacritty/alacritty.yml",
        "~/Documents/notes.txt",
    ];

    for path in paths {
        let normalized = dotr_dear::utils::normalize_home_path(path);
        assert_eq!(normalized, path, "Tilde path {} should be preserved", path);
    }
}

#[test]
fn test_import_converts_absolute_home_path_to_tilde() {
    let fixture = TestFixture::new();
    fixture.init();

    // Test 1: Path outside home should remain absolute
    let test_file = fixture.cwd.join("test_file.txt");
    fs::write(&test_file, "content").expect("Failed to write test file");

    let abs_path = test_file.to_str().unwrap().to_string();
    let _ = run_cli(fixture.get_cli(Some(Command::Import(ImportArgs {
        name: None,
        path: abs_path.clone(),
        profile: None,
        ..Default::default()
    }))));

    let config = fixture.get_config();
    let package = config
        .packages
        .values()
        .next()
        .expect("Should have package");

    // Since the path is NOT in home directory, it should remain absolute
    assert!(
        !package.dest.starts_with('~'),
        "Path outside home should not use ~ notation, got: {}",
        package.dest
    );

    // Test 2: Verify utility function correctly normalizes home paths
    let home = std::env::home_dir().expect("Should have home dir");
    let mock_home_path = format!("{}/test/path", home.to_string_lossy());
    let normalized = dotr_dear::utils::normalize_home_path(&mock_home_path);
    assert!(
        normalized.starts_with('~'),
        "Path in home directory should be normalized to ~, got: {}",
        normalized
    );
    assert_eq!(
        normalized, "~/test/path",
        "Path should be correctly normalized"
    );
}

#[test]
fn test_dotr_profile_env_var_deploy() {
    let fixture = TestFixture::new();
    fixture.init();

    // Create a test file
    fixture.write_file("dotfiles/f_profile_test/profile.conf", "profile content");

    // Create package and profile
    let mut config = fixture.get_config();
    let package = dotr_dear::package::Package {
        name: "f_profile_test".to_string(),
        src: "dotfiles/f_profile_test".to_string(),
        dest: "src/.profile_test".to_string(),
        ..Default::default()
    };

    let profile = dotr_dear::profile::Profile {
        name: "testenv".to_string(),
        dependencies: vec!["f_profile_test".to_string()],
        ..Default::default()
    };

    config
        .packages
        .insert("f_profile_test".to_string(), package);
    config.profiles.insert("testenv".to_string(), profile);
    config.save(&fixture.cwd).expect("Failed to save config");

    // Set DOTR_PROFILE env var
    fixture.write_file(".uservariables.toml", "DOTR_PROFILE = \"testenv\"\n");

    // Deploy without specifying profile (should use env var)
    let result = run_cli(fixture.get_cli(Some(Command::Deploy(DeployArgs::default()))));

    assert!(
        result.is_ok(),
        "Deploy should succeed with DOTR_PROFILE env var"
    );
    fixture.assert_file_exists(
        "src/.profile_test",
        "File should be deployed using DOTR_PROFILE env var",
    );
}

#[test]
fn test_dotr_profile_env_var_update() {
    let fixture = TestFixture::new();
    fixture.init();

    // Create dest directory
    fs::create_dir_all(fixture.cwd.join("dest")).expect("Failed to create dest dir");

    // Create profile and package with a single file
    fixture.write_file("dotfiles/f_env_update", "original");

    let mut config = fixture.get_config();
    let dest_path = fixture.cwd.join("dest/.env_update");
    let package = dotr_dear::package::Package {
        name: "f_env_update".to_string(),
        src: "dotfiles/f_env_update".to_string(),
        dest: dest_path.to_str().unwrap().to_string(),
        ..Default::default()
    };

    let profile = dotr_dear::profile::Profile {
        name: "updateenv".to_string(),
        dependencies: vec!["f_env_update".to_string()],
        ..Default::default()
    };

    config.packages.insert("f_env_update".to_string(), package);
    config
        .profiles
        .get_mut("default")
        .unwrap()
        .dependencies
        .push("f_env_update".to_string());
    config.profiles.insert("updateenv".to_string(), profile);
    config.save(&fixture.cwd).expect("Failed to save config");

    // Deploy first
    run_cli(fixture.get_cli(Some(Command::Deploy(DeployArgs {
        packages: Some(vec!["f_env_update".to_string()]),
        profile: None,
        ignore_errors: false,
        clean: Some(false),
        dry_run: false,
        ..Default::default()
    }))))
    .expect("Deploy failed");

    // Modify deployed file
    fixture.write_file("dest/.env_update", "modified");

    // Set profile via env var
    fixture.write_file(".uservariables.toml", "DOTR_PROFILE = \"updateenv\"\n");

    // Update without specifying profile - should succeed with profile from env var
    let result = run_cli(fixture.get_cli(Some(Command::Update(UpdateArgs {
        packages: Some(vec!["f_env_update".to_string()]),
        profile: None,
        ignore_errors: false,
        clean: Some(false),
        dry_run: false,
    }))));

    assert!(
        result.is_ok(),
        "Update should succeed with DOTR_PROFILE env var"
    );
}

#[test]
fn test_dotr_profile_env_var_print_vars() {
    let fixture = TestFixture::new();
    fixture.init();

    // Create profile with variables
    let mut config = fixture.get_config();
    let mut profile_vars = toml::Table::new();
    profile_vars.insert(
        "PROFILE_VAR".to_string(),
        toml::Value::String("from_env_profile".to_string()),
    );

    let profile = dotr_dear::profile::Profile {
        name: "printenv".to_string(),
        variables: profile_vars,
        ..Default::default()
    };

    config.profiles.insert("printenv".to_string(), profile);
    config.save(&fixture.cwd).expect("Failed to save config");

    // Set profile via env var
    fixture.write_file(".uservariables.toml", "DOTR_PROFILE = \"printenv\"\n");

    // Should work without specifying profile
    let result =
        run_cli(fixture.get_cli(Some(Command::PrintVars(PrintVarsArgs { profile: None }))));

    assert!(
        result.is_ok(),
        "PrintVars should succeed with DOTR_PROFILE env var"
    );
}

#[test]
fn test_cli_profile_overrides_env_var() {
    let fixture = TestFixture::new();
    fixture.init();

    fixture.write_file("dotfiles/f_override/override.txt", "content");

    let mut config = fixture.get_config();
    let package = dotr_dear::package::Package {
        name: "f_override".to_string(),
        src: "dotfiles/f_override".to_string(),
        dest: "src/.override".to_string(),
        ..Default::default()
    };

    let profile1 = dotr_dear::profile::Profile {
        name: "envprofile".to_string(),
        dependencies: vec!["f_override".to_string()],
        ..Default::default()
    };

    let profile2 = dotr_dear::profile::Profile {
        name: "cliprofile".to_string(),
        dependencies: vec!["f_override".to_string()],
        ..Default::default()
    };

    config.packages.insert("f_override".to_string(), package);
    config
        .profiles
        .get_mut("default")
        .unwrap()
        .dependencies
        .push("f_override".to_string());
    config.profiles.insert("envprofile".to_string(), profile1);
    config.profiles.insert("cliprofile".to_string(), profile2);
    config.save(&fixture.cwd).expect("Failed to save config");

    // Set env var to one profile
    fixture.write_file(".uservariables.toml", "DOTR_PROFILE = \"envprofile\"\n");

    // But explicitly pass different profile via CLI
    let result = run_cli(fixture.get_cli(Some(Command::Deploy(DeployArgs {
        packages: None,
        profile: Some("cliprofile".to_string()),
        ignore_errors: false,
        clean: Some(false),
        dry_run: false,
        ..Default::default()
    }))));

    assert!(result.is_ok(), "Deploy should use CLI profile over env var");
    fixture.assert_file_exists(
        "src/.override",
        "File should be deployed with CLI-specified profile",
    );
}

#[test]
fn test_invalid_dotr_profile_env_var_ignored() {
    let fixture = TestFixture::new();
    fixture.init();

    fixture.write_file("dotfiles/f_invalid_env/test.txt", "content");

    let mut config = fixture.get_config();
    let package = dotr_dear::package::Package {
        name: "f_invalid_env".to_string(),
        src: "dotfiles/f_invalid_env".to_string(),
        dest: "src/.invalid_env".to_string(),
        ..Default::default()
    };

    config.packages.insert("f_invalid_env".to_string(), package);
    config
        .profiles
        .get_mut("default")
        .unwrap()
        .dependencies
        .push("f_invalid_env".to_string());
    config.save(&fixture.cwd).expect("Failed to save config");

    // Set env var to non-existent profile
    fixture.write_file(".uservariables.toml", "DOTR_PROFILE = \"nonexistent\"\n");

    // Deploy without profile should fail (env var points to invalid profile)
    let result = run_cli(fixture.get_cli(Some(Command::Deploy(DeployArgs::default()))));

    assert!(
        result.is_err(),
        "Deploy should fail with invalid DOTR_PROFILE env var"
    );
}

#[test]
fn test_deploy_with_ignore_errors_continues_on_failure() {
    let fixture = TestFixture::new();

    fixture.init();

    // Create a package that will fail during deployment (non-existent source)
    let mut config = fixture.get_config();

    let package1 = Package {
        name: "f_valid_pkg".to_string(),
        src: "dotfiles/f_valid_pkg".to_string(),
        dest: "deploy_dest/valid.txt".to_string(),
        ..Default::default()
    };

    let package2 = Package {
        name: "f_invalid_pkg".to_string(),
        src: "dotfiles/f_nonexistent".to_string(), // This doesn't exist
        dest: "deploy_dest/invalid.txt".to_string(),
        ..Default::default()
    };

    let package3 = Package {
        name: "f_another_valid".to_string(),
        src: "dotfiles/f_another_valid".to_string(),
        dest: "deploy_dest/another.txt".to_string(),
        ..Default::default()
    };

    config.packages.insert("f_valid_pkg".to_string(), package1);
    config
        .profiles
        .get_mut("default")
        .unwrap()
        .dependencies
        .push("f_valid_pkg".to_string());
    config
        .packages
        .insert("f_invalid_pkg".to_string(), package2);
    config
        .profiles
        .get_mut("default")
        .unwrap()
        .dependencies
        .push("f_invalid_pkg".to_string());
    config
        .packages
        .insert("f_another_valid".to_string(), package3);
    config
        .profiles
        .get_mut("default")
        .unwrap()
        .dependencies
        .push("f_another_valid".to_string());
    config.save(&fixture.cwd).expect("Failed to save config");

    // Create the destination directory
    std::fs::create_dir_all(fixture.cwd.join("deploy_dest")).unwrap();

    // Create the valid package files
    fixture.write_file("dotfiles/f_valid_pkg", "valid content");
    fixture.write_file("dotfiles/f_another_valid", "another valid content");

    // Deploy with ignore_errors=true should succeed despite one package failing
    let result = run_cli(fixture.get_cli(Some(Command::Deploy(DeployArgs {
        packages: None,
        profile: None,
        ignore_errors: true,
        clean: Some(false),
        dry_run: false,
        ..Default::default()
    }))));

    assert!(
        result.is_ok(),
        "Deploy should succeed with ignore_errors=true even when one package fails"
    );

    // Valid packages should have been deployed
    fixture.assert_file_exists("deploy_dest/valid.txt", "Valid package should be deployed");
    fixture.assert_file_exists(
        "deploy_dest/another.txt",
        "Another valid package should be deployed",
    );
}

#[test]
fn test_deploy_without_ignore_errors_stops_on_failure() {
    let fixture = TestFixture::new();

    fixture.init();

    // Create packages where one will fail
    let mut config = fixture.get_config();

    let package1 = Package {
        name: "f_first_pkg".to_string(),
        src: "dotfiles/f_first_pkg".to_string(),
        dest: "deploy_dest/first.txt".to_string(),
        ..Default::default()
    };

    let package2 = Package {
        name: "f_failing_pkg".to_string(),
        src: "dotfiles/f_nonexistent".to_string(), // This doesn't exist
        dest: "deploy_dest/failing.txt".to_string(),
        ..Default::default()
    };

    config.packages.insert("f_first_pkg".to_string(), package1);
    config
        .profiles
        .get_mut("default")
        .unwrap()
        .dependencies
        .push("f_first_pkg".to_string());
    config
        .packages
        .insert("f_failing_pkg".to_string(), package2);
    config
        .profiles
        .get_mut("default")
        .unwrap()
        .dependencies
        .push("f_failing_pkg".to_string());
    config.save(&fixture.cwd).expect("Failed to save config");

    std::fs::create_dir_all(fixture.cwd.join("deploy_dest")).unwrap();
    fixture.write_file("dotfiles/f_first_pkg", "first content");

    // Deploy with ignore_errors=false should fail when any package fails
    let result = run_cli(fixture.get_cli(Some(Command::Deploy(DeployArgs::default()))));

    assert!(
        result.is_err(),
        "Deploy should fail with ignore_errors=false when a package fails"
    );
}

#[test]
fn test_backup_with_ignore_errors_continues_on_failure() {
    let fixture = TestFixture::new();

    fixture.init();

    // Create packages
    let mut config = fixture.get_config();

    let package1 = Package {
        name: "f_valid_backup".to_string(),
        src: "dotfiles/f_valid_backup".to_string(),
        dest: "backup_src/valid.txt".to_string(),
        ..Default::default()
    };

    let package2 = Package {
        name: "f_invalid_backup".to_string(),
        src: "dotfiles/f_invalid_backup".to_string(),
        dest: "backup_src/nonexistent.txt".to_string(), // Source doesn't exist
        ..Default::default()
    };

    config
        .packages
        .insert("f_valid_backup".to_string(), package1);
    config
        .profiles
        .get_mut("default")
        .unwrap()
        .dependencies
        .push("f_valid_backup".to_string());
    config
        .packages
        .insert("f_invalid_backup".to_string(), package2);
    config
        .profiles
        .get_mut("default")
        .unwrap()
        .dependencies
        .push("f_invalid_backup".to_string());
    config.save(&fixture.cwd).expect("Failed to save config");

    // Create the valid source file
    fixture.write_file("backup_src/valid.txt", "valid backup content");

    // Backup with ignore_errors=true should succeed despite one package failing
    let result = run_cli(fixture.get_cli(Some(Command::Update(UpdateArgs {
        packages: None,
        profile: None,
        ignore_errors: true,
        clean: Some(false),
        dry_run: false,
    }))));

    assert!(
        result.is_ok(),
        "Backup should succeed with ignore_errors=true even when one package fails"
    );

    // Valid package should have been backed up
    fixture.assert_file_exists(
        "dotfiles/f_valid_backup",
        "Valid package should be backed up",
    );
}

#[test]
fn test_update_without_ignore_errors_stops_on_failure() {
    let fixture = TestFixture::new();

    fixture.init();

    let mut config = fixture.get_config();

    let package1 = Package {
        name: "f_backup_pkg".to_string(),
        src: "dotfiles/f_backup_pkg".to_string(),
        dest: "backup_src/exists.txt".to_string(),
        ..Default::default()
    };

    let package2 = Package {
        name: "f_failing_backup".to_string(),
        src: "dotfiles/f_failing_backup".to_string(),
        dest: "backup_src/missing.txt".to_string(), // Doesn't exist
        ..Default::default()
    };

    config.packages.insert("f_backup_pkg".to_string(), package1);
    config
        .profiles
        .get_mut("default")
        .unwrap()
        .dependencies
        .push("f_backup_pkg".to_string());
    config
        .packages
        .insert("f_failing_backup".to_string(), package2);
    config
        .profiles
        .get_mut("default")
        .unwrap()
        .dependencies
        .push("f_failing_backup".to_string());
    config.save(&fixture.cwd).expect("Failed to save config");

    fixture.write_file("backup_src/exists.txt", "exists");

    // Update with ignore_errors=false should fail when any package fails
    let result = run_cli(fixture.get_cli(Some(Command::Update(UpdateArgs::default()))));

    assert!(
        result.is_err(),
        "Update should fail with ignore_errors=false when a package fails"
    );
}

#[test]
fn test_deploy_with_clean_removes_extra_files() {
    let fixture = TestFixture::new();

    fixture.init();

    let mut config = fixture.get_config();

    let package = Package {
        name: "d_config_dir".to_string(),
        src: "dotfiles/d_config_dir".to_string(),
        dest: "deploy_dest/config".to_string(),
        ..Default::default()
    };

    config.packages.insert("d_config_dir".to_string(), package);
    config
        .profiles
        .get_mut("default")
        .unwrap()
        .dependencies
        .push("d_config_dir".to_string());
    config.save(&fixture.cwd).expect("Failed to save config");

    // Create source directory with two files
    fixture.write_file("dotfiles/d_config_dir/file1.txt", "file1 content");
    fixture.write_file("dotfiles/d_config_dir/file2.txt", "file2 content");

    // Create destination directory with an extra file that shouldn't be there
    fixture.write_file("deploy_dest/config/file1.txt", "old file1");
    fixture.write_file("deploy_dest/config/file2.txt", "old file2");
    fixture.write_file(
        "deploy_dest/config/extra_file.txt",
        "this should be removed",
    );

    // Deploy with clean=true
    let result = run_cli(fixture.get_cli(Some(Command::Deploy(DeployArgs {
        packages: None,
        profile: None,
        ignore_errors: false,
        clean: Some(true),
        dry_run: false,
        ..Default::default()
    }))));

    assert!(result.is_ok(), "Deploy with clean should succeed");

    // Check that the correct files exist
    fixture.assert_file_exists("deploy_dest/config/file1.txt", "file1 should exist");
    fixture.assert_file_exists("deploy_dest/config/file2.txt", "file2 should exist");

    // Check that the extra file was removed
    fixture.assert_file_not_exists(
        "deploy_dest/config/extra_file.txt",
        "extra_file should be removed by clean",
    );
}

#[test]
fn test_deploy_without_clean_keeps_extra_files() {
    let fixture = TestFixture::new();

    fixture.init();

    let mut config = fixture.get_config();

    let package = Package {
        name: "d_another_dir".to_string(),
        src: "dotfiles/d_another_dir".to_string(),
        dest: "deploy_dest/another".to_string(),
        ..Default::default()
    };

    config.packages.insert("d_another_dir".to_string(), package);
    config
        .profiles
        .get_mut("default")
        .unwrap()
        .dependencies
        .push("d_another_dir".to_string());
    config.save(&fixture.cwd).expect("Failed to save config");

    // Create source directory with two files
    fixture.write_file("dotfiles/d_another_dir/file1.txt", "file1 content");
    fixture.write_file("dotfiles/d_another_dir/file2.txt", "file2 content");

    // Create destination directory with an extra file
    fixture.write_file("deploy_dest/another/file1.txt", "old file1");
    fixture.write_file("deploy_dest/another/file2.txt", "old file2");
    fixture.write_file("deploy_dest/another/extra_file.txt", "this should remain");

    // Deploy with clean=false
    let result = run_cli(fixture.get_cli(Some(Command::Deploy(DeployArgs {
        clean: Some(false),
        ..Default::default()
    }))));

    assert!(result.is_ok(), "Deploy without clean should succeed");

    // Check that all files exist, including the extra one
    fixture.assert_file_exists("deploy_dest/another/file1.txt", "file1 should exist");
    fixture.assert_file_exists("deploy_dest/another/file2.txt", "file2 should exist");
    fixture.assert_file_exists(
        "deploy_dest/another/extra_file.txt",
        "extra_file should remain without clean",
    );
}

#[test]
fn test_backup_with_clean_removes_extra_files() {
    let fixture = TestFixture::new();

    fixture.init();

    let mut config = fixture.get_config();

    let package = Package {
        name: "d_backup_dir".to_string(),
        src: "dotfiles/d_backup_dir".to_string(),
        dest: "source/backup_dir".to_string(),
        ..Default::default()
    };

    config.packages.insert("d_backup_dir".to_string(), package);
    config
        .profiles
        .get_mut("default")
        .unwrap()
        .dependencies
        .push("d_backup_dir".to_string());
    config.save(&fixture.cwd).expect("Failed to save config");

    // Create source directory with two files
    fixture.write_file("source/backup_dir/file1.txt", "file1 content");
    fixture.write_file("source/backup_dir/file2.txt", "file2 content");

    // Create dotfiles directory with an extra file that shouldn't be there
    fixture.write_file("dotfiles/d_backup_dir/file1.txt", "old file1");
    fixture.write_file("dotfiles/d_backup_dir/file2.txt", "old file2");
    fixture.write_file(
        "dotfiles/d_backup_dir/old_file.txt",
        "this should be removed",
    );

    // Backup with clean=true
    let result = run_cli(fixture.get_cli(Some(Command::Update(UpdateArgs {
        packages: None,
        profile: None,
        ignore_errors: false,
        clean: Some(true),
        dry_run: false,
    }))));

    assert!(result.is_ok(), "Backup with clean should succeed");

    // Check that the correct files exist
    fixture.assert_file_exists("dotfiles/d_backup_dir/file1.txt", "file1 should exist");
    fixture.assert_file_exists("dotfiles/d_backup_dir/file2.txt", "file2 should exist");

    // Check that the old file was removed
    fixture.assert_file_not_exists(
        "dotfiles/d_backup_dir/old_file.txt",
        "old_file should be removed by clean",
    );
}

#[test]
fn test_backup_without_clean_keeps_extra_files() {
    let fixture = TestFixture::new();

    fixture.init();

    let mut config = fixture.get_config();

    let package = Package {
        name: "d_backup_keep".to_string(),
        src: "dotfiles/d_backup_keep".to_string(),
        dest: "source/backup_keep".to_string(),
        ..Default::default()
    };

    config.packages.insert("d_backup_keep".to_string(), package);
    config
        .profiles
        .get_mut("default")
        .unwrap()
        .dependencies
        .push("d_backup_keep".to_string());
    config.save(&fixture.cwd).expect("Failed to save config");

    // Create source directory with two files
    fixture.write_file("source/backup_keep/file1.txt", "file1 content");
    fixture.write_file("source/backup_keep/file2.txt", "file2 content");

    // Create dotfiles directory with an extra file
    fixture.write_file("dotfiles/d_backup_keep/file1.txt", "old file1");
    fixture.write_file("dotfiles/d_backup_keep/file2.txt", "old file2");
    fixture.write_file("dotfiles/d_backup_keep/old_file.txt", "this should remain");

    // Backup with clean=false
    let result = run_cli(fixture.get_cli(Some(Command::Update(UpdateArgs {
        clean: Some(false),
        ..Default::default()
    }))));

    assert!(result.is_ok(), "Backup without clean should succeed");

    // Check that all files exist, including the extra one
    fixture.assert_file_exists("dotfiles/d_backup_keep/file1.txt", "file1 should exist");
    fixture.assert_file_exists("dotfiles/d_backup_keep/file2.txt", "file2 should exist");
    fixture.assert_file_exists(
        "dotfiles/d_backup_keep/old_file.txt",
        "old_file should remain without clean",
    );
}

#[test]
fn test_clean_preserves_backup_files() {
    let fixture = TestFixture::new();

    fixture.init();

    let mut config = fixture.get_config();

    let package = Package {
        name: "d_test_clean".to_string(),
        src: "dotfiles/d_test_clean".to_string(),
        dest: "deploy_dest/test_clean".to_string(),
        ..Default::default()
    };

    config.packages.insert("d_test_clean".to_string(), package);
    config
        .profiles
        .get_mut("default")
        .unwrap()
        .dependencies
        .push("d_test_clean".to_string());
    config.save(&fixture.cwd).expect("Failed to save config");

    // Create source files
    fixture.write_file("dotfiles/d_test_clean/config.txt", "config content");

    // Create destination with a file and a backup file
    fixture.write_file("deploy_dest/test_clean/config.txt", "old config");
    fixture.write_file("deploy_dest/test_clean/extra.txt", "should be removed");
    fixture.write_file(
        "deploy_dest/test_clean/config.txt.dotrbak",
        "backup content",
    );

    // Deploy with clean=true
    let result = run_cli(fixture.get_cli(Some(Command::Deploy(DeployArgs {
        packages: None,
        profile: None,
        ignore_errors: false,
        clean: Some(true),
        dry_run: false,
        ..Default::default()
    }))));

    assert!(result.is_ok(), "Deploy with clean should succeed");

    // Check that config file exists
    fixture.assert_file_exists(
        "deploy_dest/test_clean/config.txt",
        "config.txt should exist",
    );

    // Check that extra file was removed
    fixture.assert_file_not_exists(
        "deploy_dest/test_clean/extra.txt",
        "extra.txt should be removed",
    );

    // Check that backup file is preserved
    fixture.assert_file_exists(
        "deploy_dest/test_clean/config.txt.dotrbak",
        "backup file should be preserved",
    );
}

#[test]
fn test_clean_removes_empty_directories() {
    let fixture = TestFixture::new();

    fixture.init();

    let mut config = fixture.get_config();

    let package = Package {
        name: "d_empty_dirs".to_string(),
        src: "dotfiles/d_empty_dirs".to_string(),
        dest: "deploy_dest/empty_dirs".to_string(),
        ..Default::default()
    };

    config.packages.insert("d_empty_dirs".to_string(), package);
    config
        .profiles
        .get_mut("default")
        .unwrap()
        .dependencies
        .push("d_empty_dirs".to_string());
    config.save(&fixture.cwd).expect("Failed to save config");

    // Create source with a simple structure
    fixture.write_file("dotfiles/d_empty_dirs/file.txt", "content");

    // Create destination with nested empty directories
    std::fs::create_dir_all(fixture.cwd.join("deploy_dest/empty_dirs/subdir1/subdir2")).unwrap();
    std::fs::create_dir_all(fixture.cwd.join("deploy_dest/empty_dirs/subdir3")).unwrap();

    // Deploy with clean=true
    let result = run_cli(fixture.get_cli(Some(Command::Deploy(DeployArgs {
        packages: None,
        profile: None,
        ignore_errors: false,
        clean: Some(true),
        dry_run: false,
        ..Default::default()
    }))));

    assert!(result.is_ok(), "Deploy with clean should succeed");

    // Check that the file exists
    fixture.assert_file_exists("deploy_dest/empty_dirs/file.txt", "file.txt should exist");

    // Check that empty directories were removed
    fixture.assert_file_not_exists(
        "deploy_dest/empty_dirs/subdir1",
        "empty subdir1 should be removed",
    );
    fixture.assert_file_not_exists(
        "deploy_dest/empty_dirs/subdir3",
        "empty subdir3 should be removed",
    );
}

#[test]
fn test_clean_removes_non_empty_directories() {
    let fixture = TestFixture::new();

    fixture.init();

    let mut config = fixture.get_config();

    let package = Package {
        name: "d_nonempty_dirs".to_string(),
        src: "dotfiles/d_nonempty_dirs".to_string(),
        dest: "deploy_dest/nonempty_dirs".to_string(),
        ..Default::default()
    };

    config
        .packages
        .insert("d_nonempty_dirs".to_string(), package);
    config
        .profiles
        .get_mut("default")
        .unwrap()
        .dependencies
        .push("d_nonempty_dirs".to_string());
    config.save(&fixture.cwd).expect("Failed to save config");

    // Create source with a simple file
    fixture.write_file("dotfiles/d_nonempty_dirs/current.txt", "current content");

    // Create destination with a directory containing files
    fixture.write_file(
        "deploy_dest/nonempty_dirs/old_dir/old_file.txt",
        "old content",
    );
    fixture.write_file(
        "deploy_dest/nonempty_dirs/old_dir/another.txt",
        "more old content",
    );

    // Deploy with clean=true
    let result = run_cli(fixture.get_cli(Some(Command::Deploy(DeployArgs {
        packages: None,
        profile: None,
        ignore_errors: false,
        clean: Some(true),
        dry_run: false,
        ..Default::default()
    }))));

    assert!(result.is_ok(), "Deploy with clean should succeed");

    // Check that current file exists
    fixture.assert_file_exists(
        "deploy_dest/nonempty_dirs/current.txt",
        "current.txt should exist",
    );

    // Check that the entire old directory was removed
    fixture.assert_file_not_exists(
        "deploy_dest/nonempty_dirs/old_dir",
        "old_dir should be removed",
    );
    fixture.assert_file_not_exists(
        "deploy_dest/nonempty_dirs/old_dir/old_file.txt",
        "files in old_dir should be removed",
    );
}

#[test]
fn test_clean_handles_nested_directory_structure() {
    let fixture = TestFixture::new();

    fixture.init();

    let mut config = fixture.get_config();

    let package = Package {
        name: "d_nested".to_string(),
        src: "dotfiles/d_nested".to_string(),
        dest: "deploy_dest/nested".to_string(),
        ..Default::default()
    };

    config.packages.insert("d_nested".to_string(), package);
    config
        .profiles
        .get_mut("default")
        .unwrap()
        .dependencies
        .push("d_nested".to_string());
    config.save(&fixture.cwd).expect("Failed to save config");

    // Create source with nested structure
    fixture.write_file("dotfiles/d_nested/level1/level2/file.txt", "nested content");

    // Create destination with different structure - some to keep, some to remove
    fixture.write_file(
        "deploy_dest/nested/old_level1/old_file.txt",
        "should be removed",
    );
    fixture.write_file(
        "deploy_dest/nested/old_level1/old_level2/deep.txt",
        "should be removed",
    );
    std::fs::create_dir_all(fixture.cwd.join("deploy_dest/nested/empty_dir")).unwrap();

    // Deploy with clean=true
    let result = run_cli(fixture.get_cli(Some(Command::Deploy(DeployArgs {
        packages: None,
        profile: None,
        ignore_errors: false,
        clean: Some(true),
        dry_run: false,
        ..Default::default()
    }))));

    assert!(result.is_ok(), "Deploy with clean should succeed");

    // Check that new structure exists
    fixture.assert_file_exists(
        "deploy_dest/nested/level1/level2/file.txt",
        "nested file should exist",
    );

    // Check that old structure was removed (deepest first)
    fixture.assert_file_not_exists(
        "deploy_dest/nested/old_level1",
        "old nested structure should be removed",
    );
    fixture.assert_file_not_exists(
        "deploy_dest/nested/empty_dir",
        "empty_dir should be removed",
    );
}

#[test]
fn test_clean_preserves_kept_directories() {
    let fixture = TestFixture::new();

    fixture.init();

    let mut config = fixture.get_config();

    let package = Package {
        name: "d_preserve_dirs".to_string(),
        src: "dotfiles/d_preserve_dirs".to_string(),
        dest: "deploy_dest/preserve".to_string(),
        ..Default::default()
    };

    config
        .packages
        .insert("d_preserve_dirs".to_string(), package);
    config
        .profiles
        .get_mut("default")
        .unwrap()
        .dependencies
        .push("d_preserve_dirs".to_string());
    config.save(&fixture.cwd).expect("Failed to save config");

    // Create source with subdirectory
    fixture.write_file("dotfiles/d_preserve_dirs/subdir/file.txt", "content");
    fixture.write_file("dotfiles/d_preserve_dirs/root.txt", "root content");

    // Create destination matching the structure plus extra
    fixture.write_file("deploy_dest/preserve/subdir/file.txt", "old content");
    fixture.write_file("deploy_dest/preserve/root.txt", "old root");
    fixture.write_file(
        "deploy_dest/preserve/extra_in_subdir/extra.txt",
        "should be removed",
    );

    // Deploy with clean=true
    let result = run_cli(fixture.get_cli(Some(Command::Deploy(DeployArgs {
        packages: None,
        profile: None,
        ignore_errors: false,
        clean: Some(true),
        dry_run: false,
        ..Default::default()
    }))));

    assert!(result.is_ok(), "Deploy with clean should succeed");

    // Check that deployed structure exists
    fixture.assert_file_exists(
        "deploy_dest/preserve/subdir/file.txt",
        "subdir/file.txt should exist",
    );
    fixture.assert_file_exists("deploy_dest/preserve/root.txt", "root.txt should exist");

    // Check that extra directory was removed
    fixture.assert_file_not_exists(
        "deploy_dest/preserve/extra_in_subdir",
        "extra directory should be removed",
    );
}

#[test]
fn test_clean_respects_ignore_patterns_files() {
    let fixture = TestFixture::new();

    fixture.init();

    let mut config = fixture.get_config();

    let package = Package {
        name: "d_ignore_files".to_string(),
        src: "dotfiles/d_ignore_files".to_string(),
        dest: "deploy_dest/ignore_files".to_string(),
        ignore: vec!["*.log".to_string(), "temp*".to_string()],
        ..Default::default()
    };

    config
        .packages
        .insert("d_ignore_files".to_string(), package);
    config
        .profiles
        .get_mut("default")
        .unwrap()
        .dependencies
        .push("d_ignore_files".to_string());
    config.save(&fixture.cwd).expect("Failed to save config");

    // Create source files
    fixture.write_file("dotfiles/d_ignore_files/config.txt", "config");

    // Create destination with files matching ignore patterns and extra files
    fixture.write_file("deploy_dest/ignore_files/config.txt", "old config");
    fixture.write_file("deploy_dest/ignore_files/app.log", "logs");
    fixture.write_file("deploy_dest/ignore_files/debug.log", "debug");
    fixture.write_file("deploy_dest/ignore_files/temp_data", "temp");
    fixture.write_file("deploy_dest/ignore_files/extra.txt", "should be removed");

    // Deploy with clean=true
    let result = run_cli(fixture.get_cli(Some(Command::Deploy(DeployArgs {
        packages: None,
        profile: None,
        ignore_errors: false,
        clean: Some(true),
        dry_run: false,
        ..Default::default()
    }))));

    assert!(result.is_ok(), "Deploy with clean should succeed");

    // Check that config file exists
    fixture.assert_file_exists(
        "deploy_dest/ignore_files/config.txt",
        "config.txt should exist",
    );

    // Check that ignored files are preserved
    fixture.assert_file_exists(
        "deploy_dest/ignore_files/app.log",
        "*.log should be ignored and preserved",
    );
    fixture.assert_file_exists(
        "deploy_dest/ignore_files/debug.log",
        "*.log should be ignored and preserved",
    );
    fixture.assert_file_exists(
        "deploy_dest/ignore_files/temp_data",
        "temp* should be ignored and preserved",
    );

    // Check that non-ignored extra file was removed
    fixture.assert_file_not_exists(
        "deploy_dest/ignore_files/extra.txt",
        "extra.txt should be removed",
    );
}

#[test]
fn test_clean_respects_ignore_patterns_directories() {
    let fixture = TestFixture::new();

    fixture.init();

    let mut config = fixture.get_config();

    let package = Package {
        name: "d_ignore_dirs".to_string(),
        src: "dotfiles/d_ignore_dirs".to_string(),
        dest: "deploy_dest/ignore_dirs".to_string(),
        ignore: vec!["cache".to_string(), ".git".to_string()],
        ..Default::default()
    };

    config.packages.insert("d_ignore_dirs".to_string(), package);
    config
        .profiles
        .get_mut("default")
        .unwrap()
        .dependencies
        .push("d_ignore_dirs".to_string());
    config.save(&fixture.cwd).expect("Failed to save config");

    // Create source files
    fixture.write_file("dotfiles/d_ignore_dirs/config.txt", "config");

    // Create destination with directories that should be ignored
    fixture.write_file("deploy_dest/ignore_dirs/config.txt", "old config");
    std::fs::create_dir_all(fixture.cwd.join("deploy_dest/ignore_dirs/cache")).unwrap();
    std::fs::create_dir_all(fixture.cwd.join("deploy_dest/ignore_dirs/.git")).unwrap();
    std::fs::create_dir_all(fixture.cwd.join("deploy_dest/ignore_dirs/old_dir")).unwrap();

    // Deploy with clean=true
    let result = run_cli(fixture.get_cli(Some(Command::Deploy(DeployArgs {
        packages: None,
        profile: None,
        ignore_errors: false,
        clean: Some(true),
        dry_run: false,
        ..Default::default()
    }))));

    assert!(result.is_ok(), "Deploy with clean should succeed");

    // Check that config file exists
    fixture.assert_file_exists(
        "deploy_dest/ignore_dirs/config.txt",
        "config.txt should exist",
    );

    // Check that ignored directories are preserved (as empty dirs)
    assert!(
        fixture.cwd.join("deploy_dest/ignore_dirs/cache").exists(),
        "cache dir should be preserved"
    );
    assert!(
        fixture.cwd.join("deploy_dest/ignore_dirs/.git").exists(),
        ".git dir should be preserved"
    );

    // Check that non-ignored directory was removed
    fixture.assert_file_not_exists(
        "deploy_dest/ignore_dirs/old_dir",
        "old_dir should be removed",
    );
}

#[test]
fn test_clean_ignore_patterns_in_backup() {
    let fixture = TestFixture::new();

    fixture.init();

    let mut config = fixture.get_config();

    let package = Package {
        name: "d_backup_ignore".to_string(),
        src: "dotfiles/d_backup_ignore".to_string(),
        dest: "source/backup_ignore".to_string(),
        ignore: vec!["*.tmp".to_string(), "build".to_string()],
        ..Default::default()
    };

    config
        .packages
        .insert("d_backup_ignore".to_string(), package);
    config
        .profiles
        .get_mut("default")
        .unwrap()
        .dependencies
        .push("d_backup_ignore".to_string());
    config.save(&fixture.cwd).expect("Failed to save config");

    // Create source files
    fixture.write_file("source/backup_ignore/config.txt", "config");

    // Create dotfiles with files matching ignore patterns and old files
    fixture.write_file("dotfiles/d_backup_ignore/config.txt", "old config");
    fixture.write_file("dotfiles/d_backup_ignore/temp.tmp", "temp file");
    std::fs::create_dir_all(fixture.cwd.join("dotfiles/d_backup_ignore/build")).unwrap();
    fixture.write_file("dotfiles/d_backup_ignore/old.txt", "should be removed");

    // Backup with clean=true
    let result = run_cli(fixture.get_cli(Some(Command::Update(UpdateArgs {
        packages: None,
        profile: None,
        ignore_errors: false,
        clean: Some(true),
        dry_run: false,
    }))));

    assert!(result.is_ok(), "Backup with clean should succeed");

    // Check that config file exists
    fixture.assert_file_exists(
        "dotfiles/d_backup_ignore/config.txt",
        "config.txt should exist",
    );

    // Check that ignored files/dirs are preserved
    fixture.assert_file_exists(
        "dotfiles/d_backup_ignore/temp.tmp",
        "*.tmp should be ignored and preserved",
    );
    assert!(
        fixture.cwd.join("dotfiles/d_backup_ignore/build").exists(),
        "build dir should be preserved"
    );

    // Check that old file was removed
    fixture.assert_file_not_exists(
        "dotfiles/d_backup_ignore/old.txt",
        "old.txt should be removed",
    );
}

#[test]
fn test_clean_ignore_patterns_with_nested_paths() {
    let fixture = TestFixture::new();

    fixture.init();

    let mut config = fixture.get_config();

    let package = Package {
        name: "d_nested_ignore".to_string(),
        src: "dotfiles/d_nested_ignore".to_string(),
        dest: "deploy_dest/nested_ignore".to_string(),
        ignore: vec!["node_modules".to_string(), "**/*.swp".to_string()],
        ..Default::default()
    };

    config
        .packages
        .insert("d_nested_ignore".to_string(), package);
    config
        .profiles
        .get_mut("default")
        .unwrap()
        .dependencies
        .push("d_nested_ignore".to_string());
    config.save(&fixture.cwd).expect("Failed to save config");

    // Create source files
    fixture.write_file("dotfiles/d_nested_ignore/app/main.js", "main");

    // Create destination with nested ignored patterns
    fixture.write_file("deploy_dest/nested_ignore/app/main.js", "old main");
    std::fs::create_dir_all(fixture.cwd.join("deploy_dest/nested_ignore/node_modules")).unwrap();
    std::fs::create_dir_all(
        fixture
            .cwd
            .join("deploy_dest/nested_ignore/app/node_modules"),
    )
    .unwrap();
    fixture.write_file("deploy_dest/nested_ignore/app/file.swp", "vim swap");
    fixture.write_file("deploy_dest/nested_ignore/old.js", "should be removed");

    // Deploy with clean=true
    let result = run_cli(fixture.get_cli(Some(Command::Deploy(DeployArgs {
        packages: None,
        profile: None,
        ignore_errors: false,
        clean: Some(true),
        dry_run: false,
        ..Default::default()
    }))));

    assert!(result.is_ok(), "Deploy with clean should succeed");

    // Check that app file exists
    fixture.assert_file_exists(
        "deploy_dest/nested_ignore/app/main.js",
        "app/main.js should exist",
    );

    // Check that ignored patterns are preserved
    assert!(
        fixture
            .cwd
            .join("deploy_dest/nested_ignore/node_modules")
            .exists(),
        "node_modules dir should be preserved"
    );
    fixture.assert_file_exists(
        "deploy_dest/nested_ignore/app/file.swp",
        "**/*.swp should be preserved",
    );

    // Nested node_modules inside app will be removed since pattern matches top-level only
    fixture.assert_file_not_exists(
        "deploy_dest/nested_ignore/app/node_modules",
        "nested node_modules should be removed",
    );

    // Check that non-ignored file was removed
    fixture.assert_file_not_exists(
        "deploy_dest/nested_ignore/old.js",
        "old.js should be removed",
    );
}

#[test]
fn test_clean_without_ignore_patterns() {
    let fixture = TestFixture::new();

    fixture.init();

    let mut config = fixture.get_config();

    let package = Package {
        name: "d_no_ignore".to_string(),
        src: "dotfiles/d_no_ignore".to_string(),
        dest: "deploy_dest/no_ignore".to_string(),
        ..Default::default()
    };

    config.packages.insert("d_no_ignore".to_string(), package);
    config
        .profiles
        .get_mut("default")
        .unwrap()
        .dependencies
        .push("d_no_ignore".to_string());
    config.save(&fixture.cwd).expect("Failed to save config");

    // Create source files
    fixture.write_file("dotfiles/d_no_ignore/config.txt", "config");

    // Create destination with various files
    fixture.write_file("deploy_dest/no_ignore/config.txt", "old config");
    fixture.write_file("deploy_dest/no_ignore/app.log", "logs");
    fixture.write_file("deploy_dest/no_ignore/temp.txt", "temp");

    // Deploy with clean=true and no ignore patterns
    let result = run_cli(fixture.get_cli(Some(Command::Deploy(DeployArgs {
        packages: None,
        profile: None,
        ignore_errors: false,
        clean: Some(true),
        dry_run: false,
        ..Default::default()
    }))));

    assert!(result.is_ok(), "Deploy with clean should succeed");

    // Check that config file exists
    fixture.assert_file_exists(
        "deploy_dest/no_ignore/config.txt",
        "config.txt should exist",
    );

    // Check that all extra files are removed (no ignore patterns)
    fixture.assert_file_not_exists("deploy_dest/no_ignore/app.log", "app.log should be removed");
    fixture.assert_file_not_exists(
        "deploy_dest/no_ignore/temp.txt",
        "temp.txt should be removed",
    );
}