xdotter 0.1.0

A simple dotfile manager - single binary, no dependencies
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
#!/usr/bin/env python3
"""
Test suite for xdotter
Verifies all core functionality works correctly
"""

import os
import sys
import tempfile
import shutil
import subprocess
from pathlib import Path

# Add parent directory to path to import xd
sys.path.insert(0, str(Path(__file__).parent))

# Test results
PASSED = 0
FAILED = 0
SKIPPED = 0

def log_test(name, status, message=""):
    """Log test result"""
    global PASSED, FAILED, SKIPPED
    status_map = {
        "PASS": ("\033[0;32mPASS\033[0m", lambda: globals().update({"PASSED": PASSED + 1})),
        "FAIL": ("\033[0;31mFAIL\033[0m", lambda: globals().update({"FAILED": FAILED + 1})),
        "SKIP": ("\033[1;33mSKIP\033[0m", lambda: globals().update({"SKIPPED": SKIPPED + 1})),
    }
    colored_status, counter = status_map[status]
    counter()
    msg = f"  {message}" if message else ""
    print(f"  [{colored_status}] {name}{msg}")

def run_xd(args, cwd=None, input_data=None, env=None):
    """Run xd with arguments and return output.

    Backend selection via environment variable:
      XD_BACKEND=python  -> use Python xd.py (default)
      XD_BACKEND=rust    -> use Rust target/debug/xd binary
    """
    backend = os.environ.get("XD_BACKEND", "python")

    if backend == "rust":
        # Locate the Rust binary
        script_dir = Path(__file__).parent
        rust_bin = script_dir / "target" / "debug" / "xd"
        if not rust_bin.is_file():
            # Fallback: try cargo build
            subprocess.run(["cargo", "build"], cwd=script_dir, check=True)
        cmd = [str(rust_bin)] + args
    else:
        cmd = [sys.executable, str(Path(__file__).parent / "xd.py")] + args

    # Merge environment
    full_env = os.environ.copy()
    if env:
        full_env.update(env)
    result = subprocess.run(
        cmd,
        cwd=cwd,
        capture_output=True,
        text=True,
        input=input_data,
        env=full_env
    )
    return result.returncode, result.stdout, result.stderr

def test_help_command():
    """Test help command"""
    print("\n[Test: Help Command]")
    code, stdout, stderr = run_xd(["--help"])
    
    if code == 0 and "deploy" in stdout and "undeploy" in stdout and "new" in stdout:
        log_test("Help output contains all commands", "PASS")
    else:
        log_test("Help output contains all commands", "FAIL", f"code={code}")

def test_version_command():
    """Test version command"""
    print("\n[Test: Version Command]")
    code, stdout, stderr = run_xd(["version"])
    
    if code == 0 and "xdotter" in stdout:
        log_test("Version command works", "PASS")
    else:
        log_test("Version command works", "FAIL", f"code={code}")

def test_new_command():
    """Test new command creates config template"""
    print("\n[Test: New Command]")
    
    with tempfile.TemporaryDirectory() as tmpdir:
        tmppath = Path(tmpdir)
        code, stdout, stderr = run_xd(["new"], cwd=tmpdir)
        config_file = tmppath / "xdotter.toml"
        
        if code == 0 and config_file.exists():
            log_test("New command creates xdotter.toml", "PASS")
            
            content = config_file.read_text()
            if "[links]" in content and "[dependencies]" in content:
                log_test("Config has required sections", "PASS")
            else:
                log_test("Config has required sections", "FAIL", "Missing sections")
        else:
            log_test("New command creates xdotter.toml", "FAIL", f"code={code}")

def test_deploy_basic_link():
    """Test deploying a basic symlink"""
    print("\n[Test: Deploy Basic Link]")
    
    with tempfile.TemporaryDirectory() as tmpdir:
        tmppath = Path(tmpdir)
        
        # Create source file
        source_dir = tmppath / "source"
        source_dir.mkdir()
        source_file = source_dir / "test.txt"
        source_file.write_text("test content")
        
        # Create config
        config = tmppath / "xdotter.toml"
        config.write_text(f'''
[links]
"source/test.txt" = "~/.cache/xdotter_test_{os.getpid()}.txt"
''')

        target_path = Path.home() / f".cache/xdotter_test_{os.getpid()}.txt"

        try:
            # Ensure target dir exists
            target_path.parent.mkdir(exist_ok=True)

            # Run from the temp directory so relative paths work
            code, stdout, stderr = run_xd(["deploy", "-v"], cwd=tmpdir)
            
            if code == 0 and target_path.is_symlink():
                log_test("Deploy creates symlink", "PASS")
                
                # Verify symlink target
                if target_path.read_text() == "test content":
                    log_test("Symlink points to correct file", "PASS")
                else:
                    log_test("Symlink points to correct file", "FAIL", "Content mismatch")
            else:
                log_test("Deploy creates symlink", "FAIL", f"code={code}, target exists: {target_path.exists()}, stderr: {stderr}")
        finally:
            # Cleanup
            if target_path.exists():
                target_path.unlink()

def test_deploy_dry_run():
    """Test deploy with --dry-run flag"""
    print("\n[Test: Deploy Dry Run]")
    
    with tempfile.TemporaryDirectory() as tmpdir:
        tmppath = Path(tmpdir)
        
        # Create source file
        source_dir = tmppath / "source"
        source_dir.mkdir()
        source_file = source_dir / "test.txt"
        source_file.write_text("test content")
        
        # Create config
        config = tmppath / "xdotter.toml"
        config.write_text(f'''
[links]
"source/test.txt" = "~/.cache/xdotter_dryrun_{os.getpid()}.txt"
''')

        target_path = Path.home() / f".cache/xdotter_dryrun_{os.getpid()}.txt"

        try:
            # Ensure target doesn't exist
            if target_path.exists():
                target_path.unlink()

            # Run from temp directory
            code, stdout, stderr = run_xd(["deploy", "-n", "-v"], cwd=tmpdir)
            
            if code == 0 and not target_path.exists():
                log_test("Dry run does not create files", "PASS")
                
                if "deploy:" in stdout.lower():
                    log_test("Dry run shows what would happen", "PASS")
                else:
                    log_test("Dry run shows what would happen", "FAIL", "No output")
            else:
                log_test("Dry run does not create files", "FAIL", "File was created")
        finally:
            if target_path.exists():
                target_path.unlink()

def test_undeploy():
    """Test undeploy removes symlinks"""
    print("\n[Test: Undeploy]")
    
    with tempfile.TemporaryDirectory() as tmpdir:
        tmppath = Path(tmpdir)
        
        # Create source file
        source_dir = tmppath / "source"
        source_dir.mkdir()
        source_file = source_dir / "test.txt"
        source_file.write_text("test content")
        
        # Create config
        config = tmppath / "xdotter.toml"
        config.write_text(f'''
[links]
"source/test.txt" = "~/.cache/xdotter_undeploy_{os.getpid()}.txt"
''')

        target_path = Path.home() / f".cache/xdotter_undeploy_{os.getpid()}.txt"

        try:
            target_path.parent.mkdir(exist_ok=True)

            # First deploy (run from temp dir)
            code, _, _ = run_xd(["deploy"], cwd=tmpdir)

            if target_path.is_symlink():
                log_test("Precondition: symlink exists", "PASS")

                # Then undeploy
                code, stdout, stderr = run_xd(["undeploy", "-v"], cwd=tmpdir)
                
                if code == 0 and not target_path.exists():
                    log_test("Undeploy removes symlink", "PASS")
                else:
                    log_test("Undeploy removes symlink", "FAIL", f"Still exists: {target_path.exists()}")
            else:
                log_test("Precondition: symlink exists", "FAIL", "Deploy failed")
        finally:
            if target_path.exists():
                target_path.unlink()

