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
1940
1941
1942
1943
1944
1945
1946
1947
1948
1949
1950
1951
1952
1953
1954
1955
1956
1957
1958
1959
1960
1961
1962
1963
1964
1965
1966
1967
1968
1969
1970
1971
1972
1973
1974
1975
1976
1977
1978
1979
1980
1981
1982
1983
1984
1985
1986
1987
1988
1989
1990
1991
1992
1993
1994
1995
1996
1997
1998
1999
2000
2001
2002
2003
2004
2005
2006
2007
2008
2009
2010
2011
2012
2013
2014
2015
2016
2017
2018
2019
2020
2021
2022
2023
2024
2025
2026
2027
2028
2029
use super::metadata::RepositoryMetadata;
use super::{CommitMetadata, Stack, StackEntry, StackMetadata, StackStatus};
use crate::cli::output::Output;
use crate::config::{get_repo_config_dir, Settings};
use crate::errors::{CascadeError, Result};
use crate::git::GitRepository;
use chrono::Utc;
use dialoguer::{theme::ColorfulTheme, Select};
use std::collections::HashMap;
use std::fs;
use std::path::{Path, PathBuf};
use tracing::{debug, warn};
use uuid::Uuid;

/// Types of branch modifications detected during Git integrity checks
#[derive(Debug)]
pub enum BranchModification {
    /// Branch is missing (needs to be created)
    Missing {
        branch: String,
        entry_id: Uuid,
        expected_commit: String,
    },
    /// Branch has extra commits beyond what's expected
    ExtraCommits {
        branch: String,
        entry_id: Uuid,
        expected_commit: String,
        actual_commit: String,
        extra_commit_count: usize,
        extra_commit_messages: Vec<String>,
    },
}

/// Manages all stack operations and persistence
pub struct StackManager {
    /// Git repository interface
    repo: GitRepository,
    /// Path to the repository root
    repo_path: PathBuf,
    /// Path to cascade config directory
    config_dir: PathBuf,
    /// Path to stacks data file
    stacks_file: PathBuf,
    /// Path to metadata file
    metadata_file: PathBuf,
    /// In-memory stack data
    stacks: HashMap<Uuid, Stack>,
    /// Repository metadata
    metadata: RepositoryMetadata,
}

impl StackManager {
    /// Create a new StackManager for the given repository
    pub fn new(repo_path: &Path) -> Result<Self> {
        let repo = GitRepository::open(repo_path)?;
        let config_dir = get_repo_config_dir(repo_path)?;
        let stacks_file = config_dir.join("stacks.json");
        let metadata_file = config_dir.join("metadata.json");

        // Load configuration to get the configured default branch
        let config_file = config_dir.join("config.json");
        let settings = Settings::load_from_file(&config_file).unwrap_or_default();
        let configured_default = &settings.git.default_branch;

        // Using configured default branch

        // Determine default base branch - use configured default if it exists
        let default_base = if repo.branch_exists(configured_default) {
            // Found configured default branch locally
            configured_default.clone()
        } else {
            // Fall back to detecting a suitable branch
            match repo.detect_main_branch() {
                Ok(detected) => {
                    // Configured default branch not found, using detected branch
                    detected
                }
                Err(_) => {
                    // Use configured default even if it doesn't exist yet (might be created later)
                    // Using configured default branch even though it doesn't exist locally
                    configured_default.clone()
                }
            }
        };

        let mut manager = Self {
            repo,
            repo_path: repo_path.to_path_buf(),
            config_dir,
            stacks_file,
            metadata_file,
            stacks: HashMap::new(),
            metadata: RepositoryMetadata::new(default_base),
        };

        // Load existing data if available
        manager.load_from_disk()?;

        Ok(manager)
    }

    /// Create a new stack
    pub fn create_stack(
        &mut self,
        name: String,
        base_branch: Option<String>,
        description: Option<String>,
    ) -> Result<Uuid> {
        // Check if stack with this name already exists
        if self.metadata.find_stack_by_name(&name).is_some() {
            return Err(CascadeError::config(format!(
                "Stack '{name}' already exists"
            )));
        }

        // Use provided base branch, or try to detect parent branch, or fall back to default
        let base_branch = base_branch.unwrap_or_else(|| {
            // Try to detect the parent branch of the current branch
            if let Ok(Some(detected_parent)) = self.repo.detect_parent_branch() {
                detected_parent
            } else {
                // Fall back to default base branch
                self.metadata.default_base_branch.clone()
            }
        });

        // Verify base branch exists (try to fetch from remote if not local)
        if !self.repo.branch_exists_or_fetch(&base_branch)? {
            return Err(CascadeError::branch(format!(
                "Base branch '{base_branch}' does not exist locally or remotely"
            )));
        }

        // Get current branch as the working branch
        let current_branch = self.repo.get_current_branch().ok();

        // Create the stack
        let mut stack = Stack::new(name.clone(), base_branch.clone(), description.clone());

        // Set working branch if we're on a feature branch (not on base branch)
        if let Some(ref branch) = current_branch {
            if branch != &base_branch {
                stack.working_branch = Some(branch.clone());
            }
        }

        let stack_id = stack.id;

        // Create metadata
        let stack_metadata = StackMetadata::new(stack_id, name, base_branch, description);

        // Store in memory
        self.stacks.insert(stack_id, stack);
        self.metadata.add_stack(stack_metadata);

        self.save_to_disk()?;

        Ok(stack_id)
    }

    /// Get a stack by ID
    pub fn get_stack(&self, stack_id: &Uuid) -> Option<&Stack> {
        self.stacks.get(stack_id)
    }

    /// Get a mutable stack by ID
    pub fn get_stack_mut(&mut self, stack_id: &Uuid) -> Option<&mut Stack> {
        self.stacks.get_mut(stack_id)
    }

    /// Get stack by name
    pub fn get_stack_by_name(&self, name: &str) -> Option<&Stack> {
        if let Some(metadata) = self.metadata.find_stack_by_name(name) {
            self.stacks.get(&metadata.stack_id)
        } else {
            None
        }
    }

    /// Get mutable stack by name
    pub fn get_stack_by_name_mut(&mut self, name: &str) -> Option<&mut Stack> {
        if let Some(metadata) = self.metadata.find_stack_by_name(name) {
            self.stacks.get_mut(&metadata.stack_id)
        } else {
            None
        }
    }

    /// Update working branch for a stack
    pub fn update_stack_working_branch(&mut self, name: &str, branch: String) -> Result<()> {
        if let Some(stack) = self.get_stack_by_name_mut(name) {
            stack.working_branch = Some(branch);
            self.save_to_disk()?;
            Ok(())
        } else {
            Err(CascadeError::config(format!("Stack '{name}' not found")))
        }
    }

    /// Find the stack ID that owns a given branch.
    /// Checks working_branch first, then entry branches.
    fn find_stack_id_for_branch(&self, branch: &str) -> Option<Uuid> {
        for stack in self.stacks.values() {
            if stack.working_branch.as_deref() == Some(branch) {
                return Some(stack.id);
            }
        }
        for stack in self.stacks.values() {
            for entry in &stack.entries {
                if entry.branch == branch {
                    return Some(stack.id);
                }
            }
        }
        None
    }

    /// Get the ID of the currently active stack (resolved from current branch).
    fn get_active_stack_id(&self) -> Option<Uuid> {
        let current_branch = self.repo.get_current_branch().ok()?;
        self.find_stack_id_for_branch(&current_branch)
    }

