dev-pulse 0.1.0

Project health dashboard for your terminal
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
//! Integration tests for devpulse CLI.
//!
//! Each test creates temporary git repos with known state, runs the devpulse
//! binary via `std::process::Command`, and verifies stdout output.

use std::fs;
use std::path::{Path, PathBuf};
use std::process::Command;

use tempfile::TempDir;

/// Get the path to the devpulse binary (built by cargo test).
fn devpulse_bin() -> PathBuf {
    // cargo test builds the binary in target/debug
    let mut path = std::env::current_exe()
        .expect("failed to get test exe path")
        .parent()
        .expect("no parent")
        .parent()
        .expect("no grandparent")
        .to_path_buf();
    path.push("devpulse");
    path
}

/// Run devpulse with given args and return (stdout, stderr, success).
fn run_devpulse(args: &[&str]) -> (String, String, bool) {
    let output = Command::new(devpulse_bin())
        .args(args)
        .env("NO_COLOR", "1")
        .output()
        .expect("failed to run devpulse");
    (
        String::from_utf8_lossy(&output.stdout).to_string(),
        String::from_utf8_lossy(&output.stderr).to_string(),
        output.status.success(),
    )
}

/// Create a git repo with an initial commit in `dir`.
fn init_repo(dir: &Path) {
    run_git(dir, &["init", "-b", "main"]);
    run_git(dir, &["config", "user.email", "test@test.com"]);
    run_git(dir, &["config", "user.name", "Test"]);
    run_git(dir, &["commit", "--allow-empty", "-m", "initial commit"]);
}

/// Create a git repo with a dirty working tree.
fn init_dirty_repo(dir: &Path) {
    init_repo(dir);
    fs::write(dir.join("dirty.txt"), "uncommitted").expect("failed to write dirty file");
}

/// Run a git command in a directory.
fn run_git(dir: &Path, args: &[&str]) {
    let output = Command::new("git")
        .args(args)
        .current_dir(dir)
        .output()
        .expect("failed to run git");
    if !output.status.success() {
        panic!(
            "git {:?} failed in {}: {}",
            args,
            dir.display(),
            String::from_utf8_lossy(&output.stderr)
        );
    }
}

/// Create a standard test environment with multiple repos.
fn setup_multi_repo(parent: &Path) {
    let clean = parent.join("alpha-clean");
    let dirty = parent.join("beta-dirty");
    fs::create_dir_all(&clean).unwrap();
    fs::create_dir_all(&dirty).unwrap();
    init_repo(&clean);
    init_dirty_repo(&dirty);
}

// ============================================================
// Tests
// ============================================================

#[test]
fn test_scan_clean_repo() {
    let tmp = TempDir::new().unwrap();
    let repo = tmp.path().join("myproject");
    fs::create_dir_all(&repo).unwrap();
    init_repo(&repo);

    let (stdout, _stderr, success) = run_devpulse(&["--no-color", tmp.path().to_str().unwrap()]);
    assert!(success, "devpulse should exit 0");
    assert!(
        stdout.contains("myproject"),
        "output should contain project name"
    );
    assert!(stdout.contains("clean"), "clean repo should show 'clean'");
    assert!(stdout.contains("main"), "should show branch name");
}

#[test]
fn test_scan_dirty_repo() {
    let tmp = TempDir::new().unwrap();
    let repo = tmp.path().join("dirtyproject");
    fs::create_dir_all(&repo).unwrap();
    init_dirty_repo(&repo);

    let (stdout, _stderr, success) = run_devpulse(&["--no-color", tmp.path().to_str().unwrap()]);
    assert!(success);
    assert!(stdout.contains("dirtyproject"));
    assert!(stdout.contains("dirty"), "dirty repo should show 'dirty'");
    assert!(
        stdout.contains('1'),
        "should show 1 changed file somewhere in output"
    );
}

#[test]
fn test_json_output() {
    let tmp = TempDir::new().unwrap();
    let repo = tmp.path().join("jsontest");
    fs::create_dir_all(&repo).unwrap();
    init_repo(&repo);

    let (stdout, _stderr, success) = run_devpulse(&["--json", tmp.path().to_str().unwrap()]);
    assert!(success);

    let parsed: serde_json::Value = serde_json::from_str(
        stdout
            .lines()
            .filter(|l| !l.starts_with("Scanning"))
            .collect::<Vec<_>>()
            .join("\n")
            .trim(),
    )
    .expect("JSON output should be valid JSON");

    let projects = parsed["projects"]
        .as_array()
        .expect("should have projects array");
    assert_eq!(projects.len(), 1);
    assert_eq!(projects[0]["name"], "jsontest");
    assert_eq!(projects[0]["is_clean"], true);
    assert_eq!(projects[0]["branch"], "main");

    let summary = &parsed["summary"];
    assert_eq!(summary["total"], 1);
    assert_eq!(summary["dirty"], 0);
}

#[test]
fn test_csv_output() {
    let tmp = TempDir::new().unwrap();
    let repo = tmp.path().join("csvtest");
    fs::create_dir_all(&repo).unwrap();
    init_repo(&repo);

    let (stdout, _stderr, success) =
        run_devpulse(&["--format", "csv", tmp.path().to_str().unwrap()]);
    assert!(success);

    let lines: Vec<&str> = stdout
        .lines()
        .filter(|l| !l.starts_with("Scanning") && !l.is_empty())
        .collect();
    assert!(lines.len() >= 2, "CSV should have header + at least 1 row");
    assert!(
        lines[0].contains("Project") || lines[0].contains("project") || lines[0].contains("name"),
        "first line should be CSV header"
    );
    assert!(
        lines[1].contains("csvtest"),
        "data row should contain project name"
    );
}

#[test]
fn test_markdown_output() {
    let tmp = TempDir::new().unwrap();
    let repo = tmp.path().join("mdtest");
    fs::create_dir_all(&repo).unwrap();
    init_repo(&repo);

    let (stdout, _stderr, success) =
        run_devpulse(&["--format", "markdown", tmp.path().to_str().unwrap()]);
    assert!(success);

    let content: String = stdout
        .lines()
        .filter(|l| !l.starts_with("Scanning"))
        .collect::<Vec<_>>()
        .join("\n");
    assert!(
        content.contains('|'),
        "markdown output should contain pipe characters for table"
    );
    assert!(content.contains("mdtest"), "should contain project name");
}

#[test]
fn test_sort_by_name() {
    let tmp = TempDir::new().unwrap();
    setup_multi_repo(tmp.path());

    let (stdout, _stderr, success) =
        run_devpulse(&["--sort", "name", "--no-color", tmp.path().to_str().unwrap()]);
    assert!(success);

    let alpha_pos = stdout.find("alpha-clean").expect("should find alpha-clean");
    let beta_pos = stdout.find("beta-dirty").expect("should find beta-dirty");
    assert!(
        alpha_pos < beta_pos,
        "alpha should appear before beta when sorted by name"
    );
}