def test_deploy_with_tilde():
    """Test deploying with ~ in paths"""
    print("\n[Test: Tilde Expansion]")
    
    with tempfile.TemporaryDirectory() as tmpdir:
        tmppath = Path(tmpdir)
        
        # Create source file
        source_dir = tmppath / "source"
        source_dir.mkdir()
        source_file = source_dir / "test.txt"
        source_file.write_text("test content")
        
        # Create config with ~ in target
        config = tmppath / "xdotter.toml"
        config.write_text(f'''
[links]
"source/test.txt" = "~/.cache/xdotter_tilde_{os.getpid()}.txt"
''')

        target_path = Path.home() / f".cache/xdotter_tilde_{os.getpid()}.txt"

        try:
            target_path.parent.mkdir(exist_ok=True)

            # Run from temp directory
            code, stdout, stderr = run_xd(["deploy", "-v"], cwd=tmpdir)

            if code == 0 and target_path.is_symlink():
                log_test("Tilde expansion works", "PASS")
            else:
                log_test("Tilde expansion works", "FAIL", f"code={code}, stderr: {stderr}")
        finally:
            if target_path.exists():
                target_path.unlink()

def test_quiet_mode():
    """Test --quiet flag"""
    print("\n[Test: Quiet Mode]")
    
    with tempfile.TemporaryDirectory() as tmpdir:
        tmppath = Path(tmpdir)

        # Create config that doesn't exist to see quiet behavior
        config = tmppath / "xdotter.toml"

        code, stdout, stderr = run_xd(["deploy", "-q"])
        
        # Quiet mode should suppress output but still have error code
        if len(stdout.strip()) == 0:
            log_test("Quiet mode suppresses output", "PASS")
        else:
            log_test("Quiet mode suppresses output", "FAIL", f"Got output: {stdout}")

def test_verbose_mode():
    """Test --verbose flag"""
    print("\n[Test: Verbose Mode]")
    
    with tempfile.TemporaryDirectory() as tmpdir:
        tmppath = Path(tmpdir)
        
        # Create source file
        source_dir = tmppath / "source"
        source_dir.mkdir()
        source_file = source_dir / "test.txt"
        source_file.write_text("test content")
        
        # Create config
        config = tmppath / "xdotter.toml"
        config.write_text(f'''
[links]
"source/test.txt" = "~/.cache/xdotter_verbose_{os.getpid()}.txt"
''')

        target_path = Path.home() / f".cache/xdotter_verbose_{os.getpid()}.txt"

        try:
            target_path.parent.mkdir(exist_ok=True)

            code, stdout, stderr = run_xd(["deploy", "-v"])

            if "[DEBUG]" in stdout or "DEBUG" in stdout:
                log_test("Verbose mode shows debug info", "PASS")
            else:
                log_test("Verbose mode shows debug info", "FAIL", "No debug output")
        finally:
            if target_path.exists():
                target_path.unlink()

def test_force_flag():
    """Test --force flag for overwriting"""
    print("\n[Test: Force Flag]")
    
    with tempfile.TemporaryDirectory() as tmpdir:
        tmppath = Path(tmpdir)
        
        # Create source files
        source_dir = tmppath / "source"
        source_dir.mkdir()
        source_file = source_dir / "test.txt"
        source_file.write_text("new content")
        
        target_dir = Path.home() / ".cache"
        target_dir.mkdir(exist_ok=True)
        target_path = target_dir / f"xdotter_force_{os.getpid()}.txt"
        
        # Create existing file (not symlink)
        target_path.write_text("old content")
        
        # Create config
        config = tmppath / "xdotter.toml"
        config.write_text(f'''
[links]
"source/test.txt" = "~/.cache/xdotter_force_{os.getpid()}.txt"
''')

        try:
            # Try with force (run from temp dir)
            code, stdout, stderr = run_xd(["deploy", "-f", "-v"], cwd=tmpdir)
            
            if code == 0 and target_path.is_symlink():
                log_test("Force flag overwrites existing file", "PASS")
            else:
                log_test("Force flag overwrites existing file", "FAIL", f"code={code}, is_symlink={target_path.is_symlink()}, stderr: {stderr}")
        finally:
            if target_path.exists():
                if target_path.is_symlink():
                    target_path.unlink()
                else:
                    target_path.unlink()

def test_config_parsing():
    """Test TOML config parsing"""
    print("\n[Test: Config Parsing]")
    
    from xd import ConfigParser
    
    toml_content = '''
# Comment
[links]
".zshrc" = "~/.zshrc"
".config/nvim/init.lua" = "~/.config/nvim/init.lua"

[dependencies]
"go" = "testdata/go"
'''
    
    try:
        config = ConfigParser.parse(toml_content)
        
        if ".zshrc" in config["links"] and config["links"][".zshrc"] == "~/.zshrc":
            log_test("Parse links section", "PASS")
        else:
            log_test("Parse links section", "FAIL", str(config))
        
        if "go" in config["dependencies"] and config["dependencies"]["go"] == "testdata/go":
            log_test("Parse dependencies section", "PASS")
        else:
            log_test("Parse dependencies section", "FAIL", str(config))
    except Exception as e:
        log_test("Config parsing", "FAIL", str(e))

def test_multiple_links():
    """Test deploying multiple links at once"""
    print("\n[Test: Multiple Links]")
    
    with tempfile.TemporaryDirectory() as tmpdir:
        tmppath = Path(tmpdir)
        
        # Create multiple source files
        source_dir = tmppath / "source"
        source_dir.mkdir()
        (source_dir / "file1.txt").write_text("content1")
        (source_dir / "file2.txt").write_text("content2")
        (source_dir / "file3.txt").write_text("content3")
        
        # Create config with multiple links
        config = tmppath / "xdotter.toml"
        config.write_text(f'''
[links]
"source/file1.txt" = "~/.cache/xdotter_multi_1_{os.getpid()}.txt"
"source/file2.txt" = "~/.cache/xdotter_multi_2_{os.getpid()}.txt"
"source/file3.txt" = "~/.cache/xdotter_multi_3_{os.getpid()}.txt"
''')

        targets = [
            Path.home() / f".cache/xdotter_multi_{i}_{os.getpid()}.txt"
            for i in range(1, 4)
        ]

        try:
            for t in targets:
                t.parent.mkdir(exist_ok=True)
                if t.exists():
                    t.unlink()

            # Run from temp directory
            code, stdout, stderr = run_xd(["deploy", "-v"], cwd=tmpdir)
            
            all_exist = all(t.is_symlink() for t in targets)
            
            if code == 0 and all_exist:
                log_test("Multiple links deployed", "PASS")
            else:
                log_test("Multiple links deployed", "FAIL", f"code={code}, count={sum(1 for t in targets if t.is_symlink())}/3, stderr: {stderr}")
        finally:
            for t in targets:
                if t.exists():
                    t.unlink()