    /// Get the currently active stack (resolved from current branch)
    pub fn get_active_stack(&self) -> Option<&Stack> {
        let stack_id = self.get_active_stack_id()?;
        self.stacks.get(&stack_id)
    }

    /// Get the currently active stack mutably (resolved from current branch)
    pub fn get_active_stack_mut(&mut self) -> Option<&mut Stack> {
        let stack_id = self.get_active_stack_id()?;
        self.stacks.get_mut(&stack_id)
    }

    /// Checkout the branch associated with a stack, making it the active stack.
    pub fn checkout_stack_branch(&self, stack_id: &Uuid) -> Result<()> {
        let stack = self
            .stacks
            .get(stack_id)
            .ok_or_else(|| CascadeError::config(format!("Stack with ID {stack_id} not found")))?;

        let target_branch = stack
            .working_branch
            .as_deref()
            .or_else(|| stack.entries.last().map(|e| e.branch.as_str()))
            .ok_or_else(|| {
                CascadeError::config(format!(
                    "Stack '{}' has no working branch or entries",
                    stack.name
                ))
            })?
            .to_string();

        self.repo.checkout_branch(&target_branch)?;
        Ok(())
    }

    /// Delete a stack
    pub fn delete_stack(&mut self, stack_id: &Uuid) -> Result<Stack> {
        let stack = self
            .stacks
            .remove(stack_id)
            .ok_or_else(|| CascadeError::config(format!("Stack with ID {stack_id} not found")))?;

        // Remove metadata
        self.metadata.remove_stack(stack_id);

        // Remove all associated commit metadata
        let stack_commits: Vec<String> = self
            .metadata
            .commits
            .values()
            .filter(|commit| &commit.stack_id == stack_id)
            .map(|commit| commit.hash.clone())
            .collect();

        for commit_hash in stack_commits {
            self.metadata.remove_commit(&commit_hash);
        }

        self.save_to_disk()?;

        Ok(stack)
    }

    /// Push a commit to a stack
    pub fn push_to_stack(
        &mut self,
        branch: String,
        commit_hash: String,
        message: String,
        source_branch: String,
    ) -> Result<Uuid> {
        let stack_id = self.get_active_stack_id().ok_or_else(|| {
            CascadeError::config("No active stack (current branch doesn't belong to any stack)")
        })?;

        // 🆕 RECONCILE METADATA: Sync entry commit hashes with current branch HEADs before validation
        // This prevents false "branch modification" errors from stale metadata (e.g., after ca sync)
        let mut reconciled = false;
        {
            let stack = self
                .stacks
                .get_mut(&stack_id)
                .ok_or_else(|| CascadeError::config("Active stack not found"))?;

            if !stack.entries.is_empty() {
                // Collect updates first to avoid borrow checker issues
                let mut updates = Vec::new();
                for entry in &stack.entries {
                    if let Ok(current_commit) = self.repo.get_branch_head(&entry.branch) {
                        if entry.commit_hash != current_commit {
                            debug!(
                                "Reconciling stale metadata for '{}': updating hash from {} to {} (current branch HEAD)",
                                entry.branch,
                                &entry.commit_hash[..8],
                                &current_commit[..8]
                            );
                            updates.push((entry.id, current_commit));
                        }
                    }
                }

                // Apply updates using the safe wrapper function
                for (entry_id, new_hash) in updates {
                    stack
                        .update_entry_commit_hash(&entry_id, new_hash)
                        .map_err(CascadeError::config)?;
                    reconciled = true;
                }
            }
        } // End of reconciliation scope - stack borrow dropped here

        // Save reconciled metadata before validation
        if reconciled {
            debug!("Saving reconciled metadata before validation");
            self.save_to_disk()?;
        }

        // 🆕 VALIDATE GIT INTEGRITY BEFORE PUSHING (after reconciliation)
        let stack = self
            .stacks
            .get_mut(&stack_id)
            .ok_or_else(|| CascadeError::config("Active stack not found"))?;

        if !stack.entries.is_empty() {
            if let Err(integrity_error) = stack.validate_git_integrity(&self.repo) {
                return Err(CascadeError::validation(format!(
                    "Git integrity validation failed:\n{}\n\n\
                     Fix the stack integrity issues first using 'ca stack validate {}' for details.",
                    integrity_error, stack.name
                )));
            }
        }

        // Verify the commit exists
        if !self.repo.commit_exists(&commit_hash)? {
            return Err(CascadeError::branch(format!(
                "Commit {commit_hash} does not exist"
            )));
        }

        // Check for duplicate commit messages within the same stack
        // Trim both messages for comparison to handle trailing whitespace/newlines
        let message_trimmed = message.trim();
        if let Some(duplicate_entry) = stack
            .entries
            .iter()
            .find(|entry| entry.message.trim() == message_trimmed)
        {
            return Err(CascadeError::validation(format!(
                "Duplicate commit message in stack: \"{}\"\n\n\
                 This message already exists in entry {} (commit: {})\n\n\
                 💡 Consider using a more specific message:\n\
                    • Add context: \"{} - add validation\"\n\
                    • Be more specific: \"Fix user authentication timeout bug\"\n\
                    • Or amend the previous commit: git commit --amend",
                message_trimmed,
                duplicate_entry.id,
                &duplicate_entry.commit_hash[..8],
                message_trimmed
            )));
        }

        // 🎯 SMART BASE BRANCH UPDATE FOR FEATURE WORKFLOW
        // If this is the first commit in an empty stack, and the user is on a feature branch
        // that's different from the stack's base branch, update the base branch to match
        // the current workflow.
        if stack.entries.is_empty() {
            let current_branch = self.repo.get_current_branch()?;

            // Update working branch if not already set
            if stack.working_branch.is_none() && current_branch != stack.base_branch {
                stack.working_branch = Some(current_branch.clone());
                tracing::debug!(
                    "Set working branch for stack '{}' to '{}'",
                    stack.name,
                    current_branch
                );
            }

            if current_branch != stack.base_branch && current_branch != "HEAD" {
                // Check if current branch was created from the stack's base branch
                let base_exists = self.repo.branch_exists(&stack.base_branch);
                let current_is_feature = current_branch.starts_with("feature/")
                    || current_branch.starts_with("fix/")
                    || current_branch.starts_with("chore/")
                    || current_branch.contains("feature")
                    || current_branch.contains("fix");

                if base_exists && current_is_feature {
                    tracing::debug!(
                        "First commit detected: updating stack '{}' base branch from '{}' to '{}'",
                        stack.name,
                        stack.base_branch,
                        current_branch
                    );

                    Output::info("Smart Base Branch Update:");
                    Output::sub_item(format!(
                        "Stack '{}' was created with base '{}'",
                        stack.name, stack.base_branch
                    ));
                    Output::sub_item(format!(
                        "You're now working on feature branch '{current_branch}'"
                    ));
                    Output::sub_item("Updating stack base branch to match your workflow");

                    // Update the stack's base branch
                    stack.base_branch = current_branch.clone();

                    // Update metadata as well
                    if let Some(stack_meta) = self.metadata.get_stack_mut(&stack_id) {
                        stack_meta.base_branch = current_branch.clone();
                        stack_meta.set_current_branch(Some(current_branch.clone()));
                    }

                    println!(
                        "   ✅ Stack '{}' base branch updated to '{current_branch}'",
                        stack.name
                    );
                }
            }
        }

        // 🆕 CREATE ACTUAL GIT BRANCH from the specific commit
        // Check if branch already exists
        if self.repo.branch_exists(&branch) {
            // Branch already exists - update it to point to the new commit
            // This is critical: if we skip this, the branch points to the old commit
            // but metadata points to the new commit, causing stack corruption
            self.repo
                .update_branch_to_commit(&branch, &commit_hash)
                .map_err(|e| {
                    CascadeError::branch(format!(
                        "Failed to update existing branch '{}' to commit {}: {}",
                        branch,
                        &commit_hash[..8],
                        e
                    ))
                })?;
        } else {
            // Create the branch from the specific commit hash
            self.repo
                .create_branch(&branch, Some(&commit_hash))
                .map_err(|e| {
                    CascadeError::branch(format!(
                        "Failed to create branch '{}' from commit {}: {}",
                        branch,
                        &commit_hash[..8],
                        e
                    ))
                })?;

            // Branch creation succeeded - logging handled by caller
        }

        // Add to stack
        let entry_id = stack.push_entry(branch.clone(), commit_hash.clone(), message.clone());

        // Create commit metadata
        let commit_metadata = CommitMetadata::new(
            commit_hash.clone(),
            message,
            entry_id,
            stack_id,
            branch.clone(),
            source_branch,
        );

        // Update repository metadata
        self.metadata.add_commit(commit_metadata);
        if let Some(stack_meta) = self.metadata.get_stack_mut(&stack_id) {
            stack_meta.add_branch(branch);
            stack_meta.add_commit(commit_hash);
        }

        self.save_to_disk()?;

        Ok(entry_id)
    }