#[test]
fn test_sort_by_status() {
    let tmp = TempDir::new().unwrap();
    setup_multi_repo(tmp.path());

    let (stdout, _stderr, success) = run_devpulse(&[
        "--sort",
        "status",
        "--no-color",
        tmp.path().to_str().unwrap(),
    ]);
    assert!(success);

    let dirty_pos = stdout.find("beta-dirty").expect("should find beta-dirty");
    let clean_pos = stdout.find("alpha-clean").expect("should find alpha-clean");
    assert!(
        dirty_pos < clean_pos,
        "dirty projects should appear before clean when sorted by status"
    );
}

#[test]
fn test_filter_dirty() {
    let tmp = TempDir::new().unwrap();
    setup_multi_repo(tmp.path());

    let (stdout, _stderr, success) = run_devpulse(&[
        "--filter",
        "dirty",
        "--no-color",
        tmp.path().to_str().unwrap(),
    ]);
    assert!(success);
    assert!(stdout.contains("beta-dirty"), "should show dirty project");
    assert!(
        !stdout.contains("alpha-clean"),
        "should not show clean project when filtering for dirty"
    );
}

#[test]
fn test_filter_clean() {
    let tmp = TempDir::new().unwrap();
    setup_multi_repo(tmp.path());

    let (stdout, _stderr, success) = run_devpulse(&[
        "--filter",
        "clean",
        "--no-color",
        tmp.path().to_str().unwrap(),
    ]);
    assert!(success);
    assert!(stdout.contains("alpha-clean"), "should show clean project");
    assert!(
        !stdout.contains("beta-dirty"),
        "should not show dirty project when filtering for clean"
    );
}

#[test]
fn test_filter_by_name() {
    let tmp = TempDir::new().unwrap();
    setup_multi_repo(tmp.path());

    let (stdout, _stderr, success) = run_devpulse(&[
        "--filter",
        "name:alpha",
        "--no-color",
        tmp.path().to_str().unwrap(),
    ]);
    assert!(success);
    assert!(
        stdout.contains("alpha-clean"),
        "should show matching project"
    );
    assert!(
        !stdout.contains("beta-dirty"),
        "should not show non-matching project"
    );
}

#[test]
fn test_nonexistent_directory() {
    let (stdout, _stderr, success) = run_devpulse(&["/tmp/devpulse_nonexistent_dir_xyz"]);
    // Should either fail gracefully or show "no projects found"
    // The important thing is it doesn't panic
    let combined = format!("{stdout}{_stderr}");
    assert!(
        !success || combined.contains("No projects found") || combined.contains("error"),
        "should handle nonexistent directory gracefully"
    );
}

#[test]
fn test_empty_directory() {
    let tmp = TempDir::new().unwrap();
    // No git repos in this directory

    let (stdout, _stderr, success) = run_devpulse(&["--no-color", tmp.path().to_str().unwrap()]);
    assert!(success, "should exit 0 for empty dir");
    assert!(
        stdout.contains("No projects found"),
        "should indicate no projects found, got: {stdout}"
    );
}

#[test]
fn test_output_to_file() {
    let tmp = TempDir::new().unwrap();
    let repo = tmp.path().join("fileout");
    fs::create_dir_all(&repo).unwrap();
    init_repo(&repo);

    let output_file = tmp.path().join("output.json");
    let (_, _stderr, success) = run_devpulse(&[
        "--json",
        "--output",
        output_file.to_str().unwrap(),
        tmp.path().to_str().unwrap(),
    ]);
    assert!(success, "should succeed writing to file");
    assert!(output_file.exists(), "output file should be created");

    let content = fs::read_to_string(&output_file).expect("should read output file");
    let parsed: serde_json::Value =
        serde_json::from_str(&content).expect("output file should contain valid JSON");
    assert!(parsed["projects"].is_array());
}

#[test]
fn test_group_flag() {
    let tmp = TempDir::new().unwrap();

    // Create repos in subdirectories to test grouping
    let subdir1 = tmp.path().join("group1");
    let subdir2 = tmp.path().join("group2");
    fs::create_dir_all(&subdir1).unwrap();
    fs::create_dir_all(&subdir2).unwrap();

    let repo1 = subdir1.join("proj-a");
    let repo2 = subdir2.join("proj-b");
    fs::create_dir_all(&repo1).unwrap();
    fs::create_dir_all(&repo2).unwrap();
    init_repo(&repo1);
    init_repo(&repo2);

    let (stdout, _stderr, success) = run_devpulse(&[
        "--group",
        "--no-color",
        "--depth",
        "2",
        tmp.path().to_str().unwrap(),
    ]);
    assert!(success, "grouped output should succeed");
    assert!(
        stdout.contains("proj-a") && stdout.contains("proj-b"),
        "should show both projects"
    );
}

#[test]
fn test_no_color_flag() {
    let tmp = TempDir::new().unwrap();
    let repo = tmp.path().join("colortest");
    fs::create_dir_all(&repo).unwrap();
    init_repo(&repo);

    let (stdout, _stderr, success) = run_devpulse(&["--no-color", tmp.path().to_str().unwrap()]);
    assert!(success);
    // ANSI escape codes start with \x1b[
    assert!(
        !stdout.contains("\x1b["),
        "no-color output should not contain ANSI escape codes"
    );
}

#[test]
fn test_no_color_env_var() {
    let tmp = TempDir::new().unwrap();
    let repo = tmp.path().join("envcolortest");
    fs::create_dir_all(&repo).unwrap();
    init_repo(&repo);

    let output = Command::new(devpulse_bin())
        .args([tmp.path().to_str().unwrap()])
        .env("NO_COLOR", "1")
        .output()
        .expect("failed to run devpulse");

    let stdout = String::from_utf8_lossy(&output.stdout);
    assert!(output.status.success());
    assert!(
        !stdout.contains("\x1b["),
        "NO_COLOR env should suppress ANSI codes"
    );
}

#[test]
fn test_version_flag() {
    let (stdout, _stderr, success) = run_devpulse(&["--version"]);
    assert!(success);
    assert!(
        stdout.contains("devpulse") && stdout.contains("0.1.0"),
        "version output should contain name and version, got: {stdout}"
    );
}

#[test]
fn test_help_flag() {
    let (stdout, _stderr, success) = run_devpulse(&["--help"]);
    assert!(success);
    assert!(stdout.contains("Usage:"), "help should contain usage info");
    assert!(stdout.contains("--sort"), "help should list --sort flag");
    assert!(stdout.contains("--json"), "help should list --json flag");
}

#[test]
fn test_invalid_filter() {
    let tmp = TempDir::new().unwrap();
    let (_, stderr, success) =
        run_devpulse(&["--filter", "bogus_filter", tmp.path().to_str().unwrap()]);
    assert!(!success, "invalid filter should cause non-zero exit");
    assert!(
        stderr.contains("Unknown filter") || stderr.contains("error") || stderr.contains("bogus"),
        "should report invalid filter in stderr"
    );
}

