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
use crate::cli::output::Output;
use crate::errors::{CascadeError, Result};
use crate::git::{find_repository_root, GitRepository};
use crate::stack::{StackEntry, StackManager};
use clap::Subcommand;
use crossterm::{
    event::{self, DisableMouseCapture, EnableMouseCapture, Event, KeyCode, KeyEventKind},
    execute,
    terminal::{disable_raw_mode, enable_raw_mode, EnterAlternateScreen, LeaveAlternateScreen},
};
use dialoguer::{theme::ColorfulTheme, Confirm};
use ratatui::{
    backend::CrosstermBackend,
    layout::{Alignment, Constraint, Direction, Layout},
    style::{Color, Modifier, Style},
    text::{Line, Span},
    widgets::{Block, Borders, List, ListItem, ListState, Paragraph},
    Terminal,
};
use serde::{Deserialize, Serialize};
use std::env;
use std::io;
use std::path::{Path, PathBuf};
use tracing::debug;
use uuid::Uuid;

/// State tracking for in-progress restack operations
/// Persisted to .git/CASCADE_RESTACK_STATE
#[derive(Debug, Clone, Serialize, Deserialize)]
struct RestackState {
    /// ID of the stack being restacked
    stack_id: Uuid,
    /// Index of the entry that was amended (starting point)
    amended_entry_index: usize,
    /// Branch name of the amended entry (to return to after restack)
    amended_branch: String,
    /// Index of the entry currently being cherry-picked
    current_entry_index: usize,
    /// List of (index, entry) pairs that still need to be restacked
    remaining_entries: Vec<(usize, StackEntry)>,
}

impl RestackState {
    fn state_file_path(repo_root: &Path) -> Result<PathBuf> {
        Ok(crate::git::resolve_git_dir(repo_root)?.join("CASCADE_RESTACK_STATE"))
    }

    fn save(&self, repo_root: &Path) -> Result<()> {
        let path = Self::state_file_path(repo_root)?;
        let json = serde_json::to_string_pretty(self).map_err(|e| {
            CascadeError::config(format!("Failed to serialize restack state: {}", e))
        })?;
        std::fs::write(&path, json)
            .map_err(|e| CascadeError::config(format!("Failed to write restack state: {}", e)))?;
        debug!("Saved restack state to {:?}", path);
        Ok(())
    }

    fn load(repo_root: &Path) -> Result<Option<Self>> {
        let path = Self::state_file_path(repo_root)?;
        if !path.exists() {
            return Ok(None);
        }

        let json = std::fs::read_to_string(&path)
            .map_err(|e| CascadeError::config(format!("Failed to read restack state: {}", e)))?;
        let state: Self = serde_json::from_str(&json)
            .map_err(|e| CascadeError::config(format!("Failed to parse restack state: {}", e)))?;
        debug!("Loaded restack state from {:?}", path);
        Ok(Some(state))
    }

    fn delete(repo_root: &Path) -> Result<()> {
        let path = Self::state_file_path(repo_root)?;
        if path.exists() {
            std::fs::remove_file(&path).map_err(|e| {
                CascadeError::config(format!("Failed to delete restack state: {}", e))
            })?;
            debug!("Deleted restack state file: {:?}", path);
        }
        Ok(())
    }
}

#[derive(Debug, Subcommand)]
pub enum EntryAction {
    /// Interactively checkout a stack entry for editing
    Checkout {
        /// Stack entry number (optional, shows picker if not provided)
        entry: Option<usize>,
        /// Skip interactive picker and use entry number directly
        #[arg(long)]
        direct: bool,
        /// Skip confirmation prompts
        #[arg(long, short)]
        yes: bool,
    },
    /// Show current edit mode status
    Status {
        /// Show brief status only
        #[arg(long)]
        quiet: bool,
    },
    /// List all entries with their edit status
    List {
        /// Show detailed information
        #[arg(long, short)]
        verbose: bool,
    },
    /// Clear/exit edit mode (useful for recovering from corrupted state)
    Clear {
        /// Skip confirmation prompt
        #[arg(long, short)]
        yes: bool,
    },
    /// Amend the current stack entry commit and automatically restack dependent entries
    ///
    /// Automatically includes all modified tracked files (like 'git commit -a --amend')
    /// and rebases all dependent entries onto the amended commit
    Amend {
        /// New commit message (optional, uses git editor if not provided)
        #[arg(long, short)]
        message: Option<String>,
        /// (Deprecated: now default behavior) Include all changes
        #[arg(long, short)]
        all: bool,
        /// Automatically force-push after amending (if PR exists)
        #[arg(long)]
        push: bool,
    },
    /// Continue restacking after resolving cherry-pick conflicts
    ///
    /// Use this after manually resolving conflicts during 'ca entry amend'
    Continue,
    /// Abort an in-progress restack operation
    ///
    /// Safely aborts the cherry-pick and cleans up any partial restack state
    Abort,
}

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

    match action {
        EntryAction::Checkout { entry, direct, yes } => checkout_entry(entry, direct, yes).await,
        EntryAction::Status { quiet } => show_edit_status(quiet).await,
        EntryAction::List { verbose } => list_entries(verbose).await,
        EntryAction::Clear { yes } => clear_edit_mode(yes).await,
        EntryAction::Amend { message, all, push } => amend_entry(message, all, push).await,
        EntryAction::Continue => continue_restack().await,
        EntryAction::Abort => abort_restack().await,
    }
}

