cascade-cli 0.1.152

Stacked diffs CLI for Bitbucket Server
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
1205
1206
1207
1208
1209
1210
1211
1212
1213
1214
1215
1216
1217
1218
1219
1220
1221
1222
1223
1224
1225
1226
1227
1228
1229
1230
1231
1232
1233
1234
1235
1236
1237
1238
1239
1240
1241
1242
1243
1244
1245
1246
1247
1248
1249
1250
1251
1252
1253
1254
1255
1256
1257
1258
1259
1260
1261
1262
1263
1264
1265
1266
1267
1268
1269
1270
1271
1272
1273
1274
1275
1276
1277
1278
1279
1280
1281
1282
1283
1284
1285
1286
1287
1288
1289
1290
1291
1292
1293
1294
1295
1296
1297
1298
1299
1300
1301
1302
1303
1304
1305
1306
1307
1308
1309
1310
1311
1312
1313
1314
1315
1316
1317
1318
1319
1320
1321
1322
1323
1324
1325
1326
1327
1328
1329
1330
1331
1332
1333
1334
1335
1336
1337
1338
1339
1340
1341
1342
1343
1344
1345
1346
1347
1348
1349
1350
1351
1352
1353
1354
1355
1356
1357
1358
1359
1360
1361
1362
1363
1364
1365
1366
1367
1368
1369
1370
1371
1372
1373
1374
1375
1376
1377
1378
1379
1380
1381
1382
1383
1384
1385
1386
1387
1388
1389
1390
1391
1392
1393
1394
1395
1396
1397
1398
1399
1400
1401
1402
1403
1404
1405
1406
1407
1408
1409
1410
1411
1412
1413
1414
1415
1416
1417
1418
1419
1420
1421
1422
1423
1424
1425
1426
1427
1428
1429
1430
1431
1432
1433
1434
1435
1436
1437
1438
1439
1440
1441
1442
1443
1444
1445
1446
1447
1448
1449
1450
1451
1452
1453
1454
1455
1456
1457
1458
1459
1460
1461
1462
1463
1464
1465
1466
1467
1468
1469
1470
1471
1472
1473
1474
1475
1476
1477
1478
1479
1480
1481
1482
1483
1484
1485
1486
1487
1488
1489
1490
1491
1492
1493
1494
1495
1496
1497
1498
1499
1500
1501
1502
1503
1504
1505
1506
1507
1508
1509
1510
1511
1512
1513
1514
1515
1516
1517
1518
1519
1520
1521
1522
1523
1524
1525
1526
1527
1528
1529
1530
1531
1532
1533
1534
1535
1536
1537
1538
1539
1540
1541
1542
1543
1544
1545
1546
1547
1548
1549
1550
1551
1552
1553
1554
1555
1556
1557
1558
1559
1560
1561
1562
1563
1564
1565
1566
1567
1568
1569
1570
1571
1572
1573
1574
1575
1576
1577
1578
1579
1580
1581
1582
1583
1584
1585
1586
1587
1588
1589
1590
1591
1592
1593
1594
1595
1596
1597
1598
1599
1600
1601
1602
1603
1604
1605
1606
1607
1608
1609
1610
1611
1612
1613
1614
1615
1616
1617
1618
1619
1620
1621
1622
1623
1624
1625
1626
1627
1628
1629
1630
1631
1632
1633
1634
1635
1636
1637
1638
1639
1640
1641
1642
1643
1644
1645
1646
1647
1648
1649
1650
1651
1652
1653
1654
1655
1656
1657
1658
1659
1660
1661
1662
1663
1664
1665
1666
1667
1668
1669
1670
1671
1672
1673
1674
1675
1676
1677
1678
1679
1680
1681
1682
1683
1684
1685
1686
1687
1688
1689
1690
1691
1692
1693
1694
1695
1696
1697
1698
1699
1700
1701
1702
1703
1704
1705
1706
1707
1708
1709
1710
1711
1712
1713
1714
1715
1716
1717
1718
1719
1720
1721
1722
1723
1724
1725
1726
1727
1728
1729
1730
1731
1732
1733
1734
1735
1736
1737
1738
1739
1740
1741
1742
1743
1744
1745
1746
1747
1748
1749
1750
1751
1752
1753
1754
1755
1756
1757
1758
1759
1760
1761
1762
1763
1764
1765
1766
1767
1768
1769
1770
1771
1772
1773
1774
1775
1776
1777
1778
1779
1780
1781
1782
1783
1784
1785
1786
1787
1788
1789
1790
1791
1792
1793
1794
1795
1796
1797
1798
1799
1800
1801
1802
1803
1804
1805
1806
1807
1808
1809
1810
1811
1812
1813
1814
1815
1816
1817
1818
1819
1820
1821
1822
1823
1824
1825
1826
1827
1828
1829
1830
1831
1832
1833
1834
1835
1836
1837
1838
1839
1840
1841
1842
1843
1844
1845
1846
1847
1848
1849
1850
1851
1852
1853
1854
1855
1856
1857
1858
1859
1860
1861
1862
1863
1864
1865
1866
1867
1868
1869
1870
1871
1872
1873
1874
1875
1876
1877
1878
1879
1880
1881
1882
1883
1884
1885
1886
1887
1888
1889
1890
1891
1892
1893
1894
1895
1896
1897
1898
1899
1900
1901
1902
1903
1904
1905
1906
1907
1908
1909
1910
1911
1912
1913
1914
1915
1916
1917
1918
1919
1920
1921
1922
1923
1924
1925
1926
1927
1928
1929
1930
1931
1932
1933
1934
1935
1936
1937
1938
1939
use crate::cli::output::Output;
use crate::config::Settings;
use crate::errors::{CascadeError, Result};
use crate::git::find_repository_root;
use dialoguer::{theme::ColorfulTheme, Confirm};
use std::env;
use std::fs;
use std::path::{Path, PathBuf};
use std::process::Command;
use tracing::debug;

/// Git repository type detection
#[derive(Debug, Clone, PartialEq)]
pub enum RepositoryType {
    Bitbucket,
    GitHub,
    GitLab,
    AzureDevOps,
    Unknown,
}

/// Branch type classification
#[derive(Debug, Clone, PartialEq)]
pub enum BranchType {
    Main,    // main, master, develop
    Feature, // feature branches
    Unknown,
}

/// Installation options for smart hook activation
#[derive(Debug, Clone)]
pub struct InstallOptions {
    pub check_prerequisites: bool,
    pub feature_branches_only: bool,
    pub confirm: bool,
    pub force: bool,
}

impl Default for InstallOptions {
    fn default() -> Self {
        Self {
            check_prerequisites: true,
            feature_branches_only: true,
            confirm: true,
            force: false,
        }
    }
}

/// Git hooks integration for Cascade CLI
pub struct HooksManager {
    repo_path: PathBuf,
    repo_id: String,
}

/// Available Git hooks that Cascade can install
#[derive(Debug, Clone)]
pub enum HookType {
    /// Validates commits are added to stacks
    PostCommit,
    /// Prevents force pushes and validates stack state
    PrePush,
    /// Validates commit messages follow conventions
    CommitMsg,
    /// Smart edit mode guidance before commit
    PreCommit,
    /// Prepares commit message with stack context
    PrepareCommitMsg,
}

impl HookType {
    fn filename(&self) -> String {
        let base_name = match self {
            HookType::PostCommit => "post-commit",
            HookType::PrePush => "pre-push",
            HookType::CommitMsg => "commit-msg",
            HookType::PreCommit => "pre-commit",
            HookType::PrepareCommitMsg => "prepare-commit-msg",
        };
        format!(
            "{}{}",
            base_name,
            crate::utils::platform::git_hook_extension()
        )
    }

    fn description(&self) -> &'static str {
        match self {
            HookType::PostCommit => "Auto-add new commits to active stack",
            HookType::PrePush => "Prevent force pushes and validate stack state",
            HookType::CommitMsg => "Validate commit message format",
            HookType::PreCommit => "Smart edit mode guidance for better UX",
            HookType::PrepareCommitMsg => "Add stack context to commit messages",
        }
    }
}

impl HooksManager {
    pub fn new(repo_path: &Path) -> Result<Self> {
        // Verify this is a git repository
        let git_dir = repo_path.join(".git");
        if !git_dir.exists() {
            return Err(CascadeError::config(
                "Not a Git repository. Git hooks require a valid Git repository.".to_string(),
            ));
        }

        // Generate a unique repo ID based on remote URL
        let repo_id = Self::generate_repo_id(repo_path)?;

        Ok(Self {
            repo_path: repo_path.to_path_buf(),
            repo_id,
        })
    }

    /// Generate a unique repository identifier based on remote URL
    fn generate_repo_id(repo_path: &Path) -> Result<String> {
        use std::process::Command;

        let output = Command::new("git")
            .args(["remote", "get-url", "origin"])
            .current_dir(repo_path)
            .output()
            .map_err(|e| CascadeError::config(format!("Failed to get remote URL: {e}")))?;

        if !output.status.success() {
            // Fallback to absolute path hash if no remote
            use sha2::{Digest, Sha256};
            let canonical_path = repo_path
                .canonicalize()
                .unwrap_or_else(|_| repo_path.to_path_buf());
            let path_str = canonical_path.to_string_lossy();
            let mut hasher = Sha256::new();
            hasher.update(path_str.as_bytes());
            let result = hasher.finalize();
            let hash = format!("{result:x}");
            return Ok(format!("local-{}", &hash[..8]));
        }

        let remote_url = String::from_utf8_lossy(&output.stdout).trim().to_string();

        // Convert URL to safe directory name
        // e.g., https://github.com/user/repo.git -> github.com-user-repo
        let safe_name = remote_url
            .replace("https://", "")
            .replace("http://", "")
            .replace("git@", "")
            .replace("ssh://", "")
            .replace(".git", "")
            .replace([':', '/', '\\'], "-")
            .chars()
            .filter(|c| c.is_alphanumeric() || *c == '-' || *c == '.' || *c == '_')
            .collect::<String>();

        Ok(safe_name)
    }