#[test]
fn test_since_flag() {
    let tmp = TempDir::new().unwrap();
    let repo = tmp.path().join("sincetest");
    fs::create_dir_all(&repo).unwrap();
    init_repo(&repo);

    // Recent commit should appear with --since 1d
    let (stdout, _stderr, success) =
        run_devpulse(&["--since", "1d", "--no-color", tmp.path().to_str().unwrap()]);
    assert!(success);
    assert!(
        stdout.contains("sincetest"),
        "recent project should appear with --since 1d"
    );
}

#[test]
fn test_since_flag_excludes_old() {
    let tmp = TempDir::new().unwrap();
    let repo = tmp.path().join("oldproject");
    fs::create_dir_all(&repo).unwrap();
    init_repo(&repo);

    // With an extremely short since window, we still find it because
    // commit was just made. But --since 0d should filter everything
    // (0 days = now, nothing matches). This tests the filter works at all.
    // Using --json to check programmatically.
    let (stdout, _stderr, success) =
        run_devpulse(&["--json", "--since", "1d", tmp.path().to_str().unwrap()]);
    assert!(success);

    let json_str: String = stdout
        .lines()
        .filter(|l| !l.starts_with("Scanning"))
        .collect::<Vec<_>>()
        .join("\n");
    let parsed: serde_json::Value =
        serde_json::from_str(json_str.trim()).expect("should be valid JSON");
    let projects = parsed["projects"].as_array().unwrap();
    assert_eq!(
        projects.len(),
        1,
        "project with recent commit should appear with --since 1d"
    );
}

#[test]
fn test_multiple_filters() {
    let tmp = TempDir::new().unwrap();
    setup_multi_repo(tmp.path());

    // Filter for dirty AND name contains beta — should match beta-dirty
    let (stdout, _stderr, success) = run_devpulse(&[
        "--filter",
        "dirty",
        "--filter",
        "name:beta",
        "--no-color",
        tmp.path().to_str().unwrap(),
    ]);
    assert!(success);
    assert!(
        stdout.contains("beta-dirty"),
        "combined filters should match beta-dirty"
    );
    assert!(
        !stdout.contains("alpha-clean"),
        "combined filters should exclude alpha-clean"
    );
}

#[test]
fn test_depth_zero() {
    let tmp = TempDir::new().unwrap();
    // Initialize the root as a git repo itself
    init_repo(tmp.path());

    let (stdout, _stderr, success) =
        run_devpulse(&["--depth", "0", "--no-color", tmp.path().to_str().unwrap()]);
    assert!(success);
    // With depth 0, it should check the target directory itself
    let dir_name = tmp.path().file_name().unwrap().to_str().unwrap();
    assert!(
        stdout.contains(dir_name) || stdout.contains("clean"),
        "depth 0 should scan the directory itself"
    );
}

#[test]
fn test_json_summary_counts() {
    let tmp = TempDir::new().unwrap();
    setup_multi_repo(tmp.path());

    let (stdout, _stderr, success) = run_devpulse(&["--json", tmp.path().to_str().unwrap()]);
    assert!(success);

    let json_str: String = stdout
        .lines()
        .filter(|l| !l.starts_with("Scanning"))
        .collect::<Vec<_>>()
        .join("\n");
    let parsed: serde_json::Value =
        serde_json::from_str(json_str.trim()).expect("should be valid JSON");

    let summary = &parsed["summary"];
    assert_eq!(summary["total"], 2, "should have 2 total projects");
    assert_eq!(summary["dirty"], 1, "should have 1 dirty project");
}

#[test]
fn test_csv_output_to_file() {
    let tmp = TempDir::new().unwrap();
    let repo = tmp.path().join("csvfile");
    fs::create_dir_all(&repo).unwrap();
    init_repo(&repo);

    let output_file = tmp.path().join("output.csv");
    let (_, _stderr, success) = run_devpulse(&[
        "--format",
        "csv",
        "--output",
        output_file.to_str().unwrap(),
        tmp.path().to_str().unwrap(),
    ]);
    assert!(success);
    assert!(output_file.exists(), "CSV output file should be created");

    let content = fs::read_to_string(&output_file).unwrap();
    assert!(
        content.contains("csvfile"),
        "CSV file should contain project name"
    );
}

#[test]
fn test_markdown_output_to_file() {
    let tmp = TempDir::new().unwrap();
    let repo = tmp.path().join("mdfile");
    fs::create_dir_all(&repo).unwrap();
    init_repo(&repo);

    let output_file = tmp.path().join("output.md");
    let (_, _stderr, success) = run_devpulse(&[
        "--format",
        "md",
        "--output",
        output_file.to_str().unwrap(),
        tmp.path().to_str().unwrap(),
    ]);
    assert!(success);
    assert!(
        output_file.exists(),
        "markdown output file should be created"
    );

    let content = fs::read_to_string(&output_file).unwrap();
    assert!(
        content.contains('|'),
        "markdown file should contain table separators"
    );
    assert!(content.contains("mdfile"));
}

#[test]
fn test_stash_count_in_json() {
    let tmp = TempDir::new().unwrap();
    let repo = tmp.path().join("stashtest");
    fs::create_dir_all(&repo).unwrap();
    init_repo(&repo);

    // Create a stash
    fs::write(repo.join("stash.txt"), "stashme").unwrap();
    run_git(&repo, &["add", "stash.txt"]);
    run_git(&repo, &["stash", "push", "-m", "test stash"]);

    let (stdout, _stderr, success) = run_devpulse(&["--json", tmp.path().to_str().unwrap()]);
    assert!(success);

    let json_str: String = stdout
        .lines()
        .filter(|l| !l.starts_with("Scanning"))
        .collect::<Vec<_>>()
        .join("\n");
    let parsed: serde_json::Value =
        serde_json::from_str(json_str.trim()).expect("should be valid JSON");
    let stash_count = parsed["projects"][0]["stash_count"]
        .as_u64()
        .expect("stash_count should be a number");
    assert_eq!(stash_count, 1, "should detect 1 stash entry");
}

#[test]
fn test_last_commit_message_in_json() {
    let tmp = TempDir::new().unwrap();
    let repo = tmp.path().join("msgtest");
    fs::create_dir_all(&repo).unwrap();
    init_repo(&repo);

    // The initial commit message is "initial commit"
    let (stdout, _stderr, success) = run_devpulse(&["--json", tmp.path().to_str().unwrap()]);
    assert!(success);

    let json_str: String = stdout
        .lines()
        .filter(|l| !l.starts_with("Scanning"))
        .collect::<Vec<_>>()
        .join("\n");
    let parsed: serde_json::Value =
        serde_json::from_str(json_str.trim()).expect("should be valid JSON");
    let msg = parsed["projects"][0]["last_commit_message"]
        .as_str()
        .expect("should have last_commit_message");
    assert_eq!(msg, "initial commit");
}