    /// Pop the top commit from the active stack
    pub fn pop_from_stack(&mut self) -> Result<StackEntry> {
        let stack_id = self.get_active_stack_id().ok_or_else(|| {
            CascadeError::config("No active stack (current branch doesn't belong to any stack)")
        })?;

        let stack = self
            .stacks
            .get_mut(&stack_id)
            .ok_or_else(|| CascadeError::config("Active stack not found"))?;

        let entry = stack
            .pop_entry()
            .ok_or_else(|| CascadeError::config("Stack is empty"))?;

        // Remove commit metadata
        self.metadata.remove_commit(&entry.commit_hash);

        // Update stack metadata
        if let Some(stack_meta) = self.metadata.get_stack_mut(&stack_id) {
            stack_meta.remove_commit(&entry.commit_hash);
            // Note: We don't remove the branch as there might be other commits on it
        }

        self.save_to_disk()?;

        Ok(entry)
    }

    /// Submit a stack entry for review (mark as submitted)
    pub fn submit_entry(
        &mut self,
        stack_id: &Uuid,
        entry_id: &Uuid,
        pull_request_id: String,
    ) -> Result<()> {
        let stack = self
            .stacks
            .get_mut(stack_id)
            .ok_or_else(|| CascadeError::config(format!("Stack {stack_id} not found")))?;

        let entry_commit_hash = {
            let entry = stack
                .get_entry(entry_id)
                .ok_or_else(|| CascadeError::config(format!("Entry {entry_id} not found")))?;
            entry.commit_hash.clone()
        };

        // Update stack entry
        if !stack.mark_entry_submitted(entry_id, pull_request_id.clone()) {
            return Err(CascadeError::config(format!(
                "Failed to mark entry {entry_id} as submitted"
            )));
        }

        // Update commit metadata
        if let Some(commit_meta) = self.metadata.commits.get_mut(&entry_commit_hash) {
            commit_meta.mark_submitted(pull_request_id);
        }

        // Update stack metadata statistics
        if let Some(stack_meta) = self.metadata.get_stack_mut(stack_id) {
            let submitted_count = stack.entries.iter().filter(|e| e.is_submitted).count();
            let merged_count = stack.entries.iter().filter(|e| e.is_merged).count();
            stack_meta.update_stats(stack.entries.len(), submitted_count, merged_count);
        }

        self.save_to_disk()?;

        Ok(())
    }

    /// Remove a stack entry and update metadata safely (used by cleanup flows)
    pub fn remove_stack_entry(
        &mut self,
        stack_id: &Uuid,
        entry_id: &Uuid,
    ) -> Result<Option<StackEntry>> {
        let stack = match self.stacks.get_mut(stack_id) {
            Some(stack) => stack,
            None => return Err(CascadeError::config(format!("Stack {stack_id} not found"))),
        };

        let entry = match stack.entry_map.get(entry_id) {
            Some(entry) => entry.clone(),
            None => return Ok(None),
        };

        if !entry.children.is_empty() {
            warn!(
                "Skipping removal of stack entry {} (branch '{}') because it still has {} child entr{}",
                entry.id,
                entry.branch,
                entry.children.len(),
                if entry.children.len() == 1 { "y" } else { "ies" }
            );
            return Ok(None);
        }

        // Remove entry from the ordered list
        stack.entries.retain(|e| e.id != entry.id);

        // Remove entry from lookup map
        stack.entry_map.remove(&entry.id);

        // Detach from parent so metadata stays accurate
        if let Some(parent_id) = entry.parent_id {
            if let Some(parent) = stack.entry_map.get_mut(&parent_id) {
                parent.children.retain(|child| child != &entry.id);
            }
        }

        // Sync entries vector from map to ensure consistency
        stack.repair_data_consistency();
        stack.updated_at = Utc::now();

        // Update repository metadata (commit + branch bookkeeping)
        self.metadata.remove_commit(&entry.commit_hash);
        if let Some(stack_meta) = self.metadata.get_stack_mut(stack_id) {
            stack_meta.remove_commit(&entry.commit_hash);
            stack_meta.remove_branch(&entry.branch);

            let submitted = stack.entries.iter().filter(|e| e.is_submitted).count();
            let merged = stack.entries.iter().filter(|e| e.is_merged).count();
            stack_meta.update_stats(stack.entries.len(), submitted, merged);
        }

        self.save_to_disk()?;

        Ok(Some(entry))
    }

    /// Remove a stack entry by 0-based index, reparenting children, and update metadata
    pub fn remove_stack_entry_at(
        &mut self,
        stack_id: &Uuid,
        index: usize,
    ) -> Result<Option<StackEntry>> {
        let stack = match self.stacks.get_mut(stack_id) {
            Some(stack) => stack,
            None => return Err(CascadeError::config(format!("Stack {stack_id} not found"))),
        };

        let entry = match stack.remove_entry_at(index) {
            Some(entry) => entry,
            None => return Ok(None),
        };

        // Update repository metadata (commit + branch bookkeeping)
        self.metadata.remove_commit(&entry.commit_hash);
        if let Some(stack_meta) = self.metadata.get_stack_mut(stack_id) {
            stack_meta.remove_commit(&entry.commit_hash);
            stack_meta.remove_branch(&entry.branch);

            let submitted = stack.entries.iter().filter(|e| e.is_submitted).count();
            let merged = stack.entries.iter().filter(|e| e.is_merged).count();
            stack_meta.update_stats(stack.entries.len(), submitted, merged);
        }

        self.save_to_disk()?;

        Ok(Some(entry))
    }

