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