def print_summary():
    """Print test summary"""
    total = PASSED + FAILED + SKIPPED
    print("\n" + "=" * 50)
    print(f"Test Summary: {PASSED}/{total} passed")
    print(f"  \033[0;32mPassed:  {PASSED}\033[0m")
    print(f"  \033[0;31mFailed:  {FAILED}\033[0m")
    print(f"  \033[1;33mSkipped: {SKIPPED}\033[0m")
    print("=" * 50)
    
    return FAILED == 0


# ============================================================
# Additional Test Scenarios
# ============================================================

def test_dependencies_subdirectory():
    """Test deploying with dependencies (subdirectory with its own config)"""
    print("\n[Test: Dependencies Subdirectory]")
    
    with tempfile.TemporaryDirectory() as tmpdir:
        tmppath = Path(tmpdir)
        
        # Create main source file
        source_file = tmppath / "main.txt"
        source_file.write_text("main content")
        
        # Create subdirectory with its own config
        sub_dir = tmppath / "sub"
        sub_dir.mkdir()
        sub_source = sub_dir / "sub.txt"
        sub_source.write_text("sub content")
        
        # Subdirectory config
        sub_config = sub_dir / "xdotter.toml"
        sub_config.write_text(f'''
[links]
"sub.txt" = "~/.cache/xdotter_sub_{os.getpid()}.txt"
''')
        
        # Main config with dependency
        main_config = tmppath / "xdotter.toml"
        main_config.write_text(f'''
[links]
"main.txt" = "~/.cache/xdotter_main_{os.getpid()}.txt"

[dependencies]
"sub" = "sub"
''')

        main_target = Path.home() / f".cache/xdotter_main_{os.getpid()}.txt"
        sub_target = Path.home() / f".cache/xdotter_sub_{os.getpid()}.txt"

        try:
            main_target.parent.mkdir(exist_ok=True)

            # Run from temp directory
            code, stdout, stderr = run_xd(["deploy", "-v"], cwd=tmpdir)
            
            main_ok = main_target.is_symlink()
            sub_ok = sub_target.is_symlink()
            
            if code == 0 and main_ok and sub_ok:
                log_test("Dependencies subdirectory deployed", "PASS")
            else:
                log_test("Dependencies subdirectory deployed", "FAIL", 
                    f"main={main_ok}, sub={sub_ok}, stderr: {stderr}")
        finally:
            if main_target.exists():
                main_target.unlink()
            if sub_target.exists():
                sub_target.unlink()


def test_interactive_mode_confirm():
    """Test interactive mode with confirmation"""
    print("\n[Test: Interactive Mode Confirm]")
    
    with tempfile.TemporaryDirectory() as tmpdir:
        tmppath = Path(tmpdir)
        
        # Create source file
        source_dir = tmppath / "source"
        source_dir.mkdir()
        source_file = source_dir / "test.txt"
        source_file.write_text("test content")
        
        # Create config
        config = tmppath / "xdotter.toml"
        config.write_text(f'''
[links]
"source/test.txt" = "~/.cache/xdotter_inter_{os.getpid()}.txt"
''')

        target_path = Path.home() / f".cache/xdotter_inter_{os.getpid()}.txt"

        try:
            target_path.parent.mkdir(exist_ok=True)

            # First deploy
            run_xd(["deploy"], cwd=tmpdir)

            if target_path.is_symlink():
                log_test("Precondition: symlink exists", "PASS")

                # Remove source to create a different one
                source_file.write_text("different content")

                # Try interactive mode with 'n' (no)
                code, stdout, stderr = run_xd(
                    ["deploy", "-i"],
                    cwd=tmpdir,
                    input_data="n\n"
                )
                
                # Should skip because we answered 'n'
                if target_path.is_symlink():
                    log_test("Interactive mode respects 'n' answer", "PASS")
                else:
                    log_test("Interactive mode respects 'n' answer", "FAIL", "Link was removed")
            else:
                log_test("Precondition: symlink exists", "FAIL")
        finally:
            if target_path.exists():
                target_path.unlink()


def test_interactive_mode_yes():
    """Test interactive mode with yes confirmation"""
    print("\n[Test: Interactive Mode Yes]")
    
    with tempfile.TemporaryDirectory() as tmpdir:
        tmppath = Path(tmpdir)
        
        # Create source file
        source_dir = tmppath / "source"
        source_dir.mkdir()
        source_file = source_dir / "test.txt"
        source_file.write_text("original content")
        
        target_dir = Path.home() / ".cache"
        target_dir.mkdir(exist_ok=True)
        target_path = target_dir / f"xdotter_intery_{os.getpid()}.txt"
        
        # Create existing file (not symlink)
        target_path.write_text("existing content")
        
        # Change source content
        source_file.write_text("new content")
        
        # Create config
        config = tmppath / "xdotter.toml"
        config.write_text(f'''
[links]
"source/test.txt" = "~/.cache/xdotter_intery_{os.getpid()}.txt"
''')

        try:
            # Try interactive mode with 'y' (yes)
            code, stdout, stderr = run_xd(
                ["deploy", "-i"],
                cwd=tmpdir,
                input_data="y\n"
            )
            
            if code == 0 and target_path.is_symlink():
                log_test("Interactive mode respects 'y' answer", "PASS")
            else:
                log_test("Interactive mode respects 'y' answer", "FAIL", 
                    f"code={code}, is_symlink={target_path.is_symlink()}")
        finally:
            if target_path.exists():
                if target_path.is_symlink():
                    target_path.unlink()
                else:
                    target_path.unlink()


def test_nonexistent_source():
    """Test deploying with nonexistent source file"""
    print("\n[Test: Nonexistent Source]")
    
    with tempfile.TemporaryDirectory() as tmpdir:
        tmppath = Path(tmpdir)

        # Create config pointing to nonexistent file
        config = tmppath / "xdotter.toml"
        config.write_text(f'''
[links]
"nonexistent.txt" = "~/.cache/xdotter_noexist_{os.getpid()}.txt"
''')

        target_path = Path.home() / f".cache/xdotter_noexist_{os.getpid()}.txt"

        try:
            target_path.parent.mkdir(exist_ok=True)

            code, stdout, stderr = run_xd(["deploy", "-v"], cwd=tmpdir)
            
            # Should fail gracefully, not crash
            if "does not exist" in stderr or "does not exist" in stdout or code != 0:
                log_test("Handles nonexistent source gracefully", "PASS")
            else:
                log_test("Handles nonexistent source gracefully", "FAIL", "Should report error")
        finally:
            if target_path.exists():
                target_path.unlink()


def test_nonexistent_config():
    """Test with nonexistent config file"""
    print("\n[Test: Nonexistent Config]")

    with tempfile.TemporaryDirectory() as tmpdir:
        tmppath = Path(tmpdir)

        code, stdout, stderr = run_xd(["deploy"], cwd=tmpdir)

        # Should fail with appropriate error
        if code != 0 and ("not found" in stderr.lower() or "failed to read" in stderr.lower() or "no such file" in stderr.lower()):
            log_test("Handles nonexistent config gracefully", "PASS")
        else:
            log_test("Handles nonexistent config gracefully", "FAIL", f"code={code}")