    /// Update merged state for a stack entry
    pub fn set_entry_merged(
        &mut self,
        stack_id: &Uuid,
        entry_id: &Uuid,
        merged: bool,
    ) -> Result<()> {
        let stack = self
            .stacks
            .get_mut(stack_id)
            .ok_or_else(|| CascadeError::config(format!("Stack {stack_id} not found")))?;

        let current_entry = stack
            .entry_map
            .get(entry_id)
            .cloned()
            .ok_or_else(|| CascadeError::config(format!("Entry {entry_id} not found")))?;

        if current_entry.is_merged == merged {
            return Ok(());
        }

        if !stack.mark_entry_merged(entry_id, merged) {
            return Err(CascadeError::config(format!(
                "Entry {entry_id} not found in stack {stack_id}"
            )));
        }

        // Update commit metadata using the stored commit hash
        if let Some(commit_meta) = self.metadata.commits.get_mut(&current_entry.commit_hash) {
            commit_meta.mark_merged(merged);
        }

        // Update stack metadata statistics
        if let Some(stack_meta) = self.metadata.get_stack_mut(stack_id) {
            let submitted_count = stack.entries.iter().filter(|e| e.is_submitted).count();
            let merged_count = stack.entries.iter().filter(|e| e.is_merged).count();
            stack_meta.update_stats(stack.entries.len(), submitted_count, merged_count);
        }

        self.save_to_disk()?;

        Ok(())
    }

    /// Repair data consistency issues in all stacks
    pub fn repair_all_stacks(&mut self) -> Result<()> {
        for stack in self.stacks.values_mut() {
            stack.repair_data_consistency();
        }
        self.save_to_disk()?;
        Ok(())
    }

    /// Get all stacks
    pub fn get_all_stacks(&self) -> Vec<&Stack> {
        self.stacks.values().collect()
    }

    /// Get stack metadata
    pub fn get_stack_metadata(&self, stack_id: &Uuid) -> Option<&StackMetadata> {
        self.metadata.get_stack(stack_id)
    }

    /// Get repository metadata
    pub fn get_repository_metadata(&self) -> &RepositoryMetadata {
        &self.metadata
    }

    /// Get the Git repository
    pub fn git_repo(&self) -> &GitRepository {
        &self.repo
    }

    /// Get the repository path
    pub fn repo_path(&self) -> &Path {
        &self.repo_path
    }

    // Edit mode management methods

    /// Check if currently in edit mode
    pub fn is_in_edit_mode(&self) -> bool {
        self.metadata
            .edit_mode
            .as_ref()
            .map(|edit_state| edit_state.is_active)
            .unwrap_or(false)
    }

    /// Get current edit mode information
    pub fn get_edit_mode_info(&self) -> Option<&super::metadata::EditModeState> {
        self.metadata.edit_mode.as_ref()
    }

    /// Enter edit mode for a specific stack entry
    pub fn enter_edit_mode(&mut self, stack_id: Uuid, entry_id: Uuid) -> Result<()> {
        // Get the commit hash first to avoid borrow checker issues
        let commit_hash = {
            let stack = self
                .get_stack(&stack_id)
                .ok_or_else(|| CascadeError::config(format!("Stack {stack_id} not found")))?;

            let entry = stack.get_entry(&entry_id).ok_or_else(|| {
                CascadeError::config(format!("Entry {entry_id} not found in stack"))
            })?;

            entry.commit_hash.clone()
        };

        // If already in edit mode, exit the current one first
        if self.is_in_edit_mode() {
            self.exit_edit_mode()?;
        }

        // Create new edit mode state
        let edit_state = super::metadata::EditModeState::new(stack_id, entry_id, commit_hash);

        self.metadata.edit_mode = Some(edit_state);
        self.save_to_disk()?;

        debug!(
            "Entered edit mode for entry {} in stack {}",
            entry_id, stack_id
        );
        Ok(())
    }

    /// Exit edit mode
    pub fn exit_edit_mode(&mut self) -> Result<()> {
        if !self.is_in_edit_mode() {
            return Err(CascadeError::config("Not currently in edit mode"));
        }

        // Clear edit mode state
        self.metadata.edit_mode = None;
        self.save_to_disk()?;

        debug!("Exited edit mode");
        Ok(())
    }

    /// Sync stack with Git repository state
    pub fn sync_stack(&mut self, stack_id: &Uuid) -> Result<()> {
        let stack = self
            .stacks
            .get_mut(stack_id)
            .ok_or_else(|| CascadeError::config(format!("Stack {stack_id} not found")))?;

        // 🆕 ENHANCED: Check Git integrity first (branch HEAD matches stored commits)
        if let Err(integrity_error) = stack.validate_git_integrity(&self.repo) {
            stack.update_status(StackStatus::Corrupted);
            return Err(CascadeError::branch(format!(
                "Stack '{}' Git integrity check failed:\n{}",
                stack.name, integrity_error
            )));
        }

        // Check if all commits still exist
        let mut missing_commits = Vec::new();
        for entry in &stack.entries {
            if !self.repo.commit_exists(&entry.commit_hash)? {
                missing_commits.push(entry.commit_hash.clone());
            }
        }

        if !missing_commits.is_empty() {
            stack.update_status(StackStatus::Corrupted);
            return Err(CascadeError::branch(format!(
                "Stack {} has missing commits: {}",
                stack.name,
                missing_commits.join(", ")
            )));
        }

        // Check if base branch exists and has new commits (try to fetch from remote if not local)
        if !self.repo.branch_exists_or_fetch(&stack.base_branch)? {
            return Err(CascadeError::branch(format!(
                "Base branch '{}' does not exist locally or remotely. Check the branch name or switch to a different base.",
                stack.base_branch
            )));
        }

        let _base_hash = self.repo.get_branch_head(&stack.base_branch)?;

        // Check if any stack entries are missing their commits
        let mut corrupted_entry = None;
        for entry in &stack.entries {
            if !self.repo.commit_exists(&entry.commit_hash)? {
                corrupted_entry = Some((entry.commit_hash.clone(), entry.branch.clone()));
                break;
            }
        }

        if let Some((commit_hash, branch)) = corrupted_entry {
            stack.update_status(StackStatus::Corrupted);
            return Err(CascadeError::branch(format!(
                "Commit {commit_hash} from stack entry '{branch}' no longer exists"
            )));
        }

        // Compare base branch with the earliest commit in the stack
        let needs_sync = if let Some(first_entry) = stack.entries.first() {
            // Get commits between base and first entry
            match self
                .repo
                .get_commits_between(&stack.base_branch, &first_entry.commit_hash)
            {
                Ok(commits) => !commits.is_empty(), // If there are commits, we need to sync
                Err(_) => true,                     // If we can't compare, assume we need to sync
            }
        } else {
            false // Empty stack is always clean
        };

        // Update stack status based on sync needs
        if needs_sync {
            stack.update_status(StackStatus::NeedsSync);
            debug!(
                "Stack '{}' needs sync - new commits on base branch",
                stack.name
            );
        } else {
            stack.update_status(StackStatus::Clean);
            debug!("Stack '{}' is clean", stack.name);
        }

        // Update metadata
        if let Some(stack_meta) = self.metadata.get_stack_mut(stack_id) {
            stack_meta.set_up_to_date(true);
        }

        self.save_to_disk()?;

        Ok(())
    }

    /// List all stacks with their status
    pub fn list_stacks(&self) -> Vec<(Uuid, &str, &StackStatus, usize, Option<&str>)> {
        let active_id = self.get_active_stack_id();
        self.stacks
            .values()
            .map(|stack| {
                (
                    stack.id,
                    stack.name.as_str(),
                    &stack.status,
                    stack.entries.len(),
                    if active_id == Some(stack.id) {
                        Some("active")
                    } else {
                        None
                    },
                )
            })
            .collect()
    }