/// Checkout a specific stack entry for editing
async fn checkout_entry(
    entry_num: Option<usize>,
    direct: bool,
    skip_confirmation: 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 mut manager = StackManager::new(&repo_root)?;

    // Get active stack
    let active_stack = manager.get_active_stack().ok_or_else(|| {
        CascadeError::config("No active stack. Create a stack first with 'ca stack create'")
    })?;

    if active_stack.entries.is_empty() {
        return Err(CascadeError::config(
            "Stack is empty. Push some commits first with 'ca stack push'",
        ));
    }

    // Determine which entry to checkout
    let target_entry_num = if let Some(num) = entry_num {
        if num == 0 || num > active_stack.entries.len() {
            return Err(CascadeError::config(format!(
                "Invalid entry number: {}. Stack has {} entries",
                num,
                active_stack.entries.len()
            )));
        }
        num
    } else if direct {
        return Err(CascadeError::config(
            "Entry number required when using --direct flag",
        ));
    } else {
        // Show interactive picker
        show_entry_picker(active_stack).await?
    };

    let target_entry = &active_stack.entries[target_entry_num - 1]; // Convert to 0-based index

    // Clone the values we need before borrowing manager mutably
    let stack_id = active_stack.id;
    let entry_id = target_entry.id;
    let entry_branch = target_entry.branch.clone();
    let entry_short_hash = target_entry.short_hash();
    let entry_short_message = target_entry.short_message(50);
    let entry_pr_id = target_entry.pull_request_id.clone();
    let entry_message = target_entry.message.clone();

    // Check if already in edit mode and get info before confirmation
    let already_in_edit_mode = manager.is_in_edit_mode();
    let edit_mode_display = if already_in_edit_mode {
        let edit_info = manager.get_edit_mode_info().unwrap();

        // Get the commit message for the current edit target
        let commit_message = if let Some(target_entry_id) = &edit_info.target_entry_id {
            if let Some(entry) = active_stack
                .entries
                .iter()
                .find(|e| e.id == *target_entry_id)
            {
                entry.short_message(50)
            } else {
                "Unknown entry".to_string()
            }
        } else {
            "Unknown target".to_string()
        };

        Some((edit_info.original_commit_hash.clone(), commit_message))
    } else {
        None
    };

    // Let the active_stack reference go out of scope before we potentially mutably borrow manager
    let _ = active_stack;

    // Handle edit mode exit if needed
    if let Some((commit_hash, commit_message)) = edit_mode_display {
        tracing::debug!("Already in edit mode for entry in stack");

        if !skip_confirmation {
            Output::warning("Already in edit mode!");
            Output::sub_item(format!(
                "Current target: {} ({})",
                &commit_hash[..8],
                commit_message
            ));

            // Interactive confirmation to exit current edit mode
            let should_exit_edit_mode = Confirm::with_theme(&ColorfulTheme::default())
                .with_prompt("Exit current edit mode and start a new one?")
                .default(false)
                .interact()
                .map_err(|e| {
                    CascadeError::config(format!("Failed to get user confirmation: {e}"))
                })?;

            if !should_exit_edit_mode {
                return Err(CascadeError::config(
                    "Operation cancelled. Use 'ca entry status' to see current edit mode details.",
                ));
            }

            // Exit current edit mode before starting a new one
            Output::info("Exiting current edit mode...");
            manager.exit_edit_mode()?;
            Output::success("✓ Exited previous edit mode");
        }
    }

    // Confirmation prompt
    if !skip_confirmation {
        Output::section("Checking out entry for editing");
        Output::sub_item(format!(
            "Entry #{target_entry_num}: {entry_short_hash} ({entry_short_message})"
        ));
        Output::sub_item(format!("Branch: {entry_branch}"));
        if let Some(pr_id) = &entry_pr_id {
            Output::sub_item(format!("PR: #{pr_id}"));
        }

        // Display full commit message
        Output::sub_item("Commit Message:");
        let lines: Vec<&str> = entry_message.lines().collect();
        for line in lines {
            Output::sub_item(format!("  {line}"));
        }

        Output::warning("This will checkout the commit and enter edit mode.");
        Output::info("Any changes you make can be amended to this commit or create new entries.");

        // Interactive confirmation to proceed with checkout
        let should_continue = Confirm::with_theme(&ColorfulTheme::default())
            .with_prompt("Continue with checkout?")
            .default(false)
            .interact()
            .map_err(|e| CascadeError::config(format!("Failed to get user confirmation: {e}")))?;

        if !should_continue {
            return Err(CascadeError::config("Entry checkout cancelled"));
        }
    }

    // Enter edit mode
    manager.enter_edit_mode(stack_id, entry_id)?;

    // Checkout the branch (not the commit - we want to stay on the branch)
    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 repo = crate::git::GitRepository::open(&repo_root)?;

    debug!("Checking out branch: {}", entry_branch);
    repo.checkout_branch(&entry_branch)?;

    Output::success(format!("Entered edit mode for entry #{target_entry_num}"));
    Output::sub_item(format!(
        "You are now on commit: {} ({})",
        entry_short_hash, entry_short_message
    ));
    Output::sub_item(format!("Branch: {entry_branch}"));

    Output::section("Make your changes and commit normally");
    Output::bullet("Use 'ca entry status' to see edit mode info");
    Output::bullet("When you commit, the pre-commit hook will guide you");

    // Check if prepare-commit-msg hook is installed
    let hooks_dir = repo_root.join(".git/hooks");
    let hook_path = hooks_dir.join("prepare-commit-msg");
    if !hook_path.exists() {
        Output::tip("Install the prepare-commit-msg hook for better guidance:");
        Output::sub_item("ca hooks add prepare-commit-msg");
    }

    Ok(())
}