#[test]
fn test_depth_two_nested_repos() {
    let tmp = TempDir::new().unwrap();
    // Create nested structure: parent/child/repo
    let nested = tmp.path().join("level1").join("level2-repo");
    fs::create_dir_all(&nested).unwrap();
    init_repo(&nested);

    // depth=1 should NOT find it
    let (stdout, _stderr, success) =
        run_devpulse(&["--depth", "1", "--no-color", tmp.path().to_str().unwrap()]);
    assert!(success);
    assert!(
        !stdout.contains("level2-repo"),
        "depth 1 should not find nested repo"
    );

    // depth=2 SHOULD find it
    let (stdout2, _stderr2, success2) =
        run_devpulse(&["--depth", "2", "--no-color", tmp.path().to_str().unwrap()]);
    assert!(success2);
    assert!(
        stdout2.contains("level2-repo"),
        "depth 2 should find nested repo"
    );
}

#[test]
fn test_filter_stale() {
    let tmp = TempDir::new().unwrap();
    let repo = tmp.path().join("stalerepo");
    fs::create_dir_all(&repo).unwrap();
    run_git(&repo, &["init", "-b", "main"]);
    run_git(&repo, &["config", "user.email", "test@test.com"]);
    run_git(&repo, &["config", "user.name", "Test"]);
    // Create a commit dated 60 days ago using ISO format
    let old_date = chrono::Utc::now() - chrono::Duration::days(60);
    let date_str = old_date.format("%Y-%m-%dT%H:%M:%S").to_string();
    let output = Command::new("git")
        .args([
            "commit",
            "--allow-empty",
            "-m",
            "old commit",
            "--date",
            &date_str,
        ])
        .current_dir(&repo)
        .env("GIT_COMMITTER_DATE", &date_str)
        .output()
        .expect("failed to create old commit");
    assert!(
        output.status.success(),
        "old commit should succeed: {}",
        String::from_utf8_lossy(&output.stderr)
    );

    let (stdout, _stderr, success) = run_devpulse(&[
        "--filter",
        "stale",
        "--no-color",
        tmp.path().to_str().unwrap(),
    ]);
    assert!(success);
    assert!(
        stdout.contains("stalerepo"),
        "project with 60-day old commit should be stale"
    );
}

#[test]
fn test_filter_unpushed() {
    let tmp = TempDir::new().unwrap();
    let repo = tmp.path().join("unpushed-repo");
    fs::create_dir_all(&repo).unwrap();
    init_repo(&repo);
    // No remote set up, so commits are "unpushed" — behavior depends on implementation
    // At minimum, the filter should not crash
    let (_stdout, _stderr, success) = run_devpulse(&[
        "--filter",
        "unpushed",
        "--no-color",
        tmp.path().to_str().unwrap(),
    ]);
    assert!(success, "unpushed filter should not crash");
}

#[test]
fn test_include_empty_with_since() {
    let tmp = TempDir::new().unwrap();
    let repo = tmp.path().join("empty-history");
    fs::create_dir_all(&repo).unwrap();
    // Init repo but with no commits — just git init
    run_git(&repo, &["init", "-b", "main"]);

    // Without --include-empty, empty repos should be excluded
    let (stdout1, _stderr1, success1) =
        run_devpulse(&["--since", "7d", "--no-color", tmp.path().to_str().unwrap()]);
    assert!(success1);
    assert!(
        !stdout1.contains("empty-history"),
        "empty repo should be excluded without --include-empty"
    );

    // With --include-empty, it should show up
    let (stdout2, _stderr2, success2) = run_devpulse(&[
        "--since",
        "7d",
        "--include-empty",
        "--no-color",
        tmp.path().to_str().unwrap(),
    ]);
    assert!(success2);
    assert!(
        stdout2.contains("empty-history"),
        "empty repo should appear with --include-empty"
    );
}

#[test]
fn test_config_file() {
    let tmp = TempDir::new().unwrap();
    let repo = tmp.path().join("configtest");
    fs::create_dir_all(&repo).unwrap();
    init_repo(&repo);

    // Write a .devpulse.toml that sets color = false and sort = "name"
    let config_content = r#"
sort = "name"
color = false
"#;
    fs::write(tmp.path().join(".devpulse.toml"), config_content).unwrap();

    // Run without --no-color flag — config should disable color
    let output = Command::new(devpulse_bin())
        .args([tmp.path().to_str().unwrap()])
        .env_remove("NO_COLOR")
        .output()
        .expect("failed to run devpulse");

    let stdout = String::from_utf8_lossy(&output.stdout);
    assert!(output.status.success());
    assert!(
        !stdout.contains("\x1b["),
        "config color=false should suppress ANSI codes"
    );
}

#[test]
fn test_format_table_explicit() {
    let tmp = TempDir::new().unwrap();
    let repo = tmp.path().join("tabletest");
    fs::create_dir_all(&repo).unwrap();
    init_repo(&repo);

    let (stdout, _stderr, success) = run_devpulse(&[
        "--format",
        "table",
        "--no-color",
        tmp.path().to_str().unwrap(),
    ]);
    assert!(success);
    assert!(
        stdout.contains("tabletest"),
        "table format should show project name"
    );
    // Table output should NOT be JSON or CSV
    assert!(
        serde_json::from_str::<serde_json::Value>(&stdout).is_err(),
        "table output should not be valid JSON"
    );
}

#[test]
fn test_group_json_output() {
    let tmp = TempDir::new().unwrap();
    let grp = tmp.path().join("mygroup");
    let repo = grp.join("grouped-proj");
    fs::create_dir_all(&repo).unwrap();
    init_repo(&repo);

    let (stdout, _stderr, success) = run_devpulse(&[
        "--group",
        "--json",
        "--depth",
        "2",
        tmp.path().to_str().unwrap(),
    ]);
    assert!(success);

    let json_str: String = stdout
        .lines()
        .filter(|l| !l.starts_with("Scanning"))
        .collect::<Vec<_>>()
        .join("\n");
    let parsed: serde_json::Value =
        serde_json::from_str(json_str.trim()).expect("grouped JSON should be valid");
    // With --group, JSON uses "groups" key instead of "projects"
    assert!(
        parsed["groups"].is_object(),
        "grouped JSON should have groups object, got: {json_str}"
    );
    assert!(
        parsed["summary"].is_object(),
        "grouped JSON should have summary"
    );
}

#[test]
fn test_staged_changes_detected() {
    let tmp = TempDir::new().unwrap();
    let repo = tmp.path().join("stagedtest");
    fs::create_dir_all(&repo).unwrap();
    init_repo(&repo);

    // Stage a file without committing
    fs::write(repo.join("staged.txt"), "staged content").unwrap();
    run_git(&repo, &["add", "staged.txt"]);

    let (stdout, _stderr, success) = run_devpulse(&["--json", tmp.path().to_str().unwrap()]);
    assert!(success);

    let json_str: String = stdout
        .lines()
        .filter(|l| !l.starts_with("Scanning"))
        .collect::<Vec<_>>()
        .join("\n");
    let parsed: serde_json::Value =
        serde_json::from_str(json_str.trim()).expect("should be valid JSON");
    assert_eq!(
        parsed["projects"][0]["is_clean"], false,
        "staged but uncommitted changes should be dirty"
    );
}