    /// Get all stacks as Stack objects for TUI
    pub fn get_all_stacks_objects(&self) -> Result<Vec<Stack>> {
        let active_id = self.get_active_stack_id();
        let mut stacks: Vec<Stack> = self.stacks.values().cloned().collect();
        for stack in &mut stacks {
            stack.is_active = active_id == Some(stack.id);
        }
        stacks.sort_by(|a, b| a.name.cmp(&b.name));
        Ok(stacks)
    }

    /// Validate all stacks including Git integrity
    pub fn validate_all(&self) -> Result<()> {
        for stack in self.stacks.values() {
            // Basic structure validation
            stack.validate().map_err(|e| {
                CascadeError::config(format!("Stack '{}' validation failed: {}", stack.name, e))
            })?;

            // Git integrity validation
            stack.validate_git_integrity(&self.repo).map_err(|e| {
                CascadeError::config(format!(
                    "Stack '{}' Git integrity validation failed: {}",
                    stack.name, e
                ))
            })?;
        }
        Ok(())
    }

    /// Validate a specific stack including Git integrity
    pub fn validate_stack(&self, stack_id: &Uuid) -> Result<()> {
        let stack = self
            .stacks
            .get(stack_id)
            .ok_or_else(|| CascadeError::config(format!("Stack {stack_id} not found")))?;

        // Basic structure validation
        stack.validate().map_err(|e| {
            CascadeError::config(format!("Stack '{}' validation failed: {}", stack.name, e))
        })?;

        // Git integrity validation
        stack.validate_git_integrity(&self.repo).map_err(|e| {
            CascadeError::config(format!(
                "Stack '{}' Git integrity validation failed: {}",
                stack.name, e
            ))
        })?;

        Ok(())
    }

    /// Save all data to disk
    pub fn save_to_disk(&self) -> Result<()> {
        // Ensure config directory exists
        if !self.config_dir.exists() {
            fs::create_dir_all(&self.config_dir).map_err(|e| {
                CascadeError::config(format!("Failed to create config directory: {e}"))
            })?;
        }

        // Save stacks atomically
        crate::utils::atomic_file::write_json(&self.stacks_file, &self.stacks)?;

        // Save metadata atomically
        crate::utils::atomic_file::write_json(&self.metadata_file, &self.metadata)?;

        Ok(())
    }

    /// Load data from disk
    fn load_from_disk(&mut self) -> Result<()> {
        // Load stacks if file exists
        if self.stacks_file.exists() {
            let stacks_content = fs::read_to_string(&self.stacks_file)
                .map_err(|e| CascadeError::config(format!("Failed to read stacks file: {e}")))?;

            self.stacks = serde_json::from_str(&stacks_content)
                .map_err(|e| CascadeError::config(format!("Failed to parse stacks file: {e}")))?;
        }

        // Load metadata if file exists
        if self.metadata_file.exists() {
            let metadata_content = fs::read_to_string(&self.metadata_file)
                .map_err(|e| CascadeError::config(format!("Failed to read metadata file: {e}")))?;

            self.metadata = serde_json::from_str(&metadata_content)
                .map_err(|e| CascadeError::config(format!("Failed to parse metadata file: {e}")))?;
        }

        Ok(())
    }

    /// Handle Git integrity issues with multiple user-friendly options
    /// Provides non-destructive choices for dealing with branch modifications
    pub fn handle_branch_modifications(
        &mut self,
        stack_id: &Uuid,
        auto_mode: Option<String>,
    ) -> Result<()> {
        let stack = self
            .stacks
            .get_mut(stack_id)
            .ok_or_else(|| CascadeError::config(format!("Stack {stack_id} not found")))?;

        debug!("Checking Git integrity for stack '{}'", stack.name);

        // Detect all modifications
        let mut modifications = Vec::new();
        for entry in &stack.entries {
            if !self.repo.branch_exists(&entry.branch) {
                modifications.push(BranchModification::Missing {
                    branch: entry.branch.clone(),
                    entry_id: entry.id,
                    expected_commit: entry.commit_hash.clone(),
                });
            } else if let Ok(branch_head) = self.repo.get_branch_head(&entry.branch) {
                if branch_head != entry.commit_hash {
                    // Get extra commits and their messages
                    let extra_commits = self
                        .repo
                        .get_commits_between(&entry.commit_hash, &branch_head)?;
                    let mut extra_messages = Vec::new();
                    for commit in &extra_commits {
                        if let Some(message) = commit.message() {
                            let first_line =
                                message.lines().next().unwrap_or("(no message)").to_string();
                            extra_messages.push(format!(
                                "{}: {}",
                                &commit.id().to_string()[..8],
                                first_line
                            ));
                        }
                    }

                    modifications.push(BranchModification::ExtraCommits {
                        branch: entry.branch.clone(),
                        entry_id: entry.id,
                        expected_commit: entry.commit_hash.clone(),
                        actual_commit: branch_head,
                        extra_commit_count: extra_commits.len(),
                        extra_commit_messages: extra_messages,
                    });
                }
            }
        }

        if modifications.is_empty() {
            // Silent success - no issues to report
            return Ok(());
        }

        // Show detected modifications
        println!();
        Output::section(format!("Branch modifications detected in '{}'", stack.name));
        for (i, modification) in modifications.iter().enumerate() {
            match modification {
                BranchModification::Missing { branch, .. } => {
                    Output::numbered_item(i + 1, format!("Branch '{branch}' is missing"));
                }
                BranchModification::ExtraCommits {
                    branch,
                    expected_commit,
                    actual_commit,
                    extra_commit_count,
                    extra_commit_messages,
                    ..
                } => {
                    println!(
                        "   {}. Branch '{}' has {} extra commit(s)",
                        i + 1,
                        branch,
                        extra_commit_count
                    );
                    println!(
                        "      Expected: {} | Actual: {}",
                        &expected_commit[..8],
                        &actual_commit[..8]
                    );

                    // Show extra commit messages (first few only)
                    for (j, message) in extra_commit_messages.iter().enumerate() {
                        match j.cmp(&3) {
                            std::cmp::Ordering::Less => {
                                Output::sub_item(format!("     + {message}"));
                            }
                            std::cmp::Ordering::Equal => {
                                Output::sub_item(format!(
                                    "     + ... and {} more",
                                    extra_commit_count - 3
                                ));
                                break;
                            }
                            std::cmp::Ordering::Greater => {
                                break;
                            }
                        }
                    }
                }
            }
        }
        Output::spacing();

        // Auto mode handling
        if let Some(mode) = auto_mode {
            return self.apply_auto_fix(stack_id, &modifications, &mode);
        }

        // Interactive mode - ask user for each modification
        let mut handled_count = 0;
        let mut skipped_count = 0;
        for modification in modifications.iter() {
            let was_skipped = self.handle_single_modification(stack_id, modification)?;
            if was_skipped {
                skipped_count += 1;
            } else {
                handled_count += 1;
            }
        }

        self.save_to_disk()?;

        // Show appropriate summary based on what was done
        if skipped_count == 0 {
            Output::success("All branch modifications resolved");
        } else if handled_count > 0 {
            Output::warning(format!(
                "Resolved {} modification(s), {} skipped",
                handled_count, skipped_count
            ));
        } else {
            Output::warning("All modifications skipped - integrity issues remain");
        }

        Ok(())
    }