    /// Get the Cascade-specific hooks directory for this repo
    fn get_cascade_hooks_dir(&self) -> Result<PathBuf> {
        let home = dirs::home_dir()
            .ok_or_else(|| CascadeError::config("Could not find home directory".to_string()))?;
        let cascade_hooks = home.join(".cascade").join("hooks").join(&self.repo_id);
        Ok(cascade_hooks)
    }

    /// Get the Cascade config directory for this repo
    fn get_cascade_config_dir(&self) -> Result<PathBuf> {
        let home = dirs::home_dir()
            .ok_or_else(|| CascadeError::config("Could not find home directory".to_string()))?;
        let cascade_config = home.join(".cascade").join("config").join(&self.repo_id);
        Ok(cascade_config)
    }

    /// Save the current core.hooksPath value for later restoration
    fn save_original_hooks_path(&self) -> Result<()> {
        use std::process::Command;

        let config_dir = self.get_cascade_config_dir()?;
        fs::create_dir_all(&config_dir)
            .map_err(|e| CascadeError::config(format!("Failed to create config directory: {e}")))?;

        let original_path_file = config_dir.join("original-hooks-path");

        // Check if file exists and if it's corrupted (pointing to Cascade's own directory)
        if original_path_file.exists() {
            // Self-healing: verify the saved path isn't Cascade's own directory
            if let Ok(saved_path) = fs::read_to_string(&original_path_file) {
                let saved_path = saved_path.trim();
                let cascade_hooks_dir = dirs::home_dir()
                    .ok_or_else(|| {
                        CascadeError::config("Could not find home directory".to_string())
                    })?
                    .join(".cascade")
                    .join("hooks")
                    .join(&self.repo_id);
                let cascade_hooks_path = cascade_hooks_dir.to_string_lossy().to_string();

                if saved_path == cascade_hooks_path {
                    // CORRUPTED: File contains Cascade's own path - fix it!
                    fs::write(&original_path_file, "").map_err(|e| {
                        CascadeError::config(format!("Failed to fix corrupted hooks path: {e}"))
                    })?;
                    return Ok(());
                }
            }
            // File exists and is valid - don't overwrite
            return Ok(());
        }

        let output = Command::new("git")
            .args(["config", "--get", "core.hooksPath"])
            .current_dir(&self.repo_path)
            .output()
            .map_err(|e| CascadeError::config(format!("Failed to check git config: {e}")))?;

        let original_path = if output.status.success() {
            let current_hooks_path = String::from_utf8_lossy(&output.stdout).trim().to_string();

            // Don't save Cascade's own hooks directory as "original"
            // This prevents infinite loops in hook chaining
            let cascade_hooks_dir = dirs::home_dir()
                .ok_or_else(|| CascadeError::config("Could not find home directory".to_string()))?
                .join(".cascade")
                .join("hooks")
                .join(&self.repo_id);
            let cascade_hooks_path = cascade_hooks_dir.to_string_lossy().to_string();

            if current_hooks_path == cascade_hooks_path {
                // Already pointing to Cascade hooks - no original to save
                String::new()
            } else {
                current_hooks_path
            }
        } else {
            // Empty string means it wasn't set
            String::new()
        };

        fs::write(original_path_file, original_path).map_err(|e| {
            CascadeError::config(format!("Failed to save original hooks path: {e}"))
        })?;

        Ok(())
    }

    /// Restore the original core.hooksPath value
    fn restore_original_hooks_path(&self) -> Result<()> {
        use std::process::Command;

        let config_dir = self.get_cascade_config_dir()?;
        let original_path_file = config_dir.join("original-hooks-path");

        if !original_path_file.exists() {
            // Nothing to restore
            return Ok(());
        }

        let original_path = fs::read_to_string(&original_path_file).map_err(|e| {
            CascadeError::config(format!("Failed to read original hooks path: {e}"))
        })?;

        if original_path.is_empty() {
            // It wasn't set originally, so unset it
            Command::new("git")
                .args(["config", "--unset", "core.hooksPath"])
                .current_dir(&self.repo_path)
                .output()
                .map_err(|e| {
                    CascadeError::config(format!("Failed to unset core.hooksPath: {e}"))
                })?;
        } else {
            // Restore the original value
            Command::new("git")
                .args(["config", "core.hooksPath", &original_path])
                .current_dir(&self.repo_path)
                .output()
                .map_err(|e| {
                    CascadeError::config(format!("Failed to restore core.hooksPath: {e}"))
                })?;
        }

        // Clean up the saved file
        fs::remove_file(original_path_file).ok();

        Ok(())
    }

    /// Get the actual hooks directory path, respecting core.hooksPath configuration
    #[allow(dead_code)]
    fn get_hooks_path(repo_path: &Path) -> Result<PathBuf> {
        use std::process::Command;

        // Try to get core.hooksPath configuration
        let output = Command::new("git")
            .args(["config", "--get", "core.hooksPath"])
            .current_dir(repo_path)
            .output()
            .map_err(|e| CascadeError::config(format!("Failed to check git config: {e}")))?;

        let default_hooks_dir = || -> PathBuf {
            let repo = git2::Repository::discover(repo_path).ok();
            repo.map(|r| r.commondir().join("hooks"))
                .unwrap_or_else(|| repo_path.join(".git").join("hooks"))
        };

        let hooks_path = if output.status.success() {
            let configured_path = String::from_utf8_lossy(&output.stdout).trim().to_string();
            if configured_path.is_empty() {
                // Empty value means default
                default_hooks_dir()
            } else if configured_path.starts_with('/') {
                // Absolute path
                PathBuf::from(configured_path)
            } else {
                // Relative path - relative to repo root
                repo_path.join(configured_path)
            }
        } else {
            // No core.hooksPath configured, use default
            default_hooks_dir()
        };

        Ok(hooks_path)
    }

    /// Install all recommended Cascade hooks
    pub fn install_all(&self) -> Result<()> {
        self.install_with_options(&InstallOptions::default())
    }

    /// Install only essential hooks (for setup) - excludes post-commit
    pub fn install_essential(&self) -> Result<()> {
        Output::progress("Installing essential Cascade Git hooks");

        let essential_hooks = vec![
            HookType::PrePush,
            HookType::CommitMsg,
            HookType::PrepareCommitMsg,
            HookType::PreCommit,
        ];

        for hook in essential_hooks {
            self.install_hook(&hook)?;
        }

        Output::success("Essential Cascade hooks installed successfully!");
        Output::tip("Note: Post-commit auto-add hook available with 'ca hooks install --all'");
        Output::section("Hooks installed");
        self.list_installed_hooks()?;

        Ok(())
    }

    /// Install hooks with smart validation options
    pub fn install_with_options(&self, options: &InstallOptions) -> Result<()> {
        if options.check_prerequisites && !options.force {
            self.validate_prerequisites()?;
        }

        if options.feature_branches_only && !options.force {
            self.validate_branch_suitability()?;
        }

        if options.confirm && !options.force {
            self.confirm_installation()?;
        }

        Output::progress("Installing all Cascade Git hooks");

        // Install ALL hooks (all 5 HookType variants)
        let hooks = vec![
            HookType::PostCommit,
            HookType::PrePush,
            HookType::CommitMsg,
            HookType::PrepareCommitMsg,
            HookType::PreCommit,
        ];

        for hook in hooks {
            self.install_hook(&hook)?;
        }

        Output::success("All Cascade hooks installed successfully!");
        Output::section("Hooks installed");
        self.list_installed_hooks()?;

        Ok(())
    }

    /// Install a specific hook
    pub fn install_hook(&self, hook_type: &HookType) -> Result<()> {
        // Ensure we've saved the original hooks path first
        self.save_original_hooks_path()?;

        // Create cascade hooks directory
        let cascade_hooks_dir = self.get_cascade_hooks_dir()?;
        fs::create_dir_all(&cascade_hooks_dir).map_err(|e| {
            CascadeError::config(format!("Failed to create cascade hooks directory: {e}"))
        })?;

        // Generate hook that chains to original
        let hook_content = self.generate_chaining_hook_script(hook_type)?;
        let hook_path = cascade_hooks_dir.join(hook_type.filename());

        // Write the hook
        fs::write(&hook_path, hook_content)
            .map_err(|e| CascadeError::config(format!("Failed to write hook file: {e}")))?;

        // Make executable (platform-specific)
        crate::utils::platform::make_executable(&hook_path)
            .map_err(|e| CascadeError::config(format!("Failed to make hook executable: {e}")))?;

        // Set core.hooksPath to our cascade directory
        self.set_cascade_hooks_path()?;

        Output::success(format!("Installed {} hook", hook_type.filename()));
        Ok(())
    }

    /// Set git's core.hooksPath to our cascade hooks directory
    fn set_cascade_hooks_path(&self) -> Result<()> {
        use std::process::Command;

        let cascade_hooks_dir = self.get_cascade_hooks_dir()?;
        let hooks_path_str = cascade_hooks_dir.to_string_lossy();

        let output = Command::new("git")
            .args(["config", "core.hooksPath", &hooks_path_str])
            .current_dir(&self.repo_path)
            .output()
            .map_err(|e| CascadeError::config(format!("Failed to set core.hooksPath: {e}")))?;

        if !output.status.success() {
            return Err(CascadeError::config(format!(
                "Failed to set core.hooksPath: {}",
                String::from_utf8_lossy(&output.stderr)
            )));
        }

        Ok(())
    }