#[test]
fn test_multiple_repos_sorted_by_activity() {
    let tmp = TempDir::new().unwrap();

    // Create two repos with different commit times
    let old_repo = tmp.path().join("old-repo");
    let new_repo = tmp.path().join("new-repo");
    fs::create_dir_all(&old_repo).unwrap();
    fs::create_dir_all(&new_repo).unwrap();

    // Old repo: commit dated 10 days ago
    run_git(&old_repo, &["init", "-b", "main"]);
    run_git(&old_repo, &["config", "user.email", "test@test.com"]);
    run_git(&old_repo, &["config", "user.name", "Test"]);
    let old_date = chrono::Utc::now() - chrono::Duration::days(10);
    let date_str = old_date.format("%Y-%m-%dT%H:%M:%S").to_string();
    let output = Command::new("git")
        .args(["commit", "--allow-empty", "-m", "old", "--date", &date_str])
        .current_dir(&old_repo)
        .env("GIT_COMMITTER_DATE", &date_str)
        .output()
        .unwrap();
    assert!(output.status.success(), "old commit should succeed");

    // New repo: commit now
    init_repo(&new_repo);

    let (stdout, _stderr, success) = run_devpulse(&[
        "--sort",
        "activity",
        "--no-color",
        tmp.path().to_str().unwrap(),
    ]);
    assert!(success);

    // Activity sort = most stale first, so old-repo should appear before new-repo
    let old_pos = stdout.find("old-repo").expect("should find old-repo");
    let new_pos = stdout.find("new-repo").expect("should find new-repo");
    assert!(
        old_pos < new_pos,
        "activity sort should put stale (old) repos first"
    );
}

#[test]
fn test_json_format_flag_equivalent_to_json_flag() {
    let tmp = TempDir::new().unwrap();
    let repo = tmp.path().join("fmtjson");
    fs::create_dir_all(&repo).unwrap();
    init_repo(&repo);

    let (stdout1, _, _) = run_devpulse(&["--json", tmp.path().to_str().unwrap()]);
    let (stdout2, _, _) = run_devpulse(&["--format", "json", tmp.path().to_str().unwrap()]);

    // Both should produce valid JSON with same structure
    let filter_scanning = |s: &str| -> String {
        s.lines()
            .filter(|l| !l.starts_with("Scanning"))
            .collect::<Vec<_>>()
            .join("\n")
    };
    let j1: serde_json::Value = serde_json::from_str(filter_scanning(&stdout1).trim()).unwrap();
    let j2: serde_json::Value = serde_json::from_str(filter_scanning(&stdout2).trim()).unwrap();
    assert_eq!(
        j1["projects"].as_array().unwrap().len(),
        j2["projects"].as_array().unwrap().len(),
        "--json and --format json should produce same number of projects"
    );
}

// ── Additional edge-case tests (#25) ──

#[test]
fn test_invalid_since_value() {
    let tmp = TempDir::new().unwrap();
    let repo = tmp.path().join("sincetest");
    fs::create_dir_all(&repo).unwrap();
    init_repo(&repo);

    let (_, stderr, success) = run_devpulse(&["--since", "abc", tmp.path().to_str().unwrap()]);
    assert!(!success, "invalid --since should fail");
    assert!(
        stderr.contains("Invalid") || stderr.contains("invalid") || stderr.contains("error"),
        "should show error for invalid --since: {stderr}"
    );
}

#[test]
fn test_invalid_since_zero_days() {
    let tmp = TempDir::new().unwrap();
    let repo = tmp.path().join("sincetest0");
    fs::create_dir_all(&repo).unwrap();
    init_repo(&repo);

    // 0d should either work (showing nothing recent) or fail gracefully
    let (_, _, _) = run_devpulse(&["--since", "0d", tmp.path().to_str().unwrap()]);
    // Just ensure it doesn't panic/crash
}

#[test]
fn test_help_output_contains_key_info() {
    let (stdout, _, success) = run_devpulse(&["--help"]);
    assert!(success, "help should succeed");
    assert!(stdout.contains("devpulse"), "help should mention devpulse");
    assert!(
        stdout.contains("--json"),
        "help should document --json flag"
    );
    assert!(
        stdout.contains("--filter"),
        "help should document --filter flag"
    );
    assert!(
        stdout.contains("--since"),
        "help should document --since flag"
    );
    assert!(
        stdout.contains("--sort"),
        "help should document --sort flag"
    );
    assert!(
        stdout.contains("--watch"),
        "help should document --watch flag"
    );
    assert!(stdout.contains("EXAMPLES"), "help should include examples");
}

#[test]
fn test_default_depth_scans_children() {
    // Without --depth, default is 1: scan immediate children
    let tmp = TempDir::new().unwrap();
    setup_multi_repo(tmp.path());

    let (stdout, _, success) = run_devpulse(&[tmp.path().to_str().unwrap()]);
    assert!(success, "default depth scan should succeed");
    assert!(stdout.contains("alpha-clean"), "should find child repo");
    assert!(stdout.contains("beta-dirty"), "should find child repo");
}

#[test]
fn test_repo_with_no_commits() {
    let tmp = TempDir::new().unwrap();
    let repo = tmp.path().join("no-commits");
    fs::create_dir_all(&repo).unwrap();
    // Init without committing
    run_git(&repo, &["init", "-b", "main"]);
    run_git(&repo, &["config", "user.email", "test@test.com"]);
    run_git(&repo, &["config", "user.name", "Test"]);

    let (stdout, stderr, success) = run_devpulse(&[tmp.path().to_str().unwrap()]);
    // Should handle gracefully — either show it or skip with warning
    // Main thing: shouldn't crash
    assert!(
        success || stderr.contains("Warning") || stderr.contains("skipping"),
        "no-commit repo should be handled gracefully, got: stdout={stdout} stderr={stderr}"
    );
}

#[test]
fn test_csv_format_flag() {
    let tmp = TempDir::new().unwrap();
    let repo = tmp.path().join("csvfmt");
    fs::create_dir_all(&repo).unwrap();
    init_repo(&repo);

    let (stdout, _, success) = run_devpulse(&["--format", "csv", tmp.path().to_str().unwrap()]);
    assert!(success, "csv format should succeed");
    let lines: Vec<&str> = stdout
        .lines()
        .filter(|l| !l.starts_with("Scanning") && !l.is_empty())
        .collect();
    assert!(
        lines.len() >= 2,
        "csv should have header + data rows, got: {lines:?}"
    );
    assert!(
        lines[0].contains(','),
        "csv header should contain commas: {:?}",
        lines[0]
    );
}