    /// Handle a single branch modification interactively
    /// Returns true if the modification was skipped, false if handled
    fn handle_single_modification(
        &mut self,
        stack_id: &Uuid,
        modification: &BranchModification,
    ) -> Result<bool> {
        match modification {
            BranchModification::Missing {
                branch,
                expected_commit,
                ..
            } => {
                Output::info(format!("Missing branch '{branch}'"));
                Output::sub_item(format!(
                    "Will create the branch at commit {}",
                    &expected_commit[..8]
                ));

                self.repo.create_branch(branch, Some(expected_commit))?;
                Output::success(format!("Created branch '{branch}'"));
                Ok(false) // Not skipped
            }

            BranchModification::ExtraCommits {
                branch,
                entry_id,
                expected_commit,
                extra_commit_count,
                ..
            } => {
                println!();
                Output::info(format!(
                    "Branch '{}' has {} extra commit(s)",
                    branch, extra_commit_count
                ));
                let options = vec![
                    "Incorporate - Update stack entry to include extra commits",
                    "Split - Create new stack entry for extra commits",
                    "Reset - Remove extra commits (DESTRUCTIVE)",
                    "Skip - Leave as-is for now",
                ];

                let choice = Select::with_theme(&ColorfulTheme::default())
                    .with_prompt("Choose how to handle extra commits")
                    .default(0)
                    .items(&options)
                    .interact()
                    .map_err(|e| CascadeError::config(format!("Failed to get user choice: {e}")))?;

                match choice {
                    0 => {
                        self.incorporate_extra_commits(stack_id, *entry_id, branch)?;
                        Ok(false) // Not skipped
                    }
                    1 => {
                        self.split_extra_commits(stack_id, *entry_id, branch)?;
                        Ok(false) // Not skipped
                    }
                    2 => {
                        self.reset_branch_destructive(branch, expected_commit)?;
                        Ok(false) // Not skipped
                    }
                    3 => {
                        Output::warning(format!("Skipped '{branch}' - integrity issue remains"));
                        Ok(true) // Skipped
                    }
                    _ => {
                        Output::warning(format!("Invalid choice - skipped '{branch}'"));
                        Ok(true) // Skipped
                    }
                }
            }
        }
    }

    /// Apply automatic fix based on mode
    fn apply_auto_fix(
        &mut self,
        stack_id: &Uuid,
        modifications: &[BranchModification],
        mode: &str,
    ) -> Result<()> {
        Output::info(format!("🤖 Applying automatic fix mode: {mode}"));

        for modification in modifications {
            match (modification, mode) {
                (
                    BranchModification::Missing {
                        branch,
                        expected_commit,
                        ..
                    },
                    _,
                ) => {
                    self.repo.create_branch(branch, Some(expected_commit))?;
                    Output::success(format!("Created missing branch '{branch}'"));
                }

                (
                    BranchModification::ExtraCommits {
                        branch, entry_id, ..
                    },
                    "incorporate",
                ) => {
                    self.incorporate_extra_commits(stack_id, *entry_id, branch)?;
                }

                (
                    BranchModification::ExtraCommits {
                        branch, entry_id, ..
                    },
                    "split",
                ) => {
                    self.split_extra_commits(stack_id, *entry_id, branch)?;
                }

                (
                    BranchModification::ExtraCommits {
                        branch,
                        expected_commit,
                        ..
                    },
                    "reset",
                ) => {
                    self.reset_branch_destructive(branch, expected_commit)?;
                }

                _ => {
                    return Err(CascadeError::config(format!(
                        "Unknown auto-fix mode '{mode}'. Use: incorporate, split, reset"
                    )));
                }
            }
        }

        self.save_to_disk()?;
        Output::success(format!("Auto-fix completed for mode: {mode}"));
        Ok(())
    }

    /// Incorporate extra commits into the existing stack entry (update commit hash)
    fn incorporate_extra_commits(
        &mut self,
        stack_id: &Uuid,
        entry_id: Uuid,
        branch: &str,
    ) -> Result<()> {
        let stack = self
            .stacks
            .get_mut(stack_id)
            .ok_or_else(|| CascadeError::config(format!("Stack not found: {}", stack_id)))?;

        // Find entry and get info we need before mutation
        let entry_info = stack
            .entries
            .iter()
            .find(|e| e.id == entry_id)
            .map(|e| (e.commit_hash.clone(), e.id));

        if let Some((old_commit_hash, entry_id)) = entry_info {
            let new_head = self.repo.get_branch_head(branch)?;
            let old_commit = old_commit_hash[..8].to_string();

            // Get the extra commits for message update
            let extra_commits = self.repo.get_commits_between(&old_commit_hash, &new_head)?;

            // Update the entry to point to the new HEAD using safe wrapper
            // Note: We intentionally do NOT append commit messages here
            // The entry's message should describe the feature/change, not list all commits
            stack
                .update_entry_commit_hash(&entry_id, new_head.clone())
                .map_err(CascadeError::config)?;

            Output::success(format!(
                "Incorporated {} commit(s) into entry '{}'",
                extra_commits.len(),
                &new_head[..8]
            ));
            Output::sub_item(format!("Updated: {} -> {}", old_commit, &new_head[..8]));
        }

        Ok(())
    }

    /// Split extra commits into a new stack entry
    fn split_extra_commits(&mut self, stack_id: &Uuid, entry_id: Uuid, branch: &str) -> Result<()> {
        let stack = self
            .stacks
            .get_mut(stack_id)
            .ok_or_else(|| CascadeError::config(format!("Stack not found: {}", stack_id)))?;
        let new_head = self.repo.get_branch_head(branch)?;

        // Find the position of the current entry
        let entry_position = stack
            .entries
            .iter()
            .position(|e| e.id == entry_id)
            .ok_or_else(|| CascadeError::config("Entry not found in stack"))?;

        // Create a new branch name for the split
        let base_name = branch.trim_end_matches(|c: char| c.is_ascii_digit() || c == '-');
        let new_branch = format!("{base_name}-continued");

        // Create new branch at the current HEAD
        self.repo.create_branch(&new_branch, Some(&new_head))?;

        // Get extra commits for message creation
        let original_entry = &stack.entries[entry_position];
        let original_commit_hash = original_entry.commit_hash.clone(); // Clone to avoid borrowing issue
        let extra_commits = self
            .repo
            .get_commits_between(&original_commit_hash, &new_head)?;

        // Create commit message from extra commits
        let mut extra_messages = Vec::new();
        for commit in &extra_commits {
            if let Some(message) = commit.message() {
                let first_line = message.lines().next().unwrap_or("").to_string();
                extra_messages.push(first_line);
            }
        }

        let new_message = if extra_messages.len() == 1 {
            extra_messages[0].clone()
        } else {
            format!("Combined changes:\n• {}", extra_messages.join("\n• "))
        };

        // Create new stack entry manually (no constructor method exists)
        let now = Utc::now();
        let new_entry = crate::stack::StackEntry {
            id: uuid::Uuid::new_v4(),
            branch: new_branch.clone(),
            commit_hash: new_head,
            message: new_message,
            parent_id: Some(entry_id), // Parent is the current entry
            children: Vec::new(),
            created_at: now,
            updated_at: now,
            is_submitted: false,
            pull_request_id: None,
            is_synced: false,
            is_merged: false,
        };

        // Insert the new entry after the current one
        stack.entries.insert(entry_position + 1, new_entry);

        // Reset the original branch to its expected commit
        self.repo
            .reset_branch_to_commit(branch, &original_commit_hash)?;

        println!(
            "   ✅ Split {} commit(s) into new entry '{}'",
            extra_commits.len(),
            new_branch
        );
        println!("      Original branch '{branch}' reset to expected commit");

        Ok(())
    }