def test_invalid_toml_syntax():
    """Test with invalid TOML syntax"""
    print("\n[Test: Invalid TOML Syntax]")
    
    with tempfile.TemporaryDirectory() as tmpdir:
        tmppath = Path(tmpdir)

        # Create invalid TOML
        config = tmppath / "xdotter.toml"
        config.write_text('''
[links
"invalid" = "syntax
''')

        code, stdout, stderr = run_xd(["deploy"], cwd=tmpdir)
        
        # Should fail gracefully
        if code != 0 or "parse" in stderr.lower():
            log_test("Handles invalid TOML gracefully", "PASS")
        else:
            # Parser is lenient, may just skip invalid lines
            log_test("Handles invalid TOML gracefully", "PASS", "Lenient parser accepts")


def test_empty_config():
    """Test with empty config file"""
    print("\n[Test: Empty Config]")
    
    with tempfile.TemporaryDirectory() as tmpdir:
        tmppath = Path(tmpdir)

        # Create empty config
        config = tmppath / "xdotter.toml"
        config.write_text("")

        code, stdout, stderr = run_xd(["deploy"], cwd=tmpdir)
        
        # Should succeed with nothing to do
        if code == 0:
            log_test("Handles empty config", "PASS")
        else:
            log_test("Handles empty config", "FAIL", f"code={code}")


def test_symlink_already_exists():
    """Test when symlink already points to correct target"""
    print("\n[Test: Symlink Already Exists]")
    
    with tempfile.TemporaryDirectory() as tmpdir:
        tmppath = Path(tmpdir)
        
        # Create source file
        source_dir = tmppath / "source"
        source_dir.mkdir()
        source_file = source_dir / "test.txt"
        source_file.write_text("test content")
        
        target_dir = Path.home() / ".cache"
        target_dir.mkdir(exist_ok=True)
        target_path = target_dir / f"xdotter_exist_{os.getpid()}.txt"
        
        # Create correct symlink first
        source_resolved = source_file.resolve()
        os.symlink(source_resolved, target_path)
        
        # Create config
        config = tmppath / "xdotter.toml"
        config.write_text(f'''
[links]
"source/test.txt" = "~/.cache/xdotter_exist_{os.getpid()}.txt"
''')

        try:
            code, stdout, stderr = run_xd(["deploy", "-v"], cwd=tmpdir)

            # Should skip, not error
            if code == 0 and target_path.is_symlink():
                log_test("Skips existing correct symlink", "PASS")
            else:
                log_test("Skips existing correct symlink", "FAIL", f"code={code}")
        finally:
            if target_path.exists():
                target_path.unlink()


def test_unicode_paths():
    """Test with unicode characters in paths"""
    print("\n[Test: Unicode Paths]")
    
    with tempfile.TemporaryDirectory() as tmpdir:
        tmppath = Path(tmpdir)
        
        # Create source file with unicode name
        source_dir = tmppath / "测试目录"
        source_dir.mkdir()
        source_file = source_dir / "测试文件.txt"
        source_file.write_text("中文内容 Chinese content")
        
        # Create config
        config = tmppath / "xdotter.toml"
        config.write_text(f'''
[links]
"测试目录/测试文件.txt" = "~/.cache/xdotter_unicode_{os.getpid()}.txt"
''')

        target_path = Path.home() / f".cache/xdotter_unicode_{os.getpid()}.txt"

        try:
            target_path.parent.mkdir(exist_ok=True)

            code, stdout, stderr = run_xd(["deploy"], cwd=tmpdir)

            if code == 0 and target_path.is_symlink():
                log_test("Unicode paths work", "PASS")
            else:
                log_test("Unicode paths work", "FAIL", f"code={code}")
        finally:
            if target_path.exists():
                target_path.unlink()


def test_absolute_path_in_config():
    """Test with absolute paths in config"""
    print("\n[Test: Absolute Path In Config]")
    
    with tempfile.TemporaryDirectory() as tmpdir:
        tmppath = Path(tmpdir)
        
        # Create source file
        source_file = tmppath / "source.txt"
        source_file.write_text("absolute path test")
        
        target_path = Path.home() / f".cache/xdotter_abs_{os.getpid()}.txt"
        
        # Create config with absolute path
        config = tmppath / "xdotter.toml"
        config.write_text(f'''
[links]
"{source_file}" = "~/.cache/xdotter_abs_{os.getpid()}.txt"
''')

        try:
            target_path.parent.mkdir(exist_ok=True)

            code, stdout, stderr = run_xd(["deploy"], cwd=tmpdir)

            if code == 0 and target_path.is_symlink():
                log_test("Absolute paths in config work", "PASS")
            else:
                log_test("Absolute paths in config work", "FAIL", f"code={code}")
        finally:
            if target_path.exists():
                target_path.unlink()


def test_undeploy_nonexistent_link():
    """Test undeploy when link doesn't exist"""
    print("\n[Test: Undeploy Nonexistent Link]")
    
    with tempfile.TemporaryDirectory() as tmpdir:
        tmppath = Path(tmpdir)

        # Create config for nonexistent link
        config = tmppath / "xdotter.toml"
        config.write_text(f'''
[links]
"source.txt" = "~/.cache/xdotter_nolink_{os.getpid()}.txt"
''')

        code, stdout, stderr = run_xd(["undeploy", "-v"], cwd=tmpdir)
        
        # Should succeed (skip nonexistent)
        if code == 0:
            log_test("Undeploy handles nonexistent link", "PASS")
        else:
            log_test("Undeploy handles nonexistent link", "FAIL", f"code={code}")


def test_comments_in_config():
    """Test config with various comment styles"""
    print("\n[Test: Comments In Config]")
    
    with tempfile.TemporaryDirectory() as tmpdir:
        tmppath = Path(tmpdir)
        
        # Create source file
        source_dir = tmppath / "source"
        source_dir.mkdir()
        source_file = source_dir / "test.txt"
        source_file.write_text("test content")
        
        # Create config with comments
        config = tmppath / "xdotter.toml"
        config.write_text(f'''
# This is a comment
[links]
# Another comment
"source/test.txt" = "~/.cache/xdotter_comment_{os.getpid()}.txt"  # inline comment

# Comment before dependencies
[dependencies]
# Empty dependencies is ok
''')

        target_path = Path.home() / f".cache/xdotter_comment_{os.getpid()}.txt"

        try:
            target_path.parent.mkdir(exist_ok=True)

            code, stdout, stderr = run_xd(["deploy"], cwd=tmpdir)

            if code == 0 and target_path.is_symlink():
                log_test("Comments in config handled", "PASS")
            else:
                log_test("Comments in config handled", "FAIL", f"code={code}")
        finally:
            if target_path.exists():
                target_path.unlink()