#[test]
fn test_markdown_format_flag() {
    let tmp = TempDir::new().unwrap();
    let repo = tmp.path().join("mdfmt");
    fs::create_dir_all(&repo).unwrap();
    init_repo(&repo);

    let (stdout, _, success) =
        run_devpulse(&["--format", "markdown", tmp.path().to_str().unwrap()]);
    assert!(success, "markdown format should succeed");
    let content: String = stdout
        .lines()
        .filter(|l| !l.starts_with("Scanning"))
        .collect::<Vec<_>>()
        .join("\n");
    assert!(
        content.contains('|'),
        "markdown should contain pipe separators: {content}"
    );
}

#[test]
fn test_group_with_csv_output() {
    let tmp = TempDir::new().unwrap();
    setup_multi_repo(tmp.path());

    let (stdout, _, success) =
        run_devpulse(&["--group", "--format", "csv", tmp.path().to_str().unwrap()]);
    assert!(success, "grouped csv should succeed");
    let content: String = stdout
        .lines()
        .filter(|l| !l.starts_with("Scanning"))
        .collect::<Vec<_>>()
        .join("\n");
    assert!(!content.is_empty(), "grouped csv should produce output");
}

#[test]
fn test_group_with_markdown_output() {
    let tmp = TempDir::new().unwrap();
    setup_multi_repo(tmp.path());

    let (stdout, _, success) = run_devpulse(&[
        "--group",
        "--format",
        "markdown",
        tmp.path().to_str().unwrap(),
    ]);
    assert!(success, "grouped markdown should succeed");
    let content: String = stdout
        .lines()
        .filter(|l| !l.starts_with("Scanning"))
        .collect::<Vec<_>>()
        .join("\n");
    assert!(
        content.contains('|'),
        "grouped markdown should have table syntax"
    );
}

#[test]
fn test_output_file_creates_parent_dirs() {
    let tmp = TempDir::new().unwrap();
    let repo = tmp.path().join("outrepo");
    fs::create_dir_all(&repo).unwrap();
    init_repo(&repo);

    let output_path = tmp.path().join("subdir").join("nested").join("output.json");
    let (_, _, success) = run_devpulse(&[
        "--json",
        "-o",
        output_path.to_str().unwrap(),
        tmp.path().to_str().unwrap(),
    ]);
    assert!(success, "output to nested path should succeed");
    assert!(output_path.exists(), "output file should be created");
    let content = fs::read_to_string(&output_path).unwrap();
    assert!(
        content.contains("projects"),
        "output should contain JSON data"
    );
}

#[test]
fn test_filter_combined_dirty_and_name() {
    let tmp = TempDir::new().unwrap();
    setup_multi_repo(tmp.path());

    let (stdout, _, success) = run_devpulse(&[
        "--filter",
        "dirty",
        "--filter",
        "name:beta",
        "--json",
        tmp.path().to_str().unwrap(),
    ]);
    assert!(success, "combined filter should succeed");
    let content: String = stdout
        .lines()
        .filter(|l| !l.starts_with("Scanning"))
        .collect::<Vec<_>>()
        .join("\n");
    let json: serde_json::Value = serde_json::from_str(content.trim()).unwrap();
    let projects = json["projects"].as_array().unwrap();
    assert_eq!(projects.len(), 1, "should match exactly beta-dirty");
    assert!(projects[0]["name"].as_str().unwrap().contains("beta"));
}

#[test]
fn test_scan_single_repo_depth_zero() {
    // --depth 0 checks the target directory itself as a repo
    let tmp = TempDir::new().unwrap();
    init_repo(tmp.path());

    let (stdout, _, success) = run_devpulse(&["--depth", "0", tmp.path().to_str().unwrap()]);
    assert!(success, "depth 0 on a repo should succeed");
    // Should show the repo itself
    let lower = stdout.to_lowercase();
    assert!(
        lower.contains("clean")
            || lower.contains("dirty")
            || stdout.contains("")
            || stdout.contains(""),
        "should display repo status: {stdout}"
    );
}

#[test]
#[cfg(unix)]
fn test_permission_denied_directory() {
    use std::os::unix::fs::PermissionsExt;

    let tmp = TempDir::new().unwrap();
    let restricted = tmp.path().join("no-access");
    fs::create_dir_all(&restricted).unwrap();
    init_repo(&restricted);

    // Remove read + execute permissions
    fs::set_permissions(&restricted, fs::Permissions::from_mode(0o000)).unwrap();

    let (_, stderr, _) = run_devpulse(&[tmp.path().to_str().unwrap()]);
    // Should handle gracefully — either skip or report error, not panic
    // Restore permissions so TempDir cleanup works
    fs::set_permissions(&restricted, fs::Permissions::from_mode(0o755)).unwrap();

    // The key assertion: it didn't panic. stderr may or may not contain an error message.
    // We just verify it completed without crashing.
    let _ = stderr; // silence unused warning
}

#[test]
fn test_symlink_to_repo() {
    let tmp = TempDir::new().unwrap();
    let real_repo = tmp.path().join("real-repo");
    fs::create_dir_all(&real_repo).unwrap();
    init_repo(&real_repo);

    // Create a symlink pointing to the real repo
    #[cfg(unix)]
    std::os::unix::fs::symlink(&real_repo, tmp.path().join("linked-repo")).unwrap();
    #[cfg(windows)]
    std::os::windows::fs::symlink_dir(&real_repo, tmp.path().join("linked-repo")).unwrap();

    let (stdout, _, success) = run_devpulse(&["--json", tmp.path().to_str().unwrap()]);
    assert!(success, "scanning with symlinks should succeed");
    // Should find at least the real repo
    let content: String = stdout
        .lines()
        .filter(|l| !l.starts_with("Scanning"))
        .collect::<Vec<_>>()
        .join("\n");
    let json: serde_json::Value = serde_json::from_str(content.trim()).unwrap();
    let projects = json["projects"].as_array().unwrap();
    assert!(!projects.is_empty(), "should find at least one repo");
}

#[test]
fn test_long_project_name() {
    let tmp = TempDir::new().unwrap();
    let long_name = "a".repeat(200);
    let repo = tmp.path().join(&long_name);
    fs::create_dir_all(&repo).unwrap();
    init_repo(&repo);

    let (stdout, _, success) = run_devpulse(&[tmp.path().to_str().unwrap()]);
    assert!(success, "long project name should not crash");
    assert!(!stdout.is_empty(), "should produce output");
}

#[test]
fn test_repo_with_only_staged_no_commits() {
    let tmp = TempDir::new().unwrap();
    let repo = tmp.path().join("staged-only");
    fs::create_dir_all(&repo).unwrap();

    // Init repo and add a file to staging without committing beyond initial
    init_repo(&repo);
    fs::write(repo.join("staged.txt"), "staged content").unwrap();
    run_git(&repo, &["add", "staged.txt"]);

    let (stdout, _, success) = run_devpulse(&["--json", tmp.path().to_str().unwrap()]);
    assert!(success, "repo with staged changes should succeed");
    let content: String = stdout
        .lines()
        .filter(|l| !l.starts_with("Scanning"))
        .collect::<Vec<_>>()
        .join("\n");
    let json: serde_json::Value = serde_json::from_str(content.trim()).unwrap();
    let projects = json["projects"].as_array().unwrap();
    assert_eq!(projects.len(), 1);
    // Should show as not clean since there are staged changes
    assert!(
        !projects[0]["is_clean"].as_bool().unwrap(),
        "staged changes should make repo dirty"
    );
}