/// Interactive entry picker using TUI
async fn show_entry_picker(stack: &crate::stack::Stack) -> Result<usize> {
    // Setup terminal
    enable_raw_mode()?;
    let mut stdout = io::stdout();
    execute!(stdout, EnterAlternateScreen, EnableMouseCapture)?;
    let backend = CrosstermBackend::new(stdout);
    let mut terminal = Terminal::new(backend)?;

    let mut list_state = ListState::default();
    list_state.select(Some(0));

    let result = loop {
        terminal.draw(|f| {
            let size = f.area();

            // Create layout
            let chunks = Layout::default()
                .direction(Direction::Vertical)
                .margin(2)
                .constraints(
                    [
                        Constraint::Length(3), // Title
                        Constraint::Min(5),    // List
                        Constraint::Length(3), // Help
                    ]
                    .as_ref(),
                )
                .split(size);

            // Title
            let title = Paragraph::new(format!("📚 Select Entry from Stack: {}", stack.name))
                .style(
                    Style::default()
                        .fg(Color::Cyan)
                        .add_modifier(Modifier::BOLD),
                )
                .alignment(Alignment::Center)
                .block(Block::default().borders(Borders::ALL));
            f.render_widget(title, chunks[0]);

            // Entry list
            let items: Vec<ListItem> = stack
                .entries
                .iter()
                .enumerate()
                .map(|(i, entry)| {
                    let status_icon = if entry.is_submitted {
                        if entry.pull_request_id.is_some() {
                            "📤"
                        } else {
                            "📝"
                        }
                    } else {
                        "🔄"
                    };

                    let pr_text = if let Some(pr_id) = &entry.pull_request_id {
                        format!(" PR: #{pr_id}")
                    } else {
                        "".to_string()
                    };

                    let line = Line::from(vec![
                        Span::raw(format!("  {}. ", i + 1)),
                        Span::raw(status_icon),
                        Span::raw(" "),
                        Span::styled(entry.short_message(40), Style::default().fg(Color::White)),
                        Span::raw(" "),
                        Span::styled(
                            format!("({})", entry.short_hash()),
                            Style::default().fg(Color::Yellow),
                        ),
                        Span::styled(pr_text, Style::default().fg(Color::Green)),
                    ]);

                    ListItem::new(line)
                })
                .collect();

            let list = List::new(items)
                .block(Block::default().borders(Borders::ALL).title("Entries"))
                .highlight_style(Style::default().fg(Color::Black).bg(Color::Cyan))
                .highlight_symbol("");

            f.render_stateful_widget(list, chunks[1], &mut list_state);

            // Help text
            let help = Paragraph::new("↑/↓: Navigate • Enter: Select • q: Quit • r: Refresh")
                .style(Style::default().fg(Color::DarkGray))
                .alignment(Alignment::Center)
                .block(Block::default().borders(Borders::ALL));
            f.render_widget(help, chunks[2]);
        })?;

        // Handle input
        if let Event::Key(key) = event::read()? {
            if key.kind == KeyEventKind::Press {
                match key.code {
                    KeyCode::Char('q') => {
                        break Err(CascadeError::config("Entry selection cancelled"));
                    }
                    KeyCode::Up => {
                        let selected = list_state.selected().unwrap_or(0);
                        if selected > 0 {
                            list_state.select(Some(selected - 1));
                        } else {
                            list_state.select(Some(stack.entries.len() - 1));
                        }
                    }
                    KeyCode::Down => {
                        let selected = list_state.selected().unwrap_or(0);
                        if selected < stack.entries.len() - 1 {
                            list_state.select(Some(selected + 1));
                        } else {
                            list_state.select(Some(0));
                        }
                    }
                    KeyCode::Enter => {
                        let selected = list_state.selected().unwrap_or(0);
                        break Ok(selected + 1); // Convert to 1-based index
                    }
                    KeyCode::Char('r') => {
                        // Refresh - for now just continue the loop
                        continue;
                    }
                    _ => {}
                }
            }
        }
    };

    // Restore terminal
    disable_raw_mode()?;
    execute!(
        terminal.backend_mut(),
        LeaveAlternateScreen,
        DisableMouseCapture
    )?;
    terminal.show_cursor()?;

    result
}

/// Show current edit mode status
async fn show_edit_status(quiet: 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 manager = StackManager::new(&repo_root)?;

    if !manager.is_in_edit_mode() {
        if quiet {
            println!("inactive");
        } else {
            Output::info("Not in edit mode");
            Output::sub_item("Use 'ca entry checkout' to start editing a stack entry");
        }
        return Ok(());
    }

    let edit_info = manager.get_edit_mode_info().unwrap();

    if quiet {
        println!("active:{:?}", edit_info.target_entry_id);
        return Ok(());
    }

    Output::section("Currently in edit mode");

    // Try to get the entry information
    if let Some(active_stack) = manager.get_active_stack() {
        if let Some(target_entry_id) = edit_info.target_entry_id {
            if let Some(entry) = active_stack
                .entries
                .iter()
                .find(|e| e.id == target_entry_id)
            {
                Output::sub_item(format!(
                    "Target entry: {} ({})",
                    entry.short_hash(),
                    entry.short_message(50)
                ));
                Output::sub_item(format!("Branch: {}", entry.branch));

                // Display full commit message
                Output::sub_item("Commit Message:");
                let lines: Vec<&str> = entry.message.lines().collect();
                for line in lines {
                    Output::sub_item(format!("  {line}"));
                }
            } else {
                Output::sub_item(format!("Target entry: {target_entry_id:?} (not found)"));
            }
        } else {
            Output::sub_item("Target entry: Unknown");
        }
    } else {
        Output::sub_item(format!("Target entry: {:?}", edit_info.target_entry_id));
    }

    Output::sub_item(format!(
        "Original commit: {}",
        &edit_info.original_commit_hash[..8]
    ));
    Output::sub_item(format!(
        "Started: {}",
        edit_info.started_at.format("%Y-%m-%d %H:%M:%S")
    ));

    // Show current Git status
    Output::section("Current state");

    // Get current repository state
    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 repo = crate::git::GitRepository::open(&repo_root)?;

    // Current HEAD vs original commit
    let current_head = repo.get_current_commit_hash()?;
    if current_head != edit_info.original_commit_hash {
        let current_short = &current_head[..8];
        let original_short = &edit_info.original_commit_hash[..8];
        Output::sub_item(format!("HEAD moved: {original_short}{current_short}"));

        // Show if there are new commits
        match repo.get_commit_count_between(&edit_info.original_commit_hash, &current_head) {
            Ok(count) if count > 0 => {
                Output::sub_item(format!("  {count} new commit(s) created"));
            }
            _ => {}
        }
    } else {
        Output::sub_item(format!("HEAD: {} (unchanged)", &current_head[..8]));
    }

    // Working directory and staging status
    match repo.get_status_summary() {
        Ok(status) => {
            if status.is_clean() {
                Output::sub_item("Working directory: clean");
            } else {
                if status.has_staged_changes() {
                    Output::sub_item(format!("Staged changes: {} files", status.staged_count()));
                }
                if status.has_unstaged_changes() {
                    Output::sub_item(format!(
                        "Unstaged changes: {} files",
                        status.unstaged_count()
                    ));
                }
                if status.has_untracked_files() {
                    Output::sub_item(format!(
                        "Untracked files: {} files",
                        status.untracked_count()
                    ));
                }
            }
        }
        Err(_) => {
            Output::sub_item("Working directory: status unavailable");
        }
    }

    Output::tip("Use 'git status' for detailed file-level status");
    Output::sub_item("Use 'ca entry list' to see all entries");

    Ok(())
}