def test_whitespace_in_config():
    """Test config with various whitespace"""
    print("\n[Test: Whitespace In Config]")
    
    with tempfile.TemporaryDirectory() as tmpdir:
        tmppath = Path(tmpdir)
        
        # Create source file
        source_dir = tmppath / "source"
        source_dir.mkdir()
        source_file = source_dir / "test.txt"
        source_file.write_text("test content")
        
        # Create config with extra whitespace
        config = tmppath / "xdotter.toml"
        config.write_text(f'''
[links]
  "source/test.txt"   =   "~/.cache/xdotter_ws_{os.getpid()}.txt"
''')

        target_path = Path.home() / f".cache/xdotter_ws_{os.getpid()}.txt"

        try:
            target_path.parent.mkdir(exist_ok=True)

            code, stdout, stderr = run_xd(["deploy"], cwd=tmpdir)

            if code == 0 and target_path.is_symlink():
                log_test("Whitespace in config handled", "PASS")
            else:
                log_test("Whitespace in config handled", "FAIL", f"code={code}")
        finally:
            if target_path.exists():
                target_path.unlink()


def test_single_quotes_in_config():
    """Test config with single quotes"""
    print("\n[Test: Single Quotes In Config]")

    with tempfile.TemporaryDirectory() as tmpdir:
        tmppath = Path(tmpdir)

        # Create source file
        source_dir = tmppath / "source"
        source_dir.mkdir()
        source_file = source_dir / "test.txt"
        source_file.write_text("test content")

        # Create config with single quotes
        config = tmppath / "xdotter.toml"
        config.write_text(f"""
[links]
'source/test.txt' = '~/.cache/xdotter_sq_{os.getpid()}.txt'
""")

        target_path = Path.home() / f".cache/xdotter_sq_{os.getpid()}.txt"

        try:
            target_path.parent.mkdir(exist_ok=True)

            code, stdout, stderr = run_xd(["deploy"], cwd=tmpdir)

            if code == 0 and target_path.is_symlink():
                log_test("Single quotes in config work", "PASS")
            else:
                log_test("Single quotes in config work", "FAIL", f"code={code}")
        finally:
            if target_path.exists():
                target_path.unlink()


# ============================================================
# Permission Check Tests
# ============================================================

def test_permission_check_ssh_key():
    """Test --check-permissions for SSH key"""
    print("\n[Test: Permission Check SSH Key]")

    with tempfile.TemporaryDirectory() as tmpdir:
        tmppath = Path(tmpdir)

        # Create source file with wrong permission (644 instead of 600)
        source_dir = tmppath / "source"
        source_dir.mkdir()
        source_file = source_dir / "id_ed25519"
        source_file.write_text("fake ssh key")
        source_file.chmod(0o644)

        # Create config - use ~/.ssh/id_ed25519 to match sensitive pattern
        # Filename must match pattern "id_ed25519*" for detection
        config = tmppath / "xdotter.toml"
        config.write_text(f'''
[links]
"source/id_ed25519" = "~/.ssh/id_ed25519_xdotter_test_{os.getpid()}"
''')

        target_path = Path.home() / ".ssh" / f"id_ed25519_xdotter_test_{os.getpid()}"

        try:
            target_path.parent.mkdir(exist_ok=True)

            # Deploy with --check-permissions --force (to allow deployment despite permission issue)
            code, stdout, stderr = run_xd(
                ["deploy", "--check-permissions", "--force", "-v"],
                cwd=tmpdir
            )

            # Should show permission warning - filename matches id_ed25519* pattern
            output = stdout + stderr
            if ("600" in output and ("warning" in output.lower() or "permission" in output.lower())) or \
               ("" in output and "600" in output):
                log_test("Detects wrong SSH key permission", "PASS")
            else:
                log_test("Detects wrong SSH key permission", "FAIL", f"stdout: {stdout[:200]}")

        finally:
            if target_path.exists() or target_path.is_symlink():
                target_path.unlink()


def test_permission_fix_ssh_key():
    """Test --fix-permissions for SSH key"""
    print("\n[Test: Permission Fix SSH Key]")

    with tempfile.TemporaryDirectory() as tmpdir:
        tmppath = Path(tmpdir)

        # Create source file with wrong permission
        source_dir = tmppath / "source"
        source_dir.mkdir()
        source_file = source_dir / "id_ed25519"
        source_file.write_text("fake ssh key")
        source_file.chmod(0o644)

        # Create config - use filename that matches id_ed25519* pattern
        # Pattern: id_ed25519* matches filenames starting with "id_ed25519"
        config = tmppath / "xdotter.toml"
        config.write_text(f'''
[links]
"source/id_ed25519" = "~/.ssh/id_ed25519_xdotter_test_{os.getpid()}"
''')

        target_path = Path.home() / ".ssh" / f"id_ed25519_xdotter_test_{os.getpid()}"

        try:
            target_path.parent.mkdir(exist_ok=True)

            # Deploy with --fix-permissions (automatically fixes and allows deployment)
            code, stdout, stderr = run_xd(
                ["deploy", "--fix-permissions", "-v"],
                cwd=tmpdir
            )

            # Check if source file permission was fixed
            import stat
            actual_mode = stat.S_IMODE(source_file.stat().st_mode)

            # Should be fixed to 600 (matches id_ed25519* pattern)
            if actual_mode == 0o600:
                log_test("Fixes SSH key permission to 600", "PASS")
            else:
                log_test("Fixes SSH key permission to 600", "FAIL", f"mode={oct(actual_mode)}")

        finally:
            if target_path.exists() or target_path.is_symlink():
                target_path.unlink()


def test_permission_check_correct_permission():
    """Test --check-permissions with correct permission"""
    print("\n[Test: Permission Check Correct]")

    with tempfile.TemporaryDirectory() as tmpdir:
        tmppath = Path(tmpdir)

        # Create source file with correct permission (600)
        source_dir = tmppath / "source"
        source_dir.mkdir()
        source_file = source_dir / "id_ed25519"
        source_file.write_text("fake ssh key")
        source_file.chmod(0o600)

        # Create config - use ~/.ssh/ path with filename matching pattern
        config = tmppath / "xdotter.toml"
        config.write_text(f'''
[links]
"source/id_ed25519" = "~/.ssh/id_ed25519_xdotter_correct_{os.getpid()}"
''')

        target_path = Path.home() / ".ssh" / f"id_ed25519_xdotter_correct_{os.getpid()}"

        try:
            target_path.parent.mkdir(exist_ok=True)

            # Deploy with --check-permissions --force (to allow deployment)
            code, stdout, stderr = run_xd(
                ["deploy", "--check-permissions", "--force", "-v"],
                cwd=tmpdir
            )

            # Should show checkmark (✓) or no warning about wrong permission
            output = stdout + stderr
            if "" in output or ("deploy" in output.lower() and "wrong" not in output.lower()):
                log_test("Recognizes correct SSH key permission", "PASS")
            else:
                log_test("Recognizes correct SSH key permission", "FAIL", f"stdout: {stdout[:200]}")

        finally:
            if target_path.exists() or target_path.is_symlink():
                target_path.unlink()