    /// Remove all Cascade hooks
    pub fn uninstall_all(&self) -> Result<()> {
        Output::progress("Removing Cascade Git hooks");

        // Restore original core.hooksPath
        self.restore_original_hooks_path()?;

        // Clean up cascade hooks directory
        let cascade_hooks_dir = self.get_cascade_hooks_dir()?;
        if cascade_hooks_dir.exists() {
            fs::remove_dir_all(&cascade_hooks_dir).map_err(|e| {
                CascadeError::config(format!("Failed to remove cascade hooks directory: {e}"))
            })?;
        }

        // Also clean up any old Cascade hooks in .git/hooks/ (from before core.hooksPath)
        // These might have been left behind from earlier versions
        // IMPORTANT: Only remove hooks that have our EXACT wrapper pattern to avoid
        // deleting user's custom hooks that might mention "Cascade"
        let git_hooks_dir = {
            let repo = git2::Repository::discover(&self.repo_path).ok();
            repo.map(|r| r.commondir().join("hooks"))
                .unwrap_or_else(|| self.repo_path.join(".git").join("hooks"))
        };
        if git_hooks_dir.exists() {
            for hook_type in &[
                HookType::PostCommit,
                HookType::PrePush,
                HookType::CommitMsg,
                HookType::PrepareCommitMsg,
                HookType::PreCommit,
            ] {
                let hook_path = git_hooks_dir.join(hook_type.filename());
                if hook_path.exists() {
                    // Check if it's a Cascade WRAPPER hook by looking for our exact wrapper signature
                    // This is different from user hooks that might just mention Cascade
                    if let Ok(content) = fs::read_to_string(&hook_path) {
                        if content.contains("# Cascade CLI Hook Wrapper")
                            && content.contains("cascade_logic()")
                            && content.contains("# Function to run Cascade logic")
                        {
                            debug!(
                                "Removing old Cascade wrapper hook from .git/hooks: {:?}",
                                hook_path
                            );
                            fs::remove_file(&hook_path).ok(); // Ignore errors
                        }
                    }
                }
            }
        }

        // Clean up config directory if empty
        let cascade_config_dir = self.get_cascade_config_dir()?;
        if cascade_config_dir.exists() {
            // Try to remove, but ignore if not empty
            fs::remove_dir(&cascade_config_dir).ok();
        }

        Output::success("All Cascade hooks removed!");
        Ok(())
    }

    /// Remove a specific hook
    pub fn uninstall_hook(&self, hook_type: &HookType) -> Result<()> {
        let cascade_hooks_dir = self.get_cascade_hooks_dir()?;
        let hook_path = cascade_hooks_dir.join(hook_type.filename());

        if hook_path.exists() {
            fs::remove_file(&hook_path)
                .map_err(|e| CascadeError::config(format!("Failed to remove hook file: {e}")))?;
            Output::success(format!("Removed {} hook", hook_type.filename()));

            // If no more hooks in cascade directory, restore original hooks path
            let remaining_hooks = fs::read_dir(&cascade_hooks_dir)
                .map_err(|e| CascadeError::config(format!("Failed to read hooks directory: {e}")))?
                .filter_map(|entry| entry.ok())
                .filter(|entry| {
                    entry.path().is_file() && !entry.file_name().to_string_lossy().starts_with('.')
                })
                .count();

            if remaining_hooks == 0 {
                Output::info(
                    "No more Cascade hooks installed, restoring original hooks configuration",
                );
                self.restore_original_hooks_path()?;
                fs::remove_dir(&cascade_hooks_dir).ok();
            }
        } else {
            Output::info(format!("{} hook not found", hook_type.filename()));
        }

        Ok(())
    }

    /// List all installed hooks and their status
    pub fn list_installed_hooks(&self) -> Result<()> {
        let hooks = vec![
            HookType::PostCommit,
            HookType::PrePush,
            HookType::CommitMsg,
            HookType::PrepareCommitMsg,
            HookType::PreCommit,
        ];

        Output::section("Git Hooks Status");

        // Check if we're using cascade hooks directory
        let cascade_hooks_dir = self.get_cascade_hooks_dir()?;
        let using_cascade_hooks = cascade_hooks_dir.exists()
            && self.get_current_hooks_path()?
                == Some(cascade_hooks_dir.to_string_lossy().to_string());

        if using_cascade_hooks {
            Output::success("✓ Cascade hooks are installed and active");
            Output::info(format!(
                "  Hooks directory: {}",
                cascade_hooks_dir.display()
            ));

            // Check what original hooks path was saved
            let config_dir = self.get_cascade_config_dir()?;
            let original_path_file = config_dir.join("original-hooks-path");
            if original_path_file.exists() {
                let original_path = fs::read_to_string(original_path_file).unwrap_or_default();
                if !original_path.is_empty() {
                    Output::info(format!("  Chaining to original hooks: {original_path}"));
                } else {
                    Output::info("  Chaining to original hooks: .git/hooks");
                }
            }
            println!();
        } else {
            Output::warning("Cascade hooks are NOT installed in this repository");
            println!();
            Output::sub_item("To install Cascade hooks:");
            Output::command_example("ca hooks install            # recommended: 4 essential hooks");
            Output::command_example(
                "ca hooks install --all      # all 5 hooks + post-commit auto-add",
            );
            println!();
            Output::sub_item("Both options preserve existing hooks by chaining to them");
            println!();
        }

        for hook in hooks {
            let cascade_hook_path = cascade_hooks_dir.join(hook.filename());

            if using_cascade_hooks && cascade_hook_path.exists() {
                Output::success(format!("{}: {} ✓", hook.filename(), hook.description()));
            } else {
                // Check default location
                let default_hook_path = {
                    let repo = git2::Repository::discover(&self.repo_path).ok();
                    repo.map(|r| r.commondir().join("hooks"))
                        .unwrap_or_else(|| self.repo_path.join(".git").join("hooks"))
                }
                .join(hook.filename());
                if default_hook_path.exists() {
                    Output::warning(format!(
                        "{}: {} (In .git/hooks, not managed by Cascade)",
                        hook.filename(),
                        hook.description()
                    ));
                } else {
                    Output::error(format!(
                        "{}: {} (Not installed)",
                        hook.filename(),
                        hook.description()
                    ));
                }
            }
        }

        Ok(())
    }

    /// Get the current core.hooksPath value
    fn get_current_hooks_path(&self) -> Result<Option<String>> {
        use std::process::Command;

        let output = Command::new("git")
            .args(["config", "--get", "core.hooksPath"])
            .current_dir(&self.repo_path)
            .output()
            .map_err(|e| CascadeError::config(format!("Failed to check git config: {e}")))?;

        if output.status.success() {
            let path = String::from_utf8_lossy(&output.stdout).trim().to_string();
            if path.is_empty() {
                Ok(None)
            } else {
                Ok(Some(path))
            }
        } else {
            Ok(None)
        }
    }

    /// Generate hook script content
    pub fn generate_hook_script(&self, hook_type: &HookType) -> Result<String> {
        let cascade_cli = env::current_exe()
            .map_err(|e| {
                CascadeError::config(format!("Failed to get current executable path: {e}"))
            })?
            .to_string_lossy()
            .to_string();

        let script = match hook_type {
            HookType::PostCommit => self.generate_post_commit_hook(&cascade_cli),
            HookType::PrePush => self.generate_pre_push_hook(&cascade_cli),
            HookType::CommitMsg => self.generate_commit_msg_hook(&cascade_cli),
            HookType::PreCommit => self.generate_pre_commit_hook(&cascade_cli),
            HookType::PrepareCommitMsg => self.generate_prepare_commit_msg_hook(&cascade_cli),
        };

        Ok(script)
    }

    /// Generate hook script that chains to original hooks
    pub fn generate_chaining_hook_script(&self, hook_type: &HookType) -> Result<String> {
        let cascade_cli = env::current_exe()
            .map_err(|e| {
                CascadeError::config(format!("Failed to get current executable path: {e}"))
            })?
            .to_string_lossy()
            .to_string();

        let config_dir = self.get_cascade_config_dir()?;
        let hook_name = match hook_type {
            HookType::PostCommit => "post-commit",
            HookType::PrePush => "pre-push",
            HookType::CommitMsg => "commit-msg",
            HookType::PreCommit => "pre-commit",
            HookType::PrepareCommitMsg => "prepare-commit-msg",
        };

        // Generate the cascade-specific hook logic
        let cascade_logic = match hook_type {
            HookType::PostCommit => self.generate_post_commit_hook(&cascade_cli),
            HookType::PrePush => self.generate_pre_push_hook(&cascade_cli),
            HookType::CommitMsg => self.generate_commit_msg_hook(&cascade_cli),
            HookType::PreCommit => self.generate_pre_commit_hook(&cascade_cli),
            HookType::PrepareCommitMsg => self.generate_prepare_commit_msg_hook(&cascade_cli),
        };

        // Create wrapper that chains to original
        #[cfg(windows)]
        return Ok(format!(
                "@echo off\n\
                 rem Cascade CLI Hook Wrapper - {}\n\
                 rem This hook runs Cascade logic first, then chains to original hooks\n\n\
                 rem Run Cascade logic first\n\
                 call :cascade_logic %*\n\
                 set CASCADE_RESULT=%ERRORLEVEL%\n\
                 if %CASCADE_RESULT% neq 0 exit /b %CASCADE_RESULT%\n\n\
                 rem Check for original hook\n\
                 set ORIGINAL_HOOKS_PATH=\n\
                 if exist \"{}\\original-hooks-path\" (\n\
                     set /p ORIGINAL_HOOKS_PATH=<\"{}\\original-hooks-path\"\n\
                 )\n\n\
                 if \"%ORIGINAL_HOOKS_PATH%\"==\"\" (\n\
                     rem Default location\n\
                     for /f \"tokens=*\" %%i in ('git rev-parse --git-dir 2^>nul') do set GIT_DIR=%%i\n\
                     if exist \"%GIT_DIR%\\hooks\\{}\" (\n\
                         call \"%GIT_DIR%\\hooks\\{}\" %*\n\
                         exit /b %ERRORLEVEL%\n\
                     )\n\
                 ) else (\n\
                     rem Custom hooks path\n\
                     if exist \"%ORIGINAL_HOOKS_PATH%\\{}\" (\n\
                         call \"%ORIGINAL_HOOKS_PATH%\\{}\" %*\n\
                         exit /b %ERRORLEVEL%\n\
                     )\n\
                 )\n\n\
                 exit /b 0\n\n\
                 :cascade_logic\n\
                 {}\n\
                 exit /b %ERRORLEVEL%\n",
                hook_name,
                config_dir.to_string_lossy(),
                config_dir.to_string_lossy(),
                hook_name,
                hook_name,
                hook_name,
                hook_name,
                cascade_logic
            ));

        #[cfg(not(windows))]
        {
            // Build the wrapper using string concatenation to avoid double-escaping issues
            let trimmed_logic = cascade_logic
                .trim_start_matches("#!/bin/sh\n")
                .trim_start_matches("set -e\n");

            let wrapper = format!(
                "#!/bin/sh\n\
                 # Cascade CLI Hook Wrapper - {}\n\
                 # This hook runs Cascade logic first, then chains to original hooks\n\n\
                 set -e\n\n\
                 # Function to run Cascade logic\n\
                 cascade_logic() {{\n",
                hook_name
            );

            let chaining_logic = format!(
                "\n\
                 }}\n\n\
                 # Run Cascade logic first\n\
                 cascade_logic \"$@\"\n\
                 CASCADE_RESULT=$?\n\
                 if [ $CASCADE_RESULT -ne 0 ]; then\n\
                     exit $CASCADE_RESULT\n\
                 fi\n\n\
                 # Check for original hook\n\
                 ORIGINAL_HOOKS_PATH=\"\"\n\
                 if [ -f \"{}/original-hooks-path\" ]; then\n\
                     ORIGINAL_HOOKS_PATH=$(cat \"{}/original-hooks-path\" 2>/dev/null || echo \"\")\n\
                 fi\n\n\
                 if [ -z \"$ORIGINAL_HOOKS_PATH\" ]; then\n\
                     # Default location\n\
                     GIT_DIR=$(git rev-parse --git-dir 2>/dev/null || echo \".git\")\n\
                     ORIGINAL_HOOK=\"$GIT_DIR/hooks/{}\"\n\
                 else\n\
                     # Custom hooks path\n\
                     ORIGINAL_HOOK=\"$ORIGINAL_HOOKS_PATH/{}\"\n\
                 fi\n\n\
                 # Run original hook if it exists and is executable\n\
                 if [ -x \"$ORIGINAL_HOOK\" ]; then\n\
                     \"$ORIGINAL_HOOK\" \"$@\"\n\
                     exit $?\n\
                 fi\n\n\
                 exit 0\n",
                config_dir.to_string_lossy(),
                config_dir.to_string_lossy(),
                hook_name,
                hook_name
            );

            Ok(format!("{}{}{}", wrapper, trimmed_logic, chaining_logic))
        }
    }