/// List all entries in the stack with edit status
async fn list_entries(verbose: 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 manager = StackManager::new(&repo_root)?;

    let active_stack = manager.get_active_stack().ok_or_else(|| {
        CascadeError::config(
            "No active stack. Create a stack first with 'ca stack create'".to_string(),
        )
    })?;

    if active_stack.entries.is_empty() {
        Output::info(format!(
            "Active stack '{}' has no entries yet",
            active_stack.name
        ));
        Output::sub_item("Add some commits to the stack with 'ca stack push'");
        return Ok(());
    }

    Output::section(format!(
        "Stack: {} ({} entries)",
        active_stack.name,
        active_stack.entries.len()
    ));

    let edit_mode_info = manager.get_edit_mode_info();
    let edit_target_entry_id = edit_mode_info
        .as_ref()
        .and_then(|info| info.target_entry_id);

    for (i, entry) in active_stack.entries.iter().enumerate() {
        let entry_num = i + 1;
        let status_label = Output::entry_status(entry.is_submitted, entry.is_merged);
        let mut entry_line = format!(
            "{} {} ({})",
            status_label,
            entry.short_message(50),
            entry.short_hash()
        );

        if let Some(pr_id) = &entry.pull_request_id {
            entry_line.push_str(&format!(" PR: #{pr_id}"));
        }

        if Some(entry.id) == edit_target_entry_id {
            entry_line.push_str(" [edit target]");
        }

        Output::numbered_item(entry_num, entry_line);

        if verbose {
            Output::sub_item(format!("Branch: {}", entry.branch));
            Output::sub_item(format!("Commit: {}", entry.commit_hash));
            Output::sub_item(format!(
                "Created: {}",
                entry.created_at.format("%Y-%m-%d %H:%M:%S")
            ));

            if entry.is_merged {
                Output::sub_item("Status: Merged");
            } else if entry.is_submitted {
                Output::sub_item("Status: Submitted");
            } else {
                Output::sub_item("Status: Draft");
            }

            Output::sub_item("Message:");
            for line in entry.message.lines() {
                Output::sub_item(format!("  {line}"));
            }

            if Some(entry.id) == edit_target_entry_id {
                Output::sub_item("Edit mode target");

                match crate::git::GitRepository::open(&repo_root) {
                    Ok(repo) => match repo.get_status_summary() {
                        Ok(status) => {
                            if !status.is_clean() {
                                Output::sub_item("Git Status:");
                                if status.has_staged_changes() {
                                    Output::sub_item(format!(
                                        "  Staged: {} files",
                                        status.staged_count()
                                    ));
                                }
                                if status.has_unstaged_changes() {
                                    Output::sub_item(format!(
                                        "  Unstaged: {} files",
                                        status.unstaged_count()
                                    ));
                                }
                                if status.has_untracked_files() {
                                    Output::sub_item(format!(
                                        "  Untracked: {} files",
                                        status.untracked_count()
                                    ));
                                }
                            } else {
                                Output::sub_item("Git Status: clean");
                            }
                        }
                        Err(_) => {
                            Output::sub_item("Git Status: unavailable");
                        }
                    },
                    Err(_) => {
                        Output::sub_item("Git Status: unavailable");
                    }
                }
            }
        }
    }

    if edit_mode_info.is_some() {
        Output::spacing();
        Output::info("Edit mode active - use 'ca entry status' for details");
    } else {
        Output::spacing();
        Output::tip("Use 'ca entry checkout' to start editing an entry");
    }

    Ok(())
}

/// Clear/exit edit mode (useful for recovering from corrupted state)
async fn clear_edit_mode(skip_confirmation: 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 mut manager = StackManager::new(&repo_root)?;

    if !manager.is_in_edit_mode() {
        Output::info("Not currently in edit mode");
        return Ok(());
    }

    // Show current edit mode info
    if let Some(edit_info) = manager.get_edit_mode_info() {
        Output::section("Current edit mode state");

        if let Some(target_entry_id) = &edit_info.target_entry_id {
            Output::sub_item(format!("Target entry: {}", target_entry_id));

            // Try to find the entry
            if let Some(active_stack) = manager.get_active_stack() {
                if let Some(entry) = active_stack
                    .entries
                    .iter()
                    .find(|e| e.id == *target_entry_id)
                {
                    Output::sub_item(format!("Entry: {}", entry.short_message(50)));
                } else {
                    Output::warning("Target entry not found in stack (corrupted state)");
                }
            }
        }

        Output::sub_item(format!(
            "Original commit: {}",
            &edit_info.original_commit_hash[..8]
        ));
        Output::sub_item(format!(
            "Started: {}",
            edit_info.started_at.format("%Y-%m-%d %H:%M:%S")
        ));
    }

    // Confirm before clearing
    if !skip_confirmation {
        println!();
        let confirmed = Confirm::with_theme(&ColorfulTheme::default())
            .with_prompt("Clear edit mode state?")
            .default(true)
            .interact()
            .map_err(|e| CascadeError::config(format!("Failed to get user confirmation: {e}")))?;

        if !confirmed {
            return Err(CascadeError::config("Operation cancelled."));
        }
    }

    // Clear edit mode
    manager.exit_edit_mode()?;

    Output::success("Edit mode cleared");
    Output::tip("Use 'ca entry checkout' to start a new edit session");

    Ok(())
}