    /// Reset branch to expected commit (destructive - loses extra work)
    fn reset_branch_destructive(&self, branch: &str, expected_commit: &str) -> Result<()> {
        self.repo.reset_branch_to_commit(branch, expected_commit)?;
        Output::warning(format!(
            "Reset branch '{}' to {} (extra commits lost)",
            branch,
            &expected_commit[..8]
        ));
        Ok(())
    }
}

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

    fn create_test_repo() -> (TempDir, 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();

        // Configure git
        Command::new("git")
            .args(["config", "user.name", "Test User"])
            .current_dir(&repo_path)
            .output()
            .unwrap();

        Command::new("git")
            .args(["config", "user.email", "test@example.com"])
            .current_dir(&repo_path)
            .output()
            .unwrap();

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

        Command::new("git")
            .args(["commit", "-m", "Initial commit"])
            .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_create_stack_manager() {
        let (_temp_dir, repo_path) = create_test_repo();
        let manager = StackManager::new(&repo_path).unwrap();

        assert_eq!(manager.stacks.len(), 0);
        assert!(manager.get_active_stack().is_none());
    }

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

        // Create a feature branch so the stack gets a working_branch
        Command::new("git")
            .args(["checkout", "-b", "feature/test-work"])
            .current_dir(&repo_path)
            .output()
            .unwrap();

        let mut manager = StackManager::new(&repo_path).unwrap();

        // Create a stack using the default branch
        let stack_id = manager
            .create_stack(
                "test-stack".to_string(),
                None, // Use default branch
                Some("Test stack description".to_string()),
            )
            .unwrap();

        // Verify stack was created
        assert_eq!(manager.stacks.len(), 1);
        let stack = manager.get_stack(&stack_id).unwrap();
        assert_eq!(stack.name, "test-stack");
        // Should use the default branch (which gets set from the Git repo)
        assert!(!stack.base_branch.is_empty());
        // Working branch should be set since we're on a feature branch
        assert_eq!(stack.working_branch.as_deref(), Some("feature/test-work"));

        // Verify it's the active stack (resolved from current branch)
        let active = manager.get_active_stack().unwrap();
        assert_eq!(active.id, stack_id);

        // Test get by name
        let found = manager.get_stack_by_name("test-stack").unwrap();
        assert_eq!(found.id, stack_id);
    }

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

        Command::new("git")
            .args(["checkout", "-b", "feature/persist-work"])
            .current_dir(&repo_path)
            .output()
            .unwrap();

        let stack_id = {
            let mut manager = StackManager::new(&repo_path).unwrap();
            manager
                .create_stack("persistent-stack".to_string(), None, None)
                .unwrap()
        };

        // Create new manager and verify data was loaded
        let manager = StackManager::new(&repo_path).unwrap();
        assert_eq!(manager.stacks.len(), 1);
        let stack = manager.get_stack(&stack_id).unwrap();
        assert_eq!(stack.name, "persistent-stack");
    }

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

        // Create branch for stack-1 and create the stack on it
        Command::new("git")
            .args(["checkout", "-b", "feature/stack-1"])
            .current_dir(&repo_path)
            .output()
            .unwrap();

        let stack1_id = manager
            .create_stack("stack-1".to_string(), None, None)
            .unwrap();

        // Create branch for stack-2 and create the stack on it
        Command::new("git")
            .args(["checkout", "-b", "feature/stack-2"])
            .current_dir(&repo_path)
            .output()
            .unwrap();

        let stack2_id = manager
            .create_stack("stack-2".to_string(), None, None)
            .unwrap();

        assert_eq!(manager.stacks.len(), 2);

        // Currently on feature/stack-2, so stack-2 should be active
        assert_eq!(manager.get_active_stack_id(), Some(stack2_id));

        // Checkout stack-1's branch to make it active
        Command::new("git")
            .args(["checkout", "feature/stack-1"])
            .current_dir(&repo_path)
            .output()
            .unwrap();

        // Reload manager to pick up branch change
        let manager = StackManager::new(&repo_path).unwrap();
        assert_eq!(manager.get_active_stack_id(), Some(stack1_id));
    }

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

        let stack_id = manager
            .create_stack("to-delete".to_string(), None, None)
            .unwrap();
        assert_eq!(manager.stacks.len(), 1);

        let deleted = manager.delete_stack(&stack_id).unwrap();
        assert_eq!(deleted.name, "to-delete");
        assert_eq!(manager.stacks.len(), 0);
        assert!(manager.get_active_stack().is_none());
    }

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

        manager
            .create_stack("valid-stack".to_string(), None, None)
            .unwrap();

        // Should pass validation
        assert!(manager.validate_all().is_ok());
    }

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

        // Create a feature branch so the stack gets a working_branch
        Command::new("git")
            .args(["checkout", "-b", "feature/test-dup"])
            .current_dir(&repo_path)
            .output()
            .unwrap();

        let mut manager = StackManager::new(&repo_path).unwrap();

        // Create a stack
        manager
            .create_stack("test-stack".to_string(), None, None)
            .unwrap();

        // Create first commit
        std::fs::write(repo_path.join("file1.txt"), "content1").unwrap();
        Command::new("git")
            .args(["add", "file1.txt"])
            .current_dir(&repo_path)
            .output()
            .unwrap();

        Command::new("git")
            .args(["commit", "-m", "Add authentication feature"])
            .current_dir(&repo_path)
            .output()
            .unwrap();

        let commit1_hash = Command::new("git")
            .args(["rev-parse", "HEAD"])
            .current_dir(&repo_path)
            .output()
            .unwrap();
        let commit1_hash = String::from_utf8_lossy(&commit1_hash.stdout)
            .trim()
            .to_string();

        // Push first commit to stack - should succeed
        let entry1_id = manager
            .push_to_stack(
                "feature/auth".to_string(),
                commit1_hash,
                "Add authentication feature".to_string(),
                "main".to_string(),
            )
            .unwrap();

        // Verify first entry was added
        assert!(manager
            .get_active_stack()
            .unwrap()
            .get_entry(&entry1_id)
            .is_some());

        // Create second commit
        std::fs::write(repo_path.join("file2.txt"), "content2").unwrap();
        Command::new("git")
            .args(["add", "file2.txt"])
            .current_dir(&repo_path)
            .output()
            .unwrap();

        Command::new("git")
            .args(["commit", "-m", "Different commit message"])
            .current_dir(&repo_path)
            .output()
            .unwrap();

        let commit2_hash = Command::new("git")
            .args(["rev-parse", "HEAD"])
            .current_dir(&repo_path)
            .output()
            .unwrap();
        let commit2_hash = String::from_utf8_lossy(&commit2_hash.stdout)
            .trim()
            .to_string();

        // Try to push second commit with the SAME message - should fail
        let result = manager.push_to_stack(
            "feature/auth2".to_string(),
            commit2_hash.clone(),
            "Add authentication feature".to_string(), // Same message as first commit
            "main".to_string(),
        );

        // Should fail with validation error
        assert!(result.is_err());
        let error = result.unwrap_err();
        assert!(matches!(error, CascadeError::Validation(_)));

        // Error message should contain helpful information
        let error_msg = error.to_string();
        assert!(error_msg.contains("Duplicate commit message"));
        assert!(error_msg.contains("Add authentication feature"));
        assert!(error_msg.contains("💡 Consider using a more specific message"));

        // Push with different message - should succeed
        let entry2_id = manager
            .push_to_stack(
                "feature/auth2".to_string(),
                commit2_hash,
                "Add authentication validation".to_string(), // Different message
                "main".to_string(),
            )
            .unwrap();

        // Verify both entries exist
        let stack = manager.get_active_stack().unwrap();
        assert_eq!(stack.entries.len(), 2);
        assert!(stack.get_entry(&entry1_id).is_some());
        assert!(stack.get_entry(&entry2_id).is_some());
    }

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

        Command::new("git")
            .args(["checkout", "-b", "feature/test-case"])
            .current_dir(&repo_path)
            .output()
            .unwrap();

        let mut manager = StackManager::new(&repo_path).unwrap();

        manager
            .create_stack("test-stack".to_string(), None, None)
            .unwrap();

        // Create and push first commit
        std::fs::write(repo_path.join("file1.txt"), "content1").unwrap();
        Command::new("git")
            .args(["add", "file1.txt"])
            .current_dir(&repo_path)
            .output()
            .unwrap();

        Command::new("git")
            .args(["commit", "-m", "fix bug"])
            .current_dir(&repo_path)
            .output()
            .unwrap();

        let commit1_hash = Command::new("git")
            .args(["rev-parse", "HEAD"])
            .current_dir(&repo_path)
            .output()
            .unwrap();
        let commit1_hash = String::from_utf8_lossy(&commit1_hash.stdout)
            .trim()
            .to_string();

        manager
            .push_to_stack(
                "feature/fix1".to_string(),
                commit1_hash,
                "fix bug".to_string(),
                "main".to_string(),
            )
            .unwrap();

        // Create second commit
        std::fs::write(repo_path.join("file2.txt"), "content2").unwrap();
        Command::new("git")
            .args(["add", "file2.txt"])
            .current_dir(&repo_path)
            .output()
            .unwrap();

        Command::new("git")
            .args(["commit", "-m", "Fix Bug"])
            .current_dir(&repo_path)
            .output()
            .unwrap();

        let commit2_hash = Command::new("git")
            .args(["rev-parse", "HEAD"])
            .current_dir(&repo_path)
            .output()
            .unwrap();
        let commit2_hash = String::from_utf8_lossy(&commit2_hash.stdout)
            .trim()
            .to_string();

        // Different case should be allowed (case-sensitive comparison)
        let result = manager.push_to_stack(
            "feature/fix2".to_string(),
            commit2_hash,
            "Fix Bug".to_string(), // Different case
            "main".to_string(),
        );

        // Should succeed because it's case-sensitive
        assert!(result.is_ok());
    }

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

        // Create first stack on its own branch
        Command::new("git")
            .args(["checkout", "-b", "feature/stack1-work"])
            .current_dir(&repo_path)
            .output()
            .unwrap();

        let mut manager = StackManager::new(&repo_path).unwrap();

        // Create first stack and push commit
        let stack1_id = manager
            .create_stack("stack1".to_string(), None, None)
            .unwrap();

        std::fs::write(repo_path.join("file1.txt"), "content1").unwrap();
        Command::new("git")
            .args(["add", "file1.txt"])
            .current_dir(&repo_path)
            .output()
            .unwrap();

        Command::new("git")
            .args(["commit", "-m", "shared message"])
            .current_dir(&repo_path)
            .output()
            .unwrap();

        let commit1_hash = Command::new("git")
            .args(["rev-parse", "HEAD"])
            .current_dir(&repo_path)
            .output()
            .unwrap();
        let commit1_hash = String::from_utf8_lossy(&commit1_hash.stdout)
            .trim()
            .to_string();

        manager
            .push_to_stack(
                "feature/shared1".to_string(),
                commit1_hash,
                "shared message".to_string(),
                "main".to_string(),
            )
            .unwrap();

        // Create second stack on a different branch so it's distinguishable
        Command::new("git")
            .args(["checkout", "-b", "feature/stack2-work"])
            .current_dir(&repo_path)
            .output()
            .unwrap();

        let stack2_id = manager
            .create_stack("stack2".to_string(), None, None)
            .unwrap();

        // Reload manager to pick up the new branch context
        let mut manager = StackManager::new(&repo_path).unwrap();

        // Create commit for second stack
        std::fs::write(repo_path.join("file2.txt"), "content2").unwrap();
        Command::new("git")
            .args(["add", "file2.txt"])
            .current_dir(&repo_path)
            .output()
            .unwrap();

        Command::new("git")
            .args(["commit", "-m", "shared message"])
            .current_dir(&repo_path)
            .output()
            .unwrap();

        let commit2_hash = Command::new("git")
            .args(["rev-parse", "HEAD"])
            .current_dir(&repo_path)
            .output()
            .unwrap();
        let commit2_hash = String::from_utf8_lossy(&commit2_hash.stdout)
            .trim()
            .to_string();

        // Same message in different stack should be allowed
        let result = manager.push_to_stack(
            "feature/shared2".to_string(),
            commit2_hash,
            "shared message".to_string(), // Same message but different stack
            "main".to_string(),
        );

        // Should succeed because it's a different stack
        assert!(result.is_ok());

        // Verify both stacks have entries with the same message
        let stack1 = manager.get_stack(&stack1_id).unwrap();
        let stack2 = manager.get_stack(&stack2_id).unwrap();

        assert_eq!(stack1.entries.len(), 1);
        assert_eq!(stack2.entries.len(), 1);
        assert_eq!(stack1.entries[0].message, "shared message");
        assert_eq!(stack2.entries[0].message, "shared message");
    }

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

        Command::new("git")
            .args(["checkout", "-b", "feature/test-pop"])
            .current_dir(&repo_path)
            .output()
            .unwrap();

        let mut manager = StackManager::new(&repo_path).unwrap();

        manager
            .create_stack("test-stack".to_string(), None, None)
            .unwrap();

        // Create and push first commit
        std::fs::write(repo_path.join("file1.txt"), "content1").unwrap();
        Command::new("git")
            .args(["add", "file1.txt"])
            .current_dir(&repo_path)
            .output()
            .unwrap();

        Command::new("git")
            .args(["commit", "-m", "temporary message"])
            .current_dir(&repo_path)
            .output()
            .unwrap();

        let commit1_hash = Command::new("git")
            .args(["rev-parse", "HEAD"])
            .current_dir(&repo_path)
            .output()
            .unwrap();
        let commit1_hash = String::from_utf8_lossy(&commit1_hash.stdout)
            .trim()
            .to_string();

        manager
            .push_to_stack(
                "feature/temp".to_string(),
                commit1_hash,
                "temporary message".to_string(),
                "main".to_string(),
            )
            .unwrap();

        // Pop the entry
        let popped = manager.pop_from_stack().unwrap();
        assert_eq!(popped.message, "temporary message");

        // Create new commit
        std::fs::write(repo_path.join("file2.txt"), "content2").unwrap();
        Command::new("git")
            .args(["add", "file2.txt"])
            .current_dir(&repo_path)
            .output()
            .unwrap();

        Command::new("git")
            .args(["commit", "-m", "temporary message"])
            .current_dir(&repo_path)
            .output()
            .unwrap();

        let commit2_hash = Command::new("git")
            .args(["rev-parse", "HEAD"])
            .current_dir(&repo_path)
            .output()
            .unwrap();
        let commit2_hash = String::from_utf8_lossy(&commit2_hash.stdout)
            .trim()
            .to_string();

        // Should be able to push same message again after popping
        let result = manager.push_to_stack(
            "feature/temp2".to_string(),
            commit2_hash,
            "temporary message".to_string(),
            "main".to_string(),
        );

        assert!(result.is_ok());
    }
}