#[test]
fn test_sort_by_name_deterministic() {
    let tmp = TempDir::new().unwrap();
    for name in &["zebra", "alpha", "mango"] {
        let repo = tmp.path().join(name);
        fs::create_dir_all(&repo).unwrap();
        init_repo(&repo);
    }

    let (stdout, _, success) =
        run_devpulse(&["--sort", "name", "--json", tmp.path().to_str().unwrap()]);
    assert!(success);
    let content: String = stdout
        .lines()
        .filter(|l| !l.starts_with("Scanning"))
        .collect::<Vec<_>>()
        .join("\n");
    let json: serde_json::Value = serde_json::from_str(content.trim()).unwrap();
    let projects = json["projects"].as_array().unwrap();
    let names: Vec<&str> = projects
        .iter()
        .map(|p| p["name"].as_str().unwrap())
        .collect();
    assert_eq!(
        names,
        vec!["alpha", "mango", "zebra"],
        "should be sorted alphabetically"
    );
}

#[test]
fn test_csv_header_and_row_count() {
    let tmp = TempDir::new().unwrap();
    for name in &["proj-a", "proj-b", "proj-c"] {
        let repo = tmp.path().join(name);
        fs::create_dir_all(&repo).unwrap();
        init_repo(&repo);
    }

    let (stdout, _, success) = run_devpulse(&["--format", "csv", tmp.path().to_str().unwrap()]);
    assert!(success, "csv output should succeed");
    let lines: Vec<&str> = stdout
        .lines()
        .filter(|l| !l.trim().is_empty() && !l.starts_with("Scanning") && !l.starts_with("Found"))
        .collect();
    // Should have header + 3 data rows
    assert!(
        lines.len() >= 4,
        "should have header + 3 rows, got {} lines: {:?}",
        lines.len(),
        lines
    );
    // First line should be a CSV header with commas
    let header = lines[0].to_lowercase();
    assert!(
        header.contains(","),
        "csv header should contain commas: {}",
        header
    );
}

#[test]
fn test_markdown_table_structure() {
    let tmp = TempDir::new().unwrap();
    let repo = tmp.path().join("md-test");
    fs::create_dir_all(&repo).unwrap();
    init_repo(&repo);

    let (stdout, _, success) =
        run_devpulse(&["--format", "markdown", tmp.path().to_str().unwrap()]);
    assert!(success, "markdown output should succeed");
    let content: String = stdout
        .lines()
        .filter(|l| !l.starts_with("Scanning"))
        .collect::<Vec<_>>()
        .join("\n");
    // Markdown table should have pipe characters
    assert!(
        content.contains("|"),
        "markdown output should contain table pipes"
    );
    // Should have a separator row with dashes
    assert!(
        content.contains("---"),
        "markdown table should have separator row"
    );
}

#[test]
fn test_empty_scan_directory_json() {
    let tmp = TempDir::new().unwrap();
    // No repos created — empty directory

    let (stdout, _, success) = run_devpulse(&["--json", tmp.path().to_str().unwrap()]);
    assert!(success, "empty directory scan should succeed");
    // When no projects found, devpulse outputs a hint message, not JSON
    assert!(
        stdout.contains("No projects found") || stdout.contains("projects"),
        "should indicate no projects found: {stdout}"
    );
}

/// Test that parallel scanning (via rayon) finds all repos and produces
/// correct results. Creates 20 repos to exercise the thread pool.
#[test]
fn test_parallel_scanning_many_repos() {
    let tmp = TempDir::new().unwrap();

    // Create 20 repos: 10 clean, 10 dirty
    for i in 0..10 {
        let clean = tmp.path().join(format!("clean-{i:02}"));
        fs::create_dir_all(&clean).unwrap();
        init_repo(&clean);

        let dirty = tmp.path().join(format!("dirty-{i:02}"));
        fs::create_dir_all(&dirty).unwrap();
        init_dirty_repo(&dirty);
    }

    let (stdout, _stderr, success) = run_devpulse(&["--json", tmp.path().to_str().unwrap()]);
    assert!(success, "parallel scan of 20 repos should succeed");

    let content: String = stdout
        .lines()
        .filter(|l| !l.starts_with("Scanning"))
        .collect::<Vec<_>>()
        .join("\n");
    let json: serde_json::Value = serde_json::from_str(content.trim()).unwrap();
    let projects = json["projects"].as_array().unwrap();

    assert_eq!(projects.len(), 20, "should find all 20 repos");

    // Verify counts: 10 clean, 10 dirty
    let clean_count = projects
        .iter()
        .filter(|p| p["is_clean"].as_bool().unwrap())
        .count();
    let dirty_count = projects
        .iter()
        .filter(|p| !p["is_clean"].as_bool().unwrap())
        .count();
    assert_eq!(clean_count, 10, "should have 10 clean repos");
    assert_eq!(dirty_count, 10, "should have 10 dirty repos");

    // Verify all names are present
    let names: Vec<&str> = projects
        .iter()
        .map(|p| p["name"].as_str().unwrap())
        .collect();
    for i in 0..10 {
        assert!(
            names.contains(&format!("clean-{i:02}").as_str()),
            "should contain clean-{i:02}"
        );
        assert!(
            names.contains(&format!("dirty-{i:02}").as_str()),
            "should contain dirty-{i:02}"
        );
    }
}

/// Test that parallel scanning with depth > 1 finds nested repos correctly.
#[test]
fn test_parallel_scanning_nested_depth() {
    let tmp = TempDir::new().unwrap();

    // Create groups with nested repos
    for group in ["frontend", "backend", "infra"] {
        let group_dir = tmp.path().join(group);
        fs::create_dir_all(&group_dir).unwrap();
        for i in 0..3 {
            let repo = group_dir.join(format!("{group}-svc-{i}"));
            fs::create_dir_all(&repo).unwrap();
            init_repo(&repo);
        }
    }

    let (stdout, _stderr, success) =
        run_devpulse(&["--json", "--depth", "2", tmp.path().to_str().unwrap()]);
    assert!(success, "parallel nested scan should succeed");

    let content: String = stdout
        .lines()
        .filter(|l| !l.starts_with("Scanning"))
        .collect::<Vec<_>>()
        .join("\n");
    let json: serde_json::Value = serde_json::from_str(content.trim()).unwrap();
    let projects = json["projects"].as_array().unwrap();

    assert_eq!(
        projects.len(),
        9,
        "should find all 9 nested repos across 3 groups"
    );
}