/// Amend the current stack entry commit and update working branch
async fn amend_entry(message: Option<String>, _all: bool, push: 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 mut manager = StackManager::new(&repo_root)?;
    let repo = crate::git::GitRepository::open(&repo_root)?;

    let current_branch = repo.get_current_branch()?;

    // Get active stack info we need (clone to avoid borrow issues)
    let (stack_id, entry_index, entry_id, entry_branch, working_branch, has_dependents, has_pr) = {
        let active_stack = manager.get_active_stack().ok_or_else(|| {
            CascadeError::config("No active stack. Create a stack first with 'ca stack create'")
        })?;

        // Find which entry we're amending (must be on a stack branch)
        let mut found_entry = None;

        for (idx, entry) in active_stack.entries.iter().enumerate() {
            if entry.branch == current_branch {
                found_entry = Some((
                    idx,
                    entry.id,
                    entry.branch.clone(),
                    entry.pull_request_id.clone(),
                ));
                break;
            }
        }

        match found_entry {
            Some((idx, id, branch, pr_id)) => {
                let has_dependents = active_stack
                    .entries
                    .iter()
                    .skip(idx + 1)
                    .any(|entry| !entry.is_merged);
                (
                    active_stack.id,
                    idx,
                    id,
                    branch,
                    active_stack.working_branch.clone(),
                    has_dependents,
                    pr_id.is_some(),
                )
            }
            None => {
                return Err(CascadeError::config(format!(
                    "Current branch '{}' is not a stack entry branch.\n\
                     Use 'ca entry checkout <N>' to checkout a stack entry first.",
                    current_branch
                )));
            }
        }
    };

    Output::section(format!("Amending stack entry #{}", entry_index + 1));

    // 1. Perform the git commit --amend
    // Always auto-stage changes (like 'git commit -a --amend')
    // This matches user expectations: "amend my changes" should include all working changes
    let mut amend_args = vec!["commit", "-a", "--amend"];

    if let Some(ref msg) = message {
        amend_args.push("-m");
        amend_args.push(msg);
    } else {
        // Use git editor for interactive message editing
        amend_args.push("--no-edit");
    }

    debug!("Running git {}", amend_args.join(" "));

    // Set environment variable to bypass pre-commit hook (avoid infinite loop)
    let output = std::process::Command::new("git")
        .args(&amend_args)
        .env("CASCADE_SKIP_HOOKS", "1")
        .current_dir(&repo_root)
        .stdout(std::process::Stdio::null()) // Suppress Git's output
        .stderr(std::process::Stdio::piped()) // Capture errors
        .output()
        .map_err(CascadeError::Io)?;

    if !output.status.success() {
        let stderr = String::from_utf8_lossy(&output.stderr);
        return Err(CascadeError::branch(format!(
            "Failed to amend commit: {}",
            stderr.trim()
        )));
    }

    Output::success("Commit amended");

    // 2. Get the new commit hash
    let new_commit_hash = repo.get_head_commit()?.id().to_string();
    debug!("New commit hash after amend: {}", new_commit_hash);

    // 3. Update stack metadata with new commit hash using safe wrapper
    {
        let stack = manager
            .get_stack_mut(&stack_id)
            .ok_or_else(|| CascadeError::config("Stack not found"))?;

        let old_hash = stack
            .entries
            .iter()
            .find(|e| e.id == entry_id)
            .map(|e| e.commit_hash.clone())
            .ok_or_else(|| CascadeError::config("Entry not found"))?;

        stack
            .update_entry_commit_hash(&entry_id, new_commit_hash.clone())
            .map_err(CascadeError::config)?;

        debug!(
            "Updated entry commit hash: {} -> {}",
            &old_hash[..8],
            &new_commit_hash[..8]
        );
        Output::sub_item(format!(
            "Updated metadata: {}{}",
            &old_hash[..8],
            &new_commit_hash[..8]
        ));
    }

    manager.save_to_disk()?;

    // 4. Update working branch to keep safety net in sync
    if let Some(ref working_branch_name) = working_branch {
        Output::sub_item(format!("Updating working branch: {}", working_branch_name));

        // Force update the working branch to point to the amended commit
        repo.update_branch_to_commit(working_branch_name, &new_commit_hash)?;

        Output::success(format!("Working branch '{}' updated", working_branch_name));
    } else {
        Output::warning("No working branch found - create one with 'ca stack create' for safety");
    }

    // 5. Auto-push if requested and entry has a PR
    if push {
        println!();

        if has_pr {
            Output::section("Force-pushing to remote");

            // Set env var to skip force-push confirmation
            std::env::set_var("FORCE_PUSH_NO_CONFIRM", "1");

            repo.force_push_branch(&current_branch, &current_branch)?;
            Output::success(format!("Force-pushed '{}' to remote", current_branch));
            Output::sub_item("PR will be automatically updated");
        } else {
            Output::warning("No PR found for this entry - skipping push");
            Output::tip("Use 'ca submit' to create a PR");
        }
    }

    // Summary
    println!();
    Output::section("Summary");
    Output::bullet(format!(
        "Amended entry #{} on branch '{}'",
        entry_index + 1,
        entry_branch
    ));
    if working_branch.is_some() {
        Output::bullet("Working branch updated");
    }
    if push {
        Output::bullet("Changes force-pushed to remote");
    }

    // Automatically restack dependent entries (no flag needed - always required)
    if has_dependents {
        println!();
        let dependent_count = {
            let stack = manager
                .get_stack(&stack_id)
                .ok_or_else(|| CascadeError::config("Stack not found"))?;
            stack
                .entries
                .iter()
                .skip(entry_index + 1)
                .filter(|entry| !entry.is_merged)
                .count()
        };

        let plural = if dependent_count == 1 {
            "entry"
        } else {
            "entries"
        };

        Output::section(format!(
            "Restacking {} dependent {}",
            dependent_count, plural
        ));

        // Rebase dependent entries using the same logic as ca sync
        // This ensures entries #4, #5, etc. are rebased onto the amended entry #3
        match restack_dependent_entries(&repo_root, &stack_id, entry_index).await {
            Ok(_) => {
                Output::success(format!(
                    "Restacked {} dependent {}",
                    dependent_count, plural
                ));
            }
            Err(e) => {
                println!();
                Output::error(format!("Failed to restack dependent entries: {}", e));
                println!();
                Output::section("Recovery Steps");
                Output::bullet("Resolve any conflicts in your editor");
                Output::bullet("Stage resolved files: git add <files>");
                Output::bullet("Continue: ca entry continue");
                Output::bullet("Or abort: ca entry abort");
                println!();
                return Err(CascadeError::validation(
                    "Restack failed - resolve conflicts and run 'ca entry continue'",
                ));
            }
        }
    }

    // Tip about --push flag
    if !push && !has_dependents {
        println!();
        Output::tip("Use --push to automatically force-push after amending");
    }

    Ok(())
}