def test_permission_pattern_matching():
    """Test permission pattern matching for various key files"""
    print("\n[Test: Permission Pattern Matching]")

    with tempfile.TemporaryDirectory() as tmpdir:
        tmppath = Path(tmpdir)

        # Create source files with wrong permissions
        source_dir = tmppath / "source"
        source_dir.mkdir()

        # Use target filenames that match patterns directly
        # Use unique prefixes that still match the patterns
        # Format: (source_name, target_name, pattern_matched)
        test_cases = [
            ("key1", f"id_rsa_custom_{os.getpid()}", "id_rsa*"),        # matches id_rsa*
            ("key2", f"id_ed25519_custom_{os.getpid()}", "id_ed25519*"), # matches id_ed25519*
            ("key3", f"cert_{os.getpid()}.pem", "*.pem"),               # matches *.pem
            ("key4", f"mykey_{os.getpid()}.key", "*.key"),              # matches *.key
        ]

        for src_name, tgt_name, pattern in test_cases:
            f = source_dir / src_name
            f.write_text("fake key")
            f.chmod(0o644)

        # Create config - use ~/.ssh/ paths with filenames that match patterns
        config = tmppath / "xdotter.toml"
        links = '\n'.join([f'"source/{src}" = "~/.ssh/{tgt}"'
                          for src, tgt, _ in test_cases])
        config.write_text(f'''
[links]
{links}
''')

        # Deploy with --check-permissions --force (to allow deployment despite permission issues)
        code, stdout, stderr = run_xd(
            ["deploy", "--check-permissions", "--force", "-v"],
            cwd=tmpdir
        )

        # All should be detected as needing permission fix
        # The exact permission depends on pattern matching
        output = stdout + stderr
        warning_count = output.lower().count("warning") + output.count("")
        if warning_count >= 4:
            log_test("Pattern matching detects all key types", "PASS")
        else:
            log_test("Pattern matching detects all key types", "FAIL", f"warning count={warning_count}")

        # Cleanup
        for src, tgt, _ in test_cases:
            target = Path.home() / ".ssh" / tgt
            if target.exists() or target.is_symlink():
                target.unlink()


def test_permission_dry_run():
    """Test --fix-permissions with --dry-run doesn't modify files"""
    print("\n[Test: Permission Dry Run]")

    with tempfile.TemporaryDirectory() as tmpdir:
        tmppath = Path(tmpdir)

        # Create source file with wrong permission
        source_dir = tmppath / "source"
        source_dir.mkdir()
        source_file = source_dir / "id_ed25519"
        source_file.write_text("fake ssh key")
        source_file.chmod(0o644)

        # Create config - use ~/.ssh/ path to match sensitive pattern
        config = tmppath / "xdotter.toml"
        config.write_text(f'''
[links]
"source/id_ed25519" = "~/.ssh/xdotter_dry_perm_{os.getpid()}"
''')

        target_path = Path.home() / ".ssh" / f"xdotter_dry_perm_{os.getpid()}"

        try:
            target_path.parent.mkdir(exist_ok=True)

            # Deploy with --fix-permissions --dry-run
            code, stdout, stderr = run_xd(
                ["deploy", "--fix-permissions", "-n", "-v"],
                cwd=tmpdir
            )

            # Check source file permission is NOT changed
            import stat
            actual_mode = stat.S_IMODE(source_file.stat().st_mode)

            if actual_mode == 0o644:
                log_test("Dry-run doesn't modify permissions", "PASS")
            else:
                log_test("Dry-run doesn't modify permissions", "FAIL", f"mode changed to {oct(actual_mode)}")

        finally:
            if target_path.exists() or target_path.is_symlink():
                target_path.unlink()


# ============================================================
# Validate Command Tests
# ============================================================

def test_validate_command_valid_toml():
    """Test validate command with valid TOML file"""
    print("\n[Test: Validate Valid TOML]")

    with tempfile.TemporaryDirectory() as tmpdir:
        tmppath = Path(tmpdir)

        # Create valid TOML config
        config = tmppath / "xdotter.toml"
        config.write_text('''
[links]
".zshrc" = "~/.zshrc"

[dependencies]
"nvim" = "config/nvim"
''')

        code, stdout, stderr = run_xd(["validate", str(config)])

        if code == 0 and "Valid" in stdout:
            log_test("Validate accepts valid TOML", "PASS")
        else:
            log_test("Validate accepts valid TOML", "FAIL", f"code={code}, stdout={stdout[:100]}")


def test_validate_command_invalid_toml():
    """Test validate command with invalid TOML file"""
    print("\n[Test: Validate Invalid TOML]")

    with tempfile.TemporaryDirectory() as tmpdir:
        tmppath = Path(tmpdir)

        # Create invalid TOML config (unclosed string)
        config = tmppath / "invalid.toml"
        config.write_text('''
[links]
".zshrc" = "~/.zshrc
''')

        code, stdout, stderr = run_xd(["validate", str(config)])

        # Should fail with error message
        if code != 0 or "错误" in stdout or "error" in stdout.lower() or "" in stdout:
            log_test("Validate rejects invalid TOML", "PASS")
        else:
            log_test("Validate rejects invalid TOML", "FAIL", f"code={code}")


def test_validate_command_rejects_json():
    """Test validate command with valid JSON file (Python still supports JSON)"""
    print("\n[Test: Validate Valid JSON]")

    with tempfile.TemporaryDirectory() as tmpdir:
        tmppath = Path(tmpdir)

        config = tmppath / "xdotter.json"
        config.write_text('{"links": {".zshrc": "~/.zshrc"}}')

        code, stdout, stderr = run_xd(["validate", str(config)])

        if code == 0 and "Valid" in stdout:
            log_test("Validate accepts valid JSON", "PASS")
        else:
            log_test("Validate accepts valid JSON", "FAIL", f"code={code}, stdout={stdout[:100]}")


def test_validate_command_invalid_json():
    """Test validate command with invalid JSON file"""
    print("\n[Test: Validate Invalid JSON]")

    with tempfile.TemporaryDirectory() as tmpdir:
        tmppath = Path(tmpdir)

        config = tmppath / "invalid.json"
        config.write_text('{"links": }')

        code, stdout, stderr = run_xd(["validate", str(config)])

        output = stdout + stderr
        if code != 0 and ("error" in output.lower() or "invalid" in output.lower()):
            log_test("Validate rejects invalid JSON", "PASS")
        else:
            log_test("Validate rejects invalid JSON", "FAIL", f"code={code}")
        if code != 0 or "错误" in stdout or "error" in stdout.lower() or "" in stdout or "Expecting" in stdout:
            log_test("Validate rejects invalid JSON", "PASS")
        else:
            log_test("Validate rejects invalid JSON", "FAIL", f"code={code}")


def test_validate_command_nonexistent_file():
    """Test validate command with nonexistent file"""
    print("\n[Test: Validate Nonexistent File]")

    with tempfile.TemporaryDirectory() as tmpdir:
        tmppath = Path(tmpdir)

        nonexistent = tmppath / "nonexistent.toml"
        code, stdout, stderr = run_xd(["validate", str(nonexistent)])

        # Should report file not found
        if code != 0 or "not found" in stdout.lower() or "not found" in stderr.lower():
            log_test("Validate handles nonexistent file", "PASS")
        else:
            log_test("Validate handles nonexistent file", "FAIL", f"code={code}")