/// Test that parallel scanning produces deterministic sorted output.
#[test]
fn test_parallel_scanning_deterministic_order() {
    let tmp = TempDir::new().unwrap();

    for name in ["zebra", "alpha", "mango", "delta", "bravo"] {
        let repo = tmp.path().join(name);
        fs::create_dir_all(&repo).unwrap();
        init_repo(&repo);
    }

    // Run multiple times and verify order is always the same
    for _ in 0..3 {
        let (stdout, _, success) =
            run_devpulse(&["--sort", "name", "--json", tmp.path().to_str().unwrap()]);
        assert!(success);

        let content: String = stdout
            .lines()
            .filter(|l| !l.starts_with("Scanning"))
            .collect::<Vec<_>>()
            .join("\n");
        let json: serde_json::Value = serde_json::from_str(content.trim()).unwrap();
        let names: Vec<&str> = json["projects"]
            .as_array()
            .unwrap()
            .iter()
            .map(|p| p["name"].as_str().unwrap())
            .collect();
        assert_eq!(
            names,
            vec!["alpha", "bravo", "delta", "mango", "zebra"],
            "parallel results should be deterministically sorted"
        );
    }
}

// ── Theme integration tests ─────────────────────────────────────────

#[test]
fn test_theme_flag_dracula() {
    let dir = TempDir::new().unwrap();
    let repo_dir = dir.path().join("myapp");
    fs::create_dir(&repo_dir).unwrap();
    init_repo(&repo_dir);
    // Run without NO_COLOR so we get themed ANSI output
    let output = Command::new(devpulse_bin())
        .args(["--theme", "dracula", dir.path().to_str().unwrap()])
        .output()
        .expect("failed to run devpulse");
    let stdout = String::from_utf8_lossy(&output.stdout);
    assert!(
        output.status.success(),
        "stderr: {}",
        String::from_utf8_lossy(&output.stderr)
    );
    assert!(stdout.contains("myapp"));
}

#[test]
fn test_theme_flag_catppuccin() {
    let dir = TempDir::new().unwrap();
    let repo_dir = dir.path().join("app");
    fs::create_dir(&repo_dir).unwrap();
    init_repo(&repo_dir);
    let output = Command::new(devpulse_bin())
        .args(["--theme", "catppuccin-mocha", dir.path().to_str().unwrap()])
        .output()
        .expect("failed to run devpulse");
    assert!(
        output.status.success(),
        "stderr: {}",
        String::from_utf8_lossy(&output.stderr)
    );
}

#[test]
fn test_theme_flag_nord() {
    let dir = TempDir::new().unwrap();
    let repo_dir = dir.path().join("app");
    fs::create_dir(&repo_dir).unwrap();
    init_repo(&repo_dir);
    let output = Command::new(devpulse_bin())
        .args(["--theme", "nord", dir.path().to_str().unwrap()])
        .output()
        .expect("failed to run devpulse");
    assert!(
        output.status.success(),
        "stderr: {}",
        String::from_utf8_lossy(&output.stderr)
    );
}

#[test]
fn test_theme_flag_invalid() {
    let dir = TempDir::new().unwrap();
    let (_, stderr, success) =
        run_devpulse(&["--theme", "solarized", dir.path().to_str().unwrap()]);
    assert!(!success, "Should fail with invalid theme");
    assert!(stderr.contains("Unknown theme") || stderr.contains("solarized"));
}

#[test]
fn test_theme_from_config_file() {
    let dir = TempDir::new().unwrap();
    let repo_dir = dir.path().join("configured");
    fs::create_dir(&repo_dir).unwrap();
    init_repo(&repo_dir);
    fs::write(dir.path().join(".devpulse.toml"), "theme = \"nord\"\n").unwrap();
    let output = Command::new(devpulse_bin())
        .args([dir.path().to_str().unwrap()])
        .output()
        .expect("failed to run devpulse");
    let stdout = String::from_utf8_lossy(&output.stdout);
    assert!(
        output.status.success(),
        "stderr: {}",
        String::from_utf8_lossy(&output.stderr)
    );
    assert!(stdout.contains("configured"));
}

#[test]
fn test_theme_cli_overrides_config() {
    let dir = TempDir::new().unwrap();
    let repo_dir = dir.path().join("overridden");
    fs::create_dir(&repo_dir).unwrap();
    init_repo(&repo_dir);
    fs::write(dir.path().join(".devpulse.toml"), "theme = \"nord\"\n").unwrap();
    // CLI --theme dracula should override config's nord
    let output = Command::new(devpulse_bin())
        .args(["--theme", "dracula", dir.path().to_str().unwrap()])
        .output()
        .expect("failed to run devpulse");
    assert!(
        output.status.success(),
        "stderr: {}",
        String::from_utf8_lossy(&output.stderr)
    );
}

// ─── Shell completions tests ───────────────────────────────────────────

#[test]
fn test_completions_bash() {
    let output = Command::new(devpulse_bin())
        .args(["completions", "bash"])
        .output()
        .expect("failed to run devpulse completions bash");
    assert!(
        output.status.success(),
        "stderr: {}",
        String::from_utf8_lossy(&output.stderr)
    );
    let stdout = String::from_utf8_lossy(&output.stdout);
    assert!(
        stdout.contains("_devpulse"),
        "bash completions should define _devpulse function"
    );
    assert!(
        stdout.contains("COMPREPLY"),
        "bash completions should use COMPREPLY"
    );
}

#[test]
fn test_completions_zsh() {
    let output = Command::new(devpulse_bin())
        .args(["completions", "zsh"])
        .output()
        .expect("failed to run devpulse completions zsh");
    assert!(
        output.status.success(),
        "stderr: {}",
        String::from_utf8_lossy(&output.stderr)
    );
    let stdout = String::from_utf8_lossy(&output.stdout);
    assert!(
        stdout.contains("#compdef devpulse"),
        "zsh completions should have #compdef header"
    );
}

#[test]
fn test_completions_fish() {
    let output = Command::new(devpulse_bin())
        .args(["completions", "fish"])
        .output()
        .expect("failed to run devpulse completions fish");
    assert!(
        output.status.success(),
        "stderr: {}",
        String::from_utf8_lossy(&output.stderr)
    );
    let stdout = String::from_utf8_lossy(&output.stdout);
    assert!(
        stdout.contains("devpulse"),
        "fish completions should reference devpulse"
    );
    assert!(
        stdout.contains("complete"),
        "fish completions should use 'complete' command"
    );
}

#[test]
fn test_completions_invalid_shell() {
    let output = Command::new(devpulse_bin())
        .args(["completions", "powershell"])
        .output()
        .expect("failed to run devpulse");
    assert!(
        !output.status.success(),
        "should fail for unsupported shell"
    );
}

#[test]
fn test_completions_contains_all_flags() {
    let output = Command::new(devpulse_bin())
        .args(["completions", "bash"])
        .output()
        .expect("failed to run devpulse completions bash");
    let stdout = String::from_utf8_lossy(&output.stdout);
    for flag in &[
        "--sort",
        "--watch",
        "--json",
        "--tui",
        "--filter",
        "--depth",
        "--no-color",
        "--theme",
        "--no-ci",
    ] {
        assert!(
            stdout.contains(flag),
            "bash completions should include flag '{}'",
            flag
        );
    }
}