/// Restack dependent entries after amending
/// This ensures entries after the amended one are rebased onto the new commit
///
/// CRITICAL CONSTRAINTS:
/// - User is currently on the amended branch (e.g., entry #3)
/// - We must NOT touch the amended entry or any entries before it
/// - We only rebase entries AFTER the amended one (e.g., #4, #5)
/// - Each dependent entry is rebased onto its parent (not develop!)
/// - After restacking, update working branch to point to new top of stack
async fn restack_dependent_entries(
    repo_root: &Path,
    stack_id: &uuid::Uuid,
    amended_entry_index: usize,
) -> Result<()> {
    use tracing::debug;

    debug!(
        "Restacking dependent entries after amending entry #{}",
        amended_entry_index + 1
    );

    // Load fresh stack manager and repo
    let mut stack_manager = StackManager::new(repo_root)?;
    let git_repo = GitRepository::open(repo_root)?;

    // Get the stack (clone to avoid borrow issues)
    let stack = stack_manager
        .get_stack(stack_id)
        .ok_or_else(|| CascadeError::config("Stack not found"))?
        .clone();

    // Get the amended entry (this is the new "base" for dependents)
    let amended_entry = &stack.entries[amended_entry_index];
    let amended_branch = &amended_entry.branch;
    let amended_commit = &amended_entry.commit_hash;

    debug!(
        "Amended entry: branch='{}', commit={}",
        amended_branch,
        &amended_commit[..8]
    );

    // Collect entries AFTER the amended one
    // We need ALL entries (including merged) to correctly advance the base commit
    let dependent_entries: Vec<(usize, StackEntry)> = stack
        .entries
        .iter()
        .enumerate()
        .skip(amended_entry_index + 1)
        .map(|(idx, entry)| (idx, entry.clone()))
        .collect();

    if dependent_entries.is_empty() {
        debug!("No dependent entries after amended entry");
        return Ok(());
    }

    let unmerged_count = dependent_entries
        .iter()
        .filter(|(_, e)| !e.is_merged)
        .count();
    debug!(
        "Will process {} dependent entries ({} unmerged, {} merged)",
        dependent_entries.len(),
        unmerged_count,
        dependent_entries.len() - unmerged_count
    );

    // We're currently on the amended branch - save it to restore later
    let original_branch = git_repo.get_current_branch()?;
    debug!("Currently on branch: {}", original_branch);

    // Rebase each dependent entry sequentially
    // Entry #4 onto amended entry #3, then entry #5 onto new entry #4, etc.
    let mut current_base_commit = amended_commit.clone();

    for (i, &(original_index, ref entry)) in dependent_entries.iter().enumerate() {
        let entry_num = original_index + 1; // Convert 0-based index to 1-based entry number

        // Skip merged entries - they're already in the base branch
        // But we still need to advance current_base_commit past them
        if entry.is_merged {
            debug!(
                "Entry #{} ({}) is merged, advancing base to {}",
                entry_num,
                entry.branch,
                &entry.commit_hash[..8]
            );
            current_base_commit = entry.commit_hash.clone();
            continue;
        }

        debug!(
            "Rebasing entry #{} ({}): {} onto {}",
            entry_num,
            entry.branch,
            &entry.commit_hash[..8],
            &current_base_commit[..8]
        );

        // Save restack state BEFORE cherry-picking
        // This allows ca entry continue to resume if there are conflicts
        let remaining_entries: Vec<(usize, StackEntry)> =
            dependent_entries.iter().skip(i + 1).cloned().collect();

        let restack_state = RestackState {
            stack_id: *stack_id,
            amended_entry_index,
            amended_branch: amended_branch.clone(),
            current_entry_index: original_index,
            remaining_entries,
        };
        restack_state.save(repo_root)?;

        // Cherry-pick this entry's commit onto the current base
        // This is similar to what rebase_all_entries does, but for one entry at a time
        let temp_branch = format!("{}-restack-temp", entry.branch);

        // Create temp branch from current base
        git_repo.create_branch(&temp_branch, Some(&current_base_commit))?;
        git_repo.checkout_branch_silent(&temp_branch)?;

        // Cherry-pick the entry's commit
        match git_repo.cherry_pick(&entry.commit_hash) {
            Ok(new_commit_hash) => {
                // Update the entry's branch to point to the new commit
                git_repo.update_branch_to_commit(&entry.branch, &new_commit_hash)?;

                // Update metadata
                {
                    let stack_mut = stack_manager
                        .get_stack_mut(stack_id)
                        .ok_or_else(|| CascadeError::config("Stack not found"))?;

                    stack_mut
                        .update_entry_commit_hash(&entry.id, new_commit_hash.clone())
                        .map_err(CascadeError::config)?;
                }
                stack_manager.save_to_disk()?;

                debug!("  → New commit: {}", &new_commit_hash[..8]);

                // This becomes the base for the next entry
                current_base_commit = new_commit_hash;
            }
            Err(e) => {
                // Cherry-pick failed - LEAVE EVERYTHING INTACT for recovery
                // CRITICAL: DO NOT checkout or delete temp branch!
                // The user needs CHERRY_PICK_HEAD and conflict state to resolve/abort

                println!();
                Output::error(format!(
                    "Failed to restack entry #{} ({}): {}",
                    entry_num, entry.branch, e
                ));
                println!();
                Output::section("Recovery Options");
                println!();
                Output::sub_item("To continue after resolving conflicts:");
                Output::bullet("1. Check for conflicts: git status");
                Output::bullet("2. Resolve conflicts in your editor");
                Output::bullet("3. Stage resolved files: git add <files>");
                Output::bullet("4. Continue restack: ca entry continue");
                println!();
                Output::sub_item("To abort and undo the restack:");
                Output::bullet("→ Run: ca entry abort");
                Output::bullet("→ Then check: ca validate");
                println!();
                Output::tip("Both commands bypass hooks to avoid edit-mode detection");

                return Err(CascadeError::validation(format!(
                    "Restack paused at entry #{} - resolve conflicts or abort",
                    entry_num
                )));
            }
        }

        // Clean up temp branch - checkout away first, then force delete
        // CRITICAL: Must checkout away from temp branch before deleting it
        git_repo.checkout_branch_unsafe(&original_branch)?;
        // Use unsafe delete to avoid interactive prompts for unpushed commits
        git_repo.delete_branch_unsafe(&temp_branch)?;
    }

    // At this point we're already on original_branch from the last loop iteration

    // Update working branch to point to the NEW top of stack (last dependent entry)
    if let Some(ref working_branch_name) = stack.working_branch {
        debug!(
            "Updating working branch '{}' to {}",
            working_branch_name,
            &current_base_commit[..8]
        );
        git_repo.update_branch_to_commit(working_branch_name, &current_base_commit)?;
    }

    // Delete restack state file - restack completed successfully
    RestackState::delete(repo_root)?;

    debug!("Successfully restacked {} entries", dependent_entries.len());
    Ok(())
}