    fn generate_post_commit_hook(&self, cascade_cli: &str) -> String {
        #[cfg(windows)]
        {
            format!(
                "@echo off\n\
                 rem Cascade CLI Hook - Post Commit\n\
                 rem Automatically adds new commits to the active stack\n\n\
                 rem Get the commit hash and message\n\
                 for /f \"tokens=*\" %%i in ('git rev-parse HEAD') do set COMMIT_HASH=%%i\n\
                 for /f \"tokens=*\" %%i in ('git log --format=%%s -n 1 HEAD') do set COMMIT_MSG=%%i\n\n\
                 rem Find repository root and check if Cascade is initialized\n\
                 for /f \"tokens=*\" %%i in ('git rev-parse --show-toplevel 2^>nul') do set REPO_ROOT=%%i\n\
                 if \"%REPO_ROOT%\"==\"\" set REPO_ROOT=.\n\
                 if not exist \"%REPO_ROOT%\\.cascade\" (\n\
                     echo \"Cascade not initialized, skipping stack management\"\n\
                     echo \"Run 'ca init' to start using stacked diffs\"\n\
                     exit /b 0\n\
                 )\n\n\
                 rem Check if there's an active stack\n\
                 \"{cascade_cli}\" stack list --active >nul 2>&1\n\
                 if %ERRORLEVEL% neq 0 (\n\
                     echo \"No active stack found, commit will not be added to any stack\"\n\
                     echo \"Tip: Use 'ca stack create ^<name^>' to create a stack for this commit\"\n\
                     exit /b 0\n\
                 )\n\n\
                 rem Add commit to active stack\n\
                 echo \"Adding commit to active stack...\"\n\
                 echo \"Commit: %COMMIT_MSG%\"\n\
                 \"{cascade_cli}\" stack push --commit \"%COMMIT_HASH%\" --message \"%COMMIT_MSG%\"\n\
                 if %ERRORLEVEL% equ 0 (\n\
                     echo \"Commit added to stack successfully\"\n\
                     echo \"Next: 'ca submit' to create PRs when ready\"\n\
                 ) else (\n\
                     echo \"Failed to add commit to stack\"\n\
                     echo \"Tip: You can manually add it with: ca push --commit %COMMIT_HASH%\"\n\
                 )\n"
            )
        }

        #[cfg(not(windows))]
        {
            format!(
                "#!/bin/sh\n\
                 # Cascade CLI Hook - Post Commit\n\
                 # Automatically adds new commits to the active stack\n\n\
                 set -e\n\n\
                 # Get the commit hash and message\n\
                 COMMIT_HASH=$(git rev-parse HEAD)\n\
                 COMMIT_MSG=$(git log --format=%s -n 1 HEAD)\n\n\
                 # Find repository root and check if Cascade is initialized\n\
                 REPO_ROOT=$(git rev-parse --show-toplevel 2>/dev/null || echo \".\")\n\
                 if [ ! -d \"$REPO_ROOT/.cascade\" ]; then\n\
                     echo \"Cascade not initialized, skipping stack management\"\n\
                     echo \"Run 'ca init' to start using stacked diffs\"\n\
                     exit 0\n\
                 fi\n\n\
                 # Check if there's an active stack\n\
                 if ! \"{cascade_cli}\" stack list --active > /dev/null 2>&1; then\n\
                     echo \"No active stack found, commit will not be added to any stack\"\n\
                     echo \"Tip: Use 'ca stack create <name>' to create a stack for this commit\"\n\
                     exit 0\n\
                 fi\n\n\
                 # Add commit to active stack (using specific commit targeting)\n\
                 echo \"Adding commit to active stack...\"\n\
                 echo \"Commit: $COMMIT_MSG\"\n\
                 if \"{cascade_cli}\" stack push --commit \"$COMMIT_HASH\" --message \"$COMMIT_MSG\"; then\n\
                     echo \"Commit added to stack successfully\"\n\
                     echo \"Next: 'ca submit' to create PRs when ready\"\n\
                 else\n\
                     echo \"Failed to add commit to stack\"\n\
                     echo \"Tip: You can manually add it with: ca push --commit $COMMIT_HASH\"\n\
                 fi\n"
            )
        }
    }

    fn generate_pre_push_hook(&self, cascade_cli: &str) -> String {
        #[cfg(windows)]
        {
            format!(
                "@echo off\n\
                 rem Cascade CLI Hook - Pre Push\n\
                 rem Prevents force pushes and validates stack state\n\n\
                 rem Allow force pushes from Cascade internal commands (ca sync, ca submit, etc.)\n\
                 rem Check for marker file (Git hooks don't inherit env vars)\n\
                 for /f \"tokens=*\" %%i in ('git rev-parse --git-dir 2^>nul') do set GIT_DIR=%%i\n\
                 if \"%GIT_DIR%\"==\"\" set GIT_DIR=.git\n\
                 if exist \"%GIT_DIR%\\.cascade-internal-push\" (\n\
                     exit /b 0\n\
                 )\n\n\
                 rem Check for force push from user\n\
                 echo %* | findstr /C:\"--force\" /C:\"--force-with-lease\" /C:\"-f\" >nul\n\
                 if %ERRORLEVEL% equ 0 (\n\
                     echo ERROR: Force push detected\n\
                     echo Cascade CLI uses stacked diffs - force pushes can break stack integrity\n\
                     echo.\n\
                     echo Instead, try these commands:\n\
                     echo   ca sync      - Sync with remote changes ^(handles rebasing^)\n\
                     echo   ca push      - Push all unpushed commits\n\
                     echo   ca submit    - Submit all entries for review\n\
                     echo   ca autoland  - Auto-merge when approved + builds pass\n\
                     echo.\n\
                     echo If you really need to force push:\n\
                     echo   git push --force-with-lease [remote] [branch]\n\
                     echo   ^(But consider if this will affect other stack entries^)\n\
                     exit /b 1\n\
                 )\n\n\
                 rem Find repository root and check if Cascade is initialized\n\
                 for /f \"tokens=*\" %%i in ('git rev-parse --show-toplevel 2^>nul') do set REPO_ROOT=%%i\n\
                 if \"%REPO_ROOT%\"==\"\" set REPO_ROOT=.\n\
                 if not exist \"%REPO_ROOT%\\.cascade\" (\n\
                     exit /b 0\n\
                 )\n\n\
                 rem Validate stack state (silent unless error)\n\
                 \"{cascade_cli}\" validate >nul 2>&1\n\
                 if %ERRORLEVEL% neq 0 (\n\
                     echo Stack validation failed - run 'ca validate' for details\n\
                     exit /b 1\n\
                 )\n"
            )
        }

        #[cfg(not(windows))]
        {
            format!(
                "#!/bin/sh\n\
                 # Cascade CLI Hook - Pre Push\n\
                 # Prevents force pushes and validates stack state\n\n\
                 set -e\n\n\
                 # Allow force pushes from Cascade internal commands (ca sync, ca submit, etc.)\n\
                 # Check for marker file (Git hooks don't inherit env vars)\n\
                 GIT_DIR=$(git rev-parse --git-dir 2>/dev/null || echo \".git\")\n\
                 if [ -f \"$GIT_DIR/.cascade-internal-push\" ]; then\n\
                     exit 0\n\
                 fi\n\n\
                 # Check for force push from user\n\
                 if echo \"$*\" | grep -q -- \"--force\\|--force-with-lease\\|-f\"; then\n\
                     echo \"ERROR: Force push detected\"\n\
                     echo \"Cascade CLI uses stacked diffs - force pushes can break stack integrity\"\n\
                     echo \"\"\n\
                     echo \"Instead, try these commands:\"\n\
                     echo \"  ca sync      - Sync with remote changes (handles rebasing)\"\n\
                     echo \"  ca push      - Push all unpushed commits\"\n\
                     echo \"  ca submit    - Submit all entries for review\"\n\
                     echo \"  ca autoland  - Auto-merge when approved + builds pass\"\n\
                     echo \"\"\n\
                     echo \"If you really need to force push:\"\n\
                     echo \"  git push --force-with-lease [remote] [branch]\"\n\
                     echo \"  (But consider if this will affect other stack entries)\"\n\
                     exit 1\n\
                 fi\n\n\
                 # Find repository root and check if Cascade is initialized\n\
                 REPO_ROOT=$(git rev-parse --show-toplevel 2>/dev/null || echo \".\")\n\
                 if [ ! -d \"$REPO_ROOT/.cascade\" ]; then\n\
                     exit 0\n\
                 fi\n\n\
                 # Validate stack state (silent unless error)\n\
                 if ! \"{cascade_cli}\" validate > /dev/null 2>&1; then\n\
                     echo \"Stack validation failed - run 'ca validate' for details\"\n\
                     exit 1\n\
                     fi\n"
            )
        }
    }

