cascade_cli/cli/commands/
stack.rs

1use crate::bitbucket::BitbucketIntegration;
2use crate::cli::output::Output;
3use crate::errors::{CascadeError, Result};
4use crate::git::{find_repository_root, GitRepository};
5use crate::stack::{CleanupManager, CleanupOptions, CleanupResult, StackManager, StackStatus};
6use clap::{Subcommand, ValueEnum};
7use dialoguer::{theme::ColorfulTheme, Confirm};
8// Progress bars removed - using professional Output module instead
9use std::env;
10use tracing::{debug, warn};
11use uuid::Uuid;
12
13/// CLI argument version of RebaseStrategy
14#[derive(ValueEnum, Clone, Debug)]
15pub enum RebaseStrategyArg {
16    /// Force-push rebased commits to original branches (preserves PR history)
17    ForcePush,
18    /// Interactive rebase with conflict resolution
19    Interactive,
20}
21
22#[derive(ValueEnum, Clone, Debug)]
23pub enum MergeStrategyArg {
24    /// Create a merge commit
25    Merge,
26    /// Squash all commits into one
27    Squash,
28    /// Fast-forward merge when possible
29    FastForward,
30}
31
32impl From<MergeStrategyArg> for crate::bitbucket::pull_request::MergeStrategy {
33    fn from(arg: MergeStrategyArg) -> Self {
34        match arg {
35            MergeStrategyArg::Merge => Self::Merge,
36            MergeStrategyArg::Squash => Self::Squash,
37            MergeStrategyArg::FastForward => Self::FastForward,
38        }
39    }
40}
41
42#[derive(Debug, Subcommand)]
43pub enum StackAction {
44    /// Create a new stack
45    Create {
46        /// Name of the stack
47        name: String,
48        /// Base branch for the stack
49        #[arg(long, short)]
50        base: Option<String>,
51        /// Description of the stack
52        #[arg(long, short)]
53        description: Option<String>,
54    },
55
56    /// List all stacks
57    List {
58        /// Show detailed information
59        #[arg(long, short)]
60        verbose: bool,
61        /// Show only active stack
62        #[arg(long)]
63        active: bool,
64        /// Output format (name, id, status)
65        #[arg(long)]
66        format: Option<String>,
67    },
68
69    /// Switch to a different stack
70    Switch {
71        /// Name of the stack to switch to
72        name: String,
73    },
74
75    /// Deactivate the current stack (turn off stack mode)
76    Deactivate {
77        /// Force deactivation without confirmation
78        #[arg(long)]
79        force: bool,
80    },
81
82    /// Show the current stack status  
83    Show {
84        /// Show detailed pull request information
85        #[arg(short, long)]
86        verbose: bool,
87        /// Show mergability status for all PRs
88        #[arg(short, long)]
89        mergeable: bool,
90    },
91
92    /// Push current commit to the top of the stack
93    Push {
94        /// Branch name for this commit
95        #[arg(long, short)]
96        branch: Option<String>,
97        /// Commit message (if creating a new commit)
98        #[arg(long, short)]
99        message: Option<String>,
100        /// Use specific commit hash instead of HEAD
101        #[arg(long)]
102        commit: Option<String>,
103        /// Push commits since this reference (e.g., HEAD~3)
104        #[arg(long)]
105        since: Option<String>,
106        /// Push multiple specific commits (comma-separated)
107        #[arg(long)]
108        commits: Option<String>,
109        /// Squash unpushed commits before pushing (optional: specify count)
110        #[arg(long, num_args = 0..=1, default_missing_value = "0")]
111        squash: Option<usize>,
112        /// Squash all commits since this reference (e.g., HEAD~5)
113        #[arg(long)]
114        squash_since: Option<String>,
115        /// Auto-create feature branch when pushing from base branch
116        #[arg(long)]
117        auto_branch: bool,
118        /// Allow pushing commits from base branch (not recommended)
119        #[arg(long)]
120        allow_base_branch: bool,
121        /// Show what would be pushed without actually pushing
122        #[arg(long)]
123        dry_run: bool,
124    },
125
126    /// Pop the top commit from the stack
127    Pop {
128        /// Keep the branch (don't delete it)
129        #[arg(long)]
130        keep_branch: bool,
131    },
132
133    /// Submit a stack entry for review
134    Submit {
135        /// Stack entry number (1-based, defaults to all unsubmitted)
136        entry: Option<usize>,
137        /// Pull request title
138        #[arg(long, short)]
139        title: Option<String>,
140        /// Pull request description
141        #[arg(long, short)]
142        description: Option<String>,
143        /// Submit range of entries (e.g., "1-3" or "2,4,6")
144        #[arg(long)]
145        range: Option<String>,
146        /// Create draft pull requests (default: true, use --no-draft to create ready PRs)
147        #[arg(long, default_value_t = true)]
148        draft: bool,
149        /// Open the PR(s) in your default browser after submission (default: true, use --no-open to disable)
150        #[arg(long, default_value_t = true)]
151        open: bool,
152    },
153
154    /// Check status of all pull requests in a stack
155    Status {
156        /// Name of the stack (defaults to active stack)
157        name: Option<String>,
158    },
159
160    /// List all pull requests for the repository
161    Prs {
162        /// Filter by state (open, merged, declined)
163        #[arg(long)]
164        state: Option<String>,
165        /// Show detailed information
166        #[arg(long, short)]
167        verbose: bool,
168    },
169
170    /// Check stack status with remote repository (read-only)
171    Check {
172        /// Force check even if there are issues
173        #[arg(long)]
174        force: bool,
175    },
176
177    /// Sync stack with remote repository (pull + rebase + cleanup)
178    Sync {
179        /// Force sync even if there are conflicts
180        #[arg(long)]
181        force: bool,
182        /// Also cleanup merged branches after sync
183        #[arg(long)]
184        cleanup: bool,
185        /// Interactive mode for conflict resolution
186        #[arg(long, short)]
187        interactive: bool,
188    },
189
190    /// Rebase stack on updated base branch
191    Rebase {
192        /// Interactive rebase
193        #[arg(long, short)]
194        interactive: bool,
195        /// Target base branch (defaults to stack's base branch)
196        #[arg(long)]
197        onto: Option<String>,
198        /// Rebase strategy to use
199        #[arg(long, value_enum)]
200        strategy: Option<RebaseStrategyArg>,
201    },
202
203    /// Continue an in-progress rebase after resolving conflicts
204    ContinueRebase,
205
206    /// Abort an in-progress rebase
207    AbortRebase,
208
209    /// Show rebase status and conflict resolution guidance
210    RebaseStatus,
211
212    /// Delete a stack
213    Delete {
214        /// Name of the stack to delete
215        name: String,
216        /// Force deletion without confirmation
217        #[arg(long)]
218        force: bool,
219    },
220
221    /// Validate stack integrity and handle branch modifications
222    ///
223    /// Checks that stack branches match their expected commit hashes.
224    /// Detects when branches have been manually modified (extra commits added).
225    ///
226    /// Available --fix modes:
227    /// • incorporate: Update stack entry to include extra commits
228    /// • split: Create new stack entry for extra commits  
229    /// • reset: Remove extra commits (DESTRUCTIVE - loses work)
230    ///
231    /// Without --fix, runs interactively asking for each modification.
232    Validate {
233        /// Name of the stack (defaults to active stack)
234        name: Option<String>,
235        /// Auto-fix mode: incorporate, split, or reset
236        #[arg(long)]
237        fix: Option<String>,
238    },
239
240    /// Land (merge) approved stack entries
241    Land {
242        /// Stack entry number to land (1-based index, optional)
243        entry: Option<usize>,
244        /// Force land even with blocking issues (dangerous)
245        #[arg(short, long)]
246        force: bool,
247        /// Dry run - show what would be landed without doing it
248        #[arg(short, long)]
249        dry_run: bool,
250        /// Use server-side validation (safer, checks approvals/builds)
251        #[arg(long)]
252        auto: bool,
253        /// Wait for builds to complete before merging
254        #[arg(long)]
255        wait_for_builds: bool,
256        /// Merge strategy to use
257        #[arg(long, value_enum, default_value = "squash")]
258        strategy: Option<MergeStrategyArg>,
259        /// Maximum time to wait for builds (seconds)
260        #[arg(long, default_value = "1800")]
261        build_timeout: u64,
262    },
263
264    /// Auto-land all ready PRs (shorthand for land --auto)
265    AutoLand {
266        /// Force land even with blocking issues (dangerous)
267        #[arg(short, long)]
268        force: bool,
269        /// Dry run - show what would be landed without doing it
270        #[arg(short, long)]
271        dry_run: bool,
272        /// Wait for builds to complete before merging
273        #[arg(long)]
274        wait_for_builds: bool,
275        /// Merge strategy to use
276        #[arg(long, value_enum, default_value = "squash")]
277        strategy: Option<MergeStrategyArg>,
278        /// Maximum time to wait for builds (seconds)
279        #[arg(long, default_value = "1800")]
280        build_timeout: u64,
281    },
282
283    /// List pull requests from Bitbucket
284    ListPrs {
285        /// Filter by state (open, merged, declined)
286        #[arg(short, long)]
287        state: Option<String>,
288        /// Show detailed information
289        #[arg(short, long)]
290        verbose: bool,
291    },
292
293    /// Continue an in-progress land operation after resolving conflicts
294    ContinueLand,
295
296    /// Abort an in-progress land operation  
297    AbortLand,
298
299    /// Show status of in-progress land operation
300    LandStatus,
301
302    /// Clean up merged and stale branches
303    Cleanup {
304        /// Show what would be cleaned up without actually deleting
305        #[arg(long)]
306        dry_run: bool,
307        /// Skip confirmation prompts
308        #[arg(long)]
309        force: bool,
310        /// Include stale branches in cleanup
311        #[arg(long)]
312        include_stale: bool,
313        /// Age threshold for stale branches (days)
314        #[arg(long, default_value = "30")]
315        stale_days: u32,
316        /// Also cleanup remote tracking branches
317        #[arg(long)]
318        cleanup_remote: bool,
319        /// Include non-stack branches in cleanup
320        #[arg(long)]
321        include_non_stack: bool,
322        /// Show detailed information about cleanup candidates
323        #[arg(long)]
324        verbose: bool,
325    },
326
327    /// Repair data consistency issues in stack metadata
328    Repair,
329}
330
331pub async fn run(action: StackAction) -> Result<()> {
332    match action {
333        StackAction::Create {
334            name,
335            base,
336            description,
337        } => create_stack(name, base, description).await,
338        StackAction::List {
339            verbose,
340            active,
341            format,
342        } => list_stacks(verbose, active, format).await,
343        StackAction::Switch { name } => switch_stack(name).await,
344        StackAction::Deactivate { force } => deactivate_stack(force).await,
345        StackAction::Show { verbose, mergeable } => show_stack(verbose, mergeable).await,
346        StackAction::Push {
347            branch,
348            message,
349            commit,
350            since,
351            commits,
352            squash,
353            squash_since,
354            auto_branch,
355            allow_base_branch,
356            dry_run,
357        } => {
358            push_to_stack(
359                branch,
360                message,
361                commit,
362                since,
363                commits,
364                squash,
365                squash_since,
366                auto_branch,
367                allow_base_branch,
368                dry_run,
369            )
370            .await
371        }
372        StackAction::Pop { keep_branch } => pop_from_stack(keep_branch).await,
373        StackAction::Submit {
374            entry,
375            title,
376            description,
377            range,
378            draft,
379            open,
380        } => submit_entry(entry, title, description, range, draft, open).await,
381        StackAction::Status { name } => check_stack_status(name).await,
382        StackAction::Prs { state, verbose } => list_pull_requests(state, verbose).await,
383        StackAction::Check { force } => check_stack(force).await,
384        StackAction::Sync {
385            force,
386            cleanup,
387            interactive,
388        } => sync_stack(force, cleanup, interactive).await,
389        StackAction::Rebase {
390            interactive,
391            onto,
392            strategy,
393        } => rebase_stack(interactive, onto, strategy).await,
394        StackAction::ContinueRebase => continue_rebase().await,
395        StackAction::AbortRebase => abort_rebase().await,
396        StackAction::RebaseStatus => rebase_status().await,
397        StackAction::Delete { name, force } => delete_stack(name, force).await,
398        StackAction::Validate { name, fix } => validate_stack(name, fix).await,
399        StackAction::Land {
400            entry,
401            force,
402            dry_run,
403            auto,
404            wait_for_builds,
405            strategy,
406            build_timeout,
407        } => {
408            land_stack(
409                entry,
410                force,
411                dry_run,
412                auto,
413                wait_for_builds,
414                strategy,
415                build_timeout,
416            )
417            .await
418        }
419        StackAction::AutoLand {
420            force,
421            dry_run,
422            wait_for_builds,
423            strategy,
424            build_timeout,
425        } => auto_land_stack(force, dry_run, wait_for_builds, strategy, build_timeout).await,
426        StackAction::ListPrs { state, verbose } => list_pull_requests(state, verbose).await,
427        StackAction::ContinueLand => continue_land().await,
428        StackAction::AbortLand => abort_land().await,
429        StackAction::LandStatus => land_status().await,
430        StackAction::Cleanup {
431            dry_run,
432            force,
433            include_stale,
434            stale_days,
435            cleanup_remote,
436            include_non_stack,
437            verbose,
438        } => {
439            cleanup_branches(
440                dry_run,
441                force,
442                include_stale,
443                stale_days,
444                cleanup_remote,
445                include_non_stack,
446                verbose,
447            )
448            .await
449        }
450        StackAction::Repair => repair_stack_data().await,
451    }
452}
453
454// Public functions for shortcut commands
455pub async fn show(verbose: bool, mergeable: bool) -> Result<()> {
456    show_stack(verbose, mergeable).await
457}
458
459#[allow(clippy::too_many_arguments)]
460pub async fn push(
461    branch: Option<String>,
462    message: Option<String>,
463    commit: Option<String>,
464    since: Option<String>,
465    commits: Option<String>,
466    squash: Option<usize>,
467    squash_since: Option<String>,
468    auto_branch: bool,
469    allow_base_branch: bool,
470    dry_run: bool,
471) -> Result<()> {
472    push_to_stack(
473        branch,
474        message,
475        commit,
476        since,
477        commits,
478        squash,
479        squash_since,
480        auto_branch,
481        allow_base_branch,
482        dry_run,
483    )
484    .await
485}
486
487pub async fn pop(keep_branch: bool) -> Result<()> {
488    pop_from_stack(keep_branch).await
489}
490
491pub async fn land(
492    entry: Option<usize>,
493    force: bool,
494    dry_run: bool,
495    auto: bool,
496    wait_for_builds: bool,
497    strategy: Option<MergeStrategyArg>,
498    build_timeout: u64,
499) -> Result<()> {
500    land_stack(
501        entry,
502        force,
503        dry_run,
504        auto,
505        wait_for_builds,
506        strategy,
507        build_timeout,
508    )
509    .await
510}
511
512pub async fn autoland(
513    force: bool,
514    dry_run: bool,
515    wait_for_builds: bool,
516    strategy: Option<MergeStrategyArg>,
517    build_timeout: u64,
518) -> Result<()> {
519    auto_land_stack(force, dry_run, wait_for_builds, strategy, build_timeout).await
520}
521
522pub async fn sync(force: bool, skip_cleanup: bool, interactive: bool) -> Result<()> {
523    sync_stack(force, skip_cleanup, interactive).await
524}
525
526pub async fn rebase(
527    interactive: bool,
528    onto: Option<String>,
529    strategy: Option<RebaseStrategyArg>,
530) -> Result<()> {
531    rebase_stack(interactive, onto, strategy).await
532}
533
534pub async fn deactivate(force: bool) -> Result<()> {
535    deactivate_stack(force).await
536}
537
538pub async fn switch(name: String) -> Result<()> {
539    switch_stack(name).await
540}
541
542async fn create_stack(
543    name: String,
544    base: Option<String>,
545    description: Option<String>,
546) -> Result<()> {
547    let current_dir = env::current_dir()
548        .map_err(|e| CascadeError::config(format!("Could not get current directory: {e}")))?;
549
550    let repo_root = find_repository_root(&current_dir)
551        .map_err(|e| CascadeError::config(format!("Could not find git repository: {e}")))?;
552
553    let mut manager = StackManager::new(&repo_root)?;
554    let stack_id = manager.create_stack(name.clone(), base.clone(), description.clone())?;
555
556    // Get the created stack to check its working branch
557    let stack = manager
558        .get_stack(&stack_id)
559        .ok_or_else(|| CascadeError::config("Failed to get created stack"))?;
560
561    // Use the new output format
562    Output::stack_info(
563        &name,
564        &stack_id.to_string(),
565        &stack.base_branch,
566        stack.working_branch.as_deref(),
567        true, // is_active
568    );
569
570    if let Some(desc) = description {
571        Output::sub_item(format!("Description: {desc}"));
572    }
573
574    // Provide helpful guidance based on the working branch situation
575    if stack.working_branch.is_none() {
576        Output::warning(format!(
577            "You're currently on the base branch '{}'",
578            stack.base_branch
579        ));
580        Output::next_steps(&[
581            &format!("Create a feature branch: git checkout -b {name}"),
582            "Make changes and commit them",
583            "Run 'ca push' to add commits to this stack",
584        ]);
585    } else {
586        Output::next_steps(&[
587            "Make changes and commit them",
588            "Run 'ca push' to add commits to this stack",
589            "Use 'ca submit' when ready to create pull requests",
590        ]);
591    }
592
593    Ok(())
594}
595
596async fn list_stacks(verbose: bool, active_only: bool, format: Option<String>) -> Result<()> {
597    let current_dir = env::current_dir()
598        .map_err(|e| CascadeError::config(format!("Could not get current directory: {e}")))?;
599
600    let repo_root = find_repository_root(&current_dir)
601        .map_err(|e| CascadeError::config(format!("Could not find git repository: {e}")))?;
602
603    let manager = StackManager::new(&repo_root)?;
604    let mut stacks = manager.list_stacks();
605
606    if active_only {
607        stacks.retain(|(_, _, _, _, active_marker)| active_marker.is_some());
608    }
609
610    if let Some(ref format) = format {
611        match format.as_str() {
612            "json" => {
613                let mut json_stacks = Vec::new();
614
615                for (stack_id, name, status, entry_count, active_marker) in &stacks {
616                    let (entries_json, working_branch, base_branch) =
617                        if let Some(stack_obj) = manager.get_stack(stack_id) {
618                            let entries_json = stack_obj
619                                .entries
620                                .iter()
621                                .enumerate()
622                                .map(|(idx, entry)| {
623                                    serde_json::json!({
624                                        "position": idx + 1,
625                                        "entry_id": entry.id.to_string(),
626                                        "branch_name": entry.branch.clone(),
627                                        "commit_hash": entry.commit_hash.clone(),
628                                        "short_hash": entry.short_hash(),
629                                        "is_submitted": entry.is_submitted,
630                                        "is_merged": entry.is_merged,
631                                        "pull_request_id": entry.pull_request_id.clone(),
632                                    })
633                                })
634                                .collect::<Vec<_>>();
635
636                            (
637                                entries_json,
638                                stack_obj.working_branch.clone(),
639                                Some(stack_obj.base_branch.clone()),
640                            )
641                        } else {
642                            (Vec::new(), None, None)
643                        };
644
645                    let status_label = format!("{status:?}");
646
647                    json_stacks.push(serde_json::json!({
648                        "id": stack_id.to_string(),
649                        "name": name,
650                        "status": status_label,
651                        "entry_count": entry_count,
652                        "is_active": active_marker.is_some(),
653                        "base_branch": base_branch,
654                        "working_branch": working_branch,
655                        "entries": entries_json,
656                    }));
657                }
658
659                let json_output = serde_json::json!({ "stacks": json_stacks });
660                let serialized = serde_json::to_string_pretty(&json_output)?;
661                println!("{serialized}");
662                return Ok(());
663            }
664            "name" => {
665                for (_, name, _, _, _) in &stacks {
666                    println!("{name}");
667                }
668                return Ok(());
669            }
670            "id" => {
671                for (stack_id, _, _, _, _) in &stacks {
672                    println!("{}", stack_id);
673                }
674                return Ok(());
675            }
676            "status" => {
677                for (_, name, status, _, active_marker) in &stacks {
678                    let status_label = format!("{status:?}");
679                    let marker = if active_marker.is_some() {
680                        " (active)"
681                    } else {
682                        ""
683                    };
684                    println!("{name}: {status_label}{marker}");
685                }
686                return Ok(());
687            }
688            other => {
689                return Err(CascadeError::config(format!(
690                    "Unsupported format '{}'. Supported formats: name, id, status, json",
691                    other
692                )));
693            }
694        }
695    }
696
697    if stacks.is_empty() {
698        if active_only {
699            Output::info("No active stack. Activate one with 'ca stack switch <name>'");
700        } else {
701            Output::info("No stacks found. Create one with: ca stack create <name>");
702        }
703        return Ok(());
704    }
705
706    println!("Stacks:");
707    for (stack_id, name, status, entry_count, active_marker) in stacks {
708        let status_icon = match status {
709            StackStatus::Clean => "✓",
710            StackStatus::Dirty => "~",
711            StackStatus::OutOfSync => "!",
712            StackStatus::Conflicted => "✗",
713            StackStatus::Rebasing => "↔",
714            StackStatus::NeedsSync => "~",
715            StackStatus::Corrupted => "✗",
716        };
717
718        let active_indicator = if active_marker.is_some() {
719            " (active)"
720        } else {
721            ""
722        };
723
724        // Get the actual stack object to access branch information
725        let stack = manager.get_stack(&stack_id);
726
727        if verbose {
728            println!("  {status_icon} {name} [{entry_count}]{active_indicator}");
729            println!("    ID: {stack_id}");
730            if let Some(stack_meta) = manager.get_stack_metadata(&stack_id) {
731                println!("    Base: {}", stack_meta.base_branch);
732                if let Some(desc) = &stack_meta.description {
733                    println!("    Description: {desc}");
734                }
735                println!(
736                    "    Commits: {} total, {} submitted",
737                    stack_meta.total_commits, stack_meta.submitted_commits
738                );
739                if stack_meta.has_conflicts {
740                    Output::warning("    Has conflicts");
741                }
742            }
743
744            // Show branch information in verbose mode
745            if let Some(stack_obj) = stack {
746                if !stack_obj.entries.is_empty() {
747                    println!("    Branches:");
748                    for (i, entry) in stack_obj.entries.iter().enumerate() {
749                        let entry_num = i + 1;
750                        let submitted_indicator = if entry.is_submitted {
751                            "[submitted]"
752                        } else {
753                            ""
754                        };
755                        let branch_name = &entry.branch;
756                        let short_message = if entry.message.len() > 40 {
757                            format!("{}...", &entry.message[..37])
758                        } else {
759                            entry.message.clone()
760                        };
761                        println!("      {entry_num}. {submitted_indicator} {branch_name} - {short_message}");
762                    }
763                }
764            }
765            println!();
766        } else {
767            // Show compact branch info in non-verbose mode
768            let branch_info = if let Some(stack_obj) = stack {
769                if stack_obj.entries.is_empty() {
770                    String::new()
771                } else if stack_obj.entries.len() == 1 {
772                    format!(" → {}", stack_obj.entries[0].branch)
773                } else {
774                    let first_branch = &stack_obj.entries[0].branch;
775                    let last_branch = &stack_obj.entries.last().unwrap().branch;
776                    format!(" → {first_branch} … {last_branch}")
777                }
778            } else {
779                String::new()
780            };
781
782            println!("  {status_icon} {name} [{entry_count}]{branch_info}{active_indicator}");
783        }
784    }
785
786    if !verbose {
787        println!("\nUse --verbose for more details");
788    }
789
790    Ok(())
791}
792
793async fn switch_stack(name: String) -> Result<()> {
794    let current_dir = env::current_dir()
795        .map_err(|e| CascadeError::config(format!("Could not get current directory: {e}")))?;
796
797    let repo_root = find_repository_root(&current_dir)
798        .map_err(|e| CascadeError::config(format!("Could not find git repository: {e}")))?;
799
800    let mut manager = StackManager::new(&repo_root)?;
801    let repo = GitRepository::open(&repo_root)?;
802
803    // Get stack information before switching
804    let stack = manager
805        .get_stack_by_name(&name)
806        .ok_or_else(|| CascadeError::config(format!("Stack '{name}' not found")))?;
807
808    // Determine the target branch and provide appropriate messaging
809    if let Some(working_branch) = &stack.working_branch {
810        // Stack has a working branch - try to switch to it
811        let current_branch = repo.get_current_branch().ok();
812
813        if current_branch.as_ref() != Some(working_branch) {
814            Output::progress(format!(
815                "Switching to stack working branch: {working_branch}"
816            ));
817
818            // Check if target branch exists
819            if repo.branch_exists(working_branch) {
820                match repo.checkout_branch(working_branch) {
821                    Ok(_) => {
822                        Output::success(format!("Checked out branch: {working_branch}"));
823                    }
824                    Err(e) => {
825                        Output::warning(format!("Failed to checkout '{working_branch}': {e}"));
826                        Output::sub_item("Stack activated but stayed on current branch");
827                        Output::sub_item(format!(
828                            "You can manually checkout with: git checkout {working_branch}"
829                        ));
830                    }
831                }
832            } else {
833                Output::warning(format!(
834                    "Stack working branch '{working_branch}' doesn't exist locally"
835                ));
836                Output::sub_item("Stack activated but stayed on current branch");
837                Output::sub_item(format!(
838                    "You may need to fetch from remote: git fetch origin {working_branch}"
839                ));
840            }
841        } else {
842            Output::success(format!("Already on stack working branch: {working_branch}"));
843        }
844    } else {
845        // No working branch - provide guidance
846        Output::warning(format!("Stack '{name}' has no working branch set"));
847        Output::sub_item(
848            "This typically happens when a stack was created while on the base branch",
849        );
850
851        Output::tip("To start working on this stack:");
852        Output::bullet(format!("Create a feature branch: git checkout -b {name}"));
853        Output::bullet("The stack will automatically track this as its working branch");
854        Output::bullet("Then use 'ca push' to add commits to the stack");
855
856        Output::sub_item(format!("Base branch: {}", stack.base_branch));
857    }
858
859    // Activate the stack (this will record the correct current branch)
860    manager.set_active_stack_by_name(&name)?;
861    Output::success(format!("Switched to stack '{name}'"));
862
863    Ok(())
864}
865
866async fn deactivate_stack(force: bool) -> Result<()> {
867    let current_dir = env::current_dir()
868        .map_err(|e| CascadeError::config(format!("Could not get current directory: {e}")))?;
869
870    let repo_root = find_repository_root(&current_dir)
871        .map_err(|e| CascadeError::config(format!("Could not find git repository: {e}")))?;
872
873    let mut manager = StackManager::new(&repo_root)?;
874
875    let active_stack = manager.get_active_stack();
876
877    if active_stack.is_none() {
878        Output::info("No active stack to deactivate");
879        return Ok(());
880    }
881
882    let stack_name = active_stack.unwrap().name.clone();
883
884    if !force {
885        Output::warning(format!(
886            "This will deactivate stack '{stack_name}' and return to normal Git workflow"
887        ));
888        Output::sub_item(format!(
889            "You can reactivate it later with 'ca stacks switch {stack_name}'"
890        ));
891        // Interactive confirmation to deactivate stack
892        let should_deactivate = Confirm::with_theme(&ColorfulTheme::default())
893            .with_prompt("Continue with deactivation?")
894            .default(false)
895            .interact()
896            .map_err(|e| CascadeError::config(format!("Failed to get user confirmation: {e}")))?;
897
898        if !should_deactivate {
899            Output::info("Cancelled deactivation");
900            return Ok(());
901        }
902    }
903
904    // Deactivate the stack
905    manager.set_active_stack(None)?;
906
907    Output::success(format!("Deactivated stack '{stack_name}'"));
908    Output::sub_item("Stack management is now OFF - you can use normal Git workflow");
909    Output::sub_item(format!("To reactivate: ca stacks switch {stack_name}"));
910
911    Ok(())
912}
913
914async fn show_stack(verbose: bool, show_mergeable: bool) -> Result<()> {
915    let current_dir = env::current_dir()
916        .map_err(|e| CascadeError::config(format!("Could not get current directory: {e}")))?;
917
918    let repo_root = find_repository_root(&current_dir)
919        .map_err(|e| CascadeError::config(format!("Could not find git repository: {e}")))?;
920
921    let stack_manager = StackManager::new(&repo_root)?;
922
923    // Get stack information first to avoid borrow conflicts
924    let (stack_id, stack_name, stack_base, stack_working, stack_entries) = {
925        let active_stack = stack_manager.get_active_stack().ok_or_else(|| {
926            CascadeError::config(
927                "No active stack. Use 'ca stacks create' or 'ca stacks switch' to select a stack"
928                    .to_string(),
929            )
930        })?;
931
932        (
933            active_stack.id,
934            active_stack.name.clone(),
935            active_stack.base_branch.clone(),
936            active_stack.working_branch.clone(),
937            active_stack.entries.clone(),
938        )
939    };
940
941    // Use the new output format for stack info
942    Output::stack_info(
943        &stack_name,
944        &stack_id.to_string(),
945        &stack_base,
946        stack_working.as_deref(),
947        true, // is_active
948    );
949    Output::sub_item(format!("Total entries: {}", stack_entries.len()));
950
951    if stack_entries.is_empty() {
952        Output::info("No entries in this stack yet");
953        Output::tip("Use 'ca push' to add commits to this stack");
954        return Ok(());
955    }
956
957    // Show entries
958    Output::section("Stack Entries");
959    for (i, entry) in stack_entries.iter().enumerate() {
960        let entry_num = i + 1;
961        let short_hash = entry.short_hash();
962        let short_msg = entry.short_message(50);
963
964        // Get source branch information for pending entries only
965        // (submitted entries have their own branch, so source is no longer relevant)
966        let metadata = stack_manager.get_repository_metadata();
967        let source_branch_info = if !entry.is_submitted {
968            if let Some(commit_meta) = metadata.get_commit(&entry.commit_hash) {
969                if commit_meta.source_branch != commit_meta.branch
970                    && !commit_meta.source_branch.is_empty()
971                {
972                    format!(" (from {})", commit_meta.source_branch)
973                } else {
974                    String::new()
975                }
976            } else {
977                String::new()
978            }
979        } else {
980            String::new()
981        };
982
983        // Use colored status: pending (yellow), submitted (muted green)
984        let status_colored = Output::entry_status(entry.is_submitted, false);
985
986        Output::numbered_item(
987            entry_num,
988            format!("{short_hash} {status_colored} {short_msg}{source_branch_info}"),
989        );
990
991        if verbose {
992            Output::sub_item(format!("Branch: {}", entry.branch));
993            Output::sub_item(format!(
994                "Created: {}",
995                entry.created_at.format("%Y-%m-%d %H:%M")
996            ));
997            if let Some(pr_id) = &entry.pull_request_id {
998                Output::sub_item(format!("PR: #{pr_id}"));
999            }
1000
1001            // Display full commit message
1002            Output::sub_item("Commit Message:");
1003            let lines: Vec<&str> = entry.message.lines().collect();
1004            for line in lines {
1005                Output::sub_item(format!("  {line}"));
1006            }
1007        }
1008    }
1009
1010    // Enhanced PR status if requested and available
1011    if show_mergeable {
1012        Output::section("Mergability Status");
1013
1014        // Load configuration and create Bitbucket integration
1015        let config_dir = crate::config::get_repo_config_dir(&repo_root)?;
1016        let config_path = config_dir.join("config.json");
1017        let settings = crate::config::Settings::load_from_file(&config_path)?;
1018
1019        let cascade_config = crate::config::CascadeConfig {
1020            bitbucket: Some(settings.bitbucket.clone()),
1021            git: settings.git.clone(),
1022            auth: crate::config::AuthConfig::default(),
1023            cascade: settings.cascade.clone(),
1024        };
1025
1026        let mut integration =
1027            crate::bitbucket::BitbucketIntegration::new(stack_manager, cascade_config)?;
1028
1029        match integration.check_enhanced_stack_status(&stack_id).await {
1030            Ok(status) => {
1031                Output::bullet(format!("Total entries: {}", status.total_entries));
1032                Output::bullet(format!("Submitted: {}", status.submitted_entries));
1033                Output::bullet(format!("Open PRs: {}", status.open_prs));
1034                Output::bullet(format!("Merged PRs: {}", status.merged_prs));
1035                Output::bullet(format!("Declined PRs: {}", status.declined_prs));
1036                Output::bullet(format!(
1037                    "Completion: {:.1}%",
1038                    status.completion_percentage()
1039                ));
1040
1041                if !status.enhanced_statuses.is_empty() {
1042                    Output::section("Pull Request Status");
1043                    let mut ready_to_land = 0;
1044
1045                    for enhanced in &status.enhanced_statuses {
1046                        let status_display = enhanced.get_display_status();
1047                        let ready_icon = if enhanced.is_ready_to_land() {
1048                            ready_to_land += 1;
1049                            "[READY]"
1050                        } else {
1051                            "[PENDING]"
1052                        };
1053
1054                        Output::bullet(format!(
1055                            "{} PR #{}: {} ({})",
1056                            ready_icon, enhanced.pr.id, enhanced.pr.title, status_display
1057                        ));
1058
1059                        if verbose {
1060                            println!(
1061                                "      {} -> {}",
1062                                enhanced.pr.from_ref.display_id, enhanced.pr.to_ref.display_id
1063                            );
1064
1065                            // Show blocking reasons if not ready
1066                            if !enhanced.is_ready_to_land() {
1067                                let blocking = enhanced.get_blocking_reasons();
1068                                if !blocking.is_empty() {
1069                                    println!("      Blocking: {}", blocking.join(", "));
1070                                }
1071                            }
1072
1073                            // Show review details (actual count from Bitbucket)
1074                            println!(
1075                                "      Reviews: {} approval{}",
1076                                enhanced.review_status.current_approvals,
1077                                if enhanced.review_status.current_approvals == 1 {
1078                                    ""
1079                                } else {
1080                                    "s"
1081                                }
1082                            );
1083
1084                            if enhanced.review_status.needs_work_count > 0 {
1085                                println!(
1086                                    "      {} reviewers requested changes",
1087                                    enhanced.review_status.needs_work_count
1088                                );
1089                            }
1090
1091                            // Show build status
1092                            if let Some(build) = &enhanced.build_status {
1093                                let build_icon = match build.state {
1094                                    crate::bitbucket::pull_request::BuildState::Successful => "✓",
1095                                    crate::bitbucket::pull_request::BuildState::Failed => "✗",
1096                                    crate::bitbucket::pull_request::BuildState::InProgress => "~",
1097                                    _ => "○",
1098                                };
1099                                println!("      Build: {} {:?}", build_icon, build.state);
1100                            }
1101
1102                            if let Some(url) = enhanced.pr.web_url() {
1103                                println!("      URL: {url}");
1104                            }
1105                            println!();
1106                        }
1107                    }
1108
1109                    if ready_to_land > 0 {
1110                        println!(
1111                            "\n🎯 {} PR{} ready to land! Use 'ca land' to land them all.",
1112                            ready_to_land,
1113                            if ready_to_land == 1 { " is" } else { "s are" }
1114                        );
1115                    }
1116                }
1117            }
1118            Err(e) => {
1119                tracing::debug!("Failed to get enhanced stack status: {}", e);
1120                Output::warning("Could not fetch mergability status");
1121                Output::sub_item("Use 'ca stack show --verbose' for basic PR information");
1122            }
1123        }
1124    } else {
1125        // Original PR status display for compatibility
1126        let config_dir = crate::config::get_repo_config_dir(&repo_root)?;
1127        let config_path = config_dir.join("config.json");
1128        let settings = crate::config::Settings::load_from_file(&config_path)?;
1129
1130        let cascade_config = crate::config::CascadeConfig {
1131            bitbucket: Some(settings.bitbucket.clone()),
1132            git: settings.git.clone(),
1133            auth: crate::config::AuthConfig::default(),
1134            cascade: settings.cascade.clone(),
1135        };
1136
1137        let integration =
1138            crate::bitbucket::BitbucketIntegration::new(stack_manager, cascade_config)?;
1139
1140        match integration.check_stack_status(&stack_id).await {
1141            Ok(status) => {
1142                println!("\nPull Request Status:");
1143                println!("   Total entries: {}", status.total_entries);
1144                println!("   Submitted: {}", status.submitted_entries);
1145                println!("   Open PRs: {}", status.open_prs);
1146                println!("   Merged PRs: {}", status.merged_prs);
1147                println!("   Declined PRs: {}", status.declined_prs);
1148                println!("   Completion: {:.1}%", status.completion_percentage());
1149
1150                if !status.pull_requests.is_empty() {
1151                    println!("\nPull Requests:");
1152                    for pr in &status.pull_requests {
1153                        let state_icon = match pr.state {
1154                            crate::bitbucket::PullRequestState::Open => "→",
1155                            crate::bitbucket::PullRequestState::Merged => "✓",
1156                            crate::bitbucket::PullRequestState::Declined => "✗",
1157                        };
1158                        println!(
1159                            "   {} PR #{}: {} ({} -> {})",
1160                            state_icon,
1161                            pr.id,
1162                            pr.title,
1163                            pr.from_ref.display_id,
1164                            pr.to_ref.display_id
1165                        );
1166                        if let Some(url) = pr.web_url() {
1167                            println!("      URL: {url}");
1168                        }
1169                    }
1170                }
1171
1172                println!();
1173                Output::tip("Use 'ca stack --mergeable' to see detailed status including build and review information");
1174            }
1175            Err(e) => {
1176                tracing::debug!("Failed to check stack status: {}", e);
1177            }
1178        }
1179    }
1180
1181    Ok(())
1182}
1183
1184#[allow(clippy::too_many_arguments)]
1185async fn push_to_stack(
1186    branch: Option<String>,
1187    message: Option<String>,
1188    commit: Option<String>,
1189    since: Option<String>,
1190    commits: Option<String>,
1191    squash: Option<usize>,
1192    squash_since: Option<String>,
1193    auto_branch: bool,
1194    allow_base_branch: bool,
1195    dry_run: bool,
1196) -> Result<()> {
1197    let current_dir = env::current_dir()
1198        .map_err(|e| CascadeError::config(format!("Could not get current directory: {e}")))?;
1199
1200    let repo_root = find_repository_root(&current_dir)
1201        .map_err(|e| CascadeError::config(format!("Could not find git repository: {e}")))?;
1202
1203    let mut manager = StackManager::new(&repo_root)?;
1204    let repo = GitRepository::open(&repo_root)?;
1205
1206    // Check for branch changes and prompt user if needed
1207    if !manager.check_for_branch_change()? {
1208        return Ok(()); // User chose to cancel or deactivate stack
1209    }
1210
1211    // Get the active stack to check base branch
1212    let active_stack = manager.get_active_stack().ok_or_else(|| {
1213        CascadeError::config("No active stack. Create a stack first with 'ca stack create'")
1214    })?;
1215
1216    // 🛡️ BASE BRANCH PROTECTION
1217    let current_branch = repo.get_current_branch()?;
1218    let base_branch = &active_stack.base_branch;
1219
1220    if current_branch == *base_branch {
1221        Output::error(format!(
1222            "You're currently on the base branch '{base_branch}'"
1223        ));
1224        Output::sub_item("Making commits directly on the base branch is not recommended.");
1225        Output::sub_item("This can pollute the base branch with work-in-progress commits.");
1226
1227        // Check if user explicitly allowed base branch work
1228        if allow_base_branch {
1229            Output::warning("Proceeding anyway due to --allow-base-branch flag");
1230        } else {
1231            // Check if we have uncommitted changes
1232            let has_changes = repo.is_dirty()?;
1233
1234            if has_changes {
1235                if auto_branch {
1236                    // Auto-create branch and commit changes
1237                    let feature_branch = format!("feature/{}-work", active_stack.name);
1238                    Output::progress(format!(
1239                        "Auto-creating feature branch '{feature_branch}'..."
1240                    ));
1241
1242                    repo.create_branch(&feature_branch, None)?;
1243                    repo.checkout_branch(&feature_branch)?;
1244
1245                    Output::success(format!("Created and switched to '{feature_branch}'"));
1246                    println!("   You can now commit and push your changes safely");
1247
1248                    // Continue with normal flow
1249                } else {
1250                    println!("\nYou have uncommitted changes. Here are your options:");
1251                    println!("   1. Create a feature branch first:");
1252                    println!("      git checkout -b feature/my-work");
1253                    println!("      git commit -am \"your work\"");
1254                    println!("      ca push");
1255                    println!("\n   2. Auto-create a branch (recommended):");
1256                    println!("      ca push --auto-branch");
1257                    println!("\n   3. Force push to base branch (dangerous):");
1258                    println!("      ca push --allow-base-branch");
1259
1260                    return Err(CascadeError::config(
1261                        "Refusing to push uncommitted changes from base branch. Use one of the options above."
1262                    ));
1263                }
1264            } else {
1265                // Check if there are existing commits to push
1266                let commits_to_check = if let Some(commits_str) = &commits {
1267                    commits_str
1268                        .split(',')
1269                        .map(|s| s.trim().to_string())
1270                        .collect::<Vec<String>>()
1271                } else if let Some(since_ref) = &since {
1272                    let since_commit = repo.resolve_reference(since_ref)?;
1273                    let head_commit = repo.get_head_commit()?;
1274                    let commits = repo.get_commits_between(
1275                        &since_commit.id().to_string(),
1276                        &head_commit.id().to_string(),
1277                    )?;
1278                    commits.into_iter().map(|c| c.id().to_string()).collect()
1279                } else if commit.is_none() {
1280                    let mut unpushed = Vec::new();
1281                    let head_commit = repo.get_head_commit()?;
1282                    let mut current_commit = head_commit;
1283
1284                    loop {
1285                        let commit_hash = current_commit.id().to_string();
1286                        let already_in_stack = active_stack
1287                            .entries
1288                            .iter()
1289                            .any(|entry| entry.commit_hash == commit_hash);
1290
1291                        if already_in_stack {
1292                            break;
1293                        }
1294
1295                        unpushed.push(commit_hash);
1296
1297                        if let Some(parent) = current_commit.parents().next() {
1298                            current_commit = parent;
1299                        } else {
1300                            break;
1301                        }
1302                    }
1303
1304                    unpushed.reverse();
1305                    unpushed
1306                } else {
1307                    vec![repo.get_head_commit()?.id().to_string()]
1308                };
1309
1310                if !commits_to_check.is_empty() {
1311                    if auto_branch {
1312                        // Auto-create feature branch and cherry-pick commits
1313                        let feature_branch = format!("feature/{}-work", active_stack.name);
1314                        Output::progress(format!(
1315                            "Auto-creating feature branch '{feature_branch}'..."
1316                        ));
1317
1318                        repo.create_branch(&feature_branch, Some(base_branch))?;
1319                        repo.checkout_branch(&feature_branch)?;
1320
1321                        // Cherry-pick the commits to the new branch
1322                        println!(
1323                            "🍒 Cherry-picking {} commit(s) to new branch...",
1324                            commits_to_check.len()
1325                        );
1326                        for commit_hash in &commits_to_check {
1327                            match repo.cherry_pick(commit_hash) {
1328                                Ok(_) => println!("   ✅ Cherry-picked {}", &commit_hash[..8]),
1329                                Err(e) => {
1330                                    Output::error(format!(
1331                                        "Failed to cherry-pick {}: {}",
1332                                        &commit_hash[..8],
1333                                        e
1334                                    ));
1335                                    Output::tip("You may need to resolve conflicts manually");
1336                                    return Err(CascadeError::branch(format!(
1337                                        "Failed to cherry-pick commit {commit_hash}: {e}"
1338                                    )));
1339                                }
1340                            }
1341                        }
1342
1343                        println!(
1344                            "✅ Successfully moved {} commit(s) to '{feature_branch}'",
1345                            commits_to_check.len()
1346                        );
1347                        println!(
1348                            "   You're now on the feature branch and can continue with 'ca push'"
1349                        );
1350
1351                        // Continue with normal flow
1352                    } else {
1353                        println!(
1354                            "\n💡 Found {} commit(s) to push from base branch '{base_branch}'",
1355                            commits_to_check.len()
1356                        );
1357                        println!("   These commits are currently ON the base branch, which may not be intended.");
1358                        println!("\n   Options:");
1359                        println!("   1. Auto-create feature branch and cherry-pick commits:");
1360                        println!("      ca push --auto-branch");
1361                        println!("\n   2. Manually create branch and move commits:");
1362                        println!("      git checkout -b feature/my-work");
1363                        println!("      ca push");
1364                        println!("\n   3. Force push from base branch (not recommended):");
1365                        println!("      ca push --allow-base-branch");
1366
1367                        return Err(CascadeError::config(
1368                            "Refusing to push commits from base branch. Use --auto-branch or create a feature branch manually."
1369                        ));
1370                    }
1371                }
1372            }
1373        }
1374    }
1375
1376    // Handle squash operations first
1377    if let Some(squash_count) = squash {
1378        if squash_count == 0 {
1379            // User used --squash without specifying count, auto-detect unpushed commits
1380            let active_stack = manager.get_active_stack().ok_or_else(|| {
1381                CascadeError::config(
1382                    "No active stack. Create a stack first with 'ca stacks create'",
1383                )
1384            })?;
1385
1386            let unpushed_count = get_unpushed_commits(&repo, active_stack)?.len();
1387
1388            if unpushed_count == 0 {
1389                Output::info("  No unpushed commits to squash");
1390            } else if unpushed_count == 1 {
1391                Output::info("  Only 1 unpushed commit, no squashing needed");
1392            } else {
1393                println!(" Auto-detected {unpushed_count} unpushed commits, squashing...");
1394                squash_commits(&repo, unpushed_count, None).await?;
1395                Output::success(" Squashed {unpushed_count} unpushed commits into one");
1396            }
1397        } else {
1398            println!(" Squashing last {squash_count} commits...");
1399            squash_commits(&repo, squash_count, None).await?;
1400            Output::success(" Squashed {squash_count} commits into one");
1401        }
1402    } else if let Some(since_ref) = squash_since {
1403        println!(" Squashing commits since {since_ref}...");
1404        let since_commit = repo.resolve_reference(&since_ref)?;
1405        let commits_count = count_commits_since(&repo, &since_commit.id().to_string())?;
1406        squash_commits(&repo, commits_count, Some(since_ref.clone())).await?;
1407        Output::success(" Squashed {commits_count} commits since {since_ref} into one");
1408    }
1409
1410    // Determine which commits to push
1411    let commits_to_push = if let Some(commits_str) = commits {
1412        // Parse comma-separated commit hashes
1413        commits_str
1414            .split(',')
1415            .map(|s| s.trim().to_string())
1416            .collect::<Vec<String>>()
1417    } else if let Some(since_ref) = since {
1418        // Get commits since the specified reference
1419        let since_commit = repo.resolve_reference(&since_ref)?;
1420        let head_commit = repo.get_head_commit()?;
1421
1422        // Get commits between since_ref and HEAD
1423        let commits = repo.get_commits_between(
1424            &since_commit.id().to_string(),
1425            &head_commit.id().to_string(),
1426        )?;
1427        commits.into_iter().map(|c| c.id().to_string()).collect()
1428    } else if let Some(hash) = commit {
1429        // Single specific commit
1430        vec![hash]
1431    } else {
1432        // Default: Get all unpushed commits (commits on current branch but not on base branch)
1433        let active_stack = manager.get_active_stack().ok_or_else(|| {
1434            CascadeError::config("No active stack. Create a stack first with 'ca stacks create'")
1435        })?;
1436
1437        // Get commits that are on current branch but not on the base branch
1438        let base_branch = &active_stack.base_branch;
1439        let current_branch = repo.get_current_branch()?;
1440
1441        // If we're on the base branch, only include commits that aren't already in the stack
1442        if current_branch == *base_branch {
1443            let mut unpushed = Vec::new();
1444            let head_commit = repo.get_head_commit()?;
1445            let mut current_commit = head_commit;
1446
1447            // Walk back from HEAD until we find a commit that's already in the stack
1448            loop {
1449                let commit_hash = current_commit.id().to_string();
1450                let already_in_stack = active_stack
1451                    .entries
1452                    .iter()
1453                    .any(|entry| entry.commit_hash == commit_hash);
1454
1455                if already_in_stack {
1456                    break;
1457                }
1458
1459                unpushed.push(commit_hash);
1460
1461                // Move to parent commit
1462                if let Some(parent) = current_commit.parents().next() {
1463                    current_commit = parent;
1464                } else {
1465                    break;
1466                }
1467            }
1468
1469            unpushed.reverse(); // Reverse to get chronological order
1470            unpushed
1471        } else {
1472            // Use git's commit range calculation to find commits on current branch but not on base
1473            match repo.get_commits_between(base_branch, &current_branch) {
1474                Ok(commits) => {
1475                    let mut unpushed: Vec<String> =
1476                        commits.into_iter().map(|c| c.id().to_string()).collect();
1477
1478                    // Filter out commits that are already in the stack
1479                    unpushed.retain(|commit_hash| {
1480                        !active_stack
1481                            .entries
1482                            .iter()
1483                            .any(|entry| entry.commit_hash == *commit_hash)
1484                    });
1485
1486                    unpushed.reverse(); // Reverse to get chronological order (oldest first)
1487                    unpushed
1488                }
1489                Err(e) => {
1490                    return Err(CascadeError::branch(format!(
1491                            "Failed to calculate commits between '{base_branch}' and '{current_branch}': {e}. \
1492                             This usually means the branches have diverged or don't share common history."
1493                        )));
1494                }
1495            }
1496        }
1497    };
1498
1499    if commits_to_push.is_empty() {
1500        Output::info("  No commits to push to stack");
1501        return Ok(());
1502    }
1503
1504    // 🛡️ SAFEGUARDS: Analyze commits before pushing
1505    analyze_commits_for_safeguards(&commits_to_push, &repo, dry_run).await?;
1506
1507    // Early return for dry run mode
1508    if dry_run {
1509        return Ok(());
1510    }
1511
1512    // Push each commit to the stack
1513    let mut pushed_count = 0;
1514    let mut source_branches = std::collections::HashSet::new();
1515
1516    for (i, commit_hash) in commits_to_push.iter().enumerate() {
1517        let commit_obj = repo.get_commit(commit_hash)?;
1518        let commit_msg = commit_obj.message().unwrap_or("").to_string();
1519
1520        // Check which branch this commit belongs to
1521        let commit_source_branch = repo
1522            .find_branch_containing_commit(commit_hash)
1523            .unwrap_or_else(|_| current_branch.clone());
1524        source_branches.insert(commit_source_branch.clone());
1525
1526        // Generate branch name (use provided branch for first commit, generate for others)
1527        let branch_name = if i == 0 && branch.is_some() {
1528            branch.clone().unwrap()
1529        } else {
1530            // Create a temporary GitRepository for branch name generation
1531            let temp_repo = GitRepository::open(&repo_root)?;
1532            let branch_mgr = crate::git::BranchManager::new(temp_repo);
1533            branch_mgr.generate_branch_name(&commit_msg)
1534        };
1535
1536        // Use provided message for first commit, original message for others
1537        let final_message = if i == 0 && message.is_some() {
1538            message.clone().unwrap()
1539        } else {
1540            commit_msg.clone()
1541        };
1542
1543        let entry_id = manager.push_to_stack(
1544            branch_name.clone(),
1545            commit_hash.clone(),
1546            final_message.clone(),
1547            commit_source_branch.clone(),
1548        )?;
1549        pushed_count += 1;
1550
1551        Output::success(format!(
1552            "Pushed commit {}/{} to stack",
1553            i + 1,
1554            commits_to_push.len()
1555        ));
1556        Output::sub_item(format!(
1557            "Commit: {} ({})",
1558            &commit_hash[..8],
1559            commit_msg.split('\n').next().unwrap_or("")
1560        ));
1561        Output::sub_item(format!("Branch: {branch_name}"));
1562        Output::sub_item(format!("Source: {commit_source_branch}"));
1563        Output::sub_item(format!("Entry ID: {entry_id}"));
1564        println!();
1565    }
1566
1567    // 🚨 SCATTERED COMMIT WARNING
1568    if source_branches.len() > 1 {
1569        Output::warning("Scattered Commit Detection");
1570        Output::sub_item(format!(
1571            "You've pushed commits from {} different Git branches:",
1572            source_branches.len()
1573        ));
1574        for branch in &source_branches {
1575            Output::bullet(branch.to_string());
1576        }
1577
1578        Output::section("This can lead to confusion because:");
1579        Output::bullet("Stack appears sequential but commits are scattered across branches");
1580        Output::bullet("Team members won't know which branch contains which work");
1581        Output::bullet("Branch cleanup becomes unclear after merge");
1582        Output::bullet("Rebase operations become more complex");
1583
1584        Output::tip("Consider consolidating work to a single feature branch:");
1585        Output::bullet("Create a new feature branch: git checkout -b feature/consolidated-work");
1586        Output::bullet("Cherry-pick commits in order: git cherry-pick <commit1> <commit2> ...");
1587        Output::bullet("Delete old scattered branches");
1588        Output::bullet("Push the consolidated branch to your stack");
1589        println!();
1590    }
1591
1592    Output::success(format!(
1593        "Successfully pushed {} commit{} to stack",
1594        pushed_count,
1595        if pushed_count == 1 { "" } else { "s" }
1596    ));
1597
1598    Ok(())
1599}
1600
1601async fn pop_from_stack(keep_branch: bool) -> Result<()> {
1602    let current_dir = env::current_dir()
1603        .map_err(|e| CascadeError::config(format!("Could not get current directory: {e}")))?;
1604
1605    let repo_root = find_repository_root(&current_dir)
1606        .map_err(|e| CascadeError::config(format!("Could not find git repository: {e}")))?;
1607
1608    let mut manager = StackManager::new(&repo_root)?;
1609    let repo = GitRepository::open(&repo_root)?;
1610
1611    let entry = manager.pop_from_stack()?;
1612
1613    Output::success("Popped commit from stack");
1614    Output::sub_item(format!(
1615        "Commit: {} ({})",
1616        entry.short_hash(),
1617        entry.short_message(50)
1618    ));
1619    Output::sub_item(format!("Branch: {}", entry.branch));
1620
1621    // Delete branch if requested and it's not the current branch
1622    if !keep_branch && entry.branch != repo.get_current_branch()? {
1623        match repo.delete_branch(&entry.branch) {
1624            Ok(_) => Output::sub_item(format!("Deleted branch: {}", entry.branch)),
1625            Err(e) => Output::warning(format!("Could not delete branch {}: {}", entry.branch, e)),
1626        }
1627    }
1628
1629    Ok(())
1630}
1631
1632async fn submit_entry(
1633    entry: Option<usize>,
1634    title: Option<String>,
1635    description: Option<String>,
1636    range: Option<String>,
1637    draft: bool,
1638    open: bool,
1639) -> Result<()> {
1640    let current_dir = env::current_dir()
1641        .map_err(|e| CascadeError::config(format!("Could not get current directory: {e}")))?;
1642
1643    let repo_root = find_repository_root(&current_dir)
1644        .map_err(|e| CascadeError::config(format!("Could not find git repository: {e}")))?;
1645
1646    let mut stack_manager = StackManager::new(&repo_root)?;
1647
1648    // Check for branch changes and prompt user if needed
1649    if !stack_manager.check_for_branch_change()? {
1650        return Ok(()); // User chose to cancel or deactivate stack
1651    }
1652
1653    // Load configuration first
1654    let config_dir = crate::config::get_repo_config_dir(&repo_root)?;
1655    let config_path = config_dir.join("config.json");
1656    let settings = crate::config::Settings::load_from_file(&config_path)?;
1657
1658    // Create the main config structure
1659    let cascade_config = crate::config::CascadeConfig {
1660        bitbucket: Some(settings.bitbucket.clone()),
1661        git: settings.git.clone(),
1662        auth: crate::config::AuthConfig::default(),
1663        cascade: settings.cascade.clone(),
1664    };
1665
1666    // Get the active stack
1667    let active_stack = stack_manager.get_active_stack().ok_or_else(|| {
1668        CascadeError::config("No active stack. Create a stack first with 'ca stack create'")
1669    })?;
1670    let stack_id = active_stack.id;
1671
1672    // Determine which entries to submit
1673    let entries_to_submit = if let Some(range_str) = range {
1674        // Parse range (e.g., "1-3" or "2,4,6")
1675        let mut entries = Vec::new();
1676
1677        if range_str.contains('-') {
1678            // Handle range like "1-3"
1679            let parts: Vec<&str> = range_str.split('-').collect();
1680            if parts.len() != 2 {
1681                return Err(CascadeError::config(
1682                    "Invalid range format. Use 'start-end' (e.g., '1-3')",
1683                ));
1684            }
1685
1686            let start: usize = parts[0]
1687                .parse()
1688                .map_err(|_| CascadeError::config("Invalid start number in range"))?;
1689            let end: usize = parts[1]
1690                .parse()
1691                .map_err(|_| CascadeError::config("Invalid end number in range"))?;
1692
1693            if start == 0
1694                || end == 0
1695                || start > active_stack.entries.len()
1696                || end > active_stack.entries.len()
1697            {
1698                return Err(CascadeError::config(format!(
1699                    "Range out of bounds. Stack has {} entries",
1700                    active_stack.entries.len()
1701                )));
1702            }
1703
1704            for i in start..=end {
1705                entries.push((i, active_stack.entries[i - 1].clone()));
1706            }
1707        } else {
1708            // Handle comma-separated list like "2,4,6"
1709            for entry_str in range_str.split(',') {
1710                let entry_num: usize = entry_str.trim().parse().map_err(|_| {
1711                    CascadeError::config(format!("Invalid entry number: {entry_str}"))
1712                })?;
1713
1714                if entry_num == 0 || entry_num > active_stack.entries.len() {
1715                    return Err(CascadeError::config(format!(
1716                        "Entry {} out of bounds. Stack has {} entries",
1717                        entry_num,
1718                        active_stack.entries.len()
1719                    )));
1720                }
1721
1722                entries.push((entry_num, active_stack.entries[entry_num - 1].clone()));
1723            }
1724        }
1725
1726        entries
1727    } else if let Some(entry_num) = entry {
1728        // Single entry specified
1729        if entry_num == 0 || entry_num > active_stack.entries.len() {
1730            return Err(CascadeError::config(format!(
1731                "Invalid entry number: {}. Stack has {} entries",
1732                entry_num,
1733                active_stack.entries.len()
1734            )));
1735        }
1736        vec![(entry_num, active_stack.entries[entry_num - 1].clone())]
1737    } else {
1738        // Default: Submit all unsubmitted entries
1739        active_stack
1740            .entries
1741            .iter()
1742            .enumerate()
1743            .filter(|(_, entry)| !entry.is_submitted)
1744            .map(|(i, entry)| (i + 1, entry.clone())) // Convert to 1-based indexing
1745            .collect::<Vec<(usize, _)>>()
1746    };
1747
1748    if entries_to_submit.is_empty() {
1749        Output::info("No entries to submit");
1750        return Ok(());
1751    }
1752
1753    // Professional output for submission
1754    Output::section(format!(
1755        "Submitting {} {}",
1756        entries_to_submit.len(),
1757        if entries_to_submit.len() == 1 {
1758            "entry"
1759        } else {
1760            "entries"
1761        }
1762    ));
1763    println!();
1764
1765    // Create a new StackManager for the integration (since the original was moved)
1766    let integration_stack_manager = StackManager::new(&repo_root)?;
1767    let mut integration =
1768        BitbucketIntegration::new(integration_stack_manager, cascade_config.clone())?;
1769
1770    // Submit each entry
1771    let mut submitted_count = 0;
1772    let mut failed_entries = Vec::new();
1773    let mut pr_urls = Vec::new(); // Collect URLs to open
1774    let total_entries = entries_to_submit.len();
1775
1776    for (entry_num, entry_to_submit) in &entries_to_submit {
1777        // Show what we're submitting
1778        let tree_char = if entries_to_submit.len() == 1 {
1779            "→"
1780        } else if entry_num == &entries_to_submit.len() {
1781            "└─"
1782        } else {
1783            "├─"
1784        };
1785        print!(
1786            "   {} Entry {}: {}... ",
1787            tree_char, entry_num, entry_to_submit.branch
1788        );
1789        std::io::Write::flush(&mut std::io::stdout()).ok();
1790
1791        // Use provided title/description only for first entry or single entry submissions
1792        let entry_title = if total_entries == 1 {
1793            title.clone()
1794        } else {
1795            None
1796        };
1797        let entry_description = if total_entries == 1 {
1798            description.clone()
1799        } else {
1800            None
1801        };
1802
1803        match integration
1804            .submit_entry(
1805                &stack_id,
1806                &entry_to_submit.id,
1807                entry_title,
1808                entry_description,
1809                draft,
1810            )
1811            .await
1812        {
1813            Ok(pr) => {
1814                submitted_count += 1;
1815                Output::success(format!("PR #{}", pr.id));
1816                if let Some(url) = pr.web_url() {
1817                    Output::sub_item(format!(
1818                        "{} → {}",
1819                        pr.from_ref.display_id, pr.to_ref.display_id
1820                    ));
1821                    Output::sub_item(format!("URL: {url}"));
1822                    pr_urls.push(url); // Collect for opening later
1823                }
1824            }
1825            Err(e) => {
1826                Output::error("Failed");
1827                // Extract clean error message (remove git stderr noise)
1828                let clean_error = if e.to_string().contains("non-fast-forward") {
1829                    "Branch has diverged (was rebased after initial submission). Update to v0.1.41+ to auto force-push.".to_string()
1830                } else if e.to_string().contains("authentication") {
1831                    "Authentication failed. Check your Bitbucket credentials.".to_string()
1832                } else {
1833                    // Extract first meaningful line, skip git hints
1834                    e.to_string()
1835                        .lines()
1836                        .filter(|l| !l.trim().starts_with("hint:") && !l.trim().is_empty())
1837                        .take(1)
1838                        .collect::<Vec<_>>()
1839                        .join(" ")
1840                        .trim()
1841                        .to_string()
1842                };
1843                Output::sub_item(format!("Error: {}", clean_error));
1844                failed_entries.push((*entry_num, clean_error));
1845            }
1846        }
1847    }
1848
1849    println!();
1850
1851    // Update all PR descriptions in the stack if any PRs were created/exist
1852    let has_any_prs = active_stack
1853        .entries
1854        .iter()
1855        .any(|e| e.pull_request_id.is_some());
1856    if has_any_prs && submitted_count > 0 {
1857        match integration.update_all_pr_descriptions(&stack_id).await {
1858            Ok(updated_prs) => {
1859                if !updated_prs.is_empty() {
1860                    Output::sub_item(format!(
1861                        "Updated {} PR description{} with stack hierarchy",
1862                        updated_prs.len(),
1863                        if updated_prs.len() == 1 { "" } else { "s" }
1864                    ));
1865                }
1866            }
1867            Err(e) => {
1868                // Suppress benign 409 "out of date" errors - these happen when PR was just created
1869                // and Bitbucket's version hasn't propagated yet. The PR still gets created successfully.
1870                let error_msg = e.to_string();
1871                if !error_msg.contains("409") && !error_msg.contains("out-of-date") {
1872                    // Only show non-409 errors, and make them concise
1873                    let clean_error = error_msg.lines().next().unwrap_or("Unknown error").trim();
1874                    Output::warning(format!(
1875                        "Could not update some PR descriptions: {}",
1876                        clean_error
1877                    ));
1878                    Output::sub_item(
1879                        "PRs were created successfully - descriptions can be updated manually",
1880                    );
1881                }
1882            }
1883        }
1884    }
1885
1886    // Summary
1887    if failed_entries.is_empty() {
1888        Output::success(format!(
1889            "{} {} submitted successfully!",
1890            submitted_count,
1891            if submitted_count == 1 {
1892                "entry"
1893            } else {
1894                "entries"
1895            }
1896        ));
1897    } else {
1898        println!();
1899        Output::section("Submission Summary");
1900        Output::success(format!("Successful: {submitted_count}"));
1901        Output::error(format!("Failed: {}", failed_entries.len()));
1902
1903        if !failed_entries.is_empty() {
1904            println!();
1905            Output::tip("Retry failed entries:");
1906            for (entry_num, _) in &failed_entries {
1907                Output::bullet(format!("ca stack submit {entry_num}"));
1908            }
1909        }
1910    }
1911
1912    // Open PRs in browser if requested (default: true)
1913    if open && !pr_urls.is_empty() {
1914        println!();
1915        for url in &pr_urls {
1916            if let Err(e) = open::that(url) {
1917                Output::warning(format!("Could not open browser: {}", e));
1918                Output::tip(format!("Open manually: {}", url));
1919            }
1920        }
1921    }
1922
1923    Ok(())
1924}
1925
1926async fn check_stack_status(name: Option<String>) -> Result<()> {
1927    let current_dir = env::current_dir()
1928        .map_err(|e| CascadeError::config(format!("Could not get current directory: {e}")))?;
1929
1930    let repo_root = find_repository_root(&current_dir)
1931        .map_err(|e| CascadeError::config(format!("Could not find git repository: {e}")))?;
1932
1933    let stack_manager = StackManager::new(&repo_root)?;
1934
1935    // Load configuration
1936    let config_dir = crate::config::get_repo_config_dir(&repo_root)?;
1937    let config_path = config_dir.join("config.json");
1938    let settings = crate::config::Settings::load_from_file(&config_path)?;
1939
1940    // Create the main config structure
1941    let cascade_config = crate::config::CascadeConfig {
1942        bitbucket: Some(settings.bitbucket.clone()),
1943        git: settings.git.clone(),
1944        auth: crate::config::AuthConfig::default(),
1945        cascade: settings.cascade.clone(),
1946    };
1947
1948    // Get stack information BEFORE moving stack_manager
1949    let stack = if let Some(name) = name {
1950        stack_manager
1951            .get_stack_by_name(&name)
1952            .ok_or_else(|| CascadeError::config(format!("Stack '{name}' not found")))?
1953    } else {
1954        stack_manager.get_active_stack().ok_or_else(|| {
1955            CascadeError::config("No active stack. Use 'ca stack list' to see available stacks")
1956        })?
1957    };
1958    let stack_id = stack.id;
1959
1960    Output::section(format!("Stack: {}", stack.name));
1961    Output::sub_item(format!("ID: {}", stack.id));
1962    Output::sub_item(format!("Base: {}", stack.base_branch));
1963
1964    if let Some(description) = &stack.description {
1965        Output::sub_item(format!("Description: {description}"));
1966    }
1967
1968    // Create Bitbucket integration (this takes ownership of stack_manager)
1969    let integration = crate::bitbucket::BitbucketIntegration::new(stack_manager, cascade_config)?;
1970
1971    // Check stack status
1972    match integration.check_stack_status(&stack_id).await {
1973        Ok(status) => {
1974            Output::section("Pull Request Status");
1975            Output::sub_item(format!("Total entries: {}", status.total_entries));
1976            Output::sub_item(format!("Submitted: {}", status.submitted_entries));
1977            Output::sub_item(format!("Open PRs: {}", status.open_prs));
1978            Output::sub_item(format!("Merged PRs: {}", status.merged_prs));
1979            Output::sub_item(format!("Declined PRs: {}", status.declined_prs));
1980            Output::sub_item(format!(
1981                "Completion: {:.1}%",
1982                status.completion_percentage()
1983            ));
1984
1985            if !status.pull_requests.is_empty() {
1986                Output::section("Pull Requests");
1987                for pr in &status.pull_requests {
1988                    let state_icon = match pr.state {
1989                        crate::bitbucket::PullRequestState::Open => "🔄",
1990                        crate::bitbucket::PullRequestState::Merged => "✅",
1991                        crate::bitbucket::PullRequestState::Declined => "❌",
1992                    };
1993                    Output::bullet(format!(
1994                        "{} PR #{}: {} ({} -> {})",
1995                        state_icon, pr.id, pr.title, pr.from_ref.display_id, pr.to_ref.display_id
1996                    ));
1997                    if let Some(url) = pr.web_url() {
1998                        Output::sub_item(format!("URL: {url}"));
1999                    }
2000                }
2001            }
2002        }
2003        Err(e) => {
2004            tracing::debug!("Failed to check stack status: {}", e);
2005            return Err(e);
2006        }
2007    }
2008
2009    Ok(())
2010}
2011
2012async fn list_pull_requests(state: Option<String>, verbose: bool) -> Result<()> {
2013    let current_dir = env::current_dir()
2014        .map_err(|e| CascadeError::config(format!("Could not get current directory: {e}")))?;
2015
2016    let repo_root = find_repository_root(&current_dir)
2017        .map_err(|e| CascadeError::config(format!("Could not find git repository: {e}")))?;
2018
2019    let stack_manager = StackManager::new(&repo_root)?;
2020
2021    // Load configuration
2022    let config_dir = crate::config::get_repo_config_dir(&repo_root)?;
2023    let config_path = config_dir.join("config.json");
2024    let settings = crate::config::Settings::load_from_file(&config_path)?;
2025
2026    // Create the main config structure
2027    let cascade_config = crate::config::CascadeConfig {
2028        bitbucket: Some(settings.bitbucket.clone()),
2029        git: settings.git.clone(),
2030        auth: crate::config::AuthConfig::default(),
2031        cascade: settings.cascade.clone(),
2032    };
2033
2034    // Create Bitbucket integration
2035    let integration = crate::bitbucket::BitbucketIntegration::new(stack_manager, cascade_config)?;
2036
2037    // Parse state filter
2038    let pr_state = if let Some(state_str) = state {
2039        match state_str.to_lowercase().as_str() {
2040            "open" => Some(crate::bitbucket::PullRequestState::Open),
2041            "merged" => Some(crate::bitbucket::PullRequestState::Merged),
2042            "declined" => Some(crate::bitbucket::PullRequestState::Declined),
2043            _ => {
2044                return Err(CascadeError::config(format!(
2045                    "Invalid state '{state_str}'. Use: open, merged, declined"
2046                )))
2047            }
2048        }
2049    } else {
2050        None
2051    };
2052
2053    // Get pull requests
2054    match integration.list_pull_requests(pr_state).await {
2055        Ok(pr_page) => {
2056            if pr_page.values.is_empty() {
2057                Output::info("No pull requests found.");
2058                return Ok(());
2059            }
2060
2061            println!("Pull Requests ({} total):", pr_page.values.len());
2062            for pr in &pr_page.values {
2063                let state_icon = match pr.state {
2064                    crate::bitbucket::PullRequestState::Open => "○",
2065                    crate::bitbucket::PullRequestState::Merged => "✓",
2066                    crate::bitbucket::PullRequestState::Declined => "✗",
2067                };
2068                println!("   {} PR #{}: {}", state_icon, pr.id, pr.title);
2069                if verbose {
2070                    println!(
2071                        "      From: {} -> {}",
2072                        pr.from_ref.display_id, pr.to_ref.display_id
2073                    );
2074                    println!(
2075                        "      Author: {}",
2076                        pr.author
2077                            .user
2078                            .display_name
2079                            .as_deref()
2080                            .unwrap_or(&pr.author.user.name)
2081                    );
2082                    if let Some(url) = pr.web_url() {
2083                        println!("      URL: {url}");
2084                    }
2085                    if let Some(desc) = &pr.description {
2086                        if !desc.is_empty() {
2087                            println!("      Description: {desc}");
2088                        }
2089                    }
2090                    println!();
2091                }
2092            }
2093
2094            if !verbose {
2095                println!("\nUse --verbose for more details");
2096            }
2097        }
2098        Err(e) => {
2099            warn!("Failed to list pull requests: {}", e);
2100            return Err(e);
2101        }
2102    }
2103
2104    Ok(())
2105}
2106
2107async fn check_stack(_force: bool) -> Result<()> {
2108    let current_dir = env::current_dir()
2109        .map_err(|e| CascadeError::config(format!("Could not get current directory: {e}")))?;
2110
2111    let repo_root = find_repository_root(&current_dir)
2112        .map_err(|e| CascadeError::config(format!("Could not find git repository: {e}")))?;
2113
2114    let mut manager = StackManager::new(&repo_root)?;
2115
2116    let active_stack = manager
2117        .get_active_stack()
2118        .ok_or_else(|| CascadeError::config("No active stack"))?;
2119    let stack_id = active_stack.id;
2120
2121    manager.sync_stack(&stack_id)?;
2122
2123    Output::success("Stack check completed successfully");
2124
2125    Ok(())
2126}
2127
2128pub async fn continue_sync() -> Result<()> {
2129    let current_dir = env::current_dir()
2130        .map_err(|e| CascadeError::config(format!("Could not get current directory: {e}")))?;
2131
2132    let repo_root = find_repository_root(&current_dir)?;
2133
2134    Output::section("Continuing sync from where it left off");
2135    println!();
2136
2137    // Check if there's an in-progress cherry-pick
2138    let cherry_pick_head = repo_root.join(".git").join("CHERRY_PICK_HEAD");
2139    if !cherry_pick_head.exists() {
2140        return Err(CascadeError::config(
2141            "No in-progress cherry-pick found. Nothing to continue.\n\n\
2142             Use 'ca sync' to start a new sync."
2143                .to_string(),
2144        ));
2145    }
2146
2147    Output::info("Staging all resolved files");
2148
2149    // Stage all resolved files
2150    std::process::Command::new("git")
2151        .args(["add", "-A"])
2152        .current_dir(&repo_root)
2153        .output()
2154        .map_err(CascadeError::Io)?;
2155
2156    let sync_state = crate::stack::SyncState::load(&repo_root).ok();
2157
2158    Output::info("Continuing cherry-pick");
2159
2160    // Continue the cherry-pick
2161    let continue_output = std::process::Command::new("git")
2162        .args(["cherry-pick", "--continue"])
2163        .current_dir(&repo_root)
2164        .output()
2165        .map_err(CascadeError::Io)?;
2166
2167    if !continue_output.status.success() {
2168        let stderr = String::from_utf8_lossy(&continue_output.stderr);
2169        return Err(CascadeError::Branch(format!(
2170            "Failed to continue cherry-pick: {}\n\n\
2171             Make sure all conflicts are resolved.",
2172            stderr
2173        )));
2174    }
2175
2176    Output::success("Cherry-pick continued successfully");
2177    println!();
2178
2179    // Now we need to:
2180    // 1. Figure out which stack branch this temp branch belongs to
2181    // 2. Force-push the temp branch to the actual stack branch
2182    // 3. Checkout to the working branch
2183    // 4. Continue with sync_stack() to process remaining entries
2184
2185    let git_repo = crate::git::GitRepository::open(&repo_root)?;
2186    let current_branch = git_repo.get_current_branch()?;
2187
2188    let stack_branch = if let Some(state) = &sync_state {
2189        if !state.current_entry_branch.is_empty() {
2190            if !state.current_temp_branch.is_empty() && current_branch != state.current_temp_branch
2191            {
2192                tracing::warn!(
2193                    "Sync state temp branch '{}' differs from current branch '{}'",
2194                    state.current_temp_branch,
2195                    current_branch
2196                );
2197            }
2198            state.current_entry_branch.clone()
2199        } else if let Some(idx) = current_branch.rfind("-temp-") {
2200            current_branch[..idx].to_string()
2201        } else {
2202            return Err(CascadeError::config(format!(
2203                "Current branch '{}' doesn't appear to be a temp branch created by cascade.\n\
2204                 Expected format: <branch>-temp-<timestamp>",
2205                current_branch
2206            )));
2207        }
2208    } else if let Some(idx) = current_branch.rfind("-temp-") {
2209        current_branch[..idx].to_string()
2210    } else {
2211        return Err(CascadeError::config(format!(
2212            "Current branch '{}' doesn't appear to be a temp branch created by cascade.\n\
2213             Expected format: <branch>-temp-<timestamp>",
2214            current_branch
2215        )));
2216    };
2217
2218    Output::info(format!("Updating stack branch: {}", stack_branch));
2219
2220    // Force-push temp branch to stack branch
2221    let output = std::process::Command::new("git")
2222        .args(["branch", "-f", &stack_branch])
2223        .current_dir(&repo_root)
2224        .output()
2225        .map_err(CascadeError::Io)?;
2226
2227    if !output.status.success() {
2228        let stderr = String::from_utf8_lossy(&output.stderr);
2229        return Err(CascadeError::validation(format!(
2230            "Failed to update branch '{}': {}\n\n\
2231            This could be due to:\n\
2232            • Git lock file (.git/index.lock or .git/refs/heads/{}.lock)\n\
2233            • Insufficient permissions\n\
2234            • Branch is checked out in another worktree\n\n\
2235            Recovery:\n\
2236            1. Check for lock files: find .git -name '*.lock'\n\
2237            2. Remove stale lock files if safe\n\
2238            3. Run 'ca sync' to retry",
2239            stack_branch,
2240            stderr.trim(),
2241            stack_branch
2242        )));
2243    }
2244
2245    // Load stack to get working branch and update metadata
2246    let mut manager = crate::stack::StackManager::new(&repo_root)?;
2247
2248    // CRITICAL: Update the stack entry's commit hash to the new rebased commit
2249    // This prevents sync_stack() from thinking the working branch has "untracked" commits
2250    let new_commit_hash = git_repo.get_branch_head(&stack_branch)?;
2251
2252    let (stack_id, entry_id_opt, working_branch) = if let Some(state) = &sync_state {
2253        let stack_uuid = Uuid::parse_str(&state.stack_id)
2254            .map_err(|e| CascadeError::config(format!("Invalid stack ID in sync state: {e}")))?;
2255
2256        let stack_snapshot = manager
2257            .get_stack(&stack_uuid)
2258            .cloned()
2259            .ok_or_else(|| CascadeError::config("Stack not found in sync state".to_string()))?;
2260
2261        let working_branch = stack_snapshot
2262            .working_branch
2263            .clone()
2264            .ok_or_else(|| CascadeError::config("Stack has no working branch".to_string()))?;
2265
2266        let entry_id = if !state.current_entry_id.is_empty() {
2267            Uuid::parse_str(&state.current_entry_id).ok()
2268        } else {
2269            stack_snapshot
2270                .entries
2271                .iter()
2272                .find(|e| e.branch == stack_branch)
2273                .map(|e| e.id)
2274        };
2275
2276        (stack_uuid, entry_id, working_branch)
2277    } else {
2278        let active_stack = manager
2279            .get_active_stack()
2280            .ok_or_else(|| CascadeError::config("No active stack found"))?;
2281
2282        let entry_id = active_stack
2283            .entries
2284            .iter()
2285            .find(|e| e.branch == stack_branch)
2286            .map(|e| e.id);
2287
2288        let working_branch = active_stack
2289            .working_branch
2290            .as_ref()
2291            .ok_or_else(|| CascadeError::config("Active stack has no working branch"))?
2292            .clone();
2293
2294        (active_stack.id, entry_id, working_branch)
2295    };
2296
2297    // Now we can mutably borrow manager to update the entry
2298    let entry_id = entry_id_opt.ok_or_else(|| {
2299        CascadeError::config(format!(
2300            "Could not find stack entry for branch '{}'",
2301            stack_branch
2302        ))
2303    })?;
2304
2305    let stack = manager
2306        .get_stack_mut(&stack_id)
2307        .ok_or_else(|| CascadeError::config("Could not get mutable stack reference"))?;
2308
2309    stack
2310        .update_entry_commit_hash(&entry_id, new_commit_hash.clone())
2311        .map_err(CascadeError::config)?;
2312
2313    manager.save_to_disk()?;
2314
2315    // Get the top of the stack to update the working branch
2316    let top_commit = {
2317        let active_stack = manager
2318            .get_active_stack()
2319            .ok_or_else(|| CascadeError::config("No active stack found"))?;
2320
2321        if let Some(last_entry) = active_stack.entries.last() {
2322            git_repo.get_branch_head(&last_entry.branch)?
2323        } else {
2324            new_commit_hash.clone()
2325        }
2326    };
2327
2328    Output::info(format!(
2329        "Checking out to working branch: {}",
2330        working_branch
2331    ));
2332
2333    // Checkout to working branch
2334    git_repo.checkout_branch_unsafe(&working_branch)?;
2335
2336    // Update working branch to point to the top of the rebased stack
2337    // In the continue_sync() context, we KNOW we just finished rebasing, so the
2338    // working branch's old commits are pre-rebase versions that should be replaced.
2339    // We unconditionally update here because:
2340    // 1. The user just resolved conflicts and continued the rebase
2341    // 2. The stack entry metadata has been updated to the new rebased commits
2342    // 3. Any "old" commits on the working branch are the pre-rebase versions
2343    // 4. The subsequent sync_stack() call will do final safety checks
2344    if let Ok(working_head) = git_repo.get_branch_head(&working_branch) {
2345        if working_head != top_commit {
2346            git_repo.update_branch_to_commit(&working_branch, &top_commit)?;
2347        }
2348    }
2349
2350    if sync_state.is_some() {
2351        crate::stack::SyncState::delete(&repo_root)?;
2352    }
2353
2354    println!();
2355    Output::info("Resuming sync to complete the rebase...");
2356    println!();
2357
2358    // Continue with the full sync to process remaining entries
2359    sync_stack(false, false, false).await
2360}
2361
2362pub async fn abort_sync() -> Result<()> {
2363    let current_dir = env::current_dir()
2364        .map_err(|e| CascadeError::config(format!("Could not get current directory: {e}")))?;
2365
2366    let repo_root = find_repository_root(&current_dir)?;
2367
2368    Output::section("Aborting sync");
2369    println!();
2370
2371    // Check if there's an in-progress cherry-pick
2372    let cherry_pick_head = repo_root.join(".git").join("CHERRY_PICK_HEAD");
2373    if !cherry_pick_head.exists() {
2374        return Err(CascadeError::config(
2375            "No in-progress cherry-pick found. Nothing to abort.\n\n\
2376             The sync may have already completed or been aborted."
2377                .to_string(),
2378        ));
2379    }
2380
2381    Output::info("Aborting cherry-pick");
2382
2383    // Abort the cherry-pick with CASCADE_SKIP_HOOKS to avoid hook interference
2384    let abort_output = std::process::Command::new("git")
2385        .args(["cherry-pick", "--abort"])
2386        .env("CASCADE_SKIP_HOOKS", "1")
2387        .current_dir(&repo_root)
2388        .output()
2389        .map_err(CascadeError::Io)?;
2390
2391    if !abort_output.status.success() {
2392        let stderr = String::from_utf8_lossy(&abort_output.stderr);
2393        return Err(CascadeError::Branch(format!(
2394            "Failed to abort cherry-pick: {}",
2395            stderr
2396        )));
2397    }
2398
2399    Output::success("Cherry-pick aborted");
2400
2401    // Load sync state if it exists to clean up temp branches
2402    let git_repo = crate::git::GitRepository::open(&repo_root)?;
2403
2404    if let Ok(state) = crate::stack::SyncState::load(&repo_root) {
2405        println!();
2406        Output::info("Cleaning up temporary branches");
2407
2408        // Clean up all temp branches
2409        for temp_branch in &state.temp_branches {
2410            if let Err(e) = git_repo.delete_branch_unsafe(temp_branch) {
2411                tracing::warn!("Could not delete temp branch '{}': {}", temp_branch, e);
2412            }
2413        }
2414
2415        // Return to original branch
2416        Output::info(format!(
2417            "Returning to original branch: {}",
2418            state.original_branch
2419        ));
2420        if let Err(e) = git_repo.checkout_branch_unsafe(&state.original_branch) {
2421            // Fall back to base branch if original branch checkout fails
2422            tracing::warn!("Could not checkout original branch: {}", e);
2423            if let Err(e2) = git_repo.checkout_branch_unsafe(&state.target_base) {
2424                tracing::warn!("Could not checkout base branch: {}", e2);
2425            }
2426        }
2427
2428        // Delete sync state file
2429        crate::stack::SyncState::delete(&repo_root)?;
2430    } else {
2431        // No state file - try to figure out where to go
2432        let current_branch = git_repo.get_current_branch()?;
2433
2434        // If on a temp branch, try to parse and return to original
2435        if let Some(idx) = current_branch.rfind("-temp-") {
2436            let original_branch = &current_branch[..idx];
2437            Output::info(format!("Returning to branch: {}", original_branch));
2438
2439            if let Err(e) = git_repo.checkout_branch_unsafe(original_branch) {
2440                tracing::warn!("Could not checkout original branch: {}", e);
2441            }
2442
2443            // Try to delete the temp branch
2444            if let Err(e) = git_repo.delete_branch_unsafe(&current_branch) {
2445                tracing::warn!("Could not delete temp branch: {}", e);
2446            }
2447        }
2448    }
2449
2450    println!();
2451    Output::success("Sync aborted");
2452    println!();
2453    Output::tip("You can start a fresh sync with: ca sync");
2454
2455    Ok(())
2456}
2457
2458async fn sync_stack(force: bool, cleanup: bool, interactive: bool) -> Result<()> {
2459    let current_dir = env::current_dir()
2460        .map_err(|e| CascadeError::config(format!("Could not get current directory: {e}")))?;
2461
2462    let repo_root = find_repository_root(&current_dir)
2463        .map_err(|e| CascadeError::config(format!("Could not find git repository: {e}")))?;
2464
2465    let mut stack_manager = StackManager::new(&repo_root)?;
2466
2467    // Exit edit mode if active (sync will invalidate commit SHAs)
2468    // TODO: Add error recovery to restore edit mode if sync fails
2469    if stack_manager.is_in_edit_mode() {
2470        debug!("Exiting edit mode before sync (commit SHAs will change)");
2471        stack_manager.exit_edit_mode()?;
2472    }
2473
2474    let git_repo = GitRepository::open(&repo_root)?;
2475
2476    if git_repo.is_dirty()? {
2477        return Err(CascadeError::branch(
2478            "Working tree has uncommitted changes. Commit or stash them before running 'ca sync'."
2479                .to_string(),
2480        ));
2481    }
2482
2483    // Get active stack
2484    let active_stack = stack_manager.get_active_stack().ok_or_else(|| {
2485        CascadeError::config("No active stack. Create a stack first with 'ca stack create'")
2486    })?;
2487
2488    let base_branch = active_stack.base_branch.clone();
2489    let _stack_name = active_stack.name.clone();
2490
2491    // Save the original working branch before any checkouts
2492    let original_branch = git_repo.get_current_branch().ok();
2493
2494    // Sync starts silently - user will see the rebase output
2495
2496    // Step 1: Pull latest changes from base branch (silent unless error)
2497    match git_repo.checkout_branch_silent(&base_branch) {
2498        Ok(_) => {
2499            match git_repo.pull(&base_branch) {
2500                Ok(_) => {
2501                    // Silent success - only show on verbose or error
2502                }
2503                Err(e) => {
2504                    if force {
2505                        Output::warning(format!("Pull failed: {e} (continuing due to --force)"));
2506                    } else {
2507                        Output::error(format!("Failed to pull latest changes: {e}"));
2508                        Output::tip("Use --force to skip pull and continue with rebase");
2509                        return Err(CascadeError::branch(format!(
2510                            "Failed to pull latest changes from '{base_branch}': {e}. Use --force to continue anyway."
2511                        )));
2512                    }
2513                }
2514            }
2515        }
2516        Err(e) => {
2517            if force {
2518                Output::warning(format!(
2519                    "Failed to checkout '{base_branch}': {e} (continuing due to --force)"
2520                ));
2521            } else {
2522                Output::error(format!(
2523                    "Failed to checkout base branch '{base_branch}': {e}"
2524                ));
2525                Output::tip("Use --force to bypass checkout issues and continue anyway");
2526                return Err(CascadeError::branch(format!(
2527                    "Failed to checkout base branch '{base_branch}': {e}. Use --force to continue anyway."
2528                )));
2529            }
2530        }
2531    }
2532
2533    // Step 2: Reconcile metadata with current Git state before checking integrity
2534    // This fixes stale metadata from previous bugs or interrupted operations
2535    let mut updated_stack_manager = StackManager::new(&repo_root)?;
2536    let stack_id = active_stack.id;
2537
2538    // Update entry commit hashes to match current branch HEADs
2539    // This prevents false "branch modification" errors from stale metadata
2540    if let Some(stack) = updated_stack_manager.get_stack_mut(&stack_id) {
2541        let mut updates = Vec::new();
2542        for entry in &stack.entries {
2543            if let Ok(current_commit) = git_repo.get_branch_head(&entry.branch) {
2544                if entry.commit_hash != current_commit {
2545                    let is_safe_descendant = match git_repo.commit_exists(&entry.commit_hash) {
2546                        Ok(true) => {
2547                            match git_repo.is_descendant_of(&current_commit, &entry.commit_hash) {
2548                                Ok(result) => result,
2549                                Err(e) => {
2550                                    warn!(
2551                                    "Cannot verify ancestry for '{}': {} - treating as unsafe to prevent potential data loss",
2552                                    entry.branch, e
2553                                );
2554                                    false
2555                                }
2556                            }
2557                        }
2558                        Ok(false) => {
2559                            debug!(
2560                                "Recorded commit {} for '{}' no longer exists in repository",
2561                                &entry.commit_hash[..8],
2562                                entry.branch
2563                            );
2564                            false
2565                        }
2566                        Err(e) => {
2567                            warn!(
2568                                "Cannot verify commit existence for '{}': {} - treating as unsafe to prevent potential data loss",
2569                                entry.branch, e
2570                            );
2571                            false
2572                        }
2573                    };
2574
2575                    if is_safe_descendant {
2576                        debug!(
2577                            "Reconciling entry '{}': updating hash from {} to {} (current branch HEAD)",
2578                            entry.branch,
2579                            &entry.commit_hash[..8],
2580                            &current_commit[..8]
2581                        );
2582                        updates.push((entry.id, current_commit));
2583                    } else {
2584                        warn!(
2585                            "Skipped automatic reconciliation for entry '{}' because local HEAD ({}) does not descend from recorded commit ({})",
2586                            entry.branch,
2587                            &current_commit[..8],
2588                            &entry.commit_hash[..8]
2589                        );
2590                        // This commonly happens after 'ca entry amend' without --restack
2591                        // The amended commit replaces the old one (not a descendant)
2592                    }
2593                }
2594            }
2595        }
2596
2597        // Apply updates using safe wrapper
2598        for (entry_id, new_hash) in updates {
2599            stack
2600                .update_entry_commit_hash(&entry_id, new_hash)
2601                .map_err(CascadeError::config)?;
2602        }
2603
2604        // Save reconciled metadata
2605        updated_stack_manager.save_to_disk()?;
2606    }
2607
2608    match updated_stack_manager.sync_stack(&stack_id) {
2609        Ok(_) => {
2610            // Check the updated status
2611            if let Some(updated_stack) = updated_stack_manager.get_stack(&stack_id) {
2612                // Check for empty stack first
2613                if updated_stack.entries.is_empty() {
2614                    println!(); // Spacing
2615                    Output::info("Stack has no entries yet");
2616                    Output::tip("Use 'ca push' to add commits to this stack");
2617                    return Ok(());
2618                }
2619
2620                match &updated_stack.status {
2621                    crate::stack::StackStatus::NeedsSync => {
2622                        // Load configuration for Bitbucket integration
2623                        let config_dir = crate::config::get_repo_config_dir(&repo_root)?;
2624                        let config_path = config_dir.join("config.json");
2625                        let settings = crate::config::Settings::load_from_file(&config_path)?;
2626
2627                        let cascade_config = crate::config::CascadeConfig {
2628                            bitbucket: Some(settings.bitbucket.clone()),
2629                            git: settings.git.clone(),
2630                            auth: crate::config::AuthConfig::default(),
2631                            cascade: settings.cascade.clone(),
2632                        };
2633
2634                        println!(); // Spacing
2635
2636                        // Use the existing rebase system with force-push strategy
2637                        // This preserves PR history by force-pushing to original branches
2638                        let options = crate::stack::RebaseOptions {
2639                            strategy: crate::stack::RebaseStrategy::ForcePush,
2640                            interactive,
2641                            target_base: Some(base_branch.clone()),
2642                            preserve_merges: true,
2643                            auto_resolve: !interactive, // Re-enabled with safety checks
2644                            max_retries: 3,
2645                            skip_pull: Some(true), // Skip pull since we already pulled above
2646                            original_working_branch: original_branch.clone(), // Pass the saved working branch
2647                        };
2648
2649                        let mut rebase_manager = crate::stack::RebaseManager::new(
2650                            updated_stack_manager,
2651                            git_repo,
2652                            options,
2653                        );
2654
2655                        // Rebase all entries (static output)
2656                        let rebase_result = rebase_manager.rebase_stack(&stack_id);
2657
2658                        match rebase_result {
2659                            Ok(result) => {
2660                                if !result.branch_mapping.is_empty() {
2661                                    // Update PRs if enabled
2662                                    if let Some(ref _bitbucket_config) = cascade_config.bitbucket {
2663                                        // Reload stack manager to get latest metadata after rebase
2664                                        let integration_stack_manager =
2665                                            StackManager::new(&repo_root)?;
2666                                        let mut integration =
2667                                            crate::bitbucket::BitbucketIntegration::new(
2668                                                integration_stack_manager,
2669                                                cascade_config,
2670                                            )?;
2671
2672                                        // Update PRs (static output)
2673                                        let pr_result = integration
2674                                            .update_prs_after_rebase(
2675                                                &stack_id,
2676                                                &result.branch_mapping,
2677                                            )
2678                                            .await;
2679
2680                                        match pr_result {
2681                                            Ok(updated_prs) => {
2682                                                if !updated_prs.is_empty() {
2683                                                    Output::success(format!(
2684                                                        "Updated {} pull request{}",
2685                                                        updated_prs.len(),
2686                                                        if updated_prs.len() == 1 {
2687                                                            ""
2688                                                        } else {
2689                                                            "s"
2690                                                        }
2691                                                    ));
2692                                                }
2693                                            }
2694                                            Err(e) => {
2695                                                Output::warning(format!(
2696                                                    "Failed to update pull requests: {e}"
2697                                                ));
2698                                            }
2699                                        }
2700                                    }
2701                                }
2702                            }
2703                            Err(e) => {
2704                                // Error already contains instructions, just propagate it
2705                                return Err(e);
2706                            }
2707                        }
2708                    }
2709                    crate::stack::StackStatus::Clean => {
2710                        // Already up to date - silent success
2711                    }
2712                    other => {
2713                        // Only show unexpected status
2714                        Output::info(format!("Stack status: {other:?}"));
2715                    }
2716                }
2717            }
2718        }
2719        Err(e) => {
2720            if force {
2721                Output::warning(format!(
2722                    "Failed to check stack status: {e} (continuing due to --force)"
2723                ));
2724            } else {
2725                return Err(e);
2726            }
2727        }
2728    }
2729
2730    // Step 3: Cleanup merged branches (optional) - only if explicitly requested
2731    if cleanup {
2732        let git_repo_for_cleanup = GitRepository::open(&repo_root)?;
2733        match perform_simple_cleanup(&stack_manager, &git_repo_for_cleanup, false).await {
2734            Ok(result) => {
2735                if result.total_candidates > 0 {
2736                    Output::section("Cleanup Summary");
2737                    if !result.cleaned_branches.is_empty() {
2738                        Output::success(format!(
2739                            "Cleaned up {} merged branches",
2740                            result.cleaned_branches.len()
2741                        ));
2742                        for branch in &result.cleaned_branches {
2743                            Output::sub_item(format!("🗑️  Deleted: {branch}"));
2744                        }
2745                    }
2746                    if !result.skipped_branches.is_empty() {
2747                        Output::sub_item(format!(
2748                            "Skipped {} branches",
2749                            result.skipped_branches.len()
2750                        ));
2751                    }
2752                    if !result.failed_branches.is_empty() {
2753                        for (branch, error) in &result.failed_branches {
2754                            Output::warning(format!("Failed to clean up {branch}: {error}"));
2755                        }
2756                    }
2757                }
2758            }
2759            Err(e) => {
2760                Output::warning(format!("Branch cleanup failed: {e}"));
2761            }
2762        }
2763    }
2764
2765    // NOTE: Don't checkout the original branch here!
2766    // The rebase_with_force_push() function already returned us to the working branch
2767    // using checkout_branch_unsafe(). If we try to checkout again with the safe version,
2768    // it will see the rebased working tree and think there are staged changes
2769    // (because the working branch HEAD was updated during rebase but we're still on the old tree).
2770    // Trust that the rebase left us in the correct state.
2771
2772    Output::success("Sync completed successfully!");
2773
2774    Ok(())
2775}
2776
2777async fn rebase_stack(
2778    interactive: bool,
2779    onto: Option<String>,
2780    strategy: Option<RebaseStrategyArg>,
2781) -> Result<()> {
2782    let current_dir = env::current_dir()
2783        .map_err(|e| CascadeError::config(format!("Could not get current directory: {e}")))?;
2784
2785    let repo_root = find_repository_root(&current_dir)
2786        .map_err(|e| CascadeError::config(format!("Could not find git repository: {e}")))?;
2787
2788    let stack_manager = StackManager::new(&repo_root)?;
2789    let git_repo = GitRepository::open(&repo_root)?;
2790
2791    // Load configuration for potential Bitbucket integration
2792    let config_dir = crate::config::get_repo_config_dir(&repo_root)?;
2793    let config_path = config_dir.join("config.json");
2794    let settings = crate::config::Settings::load_from_file(&config_path)?;
2795
2796    // Create the main config structure
2797    let cascade_config = crate::config::CascadeConfig {
2798        bitbucket: Some(settings.bitbucket.clone()),
2799        git: settings.git.clone(),
2800        auth: crate::config::AuthConfig::default(),
2801        cascade: settings.cascade.clone(),
2802    };
2803
2804    // Get active stack
2805    let active_stack = stack_manager.get_active_stack().ok_or_else(|| {
2806        CascadeError::config("No active stack. Create a stack first with 'ca stack create'")
2807    })?;
2808    let stack_id = active_stack.id;
2809
2810    let active_stack = stack_manager
2811        .get_stack(&stack_id)
2812        .ok_or_else(|| CascadeError::config("Active stack not found"))?
2813        .clone();
2814
2815    if active_stack.entries.is_empty() {
2816        Output::info("Stack is empty. Nothing to rebase.");
2817        return Ok(());
2818    }
2819
2820    // Determine rebase strategy (force-push is the industry standard for stacked diffs)
2821    let rebase_strategy = if let Some(cli_strategy) = strategy {
2822        match cli_strategy {
2823            RebaseStrategyArg::ForcePush => crate::stack::RebaseStrategy::ForcePush,
2824            RebaseStrategyArg::Interactive => crate::stack::RebaseStrategy::Interactive,
2825        }
2826    } else {
2827        // Default to force-push (industry standard for preserving PR history)
2828        crate::stack::RebaseStrategy::ForcePush
2829    };
2830
2831    // Save original branch before any operations
2832    let original_branch = git_repo.get_current_branch().ok();
2833
2834    debug!("   Strategy: {:?}", rebase_strategy);
2835    debug!("   Interactive: {}", interactive);
2836    debug!("   Target base: {:?}", onto);
2837    debug!("   Entries: {}", active_stack.entries.len());
2838
2839    println!(); // Spacing
2840
2841    // Start spinner for rebase
2842    let rebase_spinner = crate::utils::spinner::Spinner::new_with_output_below(format!(
2843        "Rebasing stack: {}",
2844        active_stack.name
2845    ));
2846
2847    // Create rebase options
2848    let options = crate::stack::RebaseOptions {
2849        strategy: rebase_strategy.clone(),
2850        interactive,
2851        target_base: onto,
2852        preserve_merges: true,
2853        auto_resolve: !interactive, // Re-enabled with safety checks
2854        max_retries: 3,
2855        skip_pull: None, // Normal rebase should pull latest changes
2856        original_working_branch: original_branch,
2857    };
2858
2859    // Check if there's already a rebase in progress
2860    let mut rebase_manager = crate::stack::RebaseManager::new(stack_manager, git_repo, options);
2861
2862    if rebase_manager.is_rebase_in_progress() {
2863        Output::warning("Rebase already in progress!");
2864        Output::tip("Use 'git status' to check the current state");
2865        Output::next_steps(&[
2866            "Run 'ca stack continue-rebase' to continue",
2867            "Run 'ca stack abort-rebase' to abort",
2868        ]);
2869        rebase_spinner.stop();
2870        return Ok(());
2871    }
2872
2873    // Perform the rebase
2874    let rebase_result = rebase_manager.rebase_stack(&stack_id);
2875
2876    // Stop spinner before showing results
2877    rebase_spinner.stop();
2878    println!(); // Spacing
2879
2880    match rebase_result {
2881        Ok(result) => {
2882            Output::success("Rebase completed!");
2883            Output::sub_item(result.get_summary());
2884
2885            if result.has_conflicts() {
2886                Output::warning(format!(
2887                    "{} conflicts were resolved",
2888                    result.conflicts.len()
2889                ));
2890                for conflict in &result.conflicts {
2891                    Output::bullet(&conflict[..8.min(conflict.len())]);
2892                }
2893            }
2894
2895            if !result.branch_mapping.is_empty() {
2896                Output::section("Branch mapping");
2897                for (old, new) in &result.branch_mapping {
2898                    Output::bullet(format!("{old} -> {new}"));
2899                }
2900
2901                // Handle PR updates if enabled
2902                if let Some(ref _bitbucket_config) = cascade_config.bitbucket {
2903                    // Create a new StackManager for the integration (since the original was moved)
2904                    let integration_stack_manager = StackManager::new(&repo_root)?;
2905                    let mut integration = BitbucketIntegration::new(
2906                        integration_stack_manager,
2907                        cascade_config.clone(),
2908                    )?;
2909
2910                    match integration
2911                        .update_prs_after_rebase(&stack_id, &result.branch_mapping)
2912                        .await
2913                    {
2914                        Ok(updated_prs) => {
2915                            if !updated_prs.is_empty() {
2916                                println!("   🔄 Preserved pull request history:");
2917                                for pr_update in updated_prs {
2918                                    println!("      ✅ {pr_update}");
2919                                }
2920                            }
2921                        }
2922                        Err(e) => {
2923                            Output::warning(format!("Failed to update pull requests: {e}"));
2924                            Output::sub_item("You may need to manually update PRs in Bitbucket");
2925                        }
2926                    }
2927                }
2928            }
2929
2930            Output::success(format!(
2931                "{} commits successfully rebased",
2932                result.success_count()
2933            ));
2934
2935            // Show next steps
2936            if matches!(rebase_strategy, crate::stack::RebaseStrategy::ForcePush) {
2937                println!();
2938                Output::section("Next steps");
2939                if !result.branch_mapping.is_empty() {
2940                    Output::numbered_item(1, "Branches have been rebased and force-pushed");
2941                    Output::numbered_item(
2942                        2,
2943                        "Pull requests updated automatically (history preserved)",
2944                    );
2945                    Output::numbered_item(3, "Review the updated PRs in Bitbucket");
2946                    Output::numbered_item(4, "Test your changes");
2947                } else {
2948                    println!("   1. Review the rebased stack");
2949                    println!("   2. Test your changes");
2950                    println!("   3. Submit new pull requests with 'ca stack submit'");
2951                }
2952            }
2953        }
2954        Err(e) => {
2955            warn!("❌ Rebase failed: {}", e);
2956            Output::tip(" Tips for resolving rebase issues:");
2957            println!("   - Check for uncommitted changes with 'git status'");
2958            println!("   - Ensure base branch is up to date");
2959            println!("   - Try interactive mode: 'ca stack rebase --interactive'");
2960            return Err(e);
2961        }
2962    }
2963
2964    Ok(())
2965}
2966
2967pub async fn continue_rebase() -> Result<()> {
2968    let current_dir = env::current_dir()
2969        .map_err(|e| CascadeError::config(format!("Could not get current directory: {e}")))?;
2970
2971    let repo_root = find_repository_root(&current_dir)
2972        .map_err(|e| CascadeError::config(format!("Could not find git repository: {e}")))?;
2973
2974    let stack_manager = StackManager::new(&repo_root)?;
2975    let git_repo = crate::git::GitRepository::open(&repo_root)?;
2976    let options = crate::stack::RebaseOptions::default();
2977    let rebase_manager = crate::stack::RebaseManager::new(stack_manager, git_repo, options);
2978
2979    if !rebase_manager.is_rebase_in_progress() {
2980        Output::info("  No rebase in progress");
2981        return Ok(());
2982    }
2983
2984    println!(" Continuing rebase...");
2985    match rebase_manager.continue_rebase() {
2986        Ok(_) => {
2987            Output::success(" Rebase continued successfully");
2988            println!("   Check 'ca stack rebase-status' for current state");
2989        }
2990        Err(e) => {
2991            warn!("❌ Failed to continue rebase: {}", e);
2992            Output::tip(" You may need to resolve conflicts first:");
2993            println!("   1. Edit conflicted files");
2994            println!("   2. Stage resolved files with 'git add'");
2995            println!("   3. Run 'ca stack continue-rebase' again");
2996        }
2997    }
2998
2999    Ok(())
3000}
3001
3002pub async fn abort_rebase() -> Result<()> {
3003    let current_dir = env::current_dir()
3004        .map_err(|e| CascadeError::config(format!("Could not get current directory: {e}")))?;
3005
3006    let repo_root = find_repository_root(&current_dir)
3007        .map_err(|e| CascadeError::config(format!("Could not find git repository: {e}")))?;
3008
3009    let stack_manager = StackManager::new(&repo_root)?;
3010    let git_repo = crate::git::GitRepository::open(&repo_root)?;
3011    let options = crate::stack::RebaseOptions::default();
3012    let rebase_manager = crate::stack::RebaseManager::new(stack_manager, git_repo, options);
3013
3014    if !rebase_manager.is_rebase_in_progress() {
3015        Output::info("  No rebase in progress");
3016        return Ok(());
3017    }
3018
3019    Output::warning("Aborting rebase...");
3020    match rebase_manager.abort_rebase() {
3021        Ok(_) => {
3022            Output::success(" Rebase aborted successfully");
3023            println!("   Repository restored to pre-rebase state");
3024        }
3025        Err(e) => {
3026            warn!("❌ Failed to abort rebase: {}", e);
3027            println!("⚠️  You may need to manually clean up the repository state");
3028        }
3029    }
3030
3031    Ok(())
3032}
3033
3034async fn rebase_status() -> Result<()> {
3035    let current_dir = env::current_dir()
3036        .map_err(|e| CascadeError::config(format!("Could not get current directory: {e}")))?;
3037
3038    let repo_root = find_repository_root(&current_dir)
3039        .map_err(|e| CascadeError::config(format!("Could not find git repository: {e}")))?;
3040
3041    let stack_manager = StackManager::new(&repo_root)?;
3042    let git_repo = crate::git::GitRepository::open(&repo_root)?;
3043
3044    println!("Rebase Status");
3045
3046    // Check if rebase is in progress by checking git state directly
3047    let git_dir = current_dir.join(".git");
3048    let rebase_in_progress = git_dir.join("REBASE_HEAD").exists()
3049        || git_dir.join("rebase-merge").exists()
3050        || git_dir.join("rebase-apply").exists();
3051
3052    if rebase_in_progress {
3053        println!("   Status: 🔄 Rebase in progress");
3054        println!(
3055            "   
3056📝 Actions available:"
3057        );
3058        println!("     - 'ca stack continue-rebase' to continue");
3059        println!("     - 'ca stack abort-rebase' to abort");
3060        println!("     - 'git status' to see conflicted files");
3061
3062        // Check for conflicts
3063        match git_repo.get_status() {
3064            Ok(statuses) => {
3065                let mut conflicts = Vec::new();
3066                for status in statuses.iter() {
3067                    if status.status().contains(git2::Status::CONFLICTED) {
3068                        if let Some(path) = status.path() {
3069                            conflicts.push(path.to_string());
3070                        }
3071                    }
3072                }
3073
3074                if !conflicts.is_empty() {
3075                    println!("   ⚠️  Conflicts in {} files:", conflicts.len());
3076                    for conflict in conflicts {
3077                        println!("      - {conflict}");
3078                    }
3079                    println!(
3080                        "   
3081💡 To resolve conflicts:"
3082                    );
3083                    println!("     1. Edit the conflicted files");
3084                    println!("     2. Stage resolved files: git add <file>");
3085                    println!("     3. Continue: ca stack continue-rebase");
3086                }
3087            }
3088            Err(e) => {
3089                warn!("Failed to get git status: {}", e);
3090            }
3091        }
3092    } else {
3093        println!("   Status: ✅ No rebase in progress");
3094
3095        // Show stack status instead
3096        if let Some(active_stack) = stack_manager.get_active_stack() {
3097            println!("   Active stack: {}", active_stack.name);
3098            println!("   Entries: {}", active_stack.entries.len());
3099            println!("   Base branch: {}", active_stack.base_branch);
3100        }
3101    }
3102
3103    Ok(())
3104}
3105
3106async fn delete_stack(name: String, force: bool) -> Result<()> {
3107    let current_dir = env::current_dir()
3108        .map_err(|e| CascadeError::config(format!("Could not get current directory: {e}")))?;
3109
3110    let repo_root = find_repository_root(&current_dir)
3111        .map_err(|e| CascadeError::config(format!("Could not find git repository: {e}")))?;
3112
3113    let mut manager = StackManager::new(&repo_root)?;
3114
3115    let stack = manager
3116        .get_stack_by_name(&name)
3117        .ok_or_else(|| CascadeError::config(format!("Stack '{name}' not found")))?;
3118    let stack_id = stack.id;
3119
3120    if !force && !stack.entries.is_empty() {
3121        return Err(CascadeError::config(format!(
3122            "Stack '{}' has {} entries. Use --force to delete anyway",
3123            name,
3124            stack.entries.len()
3125        )));
3126    }
3127
3128    let deleted = manager.delete_stack(&stack_id)?;
3129
3130    Output::success(format!("Deleted stack '{}'", deleted.name));
3131    if !deleted.entries.is_empty() {
3132        Output::warning(format!("{} entries were removed", deleted.entries.len()));
3133    }
3134
3135    Ok(())
3136}
3137
3138async fn validate_stack(name: Option<String>, fix_mode: Option<String>) -> Result<()> {
3139    let current_dir = env::current_dir()
3140        .map_err(|e| CascadeError::config(format!("Could not get current directory: {e}")))?;
3141
3142    let repo_root = find_repository_root(&current_dir)
3143        .map_err(|e| CascadeError::config(format!("Could not find git repository: {e}")))?;
3144
3145    let mut manager = StackManager::new(&repo_root)?;
3146
3147    if let Some(name) = name {
3148        // Validate specific stack
3149        let stack = manager
3150            .get_stack_by_name(&name)
3151            .ok_or_else(|| CascadeError::config(format!("Stack '{name}' not found")))?;
3152
3153        let stack_id = stack.id;
3154
3155        // Basic structure validation first
3156        match stack.validate() {
3157            Ok(_message) => {
3158                Output::success(format!("Stack '{}' structure validation passed", name));
3159            }
3160            Err(e) => {
3161                Output::error(format!(
3162                    "Stack '{}' structure validation failed: {}",
3163                    name, e
3164                ));
3165                return Err(CascadeError::config(e));
3166            }
3167        }
3168
3169        // Handle branch modifications (includes Git integrity checks)
3170        manager.handle_branch_modifications(&stack_id, fix_mode)?;
3171
3172        println!();
3173        Output::success(format!("Stack '{name}' validation completed"));
3174        Ok(())
3175    } else {
3176        // Validate all stacks
3177        Output::section("Validating all stacks");
3178        println!();
3179
3180        // Get all stack IDs through public method
3181        let all_stacks = manager.get_all_stacks();
3182        let stack_ids: Vec<uuid::Uuid> = all_stacks.iter().map(|s| s.id).collect();
3183
3184        if stack_ids.is_empty() {
3185            Output::info("No stacks found");
3186            return Ok(());
3187        }
3188
3189        let mut all_valid = true;
3190        for stack_id in stack_ids {
3191            let stack = manager.get_stack(&stack_id).unwrap();
3192            let stack_name = &stack.name;
3193
3194            println!("Checking stack '{stack_name}':");
3195
3196            // Basic structure validation
3197            match stack.validate() {
3198                Ok(message) => {
3199                    Output::sub_item(format!("Structure: {message}"));
3200                }
3201                Err(e) => {
3202                    Output::sub_item(format!("Structure: {e}"));
3203                    all_valid = false;
3204                    continue;
3205                }
3206            }
3207
3208            // Handle branch modifications
3209            match manager.handle_branch_modifications(&stack_id, fix_mode.clone()) {
3210                Ok(_) => {
3211                    Output::sub_item("Git integrity: OK");
3212                }
3213                Err(e) => {
3214                    Output::sub_item(format!("Git integrity: {e}"));
3215                    all_valid = false;
3216                }
3217            }
3218            println!();
3219        }
3220
3221        if all_valid {
3222            Output::success("All stacks passed validation");
3223        } else {
3224            Output::warning("Some stacks have validation issues");
3225            return Err(CascadeError::config("Stack validation failed".to_string()));
3226        }
3227
3228        Ok(())
3229    }
3230}
3231
3232/// Get commits that are not yet in any stack entry
3233#[allow(dead_code)]
3234fn get_unpushed_commits(repo: &GitRepository, stack: &crate::stack::Stack) -> Result<Vec<String>> {
3235    let mut unpushed = Vec::new();
3236    let head_commit = repo.get_head_commit()?;
3237    let mut current_commit = head_commit;
3238
3239    // Walk back from HEAD until we find a commit that's already in the stack
3240    loop {
3241        let commit_hash = current_commit.id().to_string();
3242        let already_in_stack = stack
3243            .entries
3244            .iter()
3245            .any(|entry| entry.commit_hash == commit_hash);
3246
3247        if already_in_stack {
3248            break;
3249        }
3250
3251        unpushed.push(commit_hash);
3252
3253        // Move to parent commit
3254        if let Some(parent) = current_commit.parents().next() {
3255            current_commit = parent;
3256        } else {
3257            break;
3258        }
3259    }
3260
3261    unpushed.reverse(); // Reverse to get chronological order
3262    Ok(unpushed)
3263}
3264
3265/// Squash the last N commits into a single commit
3266pub async fn squash_commits(
3267    repo: &GitRepository,
3268    count: usize,
3269    since_ref: Option<String>,
3270) -> Result<()> {
3271    if count <= 1 {
3272        return Ok(()); // Nothing to squash
3273    }
3274
3275    // Get the current branch
3276    let _current_branch = repo.get_current_branch()?;
3277
3278    // Determine the range for interactive rebase
3279    let rebase_range = if let Some(ref since) = since_ref {
3280        since.clone()
3281    } else {
3282        format!("HEAD~{count}")
3283    };
3284
3285    println!("   Analyzing {count} commits to create smart squash message...");
3286
3287    // Get the commits that will be squashed to create a smart message
3288    let head_commit = repo.get_head_commit()?;
3289    let mut commits_to_squash = Vec::new();
3290    let mut current = head_commit;
3291
3292    // Collect the last N commits
3293    for _ in 0..count {
3294        commits_to_squash.push(current.clone());
3295        if current.parent_count() > 0 {
3296            current = current.parent(0).map_err(CascadeError::Git)?;
3297        } else {
3298            break;
3299        }
3300    }
3301
3302    // Generate smart commit message from the squashed commits
3303    let smart_message = generate_squash_message(&commits_to_squash)?;
3304    println!(
3305        "   Smart message: {}",
3306        smart_message.lines().next().unwrap_or("")
3307    );
3308
3309    // Get the commit we want to reset to (the commit before our range)
3310    let reset_target = if since_ref.is_some() {
3311        // If squashing since a reference, reset to that reference
3312        format!("{rebase_range}~1")
3313    } else {
3314        // If squashing last N commits, reset to N commits before
3315        format!("HEAD~{count}")
3316    };
3317
3318    // Soft reset to preserve changes in staging area
3319    repo.reset_soft(&reset_target)?;
3320
3321    // Stage all changes (they should already be staged from the reset --soft)
3322    repo.stage_all()?;
3323
3324    // Create the new commit with the smart message
3325    let new_commit_hash = repo.commit(&smart_message)?;
3326
3327    println!(
3328        "   Created squashed commit: {} ({})",
3329        &new_commit_hash[..8],
3330        smart_message.lines().next().unwrap_or("")
3331    );
3332    println!("   💡 Tip: Use 'git commit --amend' to edit the commit message if needed");
3333
3334    Ok(())
3335}
3336
3337/// Generate a smart commit message from multiple commits being squashed
3338pub fn generate_squash_message(commits: &[git2::Commit]) -> Result<String> {
3339    if commits.is_empty() {
3340        return Ok("Squashed commits".to_string());
3341    }
3342
3343    // Get all commit messages
3344    let messages: Vec<String> = commits
3345        .iter()
3346        .map(|c| c.message().unwrap_or("").trim().to_string())
3347        .filter(|m| !m.is_empty())
3348        .collect();
3349
3350    if messages.is_empty() {
3351        return Ok("Squashed commits".to_string());
3352    }
3353
3354    // Strategy 1: If the last commit looks like a "Final:" commit, use it
3355    if let Some(last_msg) = messages.first() {
3356        // first() because we're in reverse chronological order
3357        if last_msg.starts_with("Final:") || last_msg.starts_with("final:") {
3358            return Ok(last_msg
3359                .trim_start_matches("Final:")
3360                .trim_start_matches("final:")
3361                .trim()
3362                .to_string());
3363        }
3364    }
3365
3366    // Strategy 2: If most commits are WIP, find the most descriptive non-WIP message
3367    let wip_count = messages
3368        .iter()
3369        .filter(|m| {
3370            m.to_lowercase().starts_with("wip") || m.to_lowercase().contains("work in progress")
3371        })
3372        .count();
3373
3374    if wip_count > messages.len() / 2 {
3375        // Mostly WIP commits, find the best non-WIP one or create a summary
3376        let non_wip: Vec<&String> = messages
3377            .iter()
3378            .filter(|m| {
3379                !m.to_lowercase().starts_with("wip")
3380                    && !m.to_lowercase().contains("work in progress")
3381            })
3382            .collect();
3383
3384        if let Some(best_msg) = non_wip.first() {
3385            return Ok(best_msg.to_string());
3386        }
3387
3388        // All are WIP, try to extract the feature being worked on
3389        let feature = extract_feature_from_wip(&messages);
3390        return Ok(feature);
3391    }
3392
3393    // Strategy 3: Use the last (most recent) commit message
3394    Ok(messages.first().unwrap().clone())
3395}
3396
3397/// Extract feature name from WIP commit messages
3398pub fn extract_feature_from_wip(messages: &[String]) -> String {
3399    // Look for patterns like "WIP: add authentication" -> "Add authentication"
3400    for msg in messages {
3401        // Check both case variations, but preserve original case
3402        if msg.to_lowercase().starts_with("wip:") {
3403            if let Some(rest) = msg
3404                .strip_prefix("WIP:")
3405                .or_else(|| msg.strip_prefix("wip:"))
3406            {
3407                let feature = rest.trim();
3408                if !feature.is_empty() && feature.len() > 3 {
3409                    // Capitalize first letter only, preserve rest
3410                    let mut chars: Vec<char> = feature.chars().collect();
3411                    if let Some(first) = chars.first_mut() {
3412                        *first = first.to_uppercase().next().unwrap_or(*first);
3413                    }
3414                    return chars.into_iter().collect();
3415                }
3416            }
3417        }
3418    }
3419
3420    // Fallback: Use the latest commit without WIP prefix
3421    if let Some(first) = messages.first() {
3422        let cleaned = first
3423            .trim_start_matches("WIP:")
3424            .trim_start_matches("wip:")
3425            .trim_start_matches("WIP")
3426            .trim_start_matches("wip")
3427            .trim();
3428
3429        if !cleaned.is_empty() {
3430            return format!("Implement {cleaned}");
3431        }
3432    }
3433
3434    format!("Squashed {} commits", messages.len())
3435}
3436
3437/// Count commits since a given reference
3438pub fn count_commits_since(repo: &GitRepository, since_commit_hash: &str) -> Result<usize> {
3439    let head_commit = repo.get_head_commit()?;
3440    let since_commit = repo.get_commit(since_commit_hash)?;
3441
3442    let mut count = 0;
3443    let mut current = head_commit;
3444
3445    // Walk backwards from HEAD until we reach the since commit
3446    loop {
3447        if current.id() == since_commit.id() {
3448            break;
3449        }
3450
3451        count += 1;
3452
3453        // Get parent commit
3454        if current.parent_count() == 0 {
3455            break; // Reached root commit
3456        }
3457
3458        current = current.parent(0).map_err(CascadeError::Git)?;
3459    }
3460
3461    Ok(count)
3462}
3463
3464/// Land (merge) approved stack entries
3465async fn land_stack(
3466    entry: Option<usize>,
3467    force: bool,
3468    dry_run: bool,
3469    auto: bool,
3470    wait_for_builds: bool,
3471    strategy: Option<MergeStrategyArg>,
3472    build_timeout: u64,
3473) -> Result<()> {
3474    let current_dir = env::current_dir()
3475        .map_err(|e| CascadeError::config(format!("Could not get current directory: {e}")))?;
3476
3477    let repo_root = find_repository_root(&current_dir)
3478        .map_err(|e| CascadeError::config(format!("Could not find git repository: {e}")))?;
3479
3480    let stack_manager = StackManager::new(&repo_root)?;
3481
3482    // Get stack ID and active stack before moving stack_manager
3483    let stack_id = stack_manager
3484        .get_active_stack()
3485        .map(|s| s.id)
3486        .ok_or_else(|| {
3487            CascadeError::config(
3488                "No active stack. Use 'ca stack create' or 'ca stack switch' to select a stack"
3489                    .to_string(),
3490            )
3491        })?;
3492
3493    let active_stack = stack_manager
3494        .get_active_stack()
3495        .cloned()
3496        .ok_or_else(|| CascadeError::config("No active stack found".to_string()))?;
3497
3498    // Load configuration and create Bitbucket integration
3499    let config_dir = crate::config::get_repo_config_dir(&repo_root)?;
3500    let config_path = config_dir.join("config.json");
3501    let settings = crate::config::Settings::load_from_file(&config_path)?;
3502
3503    let cascade_config = crate::config::CascadeConfig {
3504        bitbucket: Some(settings.bitbucket.clone()),
3505        git: settings.git.clone(),
3506        auth: crate::config::AuthConfig::default(),
3507        cascade: settings.cascade.clone(),
3508    };
3509
3510    let mut integration =
3511        crate::bitbucket::BitbucketIntegration::new(stack_manager, cascade_config)?;
3512
3513    // Get enhanced status
3514    let status = integration.check_enhanced_stack_status(&stack_id).await?;
3515
3516    if status.enhanced_statuses.is_empty() {
3517        println!("❌ No pull requests found to land");
3518        return Ok(());
3519    }
3520
3521    // Filter PRs that are ready to land
3522    let ready_prs: Vec<_> = status
3523        .enhanced_statuses
3524        .iter()
3525        .filter(|pr_status| {
3526            // If specific entry requested, only include that one
3527            if let Some(entry_num) = entry {
3528                // Find the corresponding stack entry for this PR
3529                if let Some(stack_entry) = active_stack.entries.get(entry_num.saturating_sub(1)) {
3530                    // Check if this PR corresponds to the requested entry
3531                    if pr_status.pr.from_ref.display_id != stack_entry.branch {
3532                        return false;
3533                    }
3534                } else {
3535                    return false; // Invalid entry number
3536                }
3537            }
3538
3539            if force {
3540                // If force is enabled, include any open PR
3541                pr_status.pr.state == crate::bitbucket::pull_request::PullRequestState::Open
3542            } else {
3543                pr_status.is_ready_to_land()
3544            }
3545        })
3546        .collect();
3547
3548    if ready_prs.is_empty() {
3549        if let Some(entry_num) = entry {
3550            println!("❌ Entry {entry_num} is not ready to land or doesn't exist");
3551        } else {
3552            println!("❌ No pull requests are ready to land");
3553        }
3554
3555        // Show what's blocking them
3556        println!("\n🚫 Blocking Issues:");
3557        for pr_status in &status.enhanced_statuses {
3558            if pr_status.pr.state == crate::bitbucket::pull_request::PullRequestState::Open {
3559                let blocking = pr_status.get_blocking_reasons();
3560                if !blocking.is_empty() {
3561                    println!("   PR #{}: {}", pr_status.pr.id, blocking.join(", "));
3562                }
3563            }
3564        }
3565
3566        if !force {
3567            println!("\n💡 Use --force to land PRs with blocking issues (dangerous!)");
3568        }
3569        return Ok(());
3570    }
3571
3572    if dry_run {
3573        if let Some(entry_num) = entry {
3574            println!("🏃 Dry Run - Entry {entry_num} that would be landed:");
3575        } else {
3576            println!("🏃 Dry Run - PRs that would be landed:");
3577        }
3578        for pr_status in &ready_prs {
3579            println!("   ✅ PR #{}: {}", pr_status.pr.id, pr_status.pr.title);
3580            if !pr_status.is_ready_to_land() && force {
3581                let blocking = pr_status.get_blocking_reasons();
3582                println!(
3583                    "      ⚠️  Would force land despite: {}",
3584                    blocking.join(", ")
3585                );
3586            }
3587        }
3588        return Ok(());
3589    }
3590
3591    // Default behavior: land all ready PRs (safest approach)
3592    // Only land specific entry if explicitly requested
3593    if entry.is_some() && ready_prs.len() > 1 {
3594        println!(
3595            "🎯 {} PRs are ready to land, but landing only entry #{}",
3596            ready_prs.len(),
3597            entry.unwrap()
3598        );
3599    }
3600
3601    // Setup auto-merge conditions
3602    let merge_strategy: crate::bitbucket::pull_request::MergeStrategy =
3603        strategy.unwrap_or(MergeStrategyArg::Squash).into();
3604    let auto_merge_conditions = crate::bitbucket::pull_request::AutoMergeConditions {
3605        merge_strategy: merge_strategy.clone(),
3606        wait_for_builds,
3607        build_timeout: std::time::Duration::from_secs(build_timeout),
3608        allowed_authors: None, // Allow all authors for now
3609    };
3610
3611    // Land the PRs
3612    println!(
3613        "🚀 Landing {} PR{}...",
3614        ready_prs.len(),
3615        if ready_prs.len() == 1 { "" } else { "s" }
3616    );
3617
3618    let pr_manager = crate::bitbucket::pull_request::PullRequestManager::new(
3619        crate::bitbucket::BitbucketClient::new(&settings.bitbucket)?,
3620    );
3621
3622    // Land PRs in dependency order
3623    let mut landed_count = 0;
3624    let mut failed_count = 0;
3625    let total_ready_prs = ready_prs.len();
3626
3627    for pr_status in ready_prs {
3628        let pr_id = pr_status.pr.id;
3629
3630        print!("🚀 Landing PR #{}: {}", pr_id, pr_status.pr.title);
3631
3632        let land_result = if auto {
3633            // Use auto-merge with conditions checking
3634            pr_manager
3635                .auto_merge_if_ready(pr_id, &auto_merge_conditions)
3636                .await
3637        } else {
3638            // Manual merge without auto-conditions
3639            pr_manager
3640                .merge_pull_request(pr_id, merge_strategy.clone())
3641                .await
3642                .map(
3643                    |pr| crate::bitbucket::pull_request::AutoMergeResult::Merged {
3644                        pr: Box::new(pr),
3645                        merge_strategy: merge_strategy.clone(),
3646                    },
3647                )
3648        };
3649
3650        match land_result {
3651            Ok(crate::bitbucket::pull_request::AutoMergeResult::Merged { .. }) => {
3652                println!(" ✅");
3653                landed_count += 1;
3654
3655                // 🔄 AUTO-RETARGETING: After each merge, retarget remaining PRs
3656                if landed_count < total_ready_prs {
3657                    println!(" Retargeting remaining PRs to latest base...");
3658
3659                    // 1️⃣ CRITICAL: Update base branch to get latest merged state
3660                    let base_branch = active_stack.base_branch.clone();
3661                    let git_repo = crate::git::GitRepository::open(&repo_root)?;
3662
3663                    println!("   📥 Updating base branch: {base_branch}");
3664                    match git_repo.pull(&base_branch) {
3665                        Ok(_) => println!("   ✅ Base branch updated successfully"),
3666                        Err(e) => {
3667                            println!("   ⚠️  Warning: Failed to update base branch: {e}");
3668                            println!(
3669                                "   💡 You may want to manually run: git pull origin {base_branch}"
3670                            );
3671                        }
3672                    }
3673
3674                    // 2️⃣ Use rebase system to retarget remaining PRs
3675                    let temp_manager = StackManager::new(&repo_root)?;
3676                    let stack_for_count = temp_manager
3677                        .get_stack(&stack_id)
3678                        .ok_or_else(|| CascadeError::config("Stack not found"))?;
3679                    let entry_count = stack_for_count.entries.len();
3680                    let plural = if entry_count == 1 { "entry" } else { "entries" };
3681
3682                    println!(); // Spacing
3683                    let rebase_spinner = crate::utils::spinner::Spinner::new(format!(
3684                        "Retargeting {} {}",
3685                        entry_count, plural
3686                    ));
3687
3688                    let mut rebase_manager = crate::stack::RebaseManager::new(
3689                        StackManager::new(&repo_root)?,
3690                        git_repo,
3691                        crate::stack::RebaseOptions {
3692                            strategy: crate::stack::RebaseStrategy::ForcePush,
3693                            target_base: Some(base_branch.clone()),
3694                            ..Default::default()
3695                        },
3696                    );
3697
3698                    let rebase_result = rebase_manager.rebase_stack(&stack_id);
3699
3700                    rebase_spinner.stop();
3701                    println!(); // Spacing
3702
3703                    match rebase_result {
3704                        Ok(rebase_result) => {
3705                            if !rebase_result.branch_mapping.is_empty() {
3706                                // Update PRs using the rebase result
3707                                let retarget_config = crate::config::CascadeConfig {
3708                                    bitbucket: Some(settings.bitbucket.clone()),
3709                                    git: settings.git.clone(),
3710                                    auth: crate::config::AuthConfig::default(),
3711                                    cascade: settings.cascade.clone(),
3712                                };
3713                                let mut retarget_integration = BitbucketIntegration::new(
3714                                    StackManager::new(&repo_root)?,
3715                                    retarget_config,
3716                                )?;
3717
3718                                match retarget_integration
3719                                    .update_prs_after_rebase(
3720                                        &stack_id,
3721                                        &rebase_result.branch_mapping,
3722                                    )
3723                                    .await
3724                                {
3725                                    Ok(updated_prs) => {
3726                                        if !updated_prs.is_empty() {
3727                                            println!(
3728                                                "   ✅ Updated {} PRs with new targets",
3729                                                updated_prs.len()
3730                                            );
3731                                        }
3732                                    }
3733                                    Err(e) => {
3734                                        println!("   ⚠️  Failed to update remaining PRs: {e}");
3735                                        println!(
3736                                            "   💡 You may need to run: ca stack rebase --onto {base_branch}"
3737                                        );
3738                                    }
3739                                }
3740                            }
3741                        }
3742                        Err(e) => {
3743                            // 🚨 CONFLICTS DETECTED - Give clear next steps
3744                            println!("   ❌ Auto-retargeting conflicts detected!");
3745                            println!("   📝 To resolve conflicts and continue landing:");
3746                            println!("      1. Resolve conflicts in the affected files");
3747                            println!("      2. Stage resolved files: git add <files>");
3748                            println!("      3. Continue the process: ca stack continue-land");
3749                            println!("      4. Or abort the operation: ca stack abort-land");
3750                            println!();
3751                            println!("   💡 Check current status: ca stack land-status");
3752                            println!("   ⚠️  Error details: {e}");
3753
3754                            // Stop the land operation here - user needs to resolve conflicts
3755                            break;
3756                        }
3757                    }
3758                }
3759            }
3760            Ok(crate::bitbucket::pull_request::AutoMergeResult::NotReady { blocking_reasons }) => {
3761                println!(" ❌ Not ready: {}", blocking_reasons.join(", "));
3762                failed_count += 1;
3763                if !force {
3764                    break;
3765                }
3766            }
3767            Ok(crate::bitbucket::pull_request::AutoMergeResult::Failed { error }) => {
3768                println!(" ❌ Failed: {error}");
3769                failed_count += 1;
3770                if !force {
3771                    break;
3772                }
3773            }
3774            Err(e) => {
3775                println!(" ❌");
3776                eprintln!("Failed to land PR #{pr_id}: {e}");
3777                failed_count += 1;
3778
3779                if !force {
3780                    break;
3781                }
3782            }
3783        }
3784    }
3785
3786    // Show summary
3787    println!("\n🎯 Landing Summary:");
3788    println!("   ✅ Successfully landed: {landed_count}");
3789    if failed_count > 0 {
3790        println!("   ❌ Failed to land: {failed_count}");
3791    }
3792
3793    if landed_count > 0 {
3794        Output::success(" Landing operation completed!");
3795    } else {
3796        println!("❌ No PRs were successfully landed");
3797    }
3798
3799    Ok(())
3800}
3801
3802/// Auto-land all ready PRs (shorthand for land --auto)
3803async fn auto_land_stack(
3804    force: bool,
3805    dry_run: bool,
3806    wait_for_builds: bool,
3807    strategy: Option<MergeStrategyArg>,
3808    build_timeout: u64,
3809) -> Result<()> {
3810    // This is a shorthand for land with --auto
3811    land_stack(
3812        None,
3813        force,
3814        dry_run,
3815        true, // auto = true
3816        wait_for_builds,
3817        strategy,
3818        build_timeout,
3819    )
3820    .await
3821}
3822
3823async fn continue_land() -> Result<()> {
3824    let current_dir = env::current_dir()
3825        .map_err(|e| CascadeError::config(format!("Could not get current directory: {e}")))?;
3826
3827    let repo_root = find_repository_root(&current_dir)
3828        .map_err(|e| CascadeError::config(format!("Could not find git repository: {e}")))?;
3829
3830    let stack_manager = StackManager::new(&repo_root)?;
3831    let git_repo = crate::git::GitRepository::open(&repo_root)?;
3832    let options = crate::stack::RebaseOptions::default();
3833    let rebase_manager = crate::stack::RebaseManager::new(stack_manager, git_repo, options);
3834
3835    if !rebase_manager.is_rebase_in_progress() {
3836        Output::info("  No rebase in progress");
3837        return Ok(());
3838    }
3839
3840    println!(" Continuing land operation...");
3841    match rebase_manager.continue_rebase() {
3842        Ok(_) => {
3843            Output::success(" Land operation continued successfully");
3844            println!("   Check 'ca stack land-status' for current state");
3845        }
3846        Err(e) => {
3847            warn!("❌ Failed to continue land operation: {}", e);
3848            Output::tip(" You may need to resolve conflicts first:");
3849            println!("   1. Edit conflicted files");
3850            println!("   2. Stage resolved files with 'git add'");
3851            println!("   3. Run 'ca stack continue-land' again");
3852        }
3853    }
3854
3855    Ok(())
3856}
3857
3858async fn abort_land() -> Result<()> {
3859    let current_dir = env::current_dir()
3860        .map_err(|e| CascadeError::config(format!("Could not get current directory: {e}")))?;
3861
3862    let repo_root = find_repository_root(&current_dir)
3863        .map_err(|e| CascadeError::config(format!("Could not find git repository: {e}")))?;
3864
3865    let stack_manager = StackManager::new(&repo_root)?;
3866    let git_repo = crate::git::GitRepository::open(&repo_root)?;
3867    let options = crate::stack::RebaseOptions::default();
3868    let rebase_manager = crate::stack::RebaseManager::new(stack_manager, git_repo, options);
3869
3870    if !rebase_manager.is_rebase_in_progress() {
3871        Output::info("  No rebase in progress");
3872        return Ok(());
3873    }
3874
3875    println!("⚠️  Aborting land operation...");
3876    match rebase_manager.abort_rebase() {
3877        Ok(_) => {
3878            Output::success(" Land operation aborted successfully");
3879            println!("   Repository restored to pre-land state");
3880        }
3881        Err(e) => {
3882            warn!("❌ Failed to abort land operation: {}", e);
3883            println!("⚠️  You may need to manually clean up the repository state");
3884        }
3885    }
3886
3887    Ok(())
3888}
3889
3890async fn land_status() -> Result<()> {
3891    let current_dir = env::current_dir()
3892        .map_err(|e| CascadeError::config(format!("Could not get current directory: {e}")))?;
3893
3894    let repo_root = find_repository_root(&current_dir)
3895        .map_err(|e| CascadeError::config(format!("Could not find git repository: {e}")))?;
3896
3897    let stack_manager = StackManager::new(&repo_root)?;
3898    let git_repo = crate::git::GitRepository::open(&repo_root)?;
3899
3900    println!("Land Status");
3901
3902    // Check if land operation is in progress by checking git state directly
3903    let git_dir = repo_root.join(".git");
3904    let land_in_progress = git_dir.join("REBASE_HEAD").exists()
3905        || git_dir.join("rebase-merge").exists()
3906        || git_dir.join("rebase-apply").exists();
3907
3908    if land_in_progress {
3909        println!("   Status: 🔄 Land operation in progress");
3910        println!(
3911            "   
3912📝 Actions available:"
3913        );
3914        println!("     - 'ca stack continue-land' to continue");
3915        println!("     - 'ca stack abort-land' to abort");
3916        println!("     - 'git status' to see conflicted files");
3917
3918        // Check for conflicts
3919        match git_repo.get_status() {
3920            Ok(statuses) => {
3921                let mut conflicts = Vec::new();
3922                for status in statuses.iter() {
3923                    if status.status().contains(git2::Status::CONFLICTED) {
3924                        if let Some(path) = status.path() {
3925                            conflicts.push(path.to_string());
3926                        }
3927                    }
3928                }
3929
3930                if !conflicts.is_empty() {
3931                    println!("   ⚠️  Conflicts in {} files:", conflicts.len());
3932                    for conflict in conflicts {
3933                        println!("      - {conflict}");
3934                    }
3935                    println!(
3936                        "   
3937💡 To resolve conflicts:"
3938                    );
3939                    println!("     1. Edit the conflicted files");
3940                    println!("     2. Stage resolved files: git add <file>");
3941                    println!("     3. Continue: ca stack continue-land");
3942                }
3943            }
3944            Err(e) => {
3945                warn!("Failed to get git status: {}", e);
3946            }
3947        }
3948    } else {
3949        println!("   Status: ✅ No land operation in progress");
3950
3951        // Show stack status instead
3952        if let Some(active_stack) = stack_manager.get_active_stack() {
3953            println!("   Active stack: {}", active_stack.name);
3954            println!("   Entries: {}", active_stack.entries.len());
3955            println!("   Base branch: {}", active_stack.base_branch);
3956        }
3957    }
3958
3959    Ok(())
3960}
3961
3962async fn repair_stack_data() -> Result<()> {
3963    let current_dir = env::current_dir()
3964        .map_err(|e| CascadeError::config(format!("Could not get current directory: {e}")))?;
3965
3966    let repo_root = find_repository_root(&current_dir)
3967        .map_err(|e| CascadeError::config(format!("Could not find git repository: {e}")))?;
3968
3969    let mut stack_manager = StackManager::new(&repo_root)?;
3970
3971    println!("🔧 Repairing stack data consistency...");
3972
3973    stack_manager.repair_all_stacks()?;
3974
3975    Output::success(" Stack data consistency repaired successfully!");
3976    Output::tip(" Run 'ca stack --mergeable' to see updated status");
3977
3978    Ok(())
3979}
3980
3981/// Clean up merged and stale branches
3982async fn cleanup_branches(
3983    dry_run: bool,
3984    force: bool,
3985    include_stale: bool,
3986    stale_days: u32,
3987    cleanup_remote: bool,
3988    include_non_stack: bool,
3989    verbose: bool,
3990) -> Result<()> {
3991    let current_dir = env::current_dir()
3992        .map_err(|e| CascadeError::config(format!("Could not get current directory: {e}")))?;
3993
3994    let repo_root = find_repository_root(&current_dir)
3995        .map_err(|e| CascadeError::config(format!("Could not find git repository: {e}")))?;
3996
3997    let stack_manager = StackManager::new(&repo_root)?;
3998    let git_repo = GitRepository::open(&repo_root)?;
3999
4000    let result = perform_cleanup(
4001        &stack_manager,
4002        &git_repo,
4003        dry_run,
4004        force,
4005        include_stale,
4006        stale_days,
4007        cleanup_remote,
4008        include_non_stack,
4009        verbose,
4010    )
4011    .await?;
4012
4013    // Display results
4014    if result.total_candidates == 0 {
4015        Output::success("No branches found that need cleanup");
4016        return Ok(());
4017    }
4018
4019    Output::section("Cleanup Results");
4020
4021    if dry_run {
4022        Output::sub_item(format!(
4023            "Found {} branches that would be cleaned up",
4024            result.total_candidates
4025        ));
4026    } else {
4027        if !result.cleaned_branches.is_empty() {
4028            Output::success(format!(
4029                "Successfully cleaned up {} branches",
4030                result.cleaned_branches.len()
4031            ));
4032            for branch in &result.cleaned_branches {
4033                Output::sub_item(format!("🗑️  Deleted: {branch}"));
4034            }
4035        }
4036
4037        if !result.skipped_branches.is_empty() {
4038            Output::sub_item(format!(
4039                "Skipped {} branches",
4040                result.skipped_branches.len()
4041            ));
4042            if verbose {
4043                for (branch, reason) in &result.skipped_branches {
4044                    Output::sub_item(format!("⏭️  {branch}: {reason}"));
4045                }
4046            }
4047        }
4048
4049        if !result.failed_branches.is_empty() {
4050            Output::warning(format!(
4051                "Failed to clean up {} branches",
4052                result.failed_branches.len()
4053            ));
4054            for (branch, error) in &result.failed_branches {
4055                Output::sub_item(format!("❌ {branch}: {error}"));
4056            }
4057        }
4058    }
4059
4060    Ok(())
4061}
4062
4063/// Perform cleanup with the given options
4064#[allow(clippy::too_many_arguments)]
4065async fn perform_cleanup(
4066    stack_manager: &StackManager,
4067    git_repo: &GitRepository,
4068    dry_run: bool,
4069    force: bool,
4070    include_stale: bool,
4071    stale_days: u32,
4072    cleanup_remote: bool,
4073    include_non_stack: bool,
4074    verbose: bool,
4075) -> Result<CleanupResult> {
4076    let options = CleanupOptions {
4077        dry_run,
4078        force,
4079        include_stale,
4080        cleanup_remote,
4081        stale_threshold_days: stale_days,
4082        cleanup_non_stack: include_non_stack,
4083    };
4084
4085    let stack_manager_copy = StackManager::new(stack_manager.repo_path())?;
4086    let git_repo_copy = GitRepository::open(git_repo.path())?;
4087    let mut cleanup_manager = CleanupManager::new(stack_manager_copy, git_repo_copy, options);
4088
4089    // Find candidates
4090    let candidates = cleanup_manager.find_cleanup_candidates()?;
4091
4092    if candidates.is_empty() {
4093        return Ok(CleanupResult {
4094            cleaned_branches: Vec::new(),
4095            failed_branches: Vec::new(),
4096            skipped_branches: Vec::new(),
4097            total_candidates: 0,
4098        });
4099    }
4100
4101    // Show candidates if verbose or dry run
4102    if verbose || dry_run {
4103        Output::section("Cleanup Candidates");
4104        for candidate in &candidates {
4105            let reason_icon = match candidate.reason {
4106                crate::stack::CleanupReason::FullyMerged => "🔀",
4107                crate::stack::CleanupReason::StackEntryMerged => "✅",
4108                crate::stack::CleanupReason::Stale => "⏰",
4109                crate::stack::CleanupReason::Orphaned => "👻",
4110            };
4111
4112            Output::sub_item(format!(
4113                "{} {} - {} ({})",
4114                reason_icon,
4115                candidate.branch_name,
4116                candidate.reason_to_string(),
4117                candidate.safety_info
4118            ));
4119        }
4120    }
4121
4122    // If not force and not dry run, ask for confirmation
4123    if !force && !dry_run && !candidates.is_empty() {
4124        Output::warning(format!("About to delete {} branches", candidates.len()));
4125
4126        // Show first few branch names for context
4127        let preview_count = 5.min(candidates.len());
4128        for candidate in candidates.iter().take(preview_count) {
4129            println!("  • {}", candidate.branch_name);
4130        }
4131        if candidates.len() > preview_count {
4132            println!("  ... and {} more", candidates.len() - preview_count);
4133        }
4134        println!(); // Spacing before prompt
4135
4136        // Interactive confirmation to proceed with cleanup
4137        let should_continue = Confirm::with_theme(&ColorfulTheme::default())
4138            .with_prompt("Continue with branch cleanup?")
4139            .default(false)
4140            .interact()
4141            .map_err(|e| CascadeError::config(format!("Failed to get user confirmation: {e}")))?;
4142
4143        if !should_continue {
4144            Output::sub_item("Cleanup cancelled");
4145            return Ok(CleanupResult {
4146                cleaned_branches: Vec::new(),
4147                failed_branches: Vec::new(),
4148                skipped_branches: Vec::new(),
4149                total_candidates: candidates.len(),
4150            });
4151        }
4152    }
4153
4154    // Perform cleanup
4155    cleanup_manager.perform_cleanup(&candidates)
4156}
4157
4158/// Simple perform_cleanup for sync command
4159async fn perform_simple_cleanup(
4160    stack_manager: &StackManager,
4161    git_repo: &GitRepository,
4162    dry_run: bool,
4163) -> Result<CleanupResult> {
4164    perform_cleanup(
4165        stack_manager,
4166        git_repo,
4167        dry_run,
4168        false, // force
4169        false, // include_stale
4170        30,    // stale_days
4171        false, // cleanup_remote
4172        false, // include_non_stack
4173        false, // verbose
4174    )
4175    .await
4176}
4177
4178/// Analyze commits for various safeguards before pushing
4179async fn analyze_commits_for_safeguards(
4180    commits_to_push: &[String],
4181    repo: &GitRepository,
4182    dry_run: bool,
4183) -> Result<()> {
4184    const LARGE_COMMIT_THRESHOLD: usize = 10;
4185    const WEEK_IN_SECONDS: i64 = 7 * 24 * 3600;
4186
4187    // 🛡️ SAFEGUARD 1: Large commit count warning
4188    if commits_to_push.len() > LARGE_COMMIT_THRESHOLD {
4189        println!(
4190            "⚠️  Warning: About to push {} commits to stack",
4191            commits_to_push.len()
4192        );
4193        println!("   This may indicate a merge commit issue or unexpected commit range.");
4194        println!("   Large commit counts often result from merging instead of rebasing.");
4195
4196        if !dry_run && !confirm_large_push(commits_to_push.len())? {
4197            return Err(CascadeError::config("Push cancelled by user"));
4198        }
4199    }
4200
4201    // Get commit objects for further analysis
4202    let commit_objects: Result<Vec<_>> = commits_to_push
4203        .iter()
4204        .map(|hash| repo.get_commit(hash))
4205        .collect();
4206    let commit_objects = commit_objects?;
4207
4208    // 🛡️ SAFEGUARD 2: Merge commit detection
4209    let merge_commits: Vec<_> = commit_objects
4210        .iter()
4211        .filter(|c| c.parent_count() > 1)
4212        .collect();
4213
4214    if !merge_commits.is_empty() {
4215        println!(
4216            "⚠️  Warning: {} merge commits detected in push",
4217            merge_commits.len()
4218        );
4219        println!("   This often indicates you merged instead of rebased.");
4220        println!("   Consider using 'ca sync' to rebase on the base branch.");
4221        println!("   Merge commits in stacks can cause confusion and duplicate work.");
4222    }
4223
4224    // 🛡️ SAFEGUARD 3: Commit age warning
4225    if commit_objects.len() > 1 {
4226        let oldest_commit_time = commit_objects.first().unwrap().time().seconds();
4227        let newest_commit_time = commit_objects.last().unwrap().time().seconds();
4228        let time_span = newest_commit_time - oldest_commit_time;
4229
4230        if time_span > WEEK_IN_SECONDS {
4231            let days = time_span / (24 * 3600);
4232            println!("⚠️  Warning: Commits span {days} days");
4233            println!("   This may indicate merged history rather than new work.");
4234            println!("   Recent work should typically span hours or days, not weeks.");
4235        }
4236    }
4237
4238    // 🛡️ SAFEGUARD 4: Better range detection suggestions
4239    if commits_to_push.len() > 5 {
4240        Output::tip(" Tip: If you only want recent commits, use:");
4241        println!(
4242            "   ca push --since HEAD~{}  # pushes last {} commits",
4243            std::cmp::min(commits_to_push.len(), 5),
4244            std::cmp::min(commits_to_push.len(), 5)
4245        );
4246        println!("   ca push --commits <hash1>,<hash2>  # pushes specific commits");
4247        println!("   ca push --dry-run  # preview what would be pushed");
4248    }
4249
4250    // 🛡️ SAFEGUARD 5: Dry run mode
4251    if dry_run {
4252        println!("🔍 DRY RUN: Would push {} commits:", commits_to_push.len());
4253        for (i, (commit_hash, commit_obj)) in commits_to_push
4254            .iter()
4255            .zip(commit_objects.iter())
4256            .enumerate()
4257        {
4258            let summary = commit_obj.summary().unwrap_or("(no message)");
4259            let short_hash = &commit_hash[..std::cmp::min(commit_hash.len(), 7)];
4260            println!("  {}: {} ({})", i + 1, summary, short_hash);
4261        }
4262        Output::tip(" Run without --dry-run to actually push these commits.");
4263    }
4264
4265    Ok(())
4266}
4267
4268/// Prompt user for confirmation when pushing large number of commits
4269fn confirm_large_push(count: usize) -> Result<bool> {
4270    // Interactive confirmation for large push
4271    let should_continue = Confirm::with_theme(&ColorfulTheme::default())
4272        .with_prompt(format!("Continue pushing {count} commits?"))
4273        .default(false)
4274        .interact()
4275        .map_err(|e| CascadeError::config(format!("Failed to get user confirmation: {e}")))?;
4276
4277    Ok(should_continue)
4278}
4279
4280#[cfg(test)]
4281mod tests {
4282    use super::*;
4283    use std::process::Command;
4284    use tempfile::TempDir;
4285
4286    fn create_test_repo() -> Result<(TempDir, std::path::PathBuf)> {
4287        let temp_dir = TempDir::new()
4288            .map_err(|e| CascadeError::config(format!("Failed to create temp directory: {e}")))?;
4289        let repo_path = temp_dir.path().to_path_buf();
4290
4291        // Initialize git repository
4292        let output = Command::new("git")
4293            .args(["init"])
4294            .current_dir(&repo_path)
4295            .output()
4296            .map_err(|e| CascadeError::config(format!("Failed to run git init: {e}")))?;
4297        if !output.status.success() {
4298            return Err(CascadeError::config("Git init failed".to_string()));
4299        }
4300
4301        let output = Command::new("git")
4302            .args(["config", "user.name", "Test User"])
4303            .current_dir(&repo_path)
4304            .output()
4305            .map_err(|e| CascadeError::config(format!("Failed to run git config: {e}")))?;
4306        if !output.status.success() {
4307            return Err(CascadeError::config(
4308                "Git config user.name failed".to_string(),
4309            ));
4310        }
4311
4312        let output = Command::new("git")
4313            .args(["config", "user.email", "test@example.com"])
4314            .current_dir(&repo_path)
4315            .output()
4316            .map_err(|e| CascadeError::config(format!("Failed to run git config: {e}")))?;
4317        if !output.status.success() {
4318            return Err(CascadeError::config(
4319                "Git config user.email failed".to_string(),
4320            ));
4321        }
4322
4323        // Create initial commit
4324        std::fs::write(repo_path.join("README.md"), "# Test")
4325            .map_err(|e| CascadeError::config(format!("Failed to write file: {e}")))?;
4326        let output = Command::new("git")
4327            .args(["add", "."])
4328            .current_dir(&repo_path)
4329            .output()
4330            .map_err(|e| CascadeError::config(format!("Failed to run git add: {e}")))?;
4331        if !output.status.success() {
4332            return Err(CascadeError::config("Git add failed".to_string()));
4333        }
4334
4335        let output = Command::new("git")
4336            .args(["commit", "-m", "Initial commit"])
4337            .current_dir(&repo_path)
4338            .output()
4339            .map_err(|e| CascadeError::config(format!("Failed to run git commit: {e}")))?;
4340        if !output.status.success() {
4341            return Err(CascadeError::config("Git commit failed".to_string()));
4342        }
4343
4344        // Initialize cascade
4345        crate::config::initialize_repo(&repo_path, Some("https://test.bitbucket.com".to_string()))?;
4346
4347        Ok((temp_dir, repo_path))
4348    }
4349
4350    #[tokio::test]
4351    async fn test_create_stack() {
4352        let (temp_dir, repo_path) = match create_test_repo() {
4353            Ok(repo) => repo,
4354            Err(_) => {
4355                println!("Skipping test due to git environment setup failure");
4356                return;
4357            }
4358        };
4359        // IMPORTANT: temp_dir must stay in scope to prevent early cleanup of test directory
4360        let _ = &temp_dir;
4361
4362        // Note: create_test_repo() already initializes Cascade configuration
4363
4364        // Change to the repo directory (with proper error handling)
4365        let original_dir = env::current_dir().map_err(|_| "Failed to get current dir");
4366        match env::set_current_dir(&repo_path) {
4367            Ok(_) => {
4368                let result = create_stack(
4369                    "test-stack".to_string(),
4370                    None, // Use default branch
4371                    Some("Test description".to_string()),
4372                )
4373                .await;
4374
4375                // Restore original directory (best effort)
4376                if let Ok(orig) = original_dir {
4377                    let _ = env::set_current_dir(orig);
4378                }
4379
4380                assert!(
4381                    result.is_ok(),
4382                    "Stack creation should succeed in initialized repository"
4383                );
4384            }
4385            Err(_) => {
4386                // Skip test if we can't change directories (CI environment issue)
4387                println!("Skipping test due to directory access restrictions");
4388            }
4389        }
4390    }
4391
4392    #[tokio::test]
4393    async fn test_list_empty_stacks() {
4394        let (temp_dir, repo_path) = match create_test_repo() {
4395            Ok(repo) => repo,
4396            Err(_) => {
4397                println!("Skipping test due to git environment setup failure");
4398                return;
4399            }
4400        };
4401        // IMPORTANT: temp_dir must stay in scope to prevent early cleanup of test directory
4402        let _ = &temp_dir;
4403
4404        // Note: create_test_repo() already initializes Cascade configuration
4405
4406        // Change to the repo directory (with proper error handling)
4407        let original_dir = env::current_dir().map_err(|_| "Failed to get current dir");
4408        match env::set_current_dir(&repo_path) {
4409            Ok(_) => {
4410                let result = list_stacks(false, false, None).await;
4411
4412                // Restore original directory (best effort)
4413                if let Ok(orig) = original_dir {
4414                    let _ = env::set_current_dir(orig);
4415                }
4416
4417                assert!(
4418                    result.is_ok(),
4419                    "Listing stacks should succeed in initialized repository"
4420                );
4421            }
4422            Err(_) => {
4423                // Skip test if we can't change directories (CI environment issue)
4424                println!("Skipping test due to directory access restrictions");
4425            }
4426        }
4427    }
4428
4429    // Tests for squashing functionality
4430
4431    #[test]
4432    fn test_extract_feature_from_wip_basic() {
4433        let messages = vec![
4434            "WIP: add authentication".to_string(),
4435            "WIP: implement login flow".to_string(),
4436        ];
4437
4438        let result = extract_feature_from_wip(&messages);
4439        assert_eq!(result, "Add authentication");
4440    }
4441
4442    #[test]
4443    fn test_extract_feature_from_wip_capitalize() {
4444        let messages = vec!["WIP: fix user validation bug".to_string()];
4445
4446        let result = extract_feature_from_wip(&messages);
4447        assert_eq!(result, "Fix user validation bug");
4448    }
4449
4450    #[test]
4451    fn test_extract_feature_from_wip_fallback() {
4452        let messages = vec![
4453            "WIP user interface changes".to_string(),
4454            "wip: css styling".to_string(),
4455        ];
4456
4457        let result = extract_feature_from_wip(&messages);
4458        // Should create a fallback message since no "WIP:" prefix found
4459        assert!(result.contains("Implement") || result.contains("Squashed") || result.len() > 5);
4460    }
4461
4462    #[test]
4463    fn test_extract_feature_from_wip_empty() {
4464        let messages = vec![];
4465
4466        let result = extract_feature_from_wip(&messages);
4467        assert_eq!(result, "Squashed 0 commits");
4468    }
4469
4470    #[test]
4471    fn test_extract_feature_from_wip_short_message() {
4472        let messages = vec!["WIP: x".to_string()]; // Too short
4473
4474        let result = extract_feature_from_wip(&messages);
4475        assert!(result.starts_with("Implement") || result.contains("Squashed"));
4476    }
4477
4478    // Integration tests for squashing that don't require real git commits
4479
4480    #[test]
4481    fn test_squash_message_final_strategy() {
4482        // This test would need real git2::Commit objects, so we'll test the logic indirectly
4483        // through the extract_feature_from_wip function which handles the core logic
4484
4485        let messages = [
4486            "Final: implement user authentication system".to_string(),
4487            "WIP: add tests".to_string(),
4488            "WIP: fix validation".to_string(),
4489        ];
4490
4491        // Test that we can identify final commits
4492        assert!(messages[0].starts_with("Final:"));
4493
4494        // Test message extraction
4495        let extracted = messages[0].trim_start_matches("Final:").trim();
4496        assert_eq!(extracted, "implement user authentication system");
4497    }
4498
4499    #[test]
4500    fn test_squash_message_wip_detection() {
4501        let messages = [
4502            "WIP: start feature".to_string(),
4503            "WIP: continue work".to_string(),
4504            "WIP: almost done".to_string(),
4505            "Regular commit message".to_string(),
4506        ];
4507
4508        let wip_count = messages
4509            .iter()
4510            .filter(|m| {
4511                m.to_lowercase().starts_with("wip") || m.to_lowercase().contains("work in progress")
4512            })
4513            .count();
4514
4515        assert_eq!(wip_count, 3); // Should detect 3 WIP commits
4516        assert!(wip_count > messages.len() / 2); // Majority are WIP
4517
4518        // Should find the non-WIP message
4519        let non_wip: Vec<&String> = messages
4520            .iter()
4521            .filter(|m| {
4522                !m.to_lowercase().starts_with("wip")
4523                    && !m.to_lowercase().contains("work in progress")
4524            })
4525            .collect();
4526
4527        assert_eq!(non_wip.len(), 1);
4528        assert_eq!(non_wip[0], "Regular commit message");
4529    }
4530
4531    #[test]
4532    fn test_squash_message_all_wip() {
4533        let messages = vec![
4534            "WIP: add feature A".to_string(),
4535            "WIP: add feature B".to_string(),
4536            "WIP: finish implementation".to_string(),
4537        ];
4538
4539        let result = extract_feature_from_wip(&messages);
4540        // Should use the first message as the main feature
4541        assert_eq!(result, "Add feature A");
4542    }
4543
4544    #[test]
4545    fn test_squash_message_edge_cases() {
4546        // Test empty messages
4547        let empty_messages: Vec<String> = vec![];
4548        let result = extract_feature_from_wip(&empty_messages);
4549        assert_eq!(result, "Squashed 0 commits");
4550
4551        // Test messages with only whitespace
4552        let whitespace_messages = vec!["   ".to_string(), "\t\n".to_string()];
4553        let result = extract_feature_from_wip(&whitespace_messages);
4554        assert!(result.contains("Squashed") || result.contains("Implement"));
4555
4556        // Test case sensitivity
4557        let mixed_case = vec!["wip: Add Feature".to_string()];
4558        let result = extract_feature_from_wip(&mixed_case);
4559        assert_eq!(result, "Add Feature");
4560    }
4561
4562    // Tests for auto-land functionality
4563
4564    #[tokio::test]
4565    async fn test_auto_land_wrapper() {
4566        // Test that auto_land_stack correctly calls land_stack with auto=true
4567        let (temp_dir, repo_path) = match create_test_repo() {
4568            Ok(repo) => repo,
4569            Err(_) => {
4570                println!("Skipping test due to git environment setup failure");
4571                return;
4572            }
4573        };
4574        // IMPORTANT: temp_dir must stay in scope to prevent early cleanup of test directory
4575        let _ = &temp_dir;
4576
4577        // Initialize cascade in the test repo
4578        crate::config::initialize_repo(&repo_path, Some("https://test.bitbucket.com".to_string()))
4579            .expect("Failed to initialize Cascade in test repo");
4580
4581        let original_dir = env::current_dir().map_err(|_| "Failed to get current dir");
4582        match env::set_current_dir(&repo_path) {
4583            Ok(_) => {
4584                // Create a stack first
4585                let result = create_stack(
4586                    "test-stack".to_string(),
4587                    None,
4588                    Some("Test stack for auto-land".to_string()),
4589                )
4590                .await;
4591
4592                if let Ok(orig) = original_dir {
4593                    let _ = env::set_current_dir(orig);
4594                }
4595
4596                // For now, just test that the function can be called without panic
4597                // (It will fail due to missing Bitbucket config, but that's expected)
4598                assert!(
4599                    result.is_ok(),
4600                    "Stack creation should succeed in initialized repository"
4601                );
4602            }
4603            Err(_) => {
4604                println!("Skipping test due to directory access restrictions");
4605            }
4606        }
4607    }
4608
4609    #[test]
4610    fn test_auto_land_action_enum() {
4611        // Test that AutoLand action is properly defined
4612        use crate::cli::commands::stack::StackAction;
4613
4614        // This ensures the AutoLand variant exists and has the expected fields
4615        let _action = StackAction::AutoLand {
4616            force: false,
4617            dry_run: true,
4618            wait_for_builds: true,
4619            strategy: Some(MergeStrategyArg::Squash),
4620            build_timeout: 1800,
4621        };
4622
4623        // Test passes if we reach this point without errors
4624    }
4625
4626    #[test]
4627    fn test_merge_strategy_conversion() {
4628        // Test that MergeStrategyArg converts properly
4629        let squash_strategy = MergeStrategyArg::Squash;
4630        let merge_strategy: crate::bitbucket::pull_request::MergeStrategy = squash_strategy.into();
4631
4632        match merge_strategy {
4633            crate::bitbucket::pull_request::MergeStrategy::Squash => {
4634                // Correct conversion
4635            }
4636            _ => unreachable!("SquashStrategyArg only has Squash variant"),
4637        }
4638
4639        let merge_strategy = MergeStrategyArg::Merge;
4640        let converted: crate::bitbucket::pull_request::MergeStrategy = merge_strategy.into();
4641
4642        match converted {
4643            crate::bitbucket::pull_request::MergeStrategy::Merge => {
4644                // Correct conversion
4645            }
4646            _ => unreachable!("MergeStrategyArg::Merge maps to MergeStrategy::Merge"),
4647        }
4648    }
4649
4650    #[test]
4651    fn test_auto_merge_conditions_structure() {
4652        // Test that AutoMergeConditions can be created with expected values
4653        use std::time::Duration;
4654
4655        let conditions = crate::bitbucket::pull_request::AutoMergeConditions {
4656            merge_strategy: crate::bitbucket::pull_request::MergeStrategy::Squash,
4657            wait_for_builds: true,
4658            build_timeout: Duration::from_secs(1800),
4659            allowed_authors: None,
4660        };
4661
4662        // Verify the conditions are set as expected for auto-land
4663        assert!(conditions.wait_for_builds);
4664        assert_eq!(conditions.build_timeout.as_secs(), 1800);
4665        assert!(conditions.allowed_authors.is_none());
4666        assert!(matches!(
4667            conditions.merge_strategy,
4668            crate::bitbucket::pull_request::MergeStrategy::Squash
4669        ));
4670    }
4671
4672    #[test]
4673    fn test_polling_constants() {
4674        // Test that polling frequency is documented and reasonable
4675        use std::time::Duration;
4676
4677        // The polling frequency should be 30 seconds as mentioned in documentation
4678        let expected_polling_interval = Duration::from_secs(30);
4679
4680        // Verify it's a reasonable value (not too frequent, not too slow)
4681        assert!(expected_polling_interval.as_secs() >= 10); // At least 10 seconds
4682        assert!(expected_polling_interval.as_secs() <= 60); // At most 1 minute
4683        assert_eq!(expected_polling_interval.as_secs(), 30); // Exactly 30 seconds
4684    }
4685
4686    #[test]
4687    fn test_build_timeout_defaults() {
4688        // Verify build timeout default is reasonable
4689        const DEFAULT_TIMEOUT: u64 = 1800; // 30 minutes
4690        assert_eq!(DEFAULT_TIMEOUT, 1800);
4691        // Test that our default timeout value is within reasonable bounds
4692        let timeout_value = 1800u64;
4693        assert!(timeout_value >= 300); // At least 5 minutes
4694        assert!(timeout_value <= 3600); // At most 1 hour
4695    }
4696
4697    #[test]
4698    fn test_scattered_commit_detection() {
4699        use std::collections::HashSet;
4700
4701        // Test scattered commit detection logic
4702        let mut source_branches = HashSet::new();
4703        source_branches.insert("feature-branch-1".to_string());
4704        source_branches.insert("feature-branch-2".to_string());
4705        source_branches.insert("feature-branch-3".to_string());
4706
4707        // Single branch should not trigger warning
4708        let single_branch = HashSet::from(["main".to_string()]);
4709        assert_eq!(single_branch.len(), 1);
4710
4711        // Multiple branches should trigger warning
4712        assert!(source_branches.len() > 1);
4713        assert_eq!(source_branches.len(), 3);
4714
4715        // Verify branch names are preserved correctly
4716        assert!(source_branches.contains("feature-branch-1"));
4717        assert!(source_branches.contains("feature-branch-2"));
4718        assert!(source_branches.contains("feature-branch-3"));
4719    }
4720
4721    #[test]
4722    fn test_source_branch_tracking() {
4723        // Test that source branch tracking correctly handles different scenarios
4724
4725        // Same branch should be consistent
4726        let branch_a = "feature-work";
4727        let branch_b = "feature-work";
4728        assert_eq!(branch_a, branch_b);
4729
4730        // Different branches should be detected
4731        let branch_1 = "feature-ui";
4732        let branch_2 = "feature-api";
4733        assert_ne!(branch_1, branch_2);
4734
4735        // Branch naming patterns
4736        assert!(branch_1.starts_with("feature-"));
4737        assert!(branch_2.starts_with("feature-"));
4738    }
4739
4740    // Tests for new default behavior (removing --all flag)
4741
4742    #[tokio::test]
4743    async fn test_push_default_behavior() {
4744        // Test the push_to_stack function structure and error handling in an isolated environment
4745        let (temp_dir, repo_path) = match create_test_repo() {
4746            Ok(repo) => repo,
4747            Err(_) => {
4748                println!("Skipping test due to git environment setup failure");
4749                return;
4750            }
4751        };
4752        // IMPORTANT: temp_dir must stay in scope to prevent early cleanup of test directory
4753        let _ = &temp_dir;
4754
4755        // Verify directory exists before changing to it
4756        if !repo_path.exists() {
4757            println!("Skipping test due to temporary directory creation issue");
4758            return;
4759        }
4760
4761        // Change to the test repository directory to ensure isolation
4762        let original_dir = env::current_dir().map_err(|_| "Failed to get current dir");
4763
4764        match env::set_current_dir(&repo_path) {
4765            Ok(_) => {
4766                // Test that push_to_stack properly handles the case when no stack is active
4767                let result = push_to_stack(
4768                    None,  // branch
4769                    None,  // message
4770                    None,  // commit
4771                    None,  // since
4772                    None,  // commits
4773                    None,  // squash
4774                    None,  // squash_since
4775                    false, // auto_branch
4776                    false, // allow_base_branch
4777                    false, // dry_run
4778                )
4779                .await;
4780
4781                // Restore original directory (best effort)
4782                if let Ok(orig) = original_dir {
4783                    let _ = env::set_current_dir(orig);
4784                }
4785
4786                // Should fail gracefully with appropriate error message when no stack is active
4787                match &result {
4788                    Err(e) => {
4789                        let error_msg = e.to_string();
4790                        // This is the expected behavior - no active stack should produce this error
4791                        assert!(
4792                            error_msg.contains("No active stack")
4793                                || error_msg.contains("config")
4794                                || error_msg.contains("current directory")
4795                                || error_msg.contains("Not a git repository")
4796                                || error_msg.contains("could not find repository"),
4797                            "Expected 'No active stack' or repository error, got: {error_msg}"
4798                        );
4799                    }
4800                    Ok(_) => {
4801                        // If it somehow succeeds, that's also fine (e.g., if environment is set up differently)
4802                        println!(
4803                            "Push succeeded unexpectedly - test environment may have active stack"
4804                        );
4805                    }
4806                }
4807            }
4808            Err(_) => {
4809                // Skip test if we can't change directories (CI environment issue)
4810                println!("Skipping test due to directory access restrictions");
4811            }
4812        }
4813
4814        // Verify we can construct the command structure correctly
4815        let push_action = StackAction::Push {
4816            branch: None,
4817            message: None,
4818            commit: None,
4819            since: None,
4820            commits: None,
4821            squash: None,
4822            squash_since: None,
4823            auto_branch: false,
4824            allow_base_branch: false,
4825            dry_run: false,
4826        };
4827
4828        assert!(matches!(
4829            push_action,
4830            StackAction::Push {
4831                branch: None,
4832                message: None,
4833                commit: None,
4834                since: None,
4835                commits: None,
4836                squash: None,
4837                squash_since: None,
4838                auto_branch: false,
4839                allow_base_branch: false,
4840                dry_run: false
4841            }
4842        ));
4843    }
4844
4845    #[tokio::test]
4846    async fn test_submit_default_behavior() {
4847        // Test the submit_entry function structure and error handling in an isolated environment
4848        let (temp_dir, repo_path) = match create_test_repo() {
4849            Ok(repo) => repo,
4850            Err(_) => {
4851                println!("Skipping test due to git environment setup failure");
4852                return;
4853            }
4854        };
4855        // IMPORTANT: temp_dir must stay in scope to prevent early cleanup of test directory
4856        let _ = &temp_dir;
4857
4858        // Verify directory exists before changing to it
4859        if !repo_path.exists() {
4860            println!("Skipping test due to temporary directory creation issue");
4861            return;
4862        }
4863
4864        // Change to the test repository directory to ensure isolation
4865        let original_dir = match env::current_dir() {
4866            Ok(dir) => dir,
4867            Err(_) => {
4868                println!("Skipping test due to current directory access restrictions");
4869                return;
4870            }
4871        };
4872
4873        match env::set_current_dir(&repo_path) {
4874            Ok(_) => {
4875                // Test that submit_entry properly handles the case when no stack is active
4876                let result = submit_entry(
4877                    None,  // entry (should default to all unsubmitted)
4878                    None,  // title
4879                    None,  // description
4880                    None,  // range
4881                    false, // draft
4882                    true,  // open
4883                )
4884                .await;
4885
4886                // Restore original directory
4887                let _ = env::set_current_dir(original_dir);
4888
4889                // Should fail gracefully with appropriate error message when no stack is active
4890                match &result {
4891                    Err(e) => {
4892                        let error_msg = e.to_string();
4893                        // This is the expected behavior - no active stack should produce this error
4894                        assert!(
4895                            error_msg.contains("No active stack")
4896                                || error_msg.contains("config")
4897                                || error_msg.contains("current directory")
4898                                || error_msg.contains("Not a git repository")
4899                                || error_msg.contains("could not find repository"),
4900                            "Expected 'No active stack' or repository error, got: {error_msg}"
4901                        );
4902                    }
4903                    Ok(_) => {
4904                        // If it somehow succeeds, that's also fine (e.g., if environment is set up differently)
4905                        println!("Submit succeeded unexpectedly - test environment may have active stack");
4906                    }
4907                }
4908            }
4909            Err(_) => {
4910                // Skip test if we can't change directories (CI environment issue)
4911                println!("Skipping test due to directory access restrictions");
4912            }
4913        }
4914
4915        // Verify we can construct the command structure correctly
4916        let submit_action = StackAction::Submit {
4917            entry: None,
4918            title: None,
4919            description: None,
4920            range: None,
4921            draft: true, // Default changed to true
4922            open: true,
4923        };
4924
4925        assert!(matches!(
4926            submit_action,
4927            StackAction::Submit {
4928                entry: None,
4929                title: None,
4930                description: None,
4931                range: None,
4932                draft: true, // Default changed to true
4933                open: true
4934            }
4935        ));
4936    }
4937
4938    #[test]
4939    fn test_targeting_options_still_work() {
4940        // Test that specific targeting options still work correctly
4941
4942        // Test commit list parsing
4943        let commits = "abc123,def456,ghi789";
4944        let parsed: Vec<&str> = commits.split(',').map(|s| s.trim()).collect();
4945        assert_eq!(parsed.len(), 3);
4946        assert_eq!(parsed[0], "abc123");
4947        assert_eq!(parsed[1], "def456");
4948        assert_eq!(parsed[2], "ghi789");
4949
4950        // Test range parsing would work
4951        let range = "1-3";
4952        assert!(range.contains('-'));
4953        let parts: Vec<&str> = range.split('-').collect();
4954        assert_eq!(parts.len(), 2);
4955
4956        // Test since reference pattern
4957        let since_ref = "HEAD~3";
4958        assert!(since_ref.starts_with("HEAD"));
4959        assert!(since_ref.contains('~'));
4960    }
4961
4962    #[test]
4963    fn test_command_flow_logic() {
4964        // These just test the command structure exists
4965        assert!(matches!(
4966            StackAction::Push {
4967                branch: None,
4968                message: None,
4969                commit: None,
4970                since: None,
4971                commits: None,
4972                squash: None,
4973                squash_since: None,
4974                auto_branch: false,
4975                allow_base_branch: false,
4976                dry_run: false
4977            },
4978            StackAction::Push { .. }
4979        ));
4980
4981        assert!(matches!(
4982            StackAction::Submit {
4983                entry: None,
4984                title: None,
4985                description: None,
4986                range: None,
4987                draft: false,
4988                open: true
4989            },
4990            StackAction::Submit { .. }
4991        ));
4992    }
4993
4994    #[tokio::test]
4995    async fn test_deactivate_command_structure() {
4996        // Test that deactivate command structure exists and can be constructed
4997        let deactivate_action = StackAction::Deactivate { force: false };
4998
4999        // Verify it matches the expected pattern
5000        assert!(matches!(
5001            deactivate_action,
5002            StackAction::Deactivate { force: false }
5003        ));
5004
5005        // Test with force flag
5006        let force_deactivate = StackAction::Deactivate { force: true };
5007        assert!(matches!(
5008            force_deactivate,
5009            StackAction::Deactivate { force: true }
5010        ));
5011    }
5012}