/// Continue restacking after resolving cherry-pick conflicts
/// This completes the cherry-pick (skipping hooks) and updates metadata
async fn continue_restack() -> Result<()> {
    use tracing::debug;

    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)?;
    let git_repo = GitRepository::open(&repo_root)?;

    // Check if there's a cherry-pick in progress
    let cherry_pick_head = git_repo.git_dir().join("CHERRY_PICK_HEAD");
    if !cherry_pick_head.exists() {
        return Err(CascadeError::validation(
            "No cherry-pick in progress. Nothing to continue.".to_string(),
        ));
    }

    Output::section("Continuing restack");

    // Get current branch (should be *-restack-temp)
    let current_branch = git_repo.get_current_branch()?;
    if !current_branch.ends_with("-restack-temp") {
        return Err(CascadeError::validation(format!(
            "Expected to be on a *-restack-temp branch, but on '{}'. Cannot continue safely.",
            current_branch
        )));
    }

    // Extract the original entry branch name
    let entry_branch = current_branch.trim_end_matches("-restack-temp");

    // Auto-stage resolved conflict files (only files that had conflicts)
    // This prevents leaking unrelated changes while helping users who forget git add
    match git_repo.stage_conflict_resolved_files() {
        Ok(_) => {
            Output::sub_item("Auto-staged resolved conflict files");
        }
        Err(e) => {
            debug!("Could not auto-stage conflict files: {}", e);
            Output::warning("Could not auto-stage files. Make sure you've run 'git add <files>'");
        }
    }

    // Complete the cherry-pick with CASCADE_SKIP_HOOKS to bypass pre-commit hook
    let output = std::process::Command::new("git")
        .args(["cherry-pick", "--continue"])
        .env("CASCADE_SKIP_HOOKS", "1")
        .current_dir(&repo_root)
        .stdout(std::process::Stdio::null())
        .stderr(std::process::Stdio::piped())
        .output()
        .map_err(CascadeError::Io)?;

    if !output.status.success() {
        let stderr = String::from_utf8_lossy(&output.stderr);
        return Err(CascadeError::validation(format!(
            "Failed to continue cherry-pick: {}\n\n\
            Make sure all conflicts are resolved and staged:\n\
            1. Check status: git status\n\
            2. Stage resolved files: git add <files>\n\
            3. Try again: ca entry continue",
            stderr.trim()
        )));
    }

    Output::success("Cherry-pick completed");

    // CRITICAL: Get the new commit hash BEFORE cleaning up temp branch
    let new_commit_hash = git_repo.get_head_commit()?.id().to_string();
    debug!("New commit hash: {}", &new_commit_hash[..8]);

    // CRITICAL: Update the entry branch to point to the new commit
    // This must happen BEFORE deleting the temp branch!
    Output::sub_item(format!("Updating branch '{}' to new commit", entry_branch));
    git_repo.update_branch_to_commit(entry_branch, &new_commit_hash)?;

    // Load restack state BEFORE updating metadata to get the correct stack ID
    // This prevents issues if user switched active stack during conflict resolution
    let restack_state = RestackState::load(&repo_root)?;

    // CRITICAL: Update metadata with the new commit hash
    let mut stack_manager = StackManager::new(&repo_root)?;

    // Use the stack ID from restack state if available, otherwise fall back to active stack
    let stack_id = if let Some(ref state) = restack_state {
        state.stack_id
    } else {
        // No restack state - this is a standalone continue, use active stack
        stack_manager
            .get_active_stack()
            .ok_or_else(|| CascadeError::config("No active stack"))?
            .id
    };

    // Get the stack and find the entry by branch name
    let stack = stack_manager
        .get_stack(&stack_id)
        .ok_or_else(|| CascadeError::config("Stack not found"))?;

    let entry_id = stack
        .entries
        .iter()
        .find(|e| e.branch == entry_branch)
        .map(|e| e.id)
        .ok_or_else(|| {
            CascadeError::config(format!(
                "Could not find entry for branch '{}'",
                entry_branch
            ))
        })?;

    {
        let stack_mut = stack_manager
            .get_stack_mut(&stack_id)
            .ok_or_else(|| CascadeError::config("Stack not found"))?;

        stack_mut
            .update_entry_commit_hash(&entry_id, new_commit_hash.clone())
            .map_err(CascadeError::config)?;
    }
    stack_manager.save_to_disk()?;

    Output::sub_item(format!("Updated metadata: {}", &new_commit_hash[..8]));

    // Now safe to clean up temp branch
    Output::sub_item(format!("Cleaning up temp branch '{}'", current_branch));

    // Checkout to entry branch (which now points to the new commit)
    git_repo.checkout_branch_unsafe(entry_branch)?;

    // Delete the temp branch
    git_repo.delete_branch_unsafe(&current_branch)?;

    // Continue with restack if there are remaining entries
    if let Some(state) = restack_state {
        if !state.remaining_entries.is_empty() {
            println!();
            Output::info(format!(
                "Continuing restack: {} remaining entries",
                state.remaining_entries.len()
            ));
            println!();

            // Continue restacking remaining entries
            // Use the new commit as the base for the next entry
            let mut current_base_commit = new_commit_hash;

            for &(original_index, ref entry) in state.remaining_entries.iter() {
                let entry_num = original_index + 1;

                // Skip merged entries
                if entry.is_merged {
                    debug!(
                        "Entry #{} ({}) is merged, advancing base",
                        entry_num, entry.branch
                    );
                    current_base_commit = entry.commit_hash.clone();
                    continue;
                }

                debug!(
                    "Restacking entry #{} ({}): {} onto {}",
                    entry_num,
                    entry.branch,
                    &entry.commit_hash[..8],
                    &current_base_commit[..8]
                );

                // Update state for this entry
                let remaining_after_this: Vec<(usize, StackEntry)> = state
                    .remaining_entries
                    .iter()
                    .skip_while(|(idx, _)| *idx != original_index)
                    .skip(1)
                    .cloned()
                    .collect();

                let updated_state = RestackState {
                    stack_id: state.stack_id,
                    amended_entry_index: state.amended_entry_index,
                    amended_branch: state.amended_branch.clone(),
                    current_entry_index: original_index,
                    remaining_entries: remaining_after_this,
                };
                updated_state.save(&repo_root)?;

                // Cherry-pick this entry
                let temp_branch = format!("{}-restack-temp", entry.branch);
                git_repo.create_branch(&temp_branch, Some(&current_base_commit))?;
                git_repo.checkout_branch_silent(&temp_branch)?;

                match git_repo.cherry_pick(&entry.commit_hash) {
                    Ok(new_hash) => {
                        // Update branch and metadata
                        git_repo.update_branch_to_commit(&entry.branch, &new_hash)?;

                        {
                            let stack_mut = stack_manager
                                .get_stack_mut(&state.stack_id)
                                .ok_or_else(|| CascadeError::config("Stack not found"))?;

                            stack_mut
                                .update_entry_commit_hash(&entry.id, new_hash.clone())
                                .map_err(CascadeError::config)?;
                        }
                        stack_manager.save_to_disk()?;

                        debug!("  → New commit: {}", &new_hash[..8]);

                        // Clean up temp branch
                        git_repo.checkout_branch_unsafe(&entry.branch)?;
                        git_repo.delete_branch_unsafe(&temp_branch)?;

                        // This becomes the base for the next entry
                        current_base_commit = new_hash;
                    }
                    Err(e) => {
                        // Cherry-pick failed - leave state intact for next continue
                        println!();
                        Output::error(format!(
                            "Failed to restack entry #{} ({}): {}",
                            entry_num, entry.branch, e
                        ));
                        println!();
                        Output::section("Recovery Options");
                        println!();
                        Output::sub_item("To continue after resolving conflicts:");
                        Output::bullet("1. Check for conflicts: git status");
                        Output::bullet("2. Resolve conflicts in your editor");
                        Output::bullet("3. Continue restack: ca entry continue");
                        println!();
                        Output::sub_item("To abort:");
                        Output::bullet("→ Run: ca entry abort");
                        println!();

                        return Err(CascadeError::validation(format!(
                            "Restack paused at entry #{} - resolve conflicts or abort",
                            entry_num
                        )));
                    }
                }
            }

            // All entries restacked successfully - update working branch
            let stack = stack_manager
                .get_stack(&state.stack_id)
                .ok_or_else(|| CascadeError::config("Stack not found"))?;

            if let Some(ref working_branch_name) = stack.working_branch {
                debug!(
                    "Updating working branch '{}' to {}",
                    working_branch_name,
                    &current_base_commit[..8]
                );
                git_repo.update_branch_to_commit(working_branch_name, &current_base_commit)?;
            }

            // Delete state file - restack completed
            RestackState::delete(&repo_root)?;

            // Checkout back to the amended branch (where we started)
            git_repo.checkout_branch_unsafe(&state.amended_branch)?;

            println!();
            Output::success("Restack completed successfully!");
            Output::sub_item("All dependent entries have been rebased");
            Output::sub_item("Working branch updated");
            println!();
        } else {
            // No remaining entries - this was the last one!
            // Update working branch to point to the newly resolved commit
            let stack = stack_manager
                .get_stack(&state.stack_id)
                .ok_or_else(|| CascadeError::config("Stack not found"))?;

            if let Some(ref working_branch_name) = stack.working_branch {
                debug!(
                    "Updating working branch '{}' to {}",
                    working_branch_name,
                    &new_commit_hash[..8]
                );
                git_repo.update_branch_to_commit(working_branch_name, &new_commit_hash)?;
                Output::sub_item(format!(
                    "Updated working branch '{}' to latest commit",
                    working_branch_name
                ));
            }

            // Clean up state file
            RestackState::delete(&repo_root)?;

            // Checkout back to the amended branch (where we started)
            git_repo.checkout_branch_unsafe(&state.amended_branch)?;

            println!();
            Output::success("Restack completed!");
            Output::sub_item("All dependent entries have been rebased");
            println!();
        }
    } else {
        // No state file - this was a standalone continue (not part of restack)
        println!();
        Output::success("Cherry-pick completed!");
        println!();
    }

    Ok(())
}