def test_validate_command_multiple_files():
    """Test validate command with multiple files"""
    print("\n[Test: Validate Multiple Files]")

    with tempfile.TemporaryDirectory() as tmpdir:
        tmppath = Path(tmpdir)

        # Create valid and invalid files
        valid_config = tmppath / "valid.toml"
        valid_config.write_text('[links]\n".zshrc" = "~/.zshrc"')

        invalid_config = tmppath / "invalid.toml"
        invalid_config.write_text('[links\n".zshrc" = "~/.zshrc"')

        code, stdout, stderr = run_xd([
            "validate",
            str(valid_config),
            str(invalid_config)
        ])

        # Should report both files - valid.toml in stdout, invalid.toml in stderr
        if "valid.toml" in stdout and "invalid.toml" in stderr:
            log_test("Validate handles multiple files", "PASS")
        else:
            log_test("Validate handles multiple files", "FAIL", f"stdout={stdout[:200]}, stderr={stderr[:200]}")


def test_validate_command_default_files():
    """Test validate command checks default files in current dir"""
    print("\n[Test: Validate Default Files]")

    with tempfile.TemporaryDirectory() as tmpdir:
        tmppath = Path(tmpdir)

        # Create valid xdotter.toml in current dir
        config = tmppath / "xdotter.toml"
        config.write_text('[links]\n".zshrc" = "~/.zshrc"')

        code, stdout, stderr = run_xd(["validate"], cwd=tmpdir)

        if code == 0 and "xdotter.toml" in stdout:
            log_test("Validate checks default xdotter.toml", "PASS")
        else:
            log_test("Validate checks default xdotter.toml", "FAIL", f"code={code}")


# ============================================================
# Completion Command Tests
# ============================================================

def test_completion_command_bash():
    """Test completion command generates Bash script"""
    print("\n[Test: Completion Bash]")

    code, stdout, stderr = run_xd(["completion", "bash"])

    # Clap completion generates _xd() function with COMPREPLY
    if code == 0 and ("_xd" in stdout or "COMPREPLY" in stdout):
        log_test("Completion generates Bash script", "PASS")
    else:
        log_test("Completion generates Bash script", "FAIL", f"code={code}")


def test_completion_command_zsh():
    """Test completion command generates Zsh script"""
    print("\n[Test: Completion Zsh]")

    code, stdout, stderr = run_xd(["completion", "zsh"])

    # Clap zsh completion generates compdef calls
    if code == 0 and ("_xd" in stdout or "compdef" in stdout):
        log_test("Completion generates Zsh script", "PASS")
    else:
        log_test("Completion generates Zsh script", "FAIL", f"code={code}")


def test_completion_command_fish():
    """Test completion command generates Fish script"""
    print("\n[Test: Completion Fish]")

    code, stdout, stderr = run_xd(["completion", "fish"])

    # argcomplete generates fish completion with __fish_*_complete
    if code == 0 and "__fish_" in stdout and "complete " in stdout:
        log_test("Completion generates Fish script", "PASS")
    else:
        log_test("Completion generates Fish script", "FAIL", f"code={code}")


def test_completion_command_no_shell():
    """Test completion command without shell argument"""
    print("\n[Test: Completion No Shell]")

    code, stdout, stderr = run_xd(["completion"])

    # Should show error and usage (clap sends errors to stderr)
    output = stdout + stderr
    if code != 0 and ("usage" in output.lower() or "error" in output.lower() or "required" in output.lower()):
        log_test("Completion requires shell argument", "PASS")
    else:
        log_test("Completion requires shell argument", "FAIL", f"code={code}")


def test_completion_command_invalid_shell():
    """Test completion command with invalid shell"""
    print("\n[Test: Completion Invalid Shell]")

    code, stdout, stderr = run_xd(["completion", "powershell"])

    # Should show error for unsupported shell (clap sends errors to stderr)
    output = stdout + stderr
    if code != 0 and ("unsupported" in output.lower() or "error" in output.lower()):
        log_test("Completion rejects invalid shell", "PASS")
    else:
        log_test("Completion rejects invalid shell", "FAIL", f"code={code}")


# ============================================================
# Auto-Validation Tests
# ============================================================

def test_deploy_auto_validation_invalid():
    """Test deploy automatically validates config and fails on invalid syntax"""
    print("\n[Test: Deploy Auto-Validation Invalid]")

    with tempfile.TemporaryDirectory() as tmpdir:
        tmppath = Path(tmpdir)

        # Create invalid TOML config
        config = tmppath / "xdotter.toml"
        config.write_text('''
[links
".zshrc" = "~/.zshrc"
''')

        code, stdout, stderr = run_xd(["deploy", "-v"], cwd=tmpdir)

        # Should fail due to validation (error messages in stderr)
        if code != 0 and ("aborted" in stderr.lower() or "错误" in stderr or "error" in stderr.lower()):
            log_test("Deploy auto-validation catches invalid syntax", "PASS")
        else:
            log_test("Deploy auto-validation catches invalid syntax", "FAIL", f"code={code}, stderr={stderr[:200]}")


def test_deploy_no_validate_flag():
    """Test deploy with --no-validate flag skips validation"""
    print("\n[Test: Deploy No Validate Flag]")

    with tempfile.TemporaryDirectory() as tmpdir:
        tmppath = Path(tmpdir)

        # Create invalid TOML but with --no-validate it should proceed
        config = tmppath / "xdotter.toml"
        config.write_text('''
[links
".zshrc" = "~/.zshrc"
''')

        code, stdout, stderr = run_xd(["deploy", "--no-validate"], cwd=tmpdir)

        # Should not fail due to validation (may fail later for other reasons)
        # The key is that validation error should not be shown
        if "aborted" not in stdout.lower() and "验证" not in stdout:
            log_test("Deploy --no-validate skips validation", "PASS")
        else:
            log_test("Deploy --no-validate skips validation", "FAIL", f"stdout={stdout[:200]}")


def test_deploy_auto_validation_valid():
    """Test deploy succeeds with valid config after auto-validation"""
    print("\n[Test: Deploy Auto-Validation Valid]")

    with tempfile.TemporaryDirectory() as tmpdir:
        tmppath = Path(tmpdir)

        # Create valid config
        source_dir = tmppath / "source"
        source_dir.mkdir()
        source_file = source_dir / "test.txt"
        source_file.write_text("test")

        config = tmppath / "xdotter.toml"
        config.write_text(f'''
[links]
"source/test.txt" = "~/.cache/xdotter_autoval_{os.getpid()}.txt"
''')

        target_path = Path.home() / f".cache/xdotter_autoval_{os.getpid()}.txt"

        try:
            target_path.parent.mkdir(exist_ok=True)

            code, stdout, stderr = run_xd(["deploy"], cwd=tmpdir)

            if code == 0 and target_path.is_symlink():
                log_test("Deploy succeeds after valid auto-validation", "PASS")
            else:
                log_test("Deploy succeeds after valid auto-validation", "FAIL", f"code={code}")
        finally:
            if target_path.exists():
                target_path.unlink()


# ============================================================
# Symlink Loop Detection Tests
# ============================================================

def test_symlink_loop_detection():
    """Test symlink loop detection function"""
    print("\n[Test: Symlink Loop Detection]")

    from xd import would_create_symlink_loop

    with tempfile.TemporaryDirectory() as tmpdir:
        tmppath = Path(tmpdir)

        # Setup: dir_a -> real_c
        real_c = tmppath / "real_c"
        real_c.mkdir()
        dir_a = tmppath / "dir_a"
        os.symlink(real_c, dir_a)

        # Test 1: Creating dir_a/sub -> real_c/sub would create loop
        link_path = dir_a / "sub"
        actual = real_c / "sub"
        actual.mkdir()

        if would_create_symlink_loop(link_path, actual):
            log_test("Detects potential symlink loop", "PASS")
        else:
            log_test("Detects potential symlink loop", "FAIL", "Should detect loop")