    fn generate_commit_msg_hook(&self, _cascade_cli: &str) -> String {
        #[cfg(windows)]
        {
            r#"@echo off
rem Cascade CLI Hook - Commit Message
rem Validates commit message format

set COMMIT_MSG_FILE=%1
if "%COMMIT_MSG_FILE%"=="" (
    echo ERROR: No commit message file provided
    exit /b 1
)

rem Read commit message (Windows batch is limited, but this covers basic cases)
for /f "delims=" %%i in ('type "%COMMIT_MSG_FILE%"') do set COMMIT_MSG=%%i

rem Skip validation for merge commits, fixup commits, etc.
echo %COMMIT_MSG% | findstr /B /C:"Merge" /C:"Revert" /C:"fixup!" /C:"squash!" >nul
if %ERRORLEVEL% equ 0 exit /b 0

rem Find repository root and check if Cascade is initialized
for /f "tokens=*" %%i in ('git rev-parse --show-toplevel 2^>nul') do set REPO_ROOT=%%i
if "%REPO_ROOT%"=="" set REPO_ROOT=.
if not exist "%REPO_ROOT%\.cascade" exit /b 0

rem Basic commit message validation
echo %COMMIT_MSG% | findstr /R "^..........*" >nul
if %ERRORLEVEL% neq 0 (
    echo ERROR: Commit message too short (minimum 10 characters)
    echo TIP: Write a descriptive commit message for better stack management
    exit /b 1
)

rem Validation passed (silent success)
exit /b 0
"#
            .to_string()
        }

        #[cfg(not(windows))]
        {
            r#"#!/bin/sh
# Cascade CLI Hook - Commit Message
# Validates commit message format

set -e

COMMIT_MSG_FILE="$1"
COMMIT_MSG=$(cat "$COMMIT_MSG_FILE")

# Skip validation for merge commits, fixup commits, etc.
if echo "$COMMIT_MSG" | grep -E "^(Merge|Revert|fixup!|squash!)" > /dev/null; then
    exit 0
fi

# Find repository root and check if Cascade is initialized
REPO_ROOT=$(git rev-parse --show-toplevel 2>/dev/null || echo ".")
if [ ! -d "$REPO_ROOT/.cascade" ]; then
    exit 0
fi

# Basic commit message validation
if [ ${#COMMIT_MSG} -lt 10 ]; then
    echo "ERROR: Commit message too short (minimum 10 characters)"
    echo "TIP: Write a descriptive commit message for better stack management"
    exit 1
fi

# Validation passed (silent success)
exit 0
"#
            .to_string()
        }
    }

    #[allow(clippy::uninlined_format_args)]
    fn generate_pre_commit_hook(&self, cascade_cli: &str) -> String {
        #[cfg(windows)]
        {
            format!(
                "@echo off\n\
                 rem Cascade CLI Hook - Pre Commit\n\
                 rem Smart edit mode guidance for better UX\n\n\
                 rem Check if Cascade is initialized\n\
                 for /f \\\"tokens=*\\\" %%i in ('git rev-parse --show-toplevel 2^>nul') do set REPO_ROOT=%%i\n\
                 if \\\"%REPO_ROOT%\\\"==\\\"\\\" set REPO_ROOT=.\n\
                 if not exist \\\"%REPO_ROOT%\\.cascade\\\" exit /b 0\n\n\
                 rem Skip hook if called from ca entry amend ^(avoid infinite loop^)\n\
                 if \\\"%CASCADE_SKIP_HOOKS%\\\"==\\\"1\\\" exit /b 0\n\n\
                 rem Skip hook during cherry-pick/rebase/merge operations\n\
                 for /f \\\"tokens=*\\\" %%i in ('git rev-parse --git-dir 2^>nul') do set GIT_DIR=%%i\n\
                 if \\\"%GIT_DIR%\\\"==\\\"\\\" set GIT_DIR=.git\n\
                 if exist \\\"%GIT_DIR%\\CHERRY_PICK_HEAD\\\" exit /b 0\n\
                 if exist \\\"%GIT_DIR%\\REBASE_HEAD\\\" exit /b 0\n\
                 if exist \\\"%GIT_DIR%\\MERGE_HEAD\\\" exit /b 0\n\n\
                 rem Get edit status\n\
                 for /f \\\"tokens=*\\\" %%i in ('\\\"{0}\\\" entry status --quiet 2^>nul') do set EDIT_STATUS=%%i\n\
                 if \\\"%EDIT_STATUS%\\\"==\\\"\\\" set EDIT_STATUS=inactive\n\n\
                 rem Check if edit status is active\n\
                 echo %EDIT_STATUS% | findstr /b \\\"active:\\\" >nul\n\
                 if %ERRORLEVEL% equ 0 (\n\
                     echo You're in EDIT MODE for a stack entry\n\
                     echo.\n\
                     echo Choose your action:\n\
                     echo   [a] amend: Modify the current entry ^(default^)\n\
                     echo   [n] new:   Create new entry on top\n\
                     echo   [c] cancel: Stop and think about it\n\
                     echo.\n\
                     set /p choice=\\\"Your choice (a/n/c): \\\" <CON\n\
                     if \\\"%choice%\\\"==\\\"\\\" set choice=a\n\
                     \n\
                    if /i \\\"%choice%\\\"==\\\"A\\\" (\n\
                        rem Use ca entry amend to update entry ^(ignore any -m flag^)\n\
                        rem Changes are already staged by git commit; --restack updates dependents\n\
                        \\\"{0}\\\" entry amend --restack\n\
                        set amend_error=%ERRORLEVEL%\n\
                        if %amend_error% EQU 0 (\n\
                            echo Amend applied - skipping git commit to avoid duplicate entry.\n\
                            echo Your commit was updated by Cascade; no further action needed.\n\
                            exit /b 1\n\
                        ) else (\n\
                            exit /b %amend_error%\n\
                        )\n\
                    ) else if /i \\\"%choice%\\\"==\\\"N\\\" (\n\
                         echo Creating new stack entry...\n\
                         echo The commit will proceed and post-commit hook will add it to your stack\n\
                         rem Let commit proceed ^(Git will use -m flag or open editor^)\n\
                         exit /b 0\n\
                     ) else if /i \\\"%choice%\\\"==\\\"C\\\" (\n\
                         echo Commit cancelled\n\
                         exit /b 1\n\
                     ) else (\n\
                         echo Invalid choice. Please choose A, n, or c\n\
                         exit /b 1\n\
                     )\n\
                 )\n\n\
                 rem Not in edit mode, proceed normally\n\
                 exit /b 0\n",
                cascade_cli
            )
        }

        #[cfg(not(windows))]
        {
            // Use string building to avoid escaping issues with format! macros
            // Check the OUTPUT of entry status, not just exit code
            let status_check = format!(
                "EDIT_STATUS=$(\"{}\" entry status --quiet 2>/dev/null || echo \"inactive\")",
                cascade_cli
            );
            // When called from pre-commit hook during 'git commit', changes are already staged
            // So we DON'T use --all flag, just amend with what's staged
            let amend_line = format!("           \"{}\" entry amend --restack", cascade_cli);

            vec![
                "#!/bin/sh".to_string(),
                "# Cascade CLI Hook - Pre Commit".to_string(),
                "# Smart edit mode guidance for better UX".to_string(),
                "".to_string(),
                "set -e".to_string(),
                "".to_string(),
                "# Check if Cascade is initialized".to_string(),
                r#"REPO_ROOT=$(git rev-parse --show-toplevel 2>/dev/null || echo ".")"#.to_string(),
                r#"if [ ! -d "$REPO_ROOT/.cascade" ]; then"#.to_string(),
                "    exit 0".to_string(),
                "fi".to_string(),
                "".to_string(),
                "# Skip hook if called from ca entry amend (avoid infinite loop)".to_string(),
                r#"if [ "$CASCADE_SKIP_HOOKS" = "1" ]; then"#.to_string(),
                "    exit 0".to_string(),
                "fi".to_string(),
                "".to_string(),
                "# Skip hook during cherry-pick/rebase/merge operations".to_string(),
                r#"GIT_DIR=$(git rev-parse --git-dir 2>/dev/null || echo ".git")"#.to_string(),
                r#"if [ -f "$GIT_DIR/CHERRY_PICK_HEAD" ] || [ -f "$GIT_DIR/REBASE_HEAD" ] || [ -f "$GIT_DIR/MERGE_HEAD" ]; then"#.to_string(),
                "    exit 0".to_string(),
                "fi".to_string(),
                "".to_string(),
                "# Check if we're in edit mode".to_string(),
                r#"CURRENT_BRANCH=$(git branch --show-current 2>/dev/null)"#.to_string(),
                status_check,
                "".to_string(),
                "# If in edit mode, check if we're on a stack entry branch".to_string(),
                r#"if echo "$EDIT_STATUS" | grep -q "^active:"; then"#.to_string(),
                "        # Check if current branch is a stack entry branch".to_string(),
                format!(r#"        if ! "{}" stacks list --format=json 2>/dev/null | grep -q "\"branch_name\": \"$CURRENT_BRANCH\""; then"#, cascade_cli),
                r#"                # Not on a stack entry branch - edit mode is for a different branch"#.to_string(),
                r#"                # Silently proceed with normal commit"#.to_string(),
                "                exit 0".to_string(),
                "        fi".to_string(),
                "        ".to_string(),
                "        # Proper edit mode - prompt user".to_string(),
                r#"        echo "You're in EDIT MODE for a stack entry""#.to_string(),
                r#"        echo """#.to_string(),
                r#"        echo "Choose your action:""#.to_string(),
                r#"        echo "  [a] amend: Modify the current entry (default)""#.to_string(),
                r#"        echo "  [n] new:   Create new entry on top""#.to_string(),
                r#"        echo "  [c] cancel: Stop and think about it""#.to_string(),
                r#"        echo """#.to_string(),
                "        ".to_string(),
                "        # Read user choice with default to amend".to_string(),
                r#"        read -p "Your choice (a/n/c): " choice < /dev/tty"#.to_string(),
                "        choice=${choice:-a}".to_string(),
                "        ".to_string(),
                "        ".to_string(),
                r#"        case "$choice" in"#.to_string(),
                "            [Aa])".to_string(),
                "                # Use ca entry amend to properly update entry + working branch (ignore any -m flag)"
                    .to_string(),
                "                # Changes are already staged by 'git commit', so no --all flag needed".to_string(),
                amend_line.replace("           ", "                "),
                "                amend_rc=$?".to_string(),
                r#"                if [ $amend_rc -eq 0 ]; then"#.to_string(),
                r#"                    echo "Amend applied - skipping git commit to avoid duplicate entry.""#
                    .to_string(),
                r#"                    echo "Your commit was updated by Cascade; no further action needed.""#
                    .to_string(),
                "                    exit 1".to_string(),
                "                else".to_string(),
                "                    exit $amend_rc".to_string(),
                "                fi".to_string(),
                "                ;;".to_string(),
                "            [Nn])".to_string(),
                r#"                echo "Creating new stack entry...""#.to_string(),
                r#"                echo "The commit will proceed and post-commit hook will add it to your stack""#.to_string(),
                "                # Let the commit proceed normally (Git will use -m flag or open editor)"
                    .to_string(),
                "                exit 0".to_string(),
                "                ;;".to_string(),
                "            [Cc])".to_string(),
                r#"                echo "Commit cancelled""#.to_string(),
                "                exit 1".to_string(),
                "                ;;".to_string(),
                "            *)".to_string(),
                r#"                echo "Invalid choice. Please choose A, n, or c""#.to_string(),
                "                exit 1".to_string(),
                "                ;;".to_string(),
                "        esac".to_string(),
                "fi".to_string(),
                "".to_string(),
                "# Not in edit mode, proceed normally".to_string(),
                "exit 0".to_string(),
            ]
            .join("\n")
        }
    }

    fn generate_prepare_commit_msg_hook(&self, cascade_cli: &str) -> String {
        #[cfg(windows)]
        {
            format!(
                "@echo off\n\
                 rem Cascade CLI Hook - Prepare Commit Message\n\
                 rem Adds stack context to commit messages\n\n\
                 set COMMIT_MSG_FILE=%1\n\
                 set COMMIT_SOURCE=%2\n\
                 set COMMIT_SHA=%3\n\n\
                 rem Skip if user provided message via -m flag, merge commit, etc.\n\
                 if not \"%COMMIT_SOURCE%\"==\"\" exit /b 0\n\n\
                 rem Find repository root and check if Cascade is initialized\n\
                 for /f \"tokens=*\" %%i in ('git rev-parse --show-toplevel 2^>nul') do set REPO_ROOT=%%i\n\
                 if \"%REPO_ROOT%\"==\"\" set REPO_ROOT=.\n\
                 if not exist \"%REPO_ROOT%\\.cascade\" exit /b 0\n\n\
                 rem Check for active stack\n\
                 for /f \"tokens=*\" %%i in ('\"{cascade_cli}\" stack list --active --format=name 2^>nul') do set ACTIVE_STACK=%%i\n\n\
                 if not \"%ACTIVE_STACK%\"==\"\" (\n\
                     rem Get current commit message\n\
                     set /p CURRENT_MSG=<%COMMIT_MSG_FILE%\n\n\
                     rem Skip if message already has stack context\n\
                     echo !CURRENT_MSG! | findstr \"[stack:\" >nul\n\
                     if %ERRORLEVEL% equ 0 exit /b 0\n\n\
                     rem Add stack context to commit message\n\
                     echo.\n\
                     echo # Stack: %ACTIVE_STACK%\n\
                     echo # This commit will be added to the active stack automatically.\n\
                     echo # Use 'ca stack status' to see the current stack state.\n\
                     type \"%COMMIT_MSG_FILE%\"\n\
                 ) > \"%COMMIT_MSG_FILE%.tmp\"\n\
                 move \"%COMMIT_MSG_FILE%.tmp\" \"%COMMIT_MSG_FILE%\"\n"
            )
        }

        #[cfg(not(windows))]
        {
            format!(
                "#!/bin/sh\n\
                 # Cascade CLI Hook - Prepare Commit Message\n\
                 # Adds stack context to commit messages\n\n\
                 set -e\n\n\
                 COMMIT_MSG_FILE=\"$1\"\n\
                 COMMIT_SOURCE=\"$2\"\n\
                 COMMIT_SHA=\"$3\"\n\n\
                 # Skip if user provided message via -m flag, merge commit, etc.\n\
                 if [ \"$COMMIT_SOURCE\" != \"\" ]; then\n\
                     exit 0\n\
                 fi\n\n\
                 # Find repository root and check if Cascade is initialized\n\
                 REPO_ROOT=$(git rev-parse --show-toplevel 2>/dev/null || echo \".\")\n\
                 if [ ! -d \"$REPO_ROOT/.cascade\" ]; then\n\
                     exit 0\n\
                 fi\n\n\
                 # Check for active stack\n\
                 ACTIVE_STACK=$(\"{cascade_cli}\" stack list --active --format=name 2>/dev/null || echo \"\")\n\
                 \n\
                 if [ -n \"$ACTIVE_STACK\" ]; then\n\
                     # Get current commit message\n\
                     CURRENT_MSG=$(cat \"$COMMIT_MSG_FILE\")\n\
                     \n\
                     # Skip if message already has stack context\n\
                     if echo \"$CURRENT_MSG\" | grep -q \"\\[stack:\"; then\n\
                         exit 0\n\
                     fi\n\
                     \n\
                     # Add stack context to commit message\n\
                     echo \"\n\
                 # Stack: $ACTIVE_STACK\n\
                 # This commit will be added to the active stack automatically.\n\
                 # Use 'ca stack status' to see the current stack state.\n\
                 $CURRENT_MSG\" > \"$COMMIT_MSG_FILE\"\n\
                 fi\n"
            )
        }
    }

    /// Detect repository type from remote URLs
    pub fn detect_repository_type(&self) -> Result<RepositoryType> {
        let output = Command::new("git")
            .args(["remote", "get-url", "origin"])
            .current_dir(&self.repo_path)
            .output()
            .map_err(|e| CascadeError::config(format!("Failed to get remote URL: {e}")))?;

        if !output.status.success() {
            return Ok(RepositoryType::Unknown);
        }

        let remote_url = String::from_utf8_lossy(&output.stdout)
            .trim()
            .to_lowercase();

        if remote_url.contains("github.com") {
            Ok(RepositoryType::GitHub)
        } else if remote_url.contains("gitlab.com") || remote_url.contains("gitlab") {
            Ok(RepositoryType::GitLab)
        } else if remote_url.contains("dev.azure.com") || remote_url.contains("visualstudio.com") {
            Ok(RepositoryType::AzureDevOps)
        } else if remote_url.contains("bitbucket") {
            Ok(RepositoryType::Bitbucket)
        } else {
            Ok(RepositoryType::Unknown)
        }
    }

    /// Detect current branch type
    pub fn detect_branch_type(&self) -> Result<BranchType> {
        let output = Command::new("git")
            .args(["branch", "--show-current"])
            .current_dir(&self.repo_path)
            .output()
            .map_err(|e| CascadeError::config(format!("Failed to get current branch: {e}")))?;

        if !output.status.success() {
            return Ok(BranchType::Unknown);
        }

        let branch_name = String::from_utf8_lossy(&output.stdout)
            .trim()
            .to_lowercase();

        if branch_name == "main" || branch_name == "master" || branch_name == "develop" {
            Ok(BranchType::Main)
        } else if !branch_name.is_empty() {
            Ok(BranchType::Feature)
        } else {
            Ok(BranchType::Unknown)
        }
    }

    /// Validate prerequisites for hook installation
    pub fn validate_prerequisites(&self) -> Result<()> {
        Output::check_start("Checking prerequisites for Cascade hooks");

        // 1. Check repository type
        let repo_type = self.detect_repository_type()?;
        match repo_type {
            RepositoryType::Bitbucket => {
                Output::success("Bitbucket repository detected");
                Output::tip("Hooks will work great with 'ca submit' and 'ca autoland' for Bitbucket integration");
            }
            RepositoryType::GitHub => {
                Output::success("GitHub repository detected");
                Output::tip("Consider setting up GitHub Actions for CI/CD integration");
            }
            RepositoryType::GitLab => {
                Output::success("GitLab repository detected");
                Output::tip("GitLab CI integration works well with Cascade stacks");
            }
            RepositoryType::AzureDevOps => {
                Output::success("Azure DevOps repository detected");
                Output::tip("Azure Pipelines can be configured to work with Cascade workflows");
            }
            RepositoryType::Unknown => {
                Output::info(
                    "Unknown repository type - hooks will still work for local Git operations",
                );
            }
        }

        // 2. Check Cascade configuration
        let config_dir = crate::config::get_repo_config_dir(&self.repo_path)?;
        let config_path = config_dir.join("config.json");
        if !config_path.exists() {
            return Err(CascadeError::config(
                "🚫 Cascade not initialized!\n\n\
                Please run 'ca init' or 'ca setup' first to configure Cascade CLI.\n\
                Hooks require proper Bitbucket Server configuration.\n\n\
                Use --force to install anyway (not recommended)."
                    .to_string(),
            ));
        }

        // 3. Validate Bitbucket configuration
        let config = Settings::load_from_file(&config_path)?;

        if config.bitbucket.url == "https://bitbucket.example.com"
            || config.bitbucket.url.contains("example.com")
        {
            return Err(CascadeError::config(
                "🚫 Invalid Bitbucket configuration!\n\n\
                Your Bitbucket URL appears to be a placeholder.\n\
                Please run 'ca setup' to configure a real Bitbucket Server.\n\n\
                Use --force to install anyway (not recommended)."
                    .to_string(),
            ));
        }

        if config.bitbucket.project == "PROJECT" || config.bitbucket.repo == "repo" {
            return Err(CascadeError::config(
                "🚫 Incomplete Bitbucket configuration!\n\n\
                Your project/repository settings appear to be placeholders.\n\
                Please run 'ca setup' to complete configuration.\n\n\
                Use --force to install anyway (not recommended)."
                    .to_string(),
            ));
        }

        Output::success("Prerequisites validation passed");
        Ok(())
    }

    /// Validate branch suitability for hooks
    pub fn validate_branch_suitability(&self) -> Result<()> {
        let branch_type = self.detect_branch_type()?;

        match branch_type {
            BranchType::Main => {
                return Err(CascadeError::config(
                    "🚫 Currently on main/master branch!\n\n\
                    Cascade hooks are designed for feature branch development.\n\
                    Working directly on main/master with stacked diffs can:\n\
                    • Complicate the commit history\n\
                    • Interfere with team collaboration\n\
                    • Break CI/CD workflows\n\n\
                    Recommended workflow:\n\
                    1. Create a feature branch: git checkout -b feature/my-feature\n\
                    2. Install hooks: ca hooks install\n\
                    3. Develop with stacked commits (auto-added with hooks)\n\
                    4. Push & submit: ca push && ca submit (all by default)\n\
                    5. Auto-land when ready: ca autoland\n\n\
                    Use --force to install anyway (not recommended)."
                        .to_string(),
                ));
            }
            BranchType::Feature => {
                Output::success("Feature branch detected - suitable for stacked development");
            }
            BranchType::Unknown => {
                Output::warning("Unknown branch type - proceeding with caution");
            }
        }

        Ok(())
    }

    /// Confirm installation with user
    pub fn confirm_installation(&self) -> Result<()> {
        Output::section("Hook Installation Summary");

        let hooks = vec![
            HookType::PostCommit,
            HookType::PrePush,
            HookType::CommitMsg,
            HookType::PrepareCommitMsg,
        ];

        for hook in &hooks {
            Output::sub_item(format!("{}: {}", hook.filename(), hook.description()));
        }

        println!();
        Output::section("These hooks will automatically");
        Output::bullet("Add commits to your active stack");
        Output::bullet("Validate commit messages");
        Output::bullet("Prevent force pushes that break stack integrity");
        Output::bullet("Add stack context to commit messages");

        println!();
        Output::section("With hooks + new defaults, your workflow becomes");
        Output::sub_item("git commit       → Auto-added to stack");
        Output::sub_item("ca push          → Pushes all by default");
        Output::sub_item("ca submit        → Submits all by default");
        Output::sub_item("ca autoland      → Auto-merges when ready");

        // Interactive confirmation to proceed with installation
        let should_install = Confirm::with_theme(&ColorfulTheme::default())
            .with_prompt("Install Cascade hooks?")
            .default(true)
            .interact()
            .map_err(|e| CascadeError::config(format!("Failed to get user confirmation: {e}")))?;

        if should_install {
            Output::success("Proceeding with installation");
            Ok(())
        } else {
            Err(CascadeError::config(
                "Installation cancelled by user".to_string(),
            ))
        }
    }
}

/// Run hooks management commands
pub async fn install() -> Result<()> {
    install_with_options(false, false, false, false).await
}

pub async fn install_essential() -> Result<()> {
    let current_dir = env::current_dir()
        .map_err(|e| CascadeError::config(format!("Could not get current directory: {e}")))?;

    let repo_root = find_repository_root(&current_dir)
        .map_err(|e| CascadeError::config(format!("Could not find git repository: {e}")))?;

    let hooks_manager = HooksManager::new(&repo_root)?;
    hooks_manager.install_essential()
}

pub async fn install_with_options(
    skip_checks: bool,
    allow_main_branch: bool,
    yes: bool,
    force: bool,
) -> Result<()> {
    let current_dir = env::current_dir()
        .map_err(|e| CascadeError::config(format!("Could not get current directory: {e}")))?;

    let repo_root = find_repository_root(&current_dir)
        .map_err(|e| CascadeError::config(format!("Could not find git repository: {e}")))?;

    let hooks_manager = HooksManager::new(&repo_root)?;

    let options = InstallOptions {
        check_prerequisites: !skip_checks,
        feature_branches_only: !allow_main_branch,
        confirm: !yes,
        force,
    };

    hooks_manager.install_with_options(&options)
}

pub async fn uninstall() -> Result<()> {
    let current_dir = env::current_dir()
        .map_err(|e| CascadeError::config(format!("Could not get current directory: {e}")))?;

    let repo_root = find_repository_root(&current_dir)
        .map_err(|e| CascadeError::config(format!("Could not find git repository: {e}")))?;

    let hooks_manager = HooksManager::new(&repo_root)?;
    hooks_manager.uninstall_all()
}

pub async fn status() -> Result<()> {
    let current_dir = env::current_dir()
        .map_err(|e| CascadeError::config(format!("Could not get current directory: {e}")))?;

    let repo_root = find_repository_root(&current_dir)
        .map_err(|e| CascadeError::config(format!("Could not find git repository: {e}")))?;

    let hooks_manager = HooksManager::new(&repo_root)?;
    hooks_manager.list_installed_hooks()
}

pub async fn install_hook(hook_name: &str) -> Result<()> {
    install_hook_with_options(hook_name, false, false).await
}

pub async fn install_hook_with_options(
    hook_name: &str,
    skip_checks: bool,
    force: bool,
) -> Result<()> {
    let current_dir = env::current_dir()
        .map_err(|e| CascadeError::config(format!("Could not get current directory: {e}")))?;

    let repo_root = find_repository_root(&current_dir)
        .map_err(|e| CascadeError::config(format!("Could not find git repository: {e}")))?;

    let hooks_manager = HooksManager::new(&repo_root)?;

    let hook_type = match hook_name {
        "post-commit" => HookType::PostCommit,
        "pre-push" => HookType::PrePush,
        "commit-msg" => HookType::CommitMsg,
        "pre-commit" => HookType::PreCommit,
        "prepare-commit-msg" => HookType::PrepareCommitMsg,
        _ => {
            return Err(CascadeError::config(format!(
                "Unknown hook type: {hook_name}"
            )))
        }
    };

    // Run basic validation if not skipped
    if !skip_checks && !force {
        hooks_manager.validate_prerequisites()?;
    }

    hooks_manager.install_hook(&hook_type)
}

pub async fn uninstall_hook(hook_name: &str) -> Result<()> {
    let current_dir = env::current_dir()
        .map_err(|e| CascadeError::config(format!("Could not get current directory: {e}")))?;

    let repo_root = find_repository_root(&current_dir)
        .map_err(|e| CascadeError::config(format!("Could not find git repository: {e}")))?;

    let hooks_manager = HooksManager::new(&repo_root)?;

    let hook_type = match hook_name {
        "post-commit" => HookType::PostCommit,
        "pre-push" => HookType::PrePush,
        "commit-msg" => HookType::CommitMsg,
        "pre-commit" => HookType::PreCommit,
        "prepare-commit-msg" => HookType::PrepareCommitMsg,
        _ => {
            return Err(CascadeError::config(format!(
                "Unknown hook type: {hook_name}"
            )))
        }
    };

    hooks_manager.uninstall_hook(&hook_type)
}

#[cfg(test)]
mod tests {
    use super::*;
    use std::process::Command;
    use tempfile::TempDir;

    fn create_test_repo() -> (TempDir, std::path::PathBuf) {
        let temp_dir = TempDir::new().unwrap();
        let repo_path = temp_dir.path().to_path_buf();

        // Initialize git repository
        Command::new("git")
            .args(["init"])
            .current_dir(&repo_path)
            .output()
            .unwrap();
        Command::new("git")
            .args(["config", "user.name", "Test"])
            .current_dir(&repo_path)
            .output()
            .unwrap();
        Command::new("git")
            .args(["config", "user.email", "test@test.com"])
            .current_dir(&repo_path)
            .output()
            .unwrap();

        // Create initial commit
        std::fs::write(repo_path.join("README.md"), "# Test").unwrap();
        Command::new("git")
            .args(["add", "."])
            .current_dir(&repo_path)
            .output()
            .unwrap();
        Command::new("git")
            .args(["commit", "-m", "Initial"])
            .current_dir(&repo_path)
            .output()
            .unwrap();

        // Initialize cascade
        crate::config::initialize_repo(&repo_path, Some("https://test.bitbucket.com".to_string()))
            .unwrap();

        (temp_dir, repo_path)
    }

    #[test]
    fn test_hooks_manager_creation() {
        let (_temp_dir, repo_path) = create_test_repo();
        let _manager = HooksManager::new(&repo_path).unwrap();

        assert_eq!(_manager.repo_path, repo_path);
        // Should create a HooksManager successfully
        assert!(!_manager.repo_id.is_empty());
    }

    #[test]
    fn test_hooks_manager_custom_hooks_path() {
        let (_temp_dir, repo_path) = create_test_repo();

        // Set custom hooks path
        Command::new("git")
            .args(["config", "core.hooksPath", "custom-hooks"])
            .current_dir(&repo_path)
            .output()
            .unwrap();

        // Create the custom hooks directory
        let custom_hooks_dir = repo_path.join("custom-hooks");
        std::fs::create_dir_all(&custom_hooks_dir).unwrap();

        let _manager = HooksManager::new(&repo_path).unwrap();

        assert_eq!(_manager.repo_path, repo_path);
        // Should create a HooksManager successfully
        assert!(!_manager.repo_id.is_empty());
    }

    #[test]
    fn test_hook_chaining_with_existing_hooks() {
        let (_temp_dir, repo_path) = create_test_repo();
        let manager = HooksManager::new(&repo_path).unwrap();

        let hook_type = HookType::PreCommit;
        let hook_path = repo_path.join(".git/hooks").join(hook_type.filename());

        // Create an existing project hook
        let existing_hook_content = "#!/bin/bash\n# Project pre-commit hook\n./scripts/lint.sh\n";
        std::fs::write(&hook_path, existing_hook_content).unwrap();
        crate::utils::platform::make_executable(&hook_path).unwrap();

        // Install cascade hook (uses core.hooksPath, doesn't modify original)
        let result = manager.install_hook(&hook_type);
        assert!(result.is_ok());

        // Original hook should remain unchanged
        let original_content = std::fs::read_to_string(&hook_path).unwrap();
        assert!(original_content.contains("# Project pre-commit hook"));
        assert!(original_content.contains("./scripts/lint.sh"));

        // Cascade hook should exist in cascade directory
        let cascade_hooks_dir = manager.get_cascade_hooks_dir().unwrap();
        let cascade_hook_path = cascade_hooks_dir.join(hook_type.filename());
        assert!(cascade_hook_path.exists());

        // Test uninstall removes cascade hooks but leaves original
        let uninstall_result = manager.uninstall_hook(&hook_type);
        assert!(uninstall_result.is_ok());

        // Original hook should still exist and be unchanged
        let after_uninstall = std::fs::read_to_string(&hook_path).unwrap();
        assert!(after_uninstall.contains("# Project pre-commit hook"));
        assert!(after_uninstall.contains("./scripts/lint.sh"));

        // Cascade hook should be removed
        assert!(!cascade_hook_path.exists());
    }

    #[test]
    fn test_hook_installation() {
        let (_temp_dir, repo_path) = create_test_repo();
        let manager = HooksManager::new(&repo_path).unwrap();

        // Test installing post-commit hook
        let hook_type = HookType::PostCommit;
        let result = manager.install_hook(&hook_type);
        assert!(result.is_ok());

        // Verify hook file exists in cascade hooks directory
        let hook_filename = hook_type.filename();
        let cascade_hooks_dir = manager.get_cascade_hooks_dir().unwrap();
        let hook_path = cascade_hooks_dir.join(&hook_filename);
        assert!(hook_path.exists());

        // Verify hook is executable (platform-specific)
        #[cfg(unix)]
        {
            use std::os::unix::fs::PermissionsExt;
            let metadata = std::fs::metadata(&hook_path).unwrap();
            let permissions = metadata.permissions();
            assert!(permissions.mode() & 0o111 != 0); // Check executable bit
        }

        #[cfg(windows)]
        {
            // On Windows, verify it has .bat extension and file exists
            assert!(hook_filename.ends_with(".bat"));
            assert!(hook_path.exists());
        }
    }

    #[test]
    fn test_hook_detection() {
        let (_temp_dir, repo_path) = create_test_repo();
        let _manager = HooksManager::new(&repo_path).unwrap();

        // Check if hook files exist with platform-appropriate filenames
        let post_commit_path = repo_path
            .join(".git/hooks")
            .join(HookType::PostCommit.filename());
        let pre_push_path = repo_path
            .join(".git/hooks")
            .join(HookType::PrePush.filename());
        let commit_msg_path = repo_path
            .join(".git/hooks")
            .join(HookType::CommitMsg.filename());

        // Initially no hooks should be installed
        assert!(!post_commit_path.exists());
        assert!(!pre_push_path.exists());
        assert!(!commit_msg_path.exists());
    }

    #[test]
    fn test_hook_validation() {
        let (_temp_dir, repo_path) = create_test_repo();
        let manager = HooksManager::new(&repo_path).unwrap();

        // Test validation - may fail in CI due to missing dependencies
        let validation = manager.validate_prerequisites();
        // In CI environment, validation might fail due to missing configuration
        // Just ensure it doesn't panic
        let _ = validation; // Don't assert ok/err, just ensure no panic

        // Test branch validation - should work regardless of environment
        let branch_validation = manager.validate_branch_suitability();
        // Branch validation should work in most cases, but be tolerant
        let _ = branch_validation; // Don't assert ok/err, just ensure no panic
    }

    #[test]
    fn test_hook_uninstallation() {
        let (_temp_dir, repo_path) = create_test_repo();
        let manager = HooksManager::new(&repo_path).unwrap();

        // Install then uninstall hook
        let hook_type = HookType::PostCommit;
        manager.install_hook(&hook_type).unwrap();

        let cascade_hooks_dir = manager.get_cascade_hooks_dir().unwrap();
        let hook_path = cascade_hooks_dir.join(hook_type.filename());
        assert!(hook_path.exists());

        let result = manager.uninstall_hook(&hook_type);
        assert!(result.is_ok());
        assert!(!hook_path.exists());
    }

    #[test]
    fn test_hook_content_generation() {
        let (_temp_dir, repo_path) = create_test_repo();
        let manager = HooksManager::new(&repo_path).unwrap();

        // Use a known binary name for testing
        let binary_name = "cascade-cli";

        // Test post-commit hook generation
        let post_commit_content = manager.generate_post_commit_hook(binary_name);
        #[cfg(windows)]
        {
            assert!(post_commit_content.contains("@echo off"));
            assert!(post_commit_content.contains("rem Cascade CLI Hook"));
        }
        #[cfg(not(windows))]
        {
            assert!(post_commit_content.contains("#!/bin/sh"));
            assert!(post_commit_content.contains("# Cascade CLI Hook"));
        }
        assert!(post_commit_content.contains(binary_name));

        // Test pre-push hook generation
        let pre_push_content = manager.generate_pre_push_hook(binary_name);
        #[cfg(windows)]
        {
            assert!(pre_push_content.contains("@echo off"));
            assert!(pre_push_content.contains("rem Cascade CLI Hook"));
        }
        #[cfg(not(windows))]
        {
            assert!(pre_push_content.contains("#!/bin/sh"));
            assert!(pre_push_content.contains("# Cascade CLI Hook"));
        }
        assert!(pre_push_content.contains(binary_name));

        // Test commit-msg hook generation (doesn't use binary, just validates)
        let commit_msg_content = manager.generate_commit_msg_hook(binary_name);
        #[cfg(windows)]
        {
            assert!(commit_msg_content.contains("@echo off"));
            assert!(commit_msg_content.contains("rem Cascade CLI Hook"));
        }
        #[cfg(not(windows))]
        {
            assert!(commit_msg_content.contains("#!/bin/sh"));
            assert!(commit_msg_content.contains("# Cascade CLI Hook"));
        }

        // Test prepare-commit-msg hook generation (does use binary)
        let prepare_commit_content = manager.generate_prepare_commit_msg_hook(binary_name);
        #[cfg(windows)]
        {
            assert!(prepare_commit_content.contains("@echo off"));
            assert!(prepare_commit_content.contains("rem Cascade CLI Hook"));
        }
        #[cfg(not(windows))]
        {
            assert!(prepare_commit_content.contains("#!/bin/sh"));
            assert!(prepare_commit_content.contains("# Cascade CLI Hook"));
        }
        assert!(prepare_commit_content.contains(binary_name));
    }

    #[test]
    fn test_hook_status_reporting() {
        let (_temp_dir, repo_path) = create_test_repo();
        let manager = HooksManager::new(&repo_path).unwrap();

        // Check repository type detection - should work with our test setup
        let repo_type = manager.detect_repository_type().unwrap();
        // In CI environment, this might be Unknown if remote detection fails
        assert!(matches!(
            repo_type,
            RepositoryType::Bitbucket | RepositoryType::Unknown
        ));

        // Check branch type detection
        let branch_type = manager.detect_branch_type().unwrap();
        // Should be on main/master branch, but allow for different default branch names
        assert!(matches!(
            branch_type,
            BranchType::Main | BranchType::Unknown
        ));
    }

    #[test]
    fn test_force_installation() {
        let (_temp_dir, repo_path) = create_test_repo();
        let manager = HooksManager::new(&repo_path).unwrap();

        // Create a fake existing hook with platform-appropriate content
        let hook_filename = HookType::PostCommit.filename();
        let hook_path = repo_path.join(".git/hooks").join(&hook_filename);

        #[cfg(windows)]
        let existing_content = "@echo off\necho existing hook";
        #[cfg(not(windows))]
        let existing_content = "#!/bin/sh\necho 'existing hook'";

        std::fs::write(&hook_path, existing_content).unwrap();

        // Install cascade hook (uses core.hooksPath, doesn't modify original)
        let hook_type = HookType::PostCommit;
        let result = manager.install_hook(&hook_type);
        assert!(result.is_ok());

        // Verify cascade hook exists in cascade directory
        let cascade_hooks_dir = manager.get_cascade_hooks_dir().unwrap();
        let cascade_hook_path = cascade_hooks_dir.join(&hook_filename);
        assert!(cascade_hook_path.exists());

        // Original hook should remain unchanged
        let original_content = std::fs::read_to_string(&hook_path).unwrap();
        assert!(original_content.contains("existing hook"));

        // Cascade hook should contain cascade logic
        let cascade_content = std::fs::read_to_string(&cascade_hook_path).unwrap();
        assert!(cascade_content.contains("cascade-cli") || cascade_content.contains("ca"));
    }
}