/// Abort an in-progress restack operation
/// Safely aborts the cherry-pick using CASCADE_SKIP_HOOKS to bypass hook issues
async fn abort_restack() -> 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)?;

    // Check if there's a cherry-pick in progress
    let cherry_pick_head = crate::git::resolve_git_dir(&repo_root)?.join("CHERRY_PICK_HEAD");
    if !cherry_pick_head.exists() {
        return Err(CascadeError::validation(
            "No cherry-pick in progress. Nothing to abort.".to_string(),
        ));
    }

    Output::section("Aborting restack");

    // Abort the cherry-pick with CASCADE_SKIP_HOOKS to bypass pre-commit hook
    let output = std::process::Command::new("git")
        .args(["cherry-pick", "--abort"])
        .env("CASCADE_SKIP_HOOKS", "1")
        .current_dir(&repo_root)
        .stdout(std::process::Stdio::null())
        .stderr(std::process::Stdio::piped())
        .output()
        .map_err(CascadeError::Io)?;

    if !output.status.success() {
        let stderr = String::from_utf8_lossy(&output.stderr);
        return Err(CascadeError::validation(format!(
            "Failed to abort cherry-pick: {}\n\n\
            You may need to manually clean up the Git state:\n\
            1. Check status: git status\n\
            2. Reset if needed: git reset --hard HEAD",
            stderr.trim()
        )));
    }

    Output::success("Cherry-pick aborted");

    // Clean up any temp restack branches
    let git_repo = GitRepository::open(&repo_root)?;
    let current_branch = git_repo.get_current_branch().ok();

    // If we're on a *-restack-temp branch, clean it up
    if let Some(ref branch) = current_branch {
        if branch.ends_with("-restack-temp") {
            // Extract the original branch name
            let original_branch = branch.trim_end_matches("-restack-temp");

            Output::sub_item(format!("Cleaning up temp branch '{}'", branch));

            // Checkout to original branch first
            if let Err(e) = git_repo.checkout_branch_unsafe(original_branch) {
                Output::warning(format!(
                    "Could not checkout to '{}': {}. You may need to checkout manually.",
                    original_branch, e
                ));
            } else {
                // Delete the temp branch
                if let Err(e) = git_repo.delete_branch_unsafe(branch) {
                    Output::warning(format!(
                        "Could not delete temp branch '{}': {}. You may need to delete it manually.",
                        branch, e
                    ));
                }
            }
        }
    }

    // Delete restack state file - operation was aborted
    RestackState::delete(&repo_root)?;

    println!();
    Output::warning("Restack was aborted - stack may be in inconsistent state");
    println!();
    Output::section("Next Steps");
    Output::bullet("Check stack state: ca validate");
    Output::bullet("If needed, fix issues with: ca validate (choose 'Incorporate' or 'Reset')");
    Output::bullet("Or try restack again: ca sync");
    println!();

    Ok(())
}