def test_deploy_symlink_loop_warning():
    """Test deploy warns about symlink loop"""
    print("\n[Test: Deploy Symlink Loop Warning]")

    with tempfile.TemporaryDirectory() as tmpdir:
        tmppath = Path(tmpdir)

        # Setup: dir_a -> real_c
        real_c = tmppath / "real_c"
        real_c.mkdir()
        (real_c / "sub").mkdir()

        dir_a = tmppath / "dir_a"
        os.symlink(real_c, dir_a)

        # Config that would create loop: dir_a/sub -> real_c/sub
        config = tmppath / "xdotter.toml"
        config.write_text(f'''
[links]
"dir_a/sub" = "real_c/sub"
''')

        code, stdout, stderr = run_xd(["deploy", "-v"], cwd=tmpdir)

        # Should warn about loop
        if "loop" in stdout.lower() or "loop" in stderr.lower() or code != 0:
            log_test("Deploy warns about symlink loop", "PASS")
        else:
            log_test("Deploy warns about symlink loop", "FAIL", "Should warn about loop")


def test_circular_symlink_scenario():
    """Test circular symlink scenario detection function"""
    print("\n[Test: Circular Symlink Scenario]")

    from xd import detect_circular_symlink_scenario

    with tempfile.TemporaryDirectory() as tmpdir:
        tmppath = Path(tmpdir)

        # Test the detection function directly
        # Scenario: C -> A, creating A/B -> C/B

        # Create A (real directory)
        A = tmppath / "A"
        A.mkdir()

        # Create C as symlink to A
        C = tmppath / "C"
        os.symlink(A, C)

        # We want to create symlink at A/B pointing to C/B
        # A/B -> C/B, but C -> A, so A/B -> C/B -> A/B (circular!)
        link_path = A / "B"  # Where symlink will be created
        actual = C / "B"  # What symlink points to

        result = detect_circular_symlink_scenario(link_path, actual)

        if result:
            log_test("Detects circular scenario", "PASS")
        else:
            log_test("Detects circular scenario", "FAIL", "Should detect circular")

        # Test 2: Verify detection works when C is parent of actual
        # Reset: recreate C as symlink
        if C.exists():
            if C.is_dir() and not C.is_symlink():
                shutil.rmtree(C)
            else:
                C.unlink()
        os.symlink(A, C)

        # Test: A/file -> C/file, where C -> A
        link_path2 = A / "file"
        actual2 = C / "file"

        result2 = detect_circular_symlink_scenario(link_path2, actual2)

        if result2:
            log_test("Detects circular scenario (direct parent)", "PASS")
        else:
            log_test("Detects circular scenario (direct parent)", "FAIL", "Should detect circular")


def test_force_fixes_parent_symlink():
    """Test that --force automatically fixes parent directory symlink issue"""
    print("\n[Test: Force Fixes Parent Symlink]")

    with tempfile.TemporaryDirectory() as tmpdir:
        tmppath = Path(tmpdir)

        # Setup: create source file and parent symlink scenario
        # dotfiles/helix/config.toml (source)
        # .config/helix -> ../dotfiles/helix (parent symlink)
        # Want to create: .config/helix/config.toml -> dotfiles/helix/config.toml

        dotfiles = tmppath / "dotfiles" / "helix"
        dotfiles.mkdir(parents=True)
        source_file = dotfiles / "config.toml"
        source_file.write_text("source content")

        config_dir = tmppath / ".config"
        config_dir.mkdir()
        parent_symlink = config_dir / "helix"
        os.symlink("../dotfiles/helix", parent_symlink)

        # Config file
        config = tmppath / "xdotter.toml"
        config.write_text(f'''
[links]
"{dotfiles}/config.toml" = "{config_dir}/helix/config.toml"
''')

        # Run with --force
        code, stdout, stderr = run_xd(
            ["deploy", "-f", "-v"],
            cwd=tmpdir,
            env={"HOME": str(tmppath)}
        )

        # Check: parent symlink should be replaced with real directory
        if parent_symlink.is_dir() and not parent_symlink.is_symlink():
            log_test("Parent symlink replaced with real directory", "PASS")
        else:
            log_test("Parent symlink replaced with real directory", "FAIL",
                     f"Still a symlink or missing: {parent_symlink}")

        # Check: symlink created correctly
        created_link = config_dir / "helix" / "config.toml"
        if created_link.is_symlink():
            target = Path(os.readlink(created_link)).resolve()
            if target == source_file.resolve():
                log_test("Symlink created with correct target", "PASS")
            else:
                log_test("Symlink created with correct target", "FAIL",
                         f"Points to {target}, expected {source_file}")
        else:
            log_test("Symlink created with correct target", "FAIL",
                     "Symlink was not created")


def main():
    """Run all tests"""
    print("=" * 50)
    print("xdotter Test Suite")
    print("=" * 50)

    # Basic command tests
    test_help_command()
    test_version_command()
    test_new_command()

    # Config parsing test
    test_config_parsing()

    # Deploy tests
    test_deploy_basic_link()
    test_deploy_dry_run()
    test_deploy_with_tilde()
    test_multiple_links()

    # Undeploy test
    test_undeploy()

    # Flag tests
    test_quiet_mode()
    test_verbose_mode()
    test_force_flag()

    # Additional test scenarios
    test_dependencies_subdirectory()
    test_interactive_mode_confirm()
    test_interactive_mode_yes()
    test_nonexistent_source()
    test_nonexistent_config()
    test_invalid_toml_syntax()
    test_empty_config()
    test_symlink_already_exists()
    test_unicode_paths()
    test_absolute_path_in_config()
    test_undeploy_nonexistent_link()
    test_comments_in_config()
    test_whitespace_in_config()
    test_single_quotes_in_config()

    # Permission check tests
    test_permission_check_ssh_key()
    test_permission_fix_ssh_key()
    test_permission_check_correct_permission()
    test_permission_pattern_matching()
    test_permission_dry_run()

    # Validate command tests
    test_validate_command_valid_toml()
    test_validate_command_invalid_toml()
    test_validate_command_rejects_json()
    test_completion_command_bash()
    test_validate_command_nonexistent_file()
    test_validate_command_multiple_files()
    test_validate_command_default_files()

    # Completion command tests
    test_completion_command_bash()
    test_completion_command_zsh()
    test_completion_command_fish()
    test_completion_command_no_shell()
    test_completion_command_invalid_shell()

    # Auto-validation tests
    test_deploy_auto_validation_invalid()
    test_deploy_no_validate_flag()
    test_deploy_auto_validation_valid()

    # Symlink loop detection tests
    test_symlink_loop_detection()
    test_deploy_symlink_loop_warning()

    # Circular symlink scenario test
    test_circular_symlink_scenario()

    # Parent symlink auto-fix test
    test_force_fixes_parent_symlink()

    # Summary
    success = print_summary()

    return 0 if success else 1

if __name__ == "__main__":
    sys.exit(main())