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 mut 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    if git_repo.is_dirty()? {
2233        return Err(CascadeError::branch(
2234            "Working tree has uncommitted changes. Commit or stash them before running 'ca sync'."
2235                .to_string(),
2236        ));
2237    }
2238
2239    // Get active stack
2240    let active_stack = stack_manager.get_active_stack().ok_or_else(|| {
2241        CascadeError::config("No active stack. Create a stack first with 'ca stack create'")
2242    })?;
2243
2244    let base_branch = active_stack.base_branch.clone();
2245    let _stack_name = active_stack.name.clone();
2246
2247    // Save the original working branch before any checkouts
2248    let original_branch = git_repo.get_current_branch().ok();
2249
2250    // Sync starts silently - user will see the rebase output
2251
2252    // Step 1: Pull latest changes from base branch (silent unless error)
2253    match git_repo.checkout_branch_silent(&base_branch) {
2254        Ok(_) => {
2255            match git_repo.pull(&base_branch) {
2256                Ok(_) => {
2257                    // Silent success - only show on verbose or error
2258                }
2259                Err(e) => {
2260                    if force {
2261                        Output::warning(format!("Pull failed: {e} (continuing due to --force)"));
2262                    } else {
2263                        Output::error(format!("Failed to pull latest changes: {e}"));
2264                        Output::tip("Use --force to skip pull and continue with rebase");
2265                        return Err(CascadeError::branch(format!(
2266                            "Failed to pull latest changes from '{base_branch}': {e}. Use --force to continue anyway."
2267                        )));
2268                    }
2269                }
2270            }
2271        }
2272        Err(e) => {
2273            if force {
2274                Output::warning(format!(
2275                    "Failed to checkout '{base_branch}': {e} (continuing due to --force)"
2276                ));
2277            } else {
2278                Output::error(format!(
2279                    "Failed to checkout base branch '{base_branch}': {e}"
2280                ));
2281                Output::tip("Use --force to bypass checkout issues and continue anyway");
2282                return Err(CascadeError::branch(format!(
2283                    "Failed to checkout base branch '{base_branch}': {e}. Use --force to continue anyway."
2284                )));
2285            }
2286        }
2287    }
2288
2289    // Step 2: Reconcile metadata with current Git state before checking integrity
2290    // This fixes stale metadata from previous bugs or interrupted operations
2291    let mut updated_stack_manager = StackManager::new(&repo_root)?;
2292    let stack_id = active_stack.id;
2293
2294    // Update entry commit hashes to match current branch HEADs
2295    // This prevents false "branch modification" errors from stale metadata
2296    if let Some(stack) = updated_stack_manager.get_stack_mut(&stack_id) {
2297        let mut updates = Vec::new();
2298        for entry in &stack.entries {
2299            if let Ok(current_commit) = git_repo.get_branch_head(&entry.branch) {
2300                if entry.commit_hash != current_commit {
2301                    let is_safe_descendant = match git_repo.commit_exists(&entry.commit_hash) {
2302                        Ok(true) => {
2303                            match git_repo.is_descendant_of(&current_commit, &entry.commit_hash) {
2304                                Ok(result) => result,
2305                                Err(e) => {
2306                                    warn!(
2307                                    "Cannot verify ancestry for '{}': {} - treating as unsafe to prevent potential data loss",
2308                                    entry.branch, e
2309                                );
2310                                    false
2311                                }
2312                            }
2313                        }
2314                        Ok(false) => {
2315                            debug!(
2316                                "Recorded commit {} for '{}' no longer exists in repository",
2317                                &entry.commit_hash[..8],
2318                                entry.branch
2319                            );
2320                            false
2321                        }
2322                        Err(e) => {
2323                            warn!(
2324                                "Cannot verify commit existence for '{}': {} - treating as unsafe to prevent potential data loss",
2325                                entry.branch, e
2326                            );
2327                            false
2328                        }
2329                    };
2330
2331                    if is_safe_descendant {
2332                        debug!(
2333                            "Reconciling entry '{}': updating hash from {} to {} (current branch HEAD)",
2334                            entry.branch,
2335                            &entry.commit_hash[..8],
2336                            &current_commit[..8]
2337                        );
2338                        updates.push((entry.id, current_commit));
2339                    } else {
2340                        warn!(
2341                            "Skipped automatic reconciliation for entry '{}' because local HEAD ({}) does not descend from recorded commit ({})",
2342                            entry.branch,
2343                            &current_commit[..8],
2344                            &entry.commit_hash[..8]
2345                        );
2346                    }
2347                }
2348            }
2349        }
2350
2351        // Apply updates using safe wrapper
2352        for (entry_id, new_hash) in updates {
2353            stack
2354                .update_entry_commit_hash(&entry_id, new_hash)
2355                .map_err(CascadeError::config)?;
2356        }
2357
2358        // Save reconciled metadata
2359        updated_stack_manager.save_to_disk()?;
2360    }
2361
2362    match updated_stack_manager.sync_stack(&stack_id) {
2363        Ok(_) => {
2364            // Check the updated status
2365            if let Some(updated_stack) = updated_stack_manager.get_stack(&stack_id) {
2366                // Check for empty stack first
2367                if updated_stack.entries.is_empty() {
2368                    println!(); // Spacing
2369                    Output::info("Stack has no entries yet");
2370                    Output::tip("Use 'ca push' to add commits to this stack");
2371                    return Ok(());
2372                }
2373
2374                match &updated_stack.status {
2375                    crate::stack::StackStatus::NeedsSync => {
2376                        // Load configuration for Bitbucket integration
2377                        let config_dir = crate::config::get_repo_config_dir(&repo_root)?;
2378                        let config_path = config_dir.join("config.json");
2379                        let settings = crate::config::Settings::load_from_file(&config_path)?;
2380
2381                        let cascade_config = crate::config::CascadeConfig {
2382                            bitbucket: Some(settings.bitbucket.clone()),
2383                            git: settings.git.clone(),
2384                            auth: crate::config::AuthConfig::default(),
2385                            cascade: settings.cascade.clone(),
2386                        };
2387
2388                        // Use the existing rebase system with force-push strategy
2389                        // This preserves PR history by force-pushing to original branches
2390                        let options = crate::stack::RebaseOptions {
2391                            strategy: crate::stack::RebaseStrategy::ForcePush,
2392                            interactive,
2393                            target_base: Some(base_branch.clone()),
2394                            preserve_merges: true,
2395                            auto_resolve: !interactive, // Re-enabled with safety checks
2396                            max_retries: 3,
2397                            skip_pull: Some(true), // Skip pull since we already pulled above
2398                            original_working_branch: original_branch.clone(), // Pass the saved working branch
2399                        };
2400
2401                        // Get entry count for spinner title before creating rebase manager
2402                        let entry_count = active_stack.entries.len();
2403                        let plural = if entry_count == 1 { "entry" } else { "entries" };
2404
2405                        let mut rebase_manager = crate::stack::RebaseManager::new(
2406                            updated_stack_manager,
2407                            git_repo,
2408                            options,
2409                        );
2410
2411                        println!(); // Spacing
2412
2413                        // Start spinner with static title
2414                        let mut rebase_spinner = crate::utils::spinner::Spinner::new(format!(
2415                            "Rebasing {} {}",
2416                            entry_count, plural
2417                        ));
2418
2419                        // Rebase all entries (tree prints as we go)
2420                        let rebase_result = rebase_manager.rebase_stack(&stack_id);
2421
2422                        // Stop rebase spinner before showing results
2423                        rebase_spinner.stop();
2424                        println!(); // Spacing after spinner
2425
2426                        match rebase_result {
2427                            Ok(result) => {
2428                                if !result.branch_mapping.is_empty() {
2429                                    // Update PRs if enabled
2430                                    if let Some(ref _bitbucket_config) = cascade_config.bitbucket {
2431                                        let integration_stack_manager =
2432                                            StackManager::new(&repo_root)?;
2433                                        let mut integration =
2434                                            crate::bitbucket::BitbucketIntegration::new(
2435                                                integration_stack_manager,
2436                                                cascade_config,
2437                                            )?;
2438
2439                                        // Show spinner during PR updates
2440                                        let pr_word = if result.branch_mapping.len() == 1 {
2441                                            "PR"
2442                                        } else {
2443                                            "PRs"
2444                                        };
2445                                        let mut pr_spinner =
2446                                            crate::utils::spinner::Spinner::new(format!(
2447                                                "Updating {} {}",
2448                                                result.branch_mapping.len(),
2449                                                pr_word
2450                                            ));
2451
2452                                        let pr_result = integration
2453                                            .update_prs_after_rebase(
2454                                                &stack_id,
2455                                                &result.branch_mapping,
2456                                            )
2457                                            .await;
2458
2459                                        pr_spinner.stop();
2460
2461                                        match pr_result {
2462                                            Ok(updated_prs) => {
2463                                                if !updated_prs.is_empty() {
2464                                                    Output::success(format!(
2465                                                        "Updated {} pull request{}",
2466                                                        updated_prs.len(),
2467                                                        if updated_prs.len() == 1 {
2468                                                            ""
2469                                                        } else {
2470                                                            "s"
2471                                                        }
2472                                                    ));
2473                                                }
2474                                            }
2475                                            Err(e) => {
2476                                                Output::warning(format!(
2477                                                    "Failed to update pull requests: {e}"
2478                                                ));
2479                                            }
2480                                        }
2481                                    }
2482                                }
2483                            }
2484                            Err(e) => {
2485                                // Error already contains instructions, just propagate it
2486                                return Err(e);
2487                            }
2488                        }
2489                    }
2490                    crate::stack::StackStatus::Clean => {
2491                        // Already up to date - silent success
2492                    }
2493                    other => {
2494                        // Only show unexpected status
2495                        Output::info(format!("Stack status: {other:?}"));
2496                    }
2497                }
2498            }
2499        }
2500        Err(e) => {
2501            if force {
2502                Output::warning(format!(
2503                    "Failed to check stack status: {e} (continuing due to --force)"
2504                ));
2505            } else {
2506                return Err(e);
2507            }
2508        }
2509    }
2510
2511    // Step 3: Cleanup merged branches (optional) - only if explicitly requested
2512    if cleanup {
2513        let git_repo_for_cleanup = GitRepository::open(&repo_root)?;
2514        match perform_simple_cleanup(&stack_manager, &git_repo_for_cleanup, false).await {
2515            Ok(result) => {
2516                if result.total_candidates > 0 {
2517                    Output::section("Cleanup Summary");
2518                    if !result.cleaned_branches.is_empty() {
2519                        Output::success(format!(
2520                            "Cleaned up {} merged branches",
2521                            result.cleaned_branches.len()
2522                        ));
2523                        for branch in &result.cleaned_branches {
2524                            Output::sub_item(format!("🗑️  Deleted: {branch}"));
2525                        }
2526                    }
2527                    if !result.skipped_branches.is_empty() {
2528                        Output::sub_item(format!(
2529                            "Skipped {} branches",
2530                            result.skipped_branches.len()
2531                        ));
2532                    }
2533                    if !result.failed_branches.is_empty() {
2534                        for (branch, error) in &result.failed_branches {
2535                            Output::warning(format!("Failed to clean up {branch}: {error}"));
2536                        }
2537                    }
2538                }
2539            }
2540            Err(e) => {
2541                Output::warning(format!("Branch cleanup failed: {e}"));
2542            }
2543        }
2544    }
2545
2546    // NOTE: Don't checkout the original branch here!
2547    // The rebase_with_force_push() function already returned us to the working branch
2548    // using checkout_branch_unsafe(). If we try to checkout again with the safe version,
2549    // it will see the rebased working tree and think there are staged changes
2550    // (because the working branch HEAD was updated during rebase but we're still on the old tree).
2551    // Trust that the rebase left us in the correct state.
2552
2553    Output::success("Sync completed successfully!");
2554
2555    Ok(())
2556}
2557
2558async fn rebase_stack(
2559    interactive: bool,
2560    onto: Option<String>,
2561    strategy: Option<RebaseStrategyArg>,
2562) -> Result<()> {
2563    let current_dir = env::current_dir()
2564        .map_err(|e| CascadeError::config(format!("Could not get current directory: {e}")))?;
2565
2566    let repo_root = find_repository_root(&current_dir)
2567        .map_err(|e| CascadeError::config(format!("Could not find git repository: {e}")))?;
2568
2569    let stack_manager = StackManager::new(&repo_root)?;
2570    let git_repo = GitRepository::open(&repo_root)?;
2571
2572    // Load configuration for potential Bitbucket integration
2573    let config_dir = crate::config::get_repo_config_dir(&repo_root)?;
2574    let config_path = config_dir.join("config.json");
2575    let settings = crate::config::Settings::load_from_file(&config_path)?;
2576
2577    // Create the main config structure
2578    let cascade_config = crate::config::CascadeConfig {
2579        bitbucket: Some(settings.bitbucket.clone()),
2580        git: settings.git.clone(),
2581        auth: crate::config::AuthConfig::default(),
2582        cascade: settings.cascade.clone(),
2583    };
2584
2585    // Get active stack
2586    let active_stack = stack_manager.get_active_stack().ok_or_else(|| {
2587        CascadeError::config("No active stack. Create a stack first with 'ca stack create'")
2588    })?;
2589    let stack_id = active_stack.id;
2590
2591    let active_stack = stack_manager
2592        .get_stack(&stack_id)
2593        .ok_or_else(|| CascadeError::config("Active stack not found"))?
2594        .clone();
2595
2596    if active_stack.entries.is_empty() {
2597        Output::info("Stack is empty. Nothing to rebase.");
2598        return Ok(());
2599    }
2600
2601    Output::progress(format!("Rebasing stack: {}", active_stack.name));
2602    Output::sub_item(format!("Base: {}", active_stack.base_branch));
2603
2604    // Determine rebase strategy (force-push is the industry standard for stacked diffs)
2605    let rebase_strategy = if let Some(cli_strategy) = strategy {
2606        match cli_strategy {
2607            RebaseStrategyArg::ForcePush => crate::stack::RebaseStrategy::ForcePush,
2608            RebaseStrategyArg::Interactive => crate::stack::RebaseStrategy::Interactive,
2609        }
2610    } else {
2611        // Default to force-push (industry standard for preserving PR history)
2612        crate::stack::RebaseStrategy::ForcePush
2613    };
2614
2615    // Save original branch before any operations
2616    let original_branch = git_repo.get_current_branch().ok();
2617
2618    // Create rebase options
2619    let options = crate::stack::RebaseOptions {
2620        strategy: rebase_strategy.clone(),
2621        interactive,
2622        target_base: onto,
2623        preserve_merges: true,
2624        auto_resolve: !interactive, // Re-enabled with safety checks
2625        max_retries: 3,
2626        skip_pull: None, // Normal rebase should pull latest changes
2627        original_working_branch: original_branch,
2628    };
2629
2630    debug!("   Strategy: {:?}", rebase_strategy);
2631    debug!("   Interactive: {}", interactive);
2632    debug!("   Target base: {:?}", options.target_base);
2633    debug!("   Entries: {}", active_stack.entries.len());
2634
2635    let entry_count = active_stack.entries.len();
2636    let plural = if entry_count == 1 { "entry" } else { "entries" };
2637
2638    // Check if there's already a rebase in progress
2639    let mut rebase_manager = crate::stack::RebaseManager::new(stack_manager, git_repo, options);
2640
2641    if rebase_manager.is_rebase_in_progress() {
2642        Output::warning("Rebase already in progress!");
2643        Output::tip("Use 'git status' to check the current state");
2644        Output::next_steps(&[
2645            "Run 'ca stack continue-rebase' to continue",
2646            "Run 'ca stack abort-rebase' to abort",
2647        ]);
2648        return Ok(());
2649    }
2650
2651    println!(); // Spacing
2652
2653    // Start spinner for rebase
2654    let mut rebase_spinner =
2655        crate::utils::spinner::Spinner::new(format!("Rebasing {} {}", entry_count, plural));
2656
2657    // Perform the rebase
2658    let rebase_result = rebase_manager.rebase_stack(&stack_id);
2659
2660    // Stop spinner before showing results
2661    rebase_spinner.stop();
2662    println!(); // Spacing
2663
2664    match rebase_result {
2665        Ok(result) => {
2666            Output::success("Rebase completed!");
2667            Output::sub_item(result.get_summary());
2668
2669            if result.has_conflicts() {
2670                Output::warning(format!(
2671                    "{} conflicts were resolved",
2672                    result.conflicts.len()
2673                ));
2674                for conflict in &result.conflicts {
2675                    Output::bullet(&conflict[..8.min(conflict.len())]);
2676                }
2677            }
2678
2679            if !result.branch_mapping.is_empty() {
2680                Output::section("Branch mapping");
2681                for (old, new) in &result.branch_mapping {
2682                    Output::bullet(format!("{old} -> {new}"));
2683                }
2684
2685                // Handle PR updates if enabled
2686                if let Some(ref _bitbucket_config) = cascade_config.bitbucket {
2687                    // Create a new StackManager for the integration (since the original was moved)
2688                    let integration_stack_manager = StackManager::new(&repo_root)?;
2689                    let mut integration = BitbucketIntegration::new(
2690                        integration_stack_manager,
2691                        cascade_config.clone(),
2692                    )?;
2693
2694                    match integration
2695                        .update_prs_after_rebase(&stack_id, &result.branch_mapping)
2696                        .await
2697                    {
2698                        Ok(updated_prs) => {
2699                            if !updated_prs.is_empty() {
2700                                println!("   🔄 Preserved pull request history:");
2701                                for pr_update in updated_prs {
2702                                    println!("      ✅ {pr_update}");
2703                                }
2704                            }
2705                        }
2706                        Err(e) => {
2707                            Output::warning(format!("Failed to update pull requests: {e}"));
2708                            Output::sub_item("You may need to manually update PRs in Bitbucket");
2709                        }
2710                    }
2711                }
2712            }
2713
2714            Output::success(format!(
2715                "{} commits successfully rebased",
2716                result.success_count()
2717            ));
2718
2719            // Show next steps
2720            if matches!(rebase_strategy, crate::stack::RebaseStrategy::ForcePush) {
2721                println!();
2722                Output::section("Next steps");
2723                if !result.branch_mapping.is_empty() {
2724                    Output::numbered_item(1, "Branches have been rebased and force-pushed");
2725                    Output::numbered_item(
2726                        2,
2727                        "Pull requests updated automatically (history preserved)",
2728                    );
2729                    Output::numbered_item(3, "Review the updated PRs in Bitbucket");
2730                    Output::numbered_item(4, "Test your changes");
2731                } else {
2732                    println!("   1. Review the rebased stack");
2733                    println!("   2. Test your changes");
2734                    println!("   3. Submit new pull requests with 'ca stack submit'");
2735                }
2736            }
2737        }
2738        Err(e) => {
2739            warn!("❌ Rebase failed: {}", e);
2740            Output::tip(" Tips for resolving rebase issues:");
2741            println!("   - Check for uncommitted changes with 'git status'");
2742            println!("   - Ensure base branch is up to date");
2743            println!("   - Try interactive mode: 'ca stack rebase --interactive'");
2744            return Err(e);
2745        }
2746    }
2747
2748    Ok(())
2749}
2750
2751async fn continue_rebase() -> Result<()> {
2752    let current_dir = env::current_dir()
2753        .map_err(|e| CascadeError::config(format!("Could not get current directory: {e}")))?;
2754
2755    let repo_root = find_repository_root(&current_dir)
2756        .map_err(|e| CascadeError::config(format!("Could not find git repository: {e}")))?;
2757
2758    let stack_manager = StackManager::new(&repo_root)?;
2759    let git_repo = crate::git::GitRepository::open(&repo_root)?;
2760    let options = crate::stack::RebaseOptions::default();
2761    let rebase_manager = crate::stack::RebaseManager::new(stack_manager, git_repo, options);
2762
2763    if !rebase_manager.is_rebase_in_progress() {
2764        Output::info("  No rebase in progress");
2765        return Ok(());
2766    }
2767
2768    println!(" Continuing rebase...");
2769    match rebase_manager.continue_rebase() {
2770        Ok(_) => {
2771            Output::success(" Rebase continued successfully");
2772            println!("   Check 'ca stack rebase-status' for current state");
2773        }
2774        Err(e) => {
2775            warn!("❌ Failed to continue rebase: {}", e);
2776            Output::tip(" You may need to resolve conflicts first:");
2777            println!("   1. Edit conflicted files");
2778            println!("   2. Stage resolved files with 'git add'");
2779            println!("   3. Run 'ca stack continue-rebase' again");
2780        }
2781    }
2782
2783    Ok(())
2784}
2785
2786async fn abort_rebase() -> Result<()> {
2787    let current_dir = env::current_dir()
2788        .map_err(|e| CascadeError::config(format!("Could not get current directory: {e}")))?;
2789
2790    let repo_root = find_repository_root(&current_dir)
2791        .map_err(|e| CascadeError::config(format!("Could not find git repository: {e}")))?;
2792
2793    let stack_manager = StackManager::new(&repo_root)?;
2794    let git_repo = crate::git::GitRepository::open(&repo_root)?;
2795    let options = crate::stack::RebaseOptions::default();
2796    let rebase_manager = crate::stack::RebaseManager::new(stack_manager, git_repo, options);
2797
2798    if !rebase_manager.is_rebase_in_progress() {
2799        Output::info("  No rebase in progress");
2800        return Ok(());
2801    }
2802
2803    Output::warning("Aborting rebase...");
2804    match rebase_manager.abort_rebase() {
2805        Ok(_) => {
2806            Output::success(" Rebase aborted successfully");
2807            println!("   Repository restored to pre-rebase state");
2808        }
2809        Err(e) => {
2810            warn!("❌ Failed to abort rebase: {}", e);
2811            println!("⚠️  You may need to manually clean up the repository state");
2812        }
2813    }
2814
2815    Ok(())
2816}
2817
2818async fn rebase_status() -> Result<()> {
2819    let current_dir = env::current_dir()
2820        .map_err(|e| CascadeError::config(format!("Could not get current directory: {e}")))?;
2821
2822    let repo_root = find_repository_root(&current_dir)
2823        .map_err(|e| CascadeError::config(format!("Could not find git repository: {e}")))?;
2824
2825    let stack_manager = StackManager::new(&repo_root)?;
2826    let git_repo = crate::git::GitRepository::open(&repo_root)?;
2827
2828    println!("Rebase Status");
2829
2830    // Check if rebase is in progress by checking git state directly
2831    let git_dir = current_dir.join(".git");
2832    let rebase_in_progress = git_dir.join("REBASE_HEAD").exists()
2833        || git_dir.join("rebase-merge").exists()
2834        || git_dir.join("rebase-apply").exists();
2835
2836    if rebase_in_progress {
2837        println!("   Status: 🔄 Rebase in progress");
2838        println!(
2839            "   
2840📝 Actions available:"
2841        );
2842        println!("     - 'ca stack continue-rebase' to continue");
2843        println!("     - 'ca stack abort-rebase' to abort");
2844        println!("     - 'git status' to see conflicted files");
2845
2846        // Check for conflicts
2847        match git_repo.get_status() {
2848            Ok(statuses) => {
2849                let mut conflicts = Vec::new();
2850                for status in statuses.iter() {
2851                    if status.status().contains(git2::Status::CONFLICTED) {
2852                        if let Some(path) = status.path() {
2853                            conflicts.push(path.to_string());
2854                        }
2855                    }
2856                }
2857
2858                if !conflicts.is_empty() {
2859                    println!("   ⚠️  Conflicts in {} files:", conflicts.len());
2860                    for conflict in conflicts {
2861                        println!("      - {conflict}");
2862                    }
2863                    println!(
2864                        "   
2865💡 To resolve conflicts:"
2866                    );
2867                    println!("     1. Edit the conflicted files");
2868                    println!("     2. Stage resolved files: git add <file>");
2869                    println!("     3. Continue: ca stack continue-rebase");
2870                }
2871            }
2872            Err(e) => {
2873                warn!("Failed to get git status: {}", e);
2874            }
2875        }
2876    } else {
2877        println!("   Status: ✅ No rebase in progress");
2878
2879        // Show stack status instead
2880        if let Some(active_stack) = stack_manager.get_active_stack() {
2881            println!("   Active stack: {}", active_stack.name);
2882            println!("   Entries: {}", active_stack.entries.len());
2883            println!("   Base branch: {}", active_stack.base_branch);
2884        }
2885    }
2886
2887    Ok(())
2888}
2889
2890async fn delete_stack(name: String, force: bool) -> Result<()> {
2891    let current_dir = env::current_dir()
2892        .map_err(|e| CascadeError::config(format!("Could not get current directory: {e}")))?;
2893
2894    let repo_root = find_repository_root(&current_dir)
2895        .map_err(|e| CascadeError::config(format!("Could not find git repository: {e}")))?;
2896
2897    let mut manager = StackManager::new(&repo_root)?;
2898
2899    let stack = manager
2900        .get_stack_by_name(&name)
2901        .ok_or_else(|| CascadeError::config(format!("Stack '{name}' not found")))?;
2902    let stack_id = stack.id;
2903
2904    if !force && !stack.entries.is_empty() {
2905        return Err(CascadeError::config(format!(
2906            "Stack '{}' has {} entries. Use --force to delete anyway",
2907            name,
2908            stack.entries.len()
2909        )));
2910    }
2911
2912    let deleted = manager.delete_stack(&stack_id)?;
2913
2914    Output::success(format!("Deleted stack '{}'", deleted.name));
2915    if !deleted.entries.is_empty() {
2916        Output::warning(format!("{} entries were removed", deleted.entries.len()));
2917    }
2918
2919    Ok(())
2920}
2921
2922async fn validate_stack(name: Option<String>, fix_mode: Option<String>) -> Result<()> {
2923    let current_dir = env::current_dir()
2924        .map_err(|e| CascadeError::config(format!("Could not get current directory: {e}")))?;
2925
2926    let repo_root = find_repository_root(&current_dir)
2927        .map_err(|e| CascadeError::config(format!("Could not find git repository: {e}")))?;
2928
2929    let mut manager = StackManager::new(&repo_root)?;
2930
2931    if let Some(name) = name {
2932        // Validate specific stack
2933        let stack = manager
2934            .get_stack_by_name(&name)
2935            .ok_or_else(|| CascadeError::config(format!("Stack '{name}' not found")))?;
2936
2937        let stack_id = stack.id;
2938
2939        // Basic structure validation first
2940        match stack.validate() {
2941            Ok(_message) => {
2942                Output::success(format!("Stack '{}' structure validation passed", name));
2943            }
2944            Err(e) => {
2945                Output::error(format!(
2946                    "Stack '{}' structure validation failed: {}",
2947                    name, e
2948                ));
2949                return Err(CascadeError::config(e));
2950            }
2951        }
2952
2953        // Handle branch modifications (includes Git integrity checks)
2954        manager.handle_branch_modifications(&stack_id, fix_mode)?;
2955
2956        println!();
2957        Output::success(format!("Stack '{name}' validation completed"));
2958        Ok(())
2959    } else {
2960        // Validate all stacks
2961        Output::section("Validating all stacks");
2962        println!();
2963
2964        // Get all stack IDs through public method
2965        let all_stacks = manager.get_all_stacks();
2966        let stack_ids: Vec<uuid::Uuid> = all_stacks.iter().map(|s| s.id).collect();
2967
2968        if stack_ids.is_empty() {
2969            Output::info("No stacks found");
2970            return Ok(());
2971        }
2972
2973        let mut all_valid = true;
2974        for stack_id in stack_ids {
2975            let stack = manager.get_stack(&stack_id).unwrap();
2976            let stack_name = &stack.name;
2977
2978            println!("Checking stack '{stack_name}':");
2979
2980            // Basic structure validation
2981            match stack.validate() {
2982                Ok(message) => {
2983                    Output::sub_item(format!("Structure: {message}"));
2984                }
2985                Err(e) => {
2986                    Output::sub_item(format!("Structure: {e}"));
2987                    all_valid = false;
2988                    continue;
2989                }
2990            }
2991
2992            // Handle branch modifications
2993            match manager.handle_branch_modifications(&stack_id, fix_mode.clone()) {
2994                Ok(_) => {
2995                    Output::sub_item("Git integrity: OK");
2996                }
2997                Err(e) => {
2998                    Output::sub_item(format!("Git integrity: {e}"));
2999                    all_valid = false;
3000                }
3001            }
3002            println!();
3003        }
3004
3005        if all_valid {
3006            Output::success("All stacks passed validation");
3007        } else {
3008            Output::warning("Some stacks have validation issues");
3009            return Err(CascadeError::config("Stack validation failed".to_string()));
3010        }
3011
3012        Ok(())
3013    }
3014}
3015
3016/// Get commits that are not yet in any stack entry
3017#[allow(dead_code)]
3018fn get_unpushed_commits(repo: &GitRepository, stack: &crate::stack::Stack) -> Result<Vec<String>> {
3019    let mut unpushed = Vec::new();
3020    let head_commit = repo.get_head_commit()?;
3021    let mut current_commit = head_commit;
3022
3023    // Walk back from HEAD until we find a commit that's already in the stack
3024    loop {
3025        let commit_hash = current_commit.id().to_string();
3026        let already_in_stack = stack
3027            .entries
3028            .iter()
3029            .any(|entry| entry.commit_hash == commit_hash);
3030
3031        if already_in_stack {
3032            break;
3033        }
3034
3035        unpushed.push(commit_hash);
3036
3037        // Move to parent commit
3038        if let Some(parent) = current_commit.parents().next() {
3039            current_commit = parent;
3040        } else {
3041            break;
3042        }
3043    }
3044
3045    unpushed.reverse(); // Reverse to get chronological order
3046    Ok(unpushed)
3047}
3048
3049/// Squash the last N commits into a single commit
3050pub async fn squash_commits(
3051    repo: &GitRepository,
3052    count: usize,
3053    since_ref: Option<String>,
3054) -> Result<()> {
3055    if count <= 1 {
3056        return Ok(()); // Nothing to squash
3057    }
3058
3059    // Get the current branch
3060    let _current_branch = repo.get_current_branch()?;
3061
3062    // Determine the range for interactive rebase
3063    let rebase_range = if let Some(ref since) = since_ref {
3064        since.clone()
3065    } else {
3066        format!("HEAD~{count}")
3067    };
3068
3069    println!("   Analyzing {count} commits to create smart squash message...");
3070
3071    // Get the commits that will be squashed to create a smart message
3072    let head_commit = repo.get_head_commit()?;
3073    let mut commits_to_squash = Vec::new();
3074    let mut current = head_commit;
3075
3076    // Collect the last N commits
3077    for _ in 0..count {
3078        commits_to_squash.push(current.clone());
3079        if current.parent_count() > 0 {
3080            current = current.parent(0).map_err(CascadeError::Git)?;
3081        } else {
3082            break;
3083        }
3084    }
3085
3086    // Generate smart commit message from the squashed commits
3087    let smart_message = generate_squash_message(&commits_to_squash)?;
3088    println!(
3089        "   Smart message: {}",
3090        smart_message.lines().next().unwrap_or("")
3091    );
3092
3093    // Get the commit we want to reset to (the commit before our range)
3094    let reset_target = if since_ref.is_some() {
3095        // If squashing since a reference, reset to that reference
3096        format!("{rebase_range}~1")
3097    } else {
3098        // If squashing last N commits, reset to N commits before
3099        format!("HEAD~{count}")
3100    };
3101
3102    // Soft reset to preserve changes in staging area
3103    repo.reset_soft(&reset_target)?;
3104
3105    // Stage all changes (they should already be staged from the reset --soft)
3106    repo.stage_all()?;
3107
3108    // Create the new commit with the smart message
3109    let new_commit_hash = repo.commit(&smart_message)?;
3110
3111    println!(
3112        "   Created squashed commit: {} ({})",
3113        &new_commit_hash[..8],
3114        smart_message.lines().next().unwrap_or("")
3115    );
3116    println!("   💡 Tip: Use 'git commit --amend' to edit the commit message if needed");
3117
3118    Ok(())
3119}
3120
3121/// Generate a smart commit message from multiple commits being squashed
3122pub fn generate_squash_message(commits: &[git2::Commit]) -> Result<String> {
3123    if commits.is_empty() {
3124        return Ok("Squashed commits".to_string());
3125    }
3126
3127    // Get all commit messages
3128    let messages: Vec<String> = commits
3129        .iter()
3130        .map(|c| c.message().unwrap_or("").trim().to_string())
3131        .filter(|m| !m.is_empty())
3132        .collect();
3133
3134    if messages.is_empty() {
3135        return Ok("Squashed commits".to_string());
3136    }
3137
3138    // Strategy 1: If the last commit looks like a "Final:" commit, use it
3139    if let Some(last_msg) = messages.first() {
3140        // first() because we're in reverse chronological order
3141        if last_msg.starts_with("Final:") || last_msg.starts_with("final:") {
3142            return Ok(last_msg
3143                .trim_start_matches("Final:")
3144                .trim_start_matches("final:")
3145                .trim()
3146                .to_string());
3147        }
3148    }
3149
3150    // Strategy 2: If most commits are WIP, find the most descriptive non-WIP message
3151    let wip_count = messages
3152        .iter()
3153        .filter(|m| {
3154            m.to_lowercase().starts_with("wip") || m.to_lowercase().contains("work in progress")
3155        })
3156        .count();
3157
3158    if wip_count > messages.len() / 2 {
3159        // Mostly WIP commits, find the best non-WIP one or create a summary
3160        let non_wip: Vec<&String> = messages
3161            .iter()
3162            .filter(|m| {
3163                !m.to_lowercase().starts_with("wip")
3164                    && !m.to_lowercase().contains("work in progress")
3165            })
3166            .collect();
3167
3168        if let Some(best_msg) = non_wip.first() {
3169            return Ok(best_msg.to_string());
3170        }
3171
3172        // All are WIP, try to extract the feature being worked on
3173        let feature = extract_feature_from_wip(&messages);
3174        return Ok(feature);
3175    }
3176
3177    // Strategy 3: Use the last (most recent) commit message
3178    Ok(messages.first().unwrap().clone())
3179}
3180
3181/// Extract feature name from WIP commit messages
3182pub fn extract_feature_from_wip(messages: &[String]) -> String {
3183    // Look for patterns like "WIP: add authentication" -> "Add authentication"
3184    for msg in messages {
3185        // Check both case variations, but preserve original case
3186        if msg.to_lowercase().starts_with("wip:") {
3187            if let Some(rest) = msg
3188                .strip_prefix("WIP:")
3189                .or_else(|| msg.strip_prefix("wip:"))
3190            {
3191                let feature = rest.trim();
3192                if !feature.is_empty() && feature.len() > 3 {
3193                    // Capitalize first letter only, preserve rest
3194                    let mut chars: Vec<char> = feature.chars().collect();
3195                    if let Some(first) = chars.first_mut() {
3196                        *first = first.to_uppercase().next().unwrap_or(*first);
3197                    }
3198                    return chars.into_iter().collect();
3199                }
3200            }
3201        }
3202    }
3203
3204    // Fallback: Use the latest commit without WIP prefix
3205    if let Some(first) = messages.first() {
3206        let cleaned = first
3207            .trim_start_matches("WIP:")
3208            .trim_start_matches("wip:")
3209            .trim_start_matches("WIP")
3210            .trim_start_matches("wip")
3211            .trim();
3212
3213        if !cleaned.is_empty() {
3214            return format!("Implement {cleaned}");
3215        }
3216    }
3217
3218    format!("Squashed {} commits", messages.len())
3219}
3220
3221/// Count commits since a given reference
3222pub fn count_commits_since(repo: &GitRepository, since_commit_hash: &str) -> Result<usize> {
3223    let head_commit = repo.get_head_commit()?;
3224    let since_commit = repo.get_commit(since_commit_hash)?;
3225
3226    let mut count = 0;
3227    let mut current = head_commit;
3228
3229    // Walk backwards from HEAD until we reach the since commit
3230    loop {
3231        if current.id() == since_commit.id() {
3232            break;
3233        }
3234
3235        count += 1;
3236
3237        // Get parent commit
3238        if current.parent_count() == 0 {
3239            break; // Reached root commit
3240        }
3241
3242        current = current.parent(0).map_err(CascadeError::Git)?;
3243    }
3244
3245    Ok(count)
3246}
3247
3248/// Land (merge) approved stack entries
3249async fn land_stack(
3250    entry: Option<usize>,
3251    force: bool,
3252    dry_run: bool,
3253    auto: bool,
3254    wait_for_builds: bool,
3255    strategy: Option<MergeStrategyArg>,
3256    build_timeout: u64,
3257) -> Result<()> {
3258    let current_dir = env::current_dir()
3259        .map_err(|e| CascadeError::config(format!("Could not get current directory: {e}")))?;
3260
3261    let repo_root = find_repository_root(&current_dir)
3262        .map_err(|e| CascadeError::config(format!("Could not find git repository: {e}")))?;
3263
3264    let stack_manager = StackManager::new(&repo_root)?;
3265
3266    // Get stack ID and active stack before moving stack_manager
3267    let stack_id = stack_manager
3268        .get_active_stack()
3269        .map(|s| s.id)
3270        .ok_or_else(|| {
3271            CascadeError::config(
3272                "No active stack. Use 'ca stack create' or 'ca stack switch' to select a stack"
3273                    .to_string(),
3274            )
3275        })?;
3276
3277    let active_stack = stack_manager
3278        .get_active_stack()
3279        .cloned()
3280        .ok_or_else(|| CascadeError::config("No active stack found".to_string()))?;
3281
3282    // Load configuration and create Bitbucket integration
3283    let config_dir = crate::config::get_repo_config_dir(&repo_root)?;
3284    let config_path = config_dir.join("config.json");
3285    let settings = crate::config::Settings::load_from_file(&config_path)?;
3286
3287    let cascade_config = crate::config::CascadeConfig {
3288        bitbucket: Some(settings.bitbucket.clone()),
3289        git: settings.git.clone(),
3290        auth: crate::config::AuthConfig::default(),
3291        cascade: settings.cascade.clone(),
3292    };
3293
3294    let mut integration =
3295        crate::bitbucket::BitbucketIntegration::new(stack_manager, cascade_config)?;
3296
3297    // Get enhanced status
3298    let status = integration.check_enhanced_stack_status(&stack_id).await?;
3299
3300    if status.enhanced_statuses.is_empty() {
3301        println!("❌ No pull requests found to land");
3302        return Ok(());
3303    }
3304
3305    // Filter PRs that are ready to land
3306    let ready_prs: Vec<_> = status
3307        .enhanced_statuses
3308        .iter()
3309        .filter(|pr_status| {
3310            // If specific entry requested, only include that one
3311            if let Some(entry_num) = entry {
3312                // Find the corresponding stack entry for this PR
3313                if let Some(stack_entry) = active_stack.entries.get(entry_num.saturating_sub(1)) {
3314                    // Check if this PR corresponds to the requested entry
3315                    if pr_status.pr.from_ref.display_id != stack_entry.branch {
3316                        return false;
3317                    }
3318                } else {
3319                    return false; // Invalid entry number
3320                }
3321            }
3322
3323            if force {
3324                // If force is enabled, include any open PR
3325                pr_status.pr.state == crate::bitbucket::pull_request::PullRequestState::Open
3326            } else {
3327                pr_status.is_ready_to_land()
3328            }
3329        })
3330        .collect();
3331
3332    if ready_prs.is_empty() {
3333        if let Some(entry_num) = entry {
3334            println!("❌ Entry {entry_num} is not ready to land or doesn't exist");
3335        } else {
3336            println!("❌ No pull requests are ready to land");
3337        }
3338
3339        // Show what's blocking them
3340        println!("\n🚫 Blocking Issues:");
3341        for pr_status in &status.enhanced_statuses {
3342            if pr_status.pr.state == crate::bitbucket::pull_request::PullRequestState::Open {
3343                let blocking = pr_status.get_blocking_reasons();
3344                if !blocking.is_empty() {
3345                    println!("   PR #{}: {}", pr_status.pr.id, blocking.join(", "));
3346                }
3347            }
3348        }
3349
3350        if !force {
3351            println!("\n💡 Use --force to land PRs with blocking issues (dangerous!)");
3352        }
3353        return Ok(());
3354    }
3355
3356    if dry_run {
3357        if let Some(entry_num) = entry {
3358            println!("🏃 Dry Run - Entry {entry_num} that would be landed:");
3359        } else {
3360            println!("🏃 Dry Run - PRs that would be landed:");
3361        }
3362        for pr_status in &ready_prs {
3363            println!("   ✅ PR #{}: {}", pr_status.pr.id, pr_status.pr.title);
3364            if !pr_status.is_ready_to_land() && force {
3365                let blocking = pr_status.get_blocking_reasons();
3366                println!(
3367                    "      ⚠️  Would force land despite: {}",
3368                    blocking.join(", ")
3369                );
3370            }
3371        }
3372        return Ok(());
3373    }
3374
3375    // Default behavior: land all ready PRs (safest approach)
3376    // Only land specific entry if explicitly requested
3377    if entry.is_some() && ready_prs.len() > 1 {
3378        println!(
3379            "🎯 {} PRs are ready to land, but landing only entry #{}",
3380            ready_prs.len(),
3381            entry.unwrap()
3382        );
3383    }
3384
3385    // Setup auto-merge conditions
3386    let merge_strategy: crate::bitbucket::pull_request::MergeStrategy =
3387        strategy.unwrap_or(MergeStrategyArg::Squash).into();
3388    let auto_merge_conditions = crate::bitbucket::pull_request::AutoMergeConditions {
3389        merge_strategy: merge_strategy.clone(),
3390        wait_for_builds,
3391        build_timeout: std::time::Duration::from_secs(build_timeout),
3392        allowed_authors: None, // Allow all authors for now
3393    };
3394
3395    // Land the PRs
3396    println!(
3397        "🚀 Landing {} PR{}...",
3398        ready_prs.len(),
3399        if ready_prs.len() == 1 { "" } else { "s" }
3400    );
3401
3402    let pr_manager = crate::bitbucket::pull_request::PullRequestManager::new(
3403        crate::bitbucket::BitbucketClient::new(&settings.bitbucket)?,
3404    );
3405
3406    // Land PRs in dependency order
3407    let mut landed_count = 0;
3408    let mut failed_count = 0;
3409    let total_ready_prs = ready_prs.len();
3410
3411    for pr_status in ready_prs {
3412        let pr_id = pr_status.pr.id;
3413
3414        print!("🚀 Landing PR #{}: {}", pr_id, pr_status.pr.title);
3415
3416        let land_result = if auto {
3417            // Use auto-merge with conditions checking
3418            pr_manager
3419                .auto_merge_if_ready(pr_id, &auto_merge_conditions)
3420                .await
3421        } else {
3422            // Manual merge without auto-conditions
3423            pr_manager
3424                .merge_pull_request(pr_id, merge_strategy.clone())
3425                .await
3426                .map(
3427                    |pr| crate::bitbucket::pull_request::AutoMergeResult::Merged {
3428                        pr: Box::new(pr),
3429                        merge_strategy: merge_strategy.clone(),
3430                    },
3431                )
3432        };
3433
3434        match land_result {
3435            Ok(crate::bitbucket::pull_request::AutoMergeResult::Merged { .. }) => {
3436                println!(" ✅");
3437                landed_count += 1;
3438
3439                // 🔄 AUTO-RETARGETING: After each merge, retarget remaining PRs
3440                if landed_count < total_ready_prs {
3441                    println!(" Retargeting remaining PRs to latest base...");
3442
3443                    // 1️⃣ CRITICAL: Update base branch to get latest merged state
3444                    let base_branch = active_stack.base_branch.clone();
3445                    let git_repo = crate::git::GitRepository::open(&repo_root)?;
3446
3447                    println!("   📥 Updating base branch: {base_branch}");
3448                    match git_repo.pull(&base_branch) {
3449                        Ok(_) => println!("   ✅ Base branch updated successfully"),
3450                        Err(e) => {
3451                            println!("   ⚠️  Warning: Failed to update base branch: {e}");
3452                            println!(
3453                                "   💡 You may want to manually run: git pull origin {base_branch}"
3454                            );
3455                        }
3456                    }
3457
3458                    // 2️⃣ Use rebase system to retarget remaining PRs
3459                    let temp_manager = StackManager::new(&repo_root)?;
3460                    let stack_for_count = temp_manager
3461                        .get_stack(&stack_id)
3462                        .ok_or_else(|| CascadeError::config("Stack not found"))?;
3463                    let entry_count = stack_for_count.entries.len();
3464                    let plural = if entry_count == 1 { "entry" } else { "entries" };
3465
3466                    let mut rebase_manager = crate::stack::RebaseManager::new(
3467                        StackManager::new(&repo_root)?,
3468                        git_repo,
3469                        crate::stack::RebaseOptions {
3470                            strategy: crate::stack::RebaseStrategy::ForcePush,
3471                            target_base: Some(base_branch.clone()),
3472                            ..Default::default()
3473                        },
3474                    );
3475
3476                    println!(); // Spacing
3477                    let mut rebase_spinner = crate::utils::spinner::Spinner::new(format!(
3478                        "Retargeting {} {}",
3479                        entry_count, plural
3480                    ));
3481
3482                    let rebase_result = rebase_manager.rebase_stack(&stack_id);
3483
3484                    rebase_spinner.stop();
3485                    println!(); // Spacing
3486
3487                    match rebase_result {
3488                        Ok(rebase_result) => {
3489                            if !rebase_result.branch_mapping.is_empty() {
3490                                // Update PRs using the rebase result
3491                                let retarget_config = crate::config::CascadeConfig {
3492                                    bitbucket: Some(settings.bitbucket.clone()),
3493                                    git: settings.git.clone(),
3494                                    auth: crate::config::AuthConfig::default(),
3495                                    cascade: settings.cascade.clone(),
3496                                };
3497                                let mut retarget_integration = BitbucketIntegration::new(
3498                                    StackManager::new(&repo_root)?,
3499                                    retarget_config,
3500                                )?;
3501
3502                                match retarget_integration
3503                                    .update_prs_after_rebase(
3504                                        &stack_id,
3505                                        &rebase_result.branch_mapping,
3506                                    )
3507                                    .await
3508                                {
3509                                    Ok(updated_prs) => {
3510                                        if !updated_prs.is_empty() {
3511                                            println!(
3512                                                "   ✅ Updated {} PRs with new targets",
3513                                                updated_prs.len()
3514                                            );
3515                                        }
3516                                    }
3517                                    Err(e) => {
3518                                        println!("   ⚠️  Failed to update remaining PRs: {e}");
3519                                        println!(
3520                                            "   💡 You may need to run: ca stack rebase --onto {base_branch}"
3521                                        );
3522                                    }
3523                                }
3524                            }
3525                        }
3526                        Err(e) => {
3527                            // 🚨 CONFLICTS DETECTED - Give clear next steps
3528                            println!("   ❌ Auto-retargeting conflicts detected!");
3529                            println!("   📝 To resolve conflicts and continue landing:");
3530                            println!("      1. Resolve conflicts in the affected files");
3531                            println!("      2. Stage resolved files: git add <files>");
3532                            println!("      3. Continue the process: ca stack continue-land");
3533                            println!("      4. Or abort the operation: ca stack abort-land");
3534                            println!();
3535                            println!("   💡 Check current status: ca stack land-status");
3536                            println!("   ⚠️  Error details: {e}");
3537
3538                            // Stop the land operation here - user needs to resolve conflicts
3539                            break;
3540                        }
3541                    }
3542                }
3543            }
3544            Ok(crate::bitbucket::pull_request::AutoMergeResult::NotReady { blocking_reasons }) => {
3545                println!(" ❌ Not ready: {}", blocking_reasons.join(", "));
3546                failed_count += 1;
3547                if !force {
3548                    break;
3549                }
3550            }
3551            Ok(crate::bitbucket::pull_request::AutoMergeResult::Failed { error }) => {
3552                println!(" ❌ Failed: {error}");
3553                failed_count += 1;
3554                if !force {
3555                    break;
3556                }
3557            }
3558            Err(e) => {
3559                println!(" ❌");
3560                eprintln!("Failed to land PR #{pr_id}: {e}");
3561                failed_count += 1;
3562
3563                if !force {
3564                    break;
3565                }
3566            }
3567        }
3568    }
3569
3570    // Show summary
3571    println!("\n🎯 Landing Summary:");
3572    println!("   ✅ Successfully landed: {landed_count}");
3573    if failed_count > 0 {
3574        println!("   ❌ Failed to land: {failed_count}");
3575    }
3576
3577    if landed_count > 0 {
3578        Output::success(" Landing operation completed!");
3579    } else {
3580        println!("❌ No PRs were successfully landed");
3581    }
3582
3583    Ok(())
3584}
3585
3586/// Auto-land all ready PRs (shorthand for land --auto)
3587async fn auto_land_stack(
3588    force: bool,
3589    dry_run: bool,
3590    wait_for_builds: bool,
3591    strategy: Option<MergeStrategyArg>,
3592    build_timeout: u64,
3593) -> Result<()> {
3594    // This is a shorthand for land with --auto
3595    land_stack(
3596        None,
3597        force,
3598        dry_run,
3599        true, // auto = true
3600        wait_for_builds,
3601        strategy,
3602        build_timeout,
3603    )
3604    .await
3605}
3606
3607async fn continue_land() -> Result<()> {
3608    let current_dir = env::current_dir()
3609        .map_err(|e| CascadeError::config(format!("Could not get current directory: {e}")))?;
3610
3611    let repo_root = find_repository_root(&current_dir)
3612        .map_err(|e| CascadeError::config(format!("Could not find git repository: {e}")))?;
3613
3614    let stack_manager = StackManager::new(&repo_root)?;
3615    let git_repo = crate::git::GitRepository::open(&repo_root)?;
3616    let options = crate::stack::RebaseOptions::default();
3617    let rebase_manager = crate::stack::RebaseManager::new(stack_manager, git_repo, options);
3618
3619    if !rebase_manager.is_rebase_in_progress() {
3620        Output::info("  No rebase in progress");
3621        return Ok(());
3622    }
3623
3624    println!(" Continuing land operation...");
3625    match rebase_manager.continue_rebase() {
3626        Ok(_) => {
3627            Output::success(" Land operation continued successfully");
3628            println!("   Check 'ca stack land-status' for current state");
3629        }
3630        Err(e) => {
3631            warn!("❌ Failed to continue land operation: {}", e);
3632            Output::tip(" You may need to resolve conflicts first:");
3633            println!("   1. Edit conflicted files");
3634            println!("   2. Stage resolved files with 'git add'");
3635            println!("   3. Run 'ca stack continue-land' again");
3636        }
3637    }
3638
3639    Ok(())
3640}
3641
3642async fn abort_land() -> Result<()> {
3643    let current_dir = env::current_dir()
3644        .map_err(|e| CascadeError::config(format!("Could not get current directory: {e}")))?;
3645
3646    let repo_root = find_repository_root(&current_dir)
3647        .map_err(|e| CascadeError::config(format!("Could not find git repository: {e}")))?;
3648
3649    let stack_manager = StackManager::new(&repo_root)?;
3650    let git_repo = crate::git::GitRepository::open(&repo_root)?;
3651    let options = crate::stack::RebaseOptions::default();
3652    let rebase_manager = crate::stack::RebaseManager::new(stack_manager, git_repo, options);
3653
3654    if !rebase_manager.is_rebase_in_progress() {
3655        Output::info("  No rebase in progress");
3656        return Ok(());
3657    }
3658
3659    println!("⚠️  Aborting land operation...");
3660    match rebase_manager.abort_rebase() {
3661        Ok(_) => {
3662            Output::success(" Land operation aborted successfully");
3663            println!("   Repository restored to pre-land state");
3664        }
3665        Err(e) => {
3666            warn!("❌ Failed to abort land operation: {}", e);
3667            println!("⚠️  You may need to manually clean up the repository state");
3668        }
3669    }
3670
3671    Ok(())
3672}
3673
3674async fn land_status() -> Result<()> {
3675    let current_dir = env::current_dir()
3676        .map_err(|e| CascadeError::config(format!("Could not get current directory: {e}")))?;
3677
3678    let repo_root = find_repository_root(&current_dir)
3679        .map_err(|e| CascadeError::config(format!("Could not find git repository: {e}")))?;
3680
3681    let stack_manager = StackManager::new(&repo_root)?;
3682    let git_repo = crate::git::GitRepository::open(&repo_root)?;
3683
3684    println!("Land Status");
3685
3686    // Check if land operation is in progress by checking git state directly
3687    let git_dir = repo_root.join(".git");
3688    let land_in_progress = git_dir.join("REBASE_HEAD").exists()
3689        || git_dir.join("rebase-merge").exists()
3690        || git_dir.join("rebase-apply").exists();
3691
3692    if land_in_progress {
3693        println!("   Status: 🔄 Land operation in progress");
3694        println!(
3695            "   
3696📝 Actions available:"
3697        );
3698        println!("     - 'ca stack continue-land' to continue");
3699        println!("     - 'ca stack abort-land' to abort");
3700        println!("     - 'git status' to see conflicted files");
3701
3702        // Check for conflicts
3703        match git_repo.get_status() {
3704            Ok(statuses) => {
3705                let mut conflicts = Vec::new();
3706                for status in statuses.iter() {
3707                    if status.status().contains(git2::Status::CONFLICTED) {
3708                        if let Some(path) = status.path() {
3709                            conflicts.push(path.to_string());
3710                        }
3711                    }
3712                }
3713
3714                if !conflicts.is_empty() {
3715                    println!("   ⚠️  Conflicts in {} files:", conflicts.len());
3716                    for conflict in conflicts {
3717                        println!("      - {conflict}");
3718                    }
3719                    println!(
3720                        "   
3721💡 To resolve conflicts:"
3722                    );
3723                    println!("     1. Edit the conflicted files");
3724                    println!("     2. Stage resolved files: git add <file>");
3725                    println!("     3. Continue: ca stack continue-land");
3726                }
3727            }
3728            Err(e) => {
3729                warn!("Failed to get git status: {}", e);
3730            }
3731        }
3732    } else {
3733        println!("   Status: ✅ No land operation in progress");
3734
3735        // Show stack status instead
3736        if let Some(active_stack) = stack_manager.get_active_stack() {
3737            println!("   Active stack: {}", active_stack.name);
3738            println!("   Entries: {}", active_stack.entries.len());
3739            println!("   Base branch: {}", active_stack.base_branch);
3740        }
3741    }
3742
3743    Ok(())
3744}
3745
3746async fn repair_stack_data() -> Result<()> {
3747    let current_dir = env::current_dir()
3748        .map_err(|e| CascadeError::config(format!("Could not get current directory: {e}")))?;
3749
3750    let repo_root = find_repository_root(&current_dir)
3751        .map_err(|e| CascadeError::config(format!("Could not find git repository: {e}")))?;
3752
3753    let mut stack_manager = StackManager::new(&repo_root)?;
3754
3755    println!("🔧 Repairing stack data consistency...");
3756
3757    stack_manager.repair_all_stacks()?;
3758
3759    Output::success(" Stack data consistency repaired successfully!");
3760    Output::tip(" Run 'ca stack --mergeable' to see updated status");
3761
3762    Ok(())
3763}
3764
3765/// Clean up merged and stale branches
3766async fn cleanup_branches(
3767    dry_run: bool,
3768    force: bool,
3769    include_stale: bool,
3770    stale_days: u32,
3771    cleanup_remote: bool,
3772    include_non_stack: bool,
3773    verbose: bool,
3774) -> Result<()> {
3775    let current_dir = env::current_dir()
3776        .map_err(|e| CascadeError::config(format!("Could not get current directory: {e}")))?;
3777
3778    let repo_root = find_repository_root(&current_dir)
3779        .map_err(|e| CascadeError::config(format!("Could not find git repository: {e}")))?;
3780
3781    let stack_manager = StackManager::new(&repo_root)?;
3782    let git_repo = GitRepository::open(&repo_root)?;
3783
3784    let result = perform_cleanup(
3785        &stack_manager,
3786        &git_repo,
3787        dry_run,
3788        force,
3789        include_stale,
3790        stale_days,
3791        cleanup_remote,
3792        include_non_stack,
3793        verbose,
3794    )
3795    .await?;
3796
3797    // Display results
3798    if result.total_candidates == 0 {
3799        Output::success("No branches found that need cleanup");
3800        return Ok(());
3801    }
3802
3803    Output::section("Cleanup Results");
3804
3805    if dry_run {
3806        Output::sub_item(format!(
3807            "Found {} branches that would be cleaned up",
3808            result.total_candidates
3809        ));
3810    } else {
3811        if !result.cleaned_branches.is_empty() {
3812            Output::success(format!(
3813                "Successfully cleaned up {} branches",
3814                result.cleaned_branches.len()
3815            ));
3816            for branch in &result.cleaned_branches {
3817                Output::sub_item(format!("🗑️  Deleted: {branch}"));
3818            }
3819        }
3820
3821        if !result.skipped_branches.is_empty() {
3822            Output::sub_item(format!(
3823                "Skipped {} branches",
3824                result.skipped_branches.len()
3825            ));
3826            if verbose {
3827                for (branch, reason) in &result.skipped_branches {
3828                    Output::sub_item(format!("⏭️  {branch}: {reason}"));
3829                }
3830            }
3831        }
3832
3833        if !result.failed_branches.is_empty() {
3834            Output::warning(format!(
3835                "Failed to clean up {} branches",
3836                result.failed_branches.len()
3837            ));
3838            for (branch, error) in &result.failed_branches {
3839                Output::sub_item(format!("❌ {branch}: {error}"));
3840            }
3841        }
3842    }
3843
3844    Ok(())
3845}
3846
3847/// Perform cleanup with the given options
3848#[allow(clippy::too_many_arguments)]
3849async fn perform_cleanup(
3850    stack_manager: &StackManager,
3851    git_repo: &GitRepository,
3852    dry_run: bool,
3853    force: bool,
3854    include_stale: bool,
3855    stale_days: u32,
3856    cleanup_remote: bool,
3857    include_non_stack: bool,
3858    verbose: bool,
3859) -> Result<CleanupResult> {
3860    let options = CleanupOptions {
3861        dry_run,
3862        force,
3863        include_stale,
3864        cleanup_remote,
3865        stale_threshold_days: stale_days,
3866        cleanup_non_stack: include_non_stack,
3867    };
3868
3869    let stack_manager_copy = StackManager::new(stack_manager.repo_path())?;
3870    let git_repo_copy = GitRepository::open(git_repo.path())?;
3871    let mut cleanup_manager = CleanupManager::new(stack_manager_copy, git_repo_copy, options);
3872
3873    // Find candidates
3874    let candidates = cleanup_manager.find_cleanup_candidates()?;
3875
3876    if candidates.is_empty() {
3877        return Ok(CleanupResult {
3878            cleaned_branches: Vec::new(),
3879            failed_branches: Vec::new(),
3880            skipped_branches: Vec::new(),
3881            total_candidates: 0,
3882        });
3883    }
3884
3885    // Show candidates if verbose or dry run
3886    if verbose || dry_run {
3887        Output::section("Cleanup Candidates");
3888        for candidate in &candidates {
3889            let reason_icon = match candidate.reason {
3890                crate::stack::CleanupReason::FullyMerged => "🔀",
3891                crate::stack::CleanupReason::StackEntryMerged => "✅",
3892                crate::stack::CleanupReason::Stale => "⏰",
3893                crate::stack::CleanupReason::Orphaned => "👻",
3894            };
3895
3896            Output::sub_item(format!(
3897                "{} {} - {} ({})",
3898                reason_icon,
3899                candidate.branch_name,
3900                candidate.reason_to_string(),
3901                candidate.safety_info
3902            ));
3903        }
3904    }
3905
3906    // If not force and not dry run, ask for confirmation
3907    if !force && !dry_run && !candidates.is_empty() {
3908        Output::warning(format!("About to delete {} branches", candidates.len()));
3909
3910        // Show first few branch names for context
3911        let preview_count = 5.min(candidates.len());
3912        for candidate in candidates.iter().take(preview_count) {
3913            println!("  • {}", candidate.branch_name);
3914        }
3915        if candidates.len() > preview_count {
3916            println!("  ... and {} more", candidates.len() - preview_count);
3917        }
3918        println!(); // Spacing before prompt
3919
3920        // Interactive confirmation to proceed with cleanup
3921        let should_continue = Confirm::with_theme(&ColorfulTheme::default())
3922            .with_prompt("Continue with branch cleanup?")
3923            .default(false)
3924            .interact()
3925            .map_err(|e| CascadeError::config(format!("Failed to get user confirmation: {e}")))?;
3926
3927        if !should_continue {
3928            Output::sub_item("Cleanup cancelled");
3929            return Ok(CleanupResult {
3930                cleaned_branches: Vec::new(),
3931                failed_branches: Vec::new(),
3932                skipped_branches: Vec::new(),
3933                total_candidates: candidates.len(),
3934            });
3935        }
3936    }
3937
3938    // Perform cleanup
3939    cleanup_manager.perform_cleanup(&candidates)
3940}
3941
3942/// Simple perform_cleanup for sync command
3943async fn perform_simple_cleanup(
3944    stack_manager: &StackManager,
3945    git_repo: &GitRepository,
3946    dry_run: bool,
3947) -> Result<CleanupResult> {
3948    perform_cleanup(
3949        stack_manager,
3950        git_repo,
3951        dry_run,
3952        false, // force
3953        false, // include_stale
3954        30,    // stale_days
3955        false, // cleanup_remote
3956        false, // include_non_stack
3957        false, // verbose
3958    )
3959    .await
3960}
3961
3962/// Analyze commits for various safeguards before pushing
3963async fn analyze_commits_for_safeguards(
3964    commits_to_push: &[String],
3965    repo: &GitRepository,
3966    dry_run: bool,
3967) -> Result<()> {
3968    const LARGE_COMMIT_THRESHOLD: usize = 10;
3969    const WEEK_IN_SECONDS: i64 = 7 * 24 * 3600;
3970
3971    // 🛡️ SAFEGUARD 1: Large commit count warning
3972    if commits_to_push.len() > LARGE_COMMIT_THRESHOLD {
3973        println!(
3974            "⚠️  Warning: About to push {} commits to stack",
3975            commits_to_push.len()
3976        );
3977        println!("   This may indicate a merge commit issue or unexpected commit range.");
3978        println!("   Large commit counts often result from merging instead of rebasing.");
3979
3980        if !dry_run && !confirm_large_push(commits_to_push.len())? {
3981            return Err(CascadeError::config("Push cancelled by user"));
3982        }
3983    }
3984
3985    // Get commit objects for further analysis
3986    let commit_objects: Result<Vec<_>> = commits_to_push
3987        .iter()
3988        .map(|hash| repo.get_commit(hash))
3989        .collect();
3990    let commit_objects = commit_objects?;
3991
3992    // 🛡️ SAFEGUARD 2: Merge commit detection
3993    let merge_commits: Vec<_> = commit_objects
3994        .iter()
3995        .filter(|c| c.parent_count() > 1)
3996        .collect();
3997
3998    if !merge_commits.is_empty() {
3999        println!(
4000            "⚠️  Warning: {} merge commits detected in push",
4001            merge_commits.len()
4002        );
4003        println!("   This often indicates you merged instead of rebased.");
4004        println!("   Consider using 'ca sync' to rebase on the base branch.");
4005        println!("   Merge commits in stacks can cause confusion and duplicate work.");
4006    }
4007
4008    // 🛡️ SAFEGUARD 3: Commit age warning
4009    if commit_objects.len() > 1 {
4010        let oldest_commit_time = commit_objects.first().unwrap().time().seconds();
4011        let newest_commit_time = commit_objects.last().unwrap().time().seconds();
4012        let time_span = newest_commit_time - oldest_commit_time;
4013
4014        if time_span > WEEK_IN_SECONDS {
4015            let days = time_span / (24 * 3600);
4016            println!("⚠️  Warning: Commits span {days} days");
4017            println!("   This may indicate merged history rather than new work.");
4018            println!("   Recent work should typically span hours or days, not weeks.");
4019        }
4020    }
4021
4022    // 🛡️ SAFEGUARD 4: Better range detection suggestions
4023    if commits_to_push.len() > 5 {
4024        Output::tip(" Tip: If you only want recent commits, use:");
4025        println!(
4026            "   ca push --since HEAD~{}  # pushes last {} commits",
4027            std::cmp::min(commits_to_push.len(), 5),
4028            std::cmp::min(commits_to_push.len(), 5)
4029        );
4030        println!("   ca push --commits <hash1>,<hash2>  # pushes specific commits");
4031        println!("   ca push --dry-run  # preview what would be pushed");
4032    }
4033
4034    // 🛡️ SAFEGUARD 5: Dry run mode
4035    if dry_run {
4036        println!("🔍 DRY RUN: Would push {} commits:", commits_to_push.len());
4037        for (i, (commit_hash, commit_obj)) in commits_to_push
4038            .iter()
4039            .zip(commit_objects.iter())
4040            .enumerate()
4041        {
4042            let summary = commit_obj.summary().unwrap_or("(no message)");
4043            let short_hash = &commit_hash[..std::cmp::min(commit_hash.len(), 7)];
4044            println!("  {}: {} ({})", i + 1, summary, short_hash);
4045        }
4046        Output::tip(" Run without --dry-run to actually push these commits.");
4047    }
4048
4049    Ok(())
4050}
4051
4052/// Prompt user for confirmation when pushing large number of commits
4053fn confirm_large_push(count: usize) -> Result<bool> {
4054    // Interactive confirmation for large push
4055    let should_continue = Confirm::with_theme(&ColorfulTheme::default())
4056        .with_prompt(format!("Continue pushing {count} commits?"))
4057        .default(false)
4058        .interact()
4059        .map_err(|e| CascadeError::config(format!("Failed to get user confirmation: {e}")))?;
4060
4061    Ok(should_continue)
4062}
4063
4064#[cfg(test)]
4065mod tests {
4066    use super::*;
4067    use std::process::Command;
4068    use tempfile::TempDir;
4069
4070    fn create_test_repo() -> Result<(TempDir, std::path::PathBuf)> {
4071        let temp_dir = TempDir::new()
4072            .map_err(|e| CascadeError::config(format!("Failed to create temp directory: {e}")))?;
4073        let repo_path = temp_dir.path().to_path_buf();
4074
4075        // Initialize git repository
4076        let output = Command::new("git")
4077            .args(["init"])
4078            .current_dir(&repo_path)
4079            .output()
4080            .map_err(|e| CascadeError::config(format!("Failed to run git init: {e}")))?;
4081        if !output.status.success() {
4082            return Err(CascadeError::config("Git init failed".to_string()));
4083        }
4084
4085        let output = Command::new("git")
4086            .args(["config", "user.name", "Test User"])
4087            .current_dir(&repo_path)
4088            .output()
4089            .map_err(|e| CascadeError::config(format!("Failed to run git config: {e}")))?;
4090        if !output.status.success() {
4091            return Err(CascadeError::config(
4092                "Git config user.name failed".to_string(),
4093            ));
4094        }
4095
4096        let output = Command::new("git")
4097            .args(["config", "user.email", "test@example.com"])
4098            .current_dir(&repo_path)
4099            .output()
4100            .map_err(|e| CascadeError::config(format!("Failed to run git config: {e}")))?;
4101        if !output.status.success() {
4102            return Err(CascadeError::config(
4103                "Git config user.email failed".to_string(),
4104            ));
4105        }
4106
4107        // Create initial commit
4108        std::fs::write(repo_path.join("README.md"), "# Test")
4109            .map_err(|e| CascadeError::config(format!("Failed to write file: {e}")))?;
4110        let output = Command::new("git")
4111            .args(["add", "."])
4112            .current_dir(&repo_path)
4113            .output()
4114            .map_err(|e| CascadeError::config(format!("Failed to run git add: {e}")))?;
4115        if !output.status.success() {
4116            return Err(CascadeError::config("Git add failed".to_string()));
4117        }
4118
4119        let output = Command::new("git")
4120            .args(["commit", "-m", "Initial commit"])
4121            .current_dir(&repo_path)
4122            .output()
4123            .map_err(|e| CascadeError::config(format!("Failed to run git commit: {e}")))?;
4124        if !output.status.success() {
4125            return Err(CascadeError::config("Git commit failed".to_string()));
4126        }
4127
4128        // Initialize cascade
4129        crate::config::initialize_repo(&repo_path, Some("https://test.bitbucket.com".to_string()))?;
4130
4131        Ok((temp_dir, repo_path))
4132    }
4133
4134    #[tokio::test]
4135    async fn test_create_stack() {
4136        let (temp_dir, repo_path) = match create_test_repo() {
4137            Ok(repo) => repo,
4138            Err(_) => {
4139                println!("Skipping test due to git environment setup failure");
4140                return;
4141            }
4142        };
4143        // IMPORTANT: temp_dir must stay in scope to prevent early cleanup of test directory
4144        let _ = &temp_dir;
4145
4146        // Note: create_test_repo() already initializes Cascade configuration
4147
4148        // Change to the repo directory (with proper error handling)
4149        let original_dir = env::current_dir().map_err(|_| "Failed to get current dir");
4150        match env::set_current_dir(&repo_path) {
4151            Ok(_) => {
4152                let result = create_stack(
4153                    "test-stack".to_string(),
4154                    None, // Use default branch
4155                    Some("Test description".to_string()),
4156                )
4157                .await;
4158
4159                // Restore original directory (best effort)
4160                if let Ok(orig) = original_dir {
4161                    let _ = env::set_current_dir(orig);
4162                }
4163
4164                assert!(
4165                    result.is_ok(),
4166                    "Stack creation should succeed in initialized repository"
4167                );
4168            }
4169            Err(_) => {
4170                // Skip test if we can't change directories (CI environment issue)
4171                println!("Skipping test due to directory access restrictions");
4172            }
4173        }
4174    }
4175
4176    #[tokio::test]
4177    async fn test_list_empty_stacks() {
4178        let (temp_dir, repo_path) = match create_test_repo() {
4179            Ok(repo) => repo,
4180            Err(_) => {
4181                println!("Skipping test due to git environment setup failure");
4182                return;
4183            }
4184        };
4185        // IMPORTANT: temp_dir must stay in scope to prevent early cleanup of test directory
4186        let _ = &temp_dir;
4187
4188        // Note: create_test_repo() already initializes Cascade configuration
4189
4190        // Change to the repo directory (with proper error handling)
4191        let original_dir = env::current_dir().map_err(|_| "Failed to get current dir");
4192        match env::set_current_dir(&repo_path) {
4193            Ok(_) => {
4194                let result = list_stacks(false, false, None).await;
4195
4196                // Restore original directory (best effort)
4197                if let Ok(orig) = original_dir {
4198                    let _ = env::set_current_dir(orig);
4199                }
4200
4201                assert!(
4202                    result.is_ok(),
4203                    "Listing stacks should succeed in initialized repository"
4204                );
4205            }
4206            Err(_) => {
4207                // Skip test if we can't change directories (CI environment issue)
4208                println!("Skipping test due to directory access restrictions");
4209            }
4210        }
4211    }
4212
4213    // Tests for squashing functionality
4214
4215    #[test]
4216    fn test_extract_feature_from_wip_basic() {
4217        let messages = vec![
4218            "WIP: add authentication".to_string(),
4219            "WIP: implement login flow".to_string(),
4220        ];
4221
4222        let result = extract_feature_from_wip(&messages);
4223        assert_eq!(result, "Add authentication");
4224    }
4225
4226    #[test]
4227    fn test_extract_feature_from_wip_capitalize() {
4228        let messages = vec!["WIP: fix user validation bug".to_string()];
4229
4230        let result = extract_feature_from_wip(&messages);
4231        assert_eq!(result, "Fix user validation bug");
4232    }
4233
4234    #[test]
4235    fn test_extract_feature_from_wip_fallback() {
4236        let messages = vec![
4237            "WIP user interface changes".to_string(),
4238            "wip: css styling".to_string(),
4239        ];
4240
4241        let result = extract_feature_from_wip(&messages);
4242        // Should create a fallback message since no "WIP:" prefix found
4243        assert!(result.contains("Implement") || result.contains("Squashed") || result.len() > 5);
4244    }
4245
4246    #[test]
4247    fn test_extract_feature_from_wip_empty() {
4248        let messages = vec![];
4249
4250        let result = extract_feature_from_wip(&messages);
4251        assert_eq!(result, "Squashed 0 commits");
4252    }
4253
4254    #[test]
4255    fn test_extract_feature_from_wip_short_message() {
4256        let messages = vec!["WIP: x".to_string()]; // Too short
4257
4258        let result = extract_feature_from_wip(&messages);
4259        assert!(result.starts_with("Implement") || result.contains("Squashed"));
4260    }
4261
4262    // Integration tests for squashing that don't require real git commits
4263
4264    #[test]
4265    fn test_squash_message_final_strategy() {
4266        // This test would need real git2::Commit objects, so we'll test the logic indirectly
4267        // through the extract_feature_from_wip function which handles the core logic
4268
4269        let messages = [
4270            "Final: implement user authentication system".to_string(),
4271            "WIP: add tests".to_string(),
4272            "WIP: fix validation".to_string(),
4273        ];
4274
4275        // Test that we can identify final commits
4276        assert!(messages[0].starts_with("Final:"));
4277
4278        // Test message extraction
4279        let extracted = messages[0].trim_start_matches("Final:").trim();
4280        assert_eq!(extracted, "implement user authentication system");
4281    }
4282
4283    #[test]
4284    fn test_squash_message_wip_detection() {
4285        let messages = [
4286            "WIP: start feature".to_string(),
4287            "WIP: continue work".to_string(),
4288            "WIP: almost done".to_string(),
4289            "Regular commit message".to_string(),
4290        ];
4291
4292        let wip_count = messages
4293            .iter()
4294            .filter(|m| {
4295                m.to_lowercase().starts_with("wip") || m.to_lowercase().contains("work in progress")
4296            })
4297            .count();
4298
4299        assert_eq!(wip_count, 3); // Should detect 3 WIP commits
4300        assert!(wip_count > messages.len() / 2); // Majority are WIP
4301
4302        // Should find the non-WIP message
4303        let non_wip: Vec<&String> = messages
4304            .iter()
4305            .filter(|m| {
4306                !m.to_lowercase().starts_with("wip")
4307                    && !m.to_lowercase().contains("work in progress")
4308            })
4309            .collect();
4310
4311        assert_eq!(non_wip.len(), 1);
4312        assert_eq!(non_wip[0], "Regular commit message");
4313    }
4314
4315    #[test]
4316    fn test_squash_message_all_wip() {
4317        let messages = vec![
4318            "WIP: add feature A".to_string(),
4319            "WIP: add feature B".to_string(),
4320            "WIP: finish implementation".to_string(),
4321        ];
4322
4323        let result = extract_feature_from_wip(&messages);
4324        // Should use the first message as the main feature
4325        assert_eq!(result, "Add feature A");
4326    }
4327
4328    #[test]
4329    fn test_squash_message_edge_cases() {
4330        // Test empty messages
4331        let empty_messages: Vec<String> = vec![];
4332        let result = extract_feature_from_wip(&empty_messages);
4333        assert_eq!(result, "Squashed 0 commits");
4334
4335        // Test messages with only whitespace
4336        let whitespace_messages = vec!["   ".to_string(), "\t\n".to_string()];
4337        let result = extract_feature_from_wip(&whitespace_messages);
4338        assert!(result.contains("Squashed") || result.contains("Implement"));
4339
4340        // Test case sensitivity
4341        let mixed_case = vec!["wip: Add Feature".to_string()];
4342        let result = extract_feature_from_wip(&mixed_case);
4343        assert_eq!(result, "Add Feature");
4344    }
4345
4346    // Tests for auto-land functionality
4347
4348    #[tokio::test]
4349    async fn test_auto_land_wrapper() {
4350        // Test that auto_land_stack correctly calls land_stack with auto=true
4351        let (temp_dir, repo_path) = match create_test_repo() {
4352            Ok(repo) => repo,
4353            Err(_) => {
4354                println!("Skipping test due to git environment setup failure");
4355                return;
4356            }
4357        };
4358        // IMPORTANT: temp_dir must stay in scope to prevent early cleanup of test directory
4359        let _ = &temp_dir;
4360
4361        // Initialize cascade in the test repo
4362        crate::config::initialize_repo(&repo_path, Some("https://test.bitbucket.com".to_string()))
4363            .expect("Failed to initialize Cascade in test repo");
4364
4365        let original_dir = env::current_dir().map_err(|_| "Failed to get current dir");
4366        match env::set_current_dir(&repo_path) {
4367            Ok(_) => {
4368                // Create a stack first
4369                let result = create_stack(
4370                    "test-stack".to_string(),
4371                    None,
4372                    Some("Test stack for auto-land".to_string()),
4373                )
4374                .await;
4375
4376                if let Ok(orig) = original_dir {
4377                    let _ = env::set_current_dir(orig);
4378                }
4379
4380                // For now, just test that the function can be called without panic
4381                // (It will fail due to missing Bitbucket config, but that's expected)
4382                assert!(
4383                    result.is_ok(),
4384                    "Stack creation should succeed in initialized repository"
4385                );
4386            }
4387            Err(_) => {
4388                println!("Skipping test due to directory access restrictions");
4389            }
4390        }
4391    }
4392
4393    #[test]
4394    fn test_auto_land_action_enum() {
4395        // Test that AutoLand action is properly defined
4396        use crate::cli::commands::stack::StackAction;
4397
4398        // This ensures the AutoLand variant exists and has the expected fields
4399        let _action = StackAction::AutoLand {
4400            force: false,
4401            dry_run: true,
4402            wait_for_builds: true,
4403            strategy: Some(MergeStrategyArg::Squash),
4404            build_timeout: 1800,
4405        };
4406
4407        // Test passes if we reach this point without errors
4408    }
4409
4410    #[test]
4411    fn test_merge_strategy_conversion() {
4412        // Test that MergeStrategyArg converts properly
4413        let squash_strategy = MergeStrategyArg::Squash;
4414        let merge_strategy: crate::bitbucket::pull_request::MergeStrategy = squash_strategy.into();
4415
4416        match merge_strategy {
4417            crate::bitbucket::pull_request::MergeStrategy::Squash => {
4418                // Correct conversion
4419            }
4420            _ => unreachable!("SquashStrategyArg only has Squash variant"),
4421        }
4422
4423        let merge_strategy = MergeStrategyArg::Merge;
4424        let converted: crate::bitbucket::pull_request::MergeStrategy = merge_strategy.into();
4425
4426        match converted {
4427            crate::bitbucket::pull_request::MergeStrategy::Merge => {
4428                // Correct conversion
4429            }
4430            _ => unreachable!("MergeStrategyArg::Merge maps to MergeStrategy::Merge"),
4431        }
4432    }
4433
4434    #[test]
4435    fn test_auto_merge_conditions_structure() {
4436        // Test that AutoMergeConditions can be created with expected values
4437        use std::time::Duration;
4438
4439        let conditions = crate::bitbucket::pull_request::AutoMergeConditions {
4440            merge_strategy: crate::bitbucket::pull_request::MergeStrategy::Squash,
4441            wait_for_builds: true,
4442            build_timeout: Duration::from_secs(1800),
4443            allowed_authors: None,
4444        };
4445
4446        // Verify the conditions are set as expected for auto-land
4447        assert!(conditions.wait_for_builds);
4448        assert_eq!(conditions.build_timeout.as_secs(), 1800);
4449        assert!(conditions.allowed_authors.is_none());
4450        assert!(matches!(
4451            conditions.merge_strategy,
4452            crate::bitbucket::pull_request::MergeStrategy::Squash
4453        ));
4454    }
4455
4456    #[test]
4457    fn test_polling_constants() {
4458        // Test that polling frequency is documented and reasonable
4459        use std::time::Duration;
4460
4461        // The polling frequency should be 30 seconds as mentioned in documentation
4462        let expected_polling_interval = Duration::from_secs(30);
4463
4464        // Verify it's a reasonable value (not too frequent, not too slow)
4465        assert!(expected_polling_interval.as_secs() >= 10); // At least 10 seconds
4466        assert!(expected_polling_interval.as_secs() <= 60); // At most 1 minute
4467        assert_eq!(expected_polling_interval.as_secs(), 30); // Exactly 30 seconds
4468    }
4469
4470    #[test]
4471    fn test_build_timeout_defaults() {
4472        // Verify build timeout default is reasonable
4473        const DEFAULT_TIMEOUT: u64 = 1800; // 30 minutes
4474        assert_eq!(DEFAULT_TIMEOUT, 1800);
4475        // Test that our default timeout value is within reasonable bounds
4476        let timeout_value = 1800u64;
4477        assert!(timeout_value >= 300); // At least 5 minutes
4478        assert!(timeout_value <= 3600); // At most 1 hour
4479    }
4480
4481    #[test]
4482    fn test_scattered_commit_detection() {
4483        use std::collections::HashSet;
4484
4485        // Test scattered commit detection logic
4486        let mut source_branches = HashSet::new();
4487        source_branches.insert("feature-branch-1".to_string());
4488        source_branches.insert("feature-branch-2".to_string());
4489        source_branches.insert("feature-branch-3".to_string());
4490
4491        // Single branch should not trigger warning
4492        let single_branch = HashSet::from(["main".to_string()]);
4493        assert_eq!(single_branch.len(), 1);
4494
4495        // Multiple branches should trigger warning
4496        assert!(source_branches.len() > 1);
4497        assert_eq!(source_branches.len(), 3);
4498
4499        // Verify branch names are preserved correctly
4500        assert!(source_branches.contains("feature-branch-1"));
4501        assert!(source_branches.contains("feature-branch-2"));
4502        assert!(source_branches.contains("feature-branch-3"));
4503    }
4504
4505    #[test]
4506    fn test_source_branch_tracking() {
4507        // Test that source branch tracking correctly handles different scenarios
4508
4509        // Same branch should be consistent
4510        let branch_a = "feature-work";
4511        let branch_b = "feature-work";
4512        assert_eq!(branch_a, branch_b);
4513
4514        // Different branches should be detected
4515        let branch_1 = "feature-ui";
4516        let branch_2 = "feature-api";
4517        assert_ne!(branch_1, branch_2);
4518
4519        // Branch naming patterns
4520        assert!(branch_1.starts_with("feature-"));
4521        assert!(branch_2.starts_with("feature-"));
4522    }
4523
4524    // Tests for new default behavior (removing --all flag)
4525
4526    #[tokio::test]
4527    async fn test_push_default_behavior() {
4528        // Test the push_to_stack function structure and error handling in an isolated environment
4529        let (temp_dir, repo_path) = match create_test_repo() {
4530            Ok(repo) => repo,
4531            Err(_) => {
4532                println!("Skipping test due to git environment setup failure");
4533                return;
4534            }
4535        };
4536        // IMPORTANT: temp_dir must stay in scope to prevent early cleanup of test directory
4537        let _ = &temp_dir;
4538
4539        // Verify directory exists before changing to it
4540        if !repo_path.exists() {
4541            println!("Skipping test due to temporary directory creation issue");
4542            return;
4543        }
4544
4545        // Change to the test repository directory to ensure isolation
4546        let original_dir = env::current_dir().map_err(|_| "Failed to get current dir");
4547
4548        match env::set_current_dir(&repo_path) {
4549            Ok(_) => {
4550                // Test that push_to_stack properly handles the case when no stack is active
4551                let result = push_to_stack(
4552                    None,  // branch
4553                    None,  // message
4554                    None,  // commit
4555                    None,  // since
4556                    None,  // commits
4557                    None,  // squash
4558                    None,  // squash_since
4559                    false, // auto_branch
4560                    false, // allow_base_branch
4561                    false, // dry_run
4562                )
4563                .await;
4564
4565                // Restore original directory (best effort)
4566                if let Ok(orig) = original_dir {
4567                    let _ = env::set_current_dir(orig);
4568                }
4569
4570                // Should fail gracefully with appropriate error message when no stack is active
4571                match &result {
4572                    Err(e) => {
4573                        let error_msg = e.to_string();
4574                        // This is the expected behavior - no active stack should produce this error
4575                        assert!(
4576                            error_msg.contains("No active stack")
4577                                || error_msg.contains("config")
4578                                || error_msg.contains("current directory")
4579                                || error_msg.contains("Not a git repository")
4580                                || error_msg.contains("could not find repository"),
4581                            "Expected 'No active stack' or repository error, got: {error_msg}"
4582                        );
4583                    }
4584                    Ok(_) => {
4585                        // If it somehow succeeds, that's also fine (e.g., if environment is set up differently)
4586                        println!(
4587                            "Push succeeded unexpectedly - test environment may have active stack"
4588                        );
4589                    }
4590                }
4591            }
4592            Err(_) => {
4593                // Skip test if we can't change directories (CI environment issue)
4594                println!("Skipping test due to directory access restrictions");
4595            }
4596        }
4597
4598        // Verify we can construct the command structure correctly
4599        let push_action = StackAction::Push {
4600            branch: None,
4601            message: None,
4602            commit: None,
4603            since: None,
4604            commits: None,
4605            squash: None,
4606            squash_since: None,
4607            auto_branch: false,
4608            allow_base_branch: false,
4609            dry_run: false,
4610        };
4611
4612        assert!(matches!(
4613            push_action,
4614            StackAction::Push {
4615                branch: None,
4616                message: None,
4617                commit: None,
4618                since: None,
4619                commits: None,
4620                squash: None,
4621                squash_since: None,
4622                auto_branch: false,
4623                allow_base_branch: false,
4624                dry_run: false
4625            }
4626        ));
4627    }
4628
4629    #[tokio::test]
4630    async fn test_submit_default_behavior() {
4631        // Test the submit_entry function structure and error handling in an isolated environment
4632        let (temp_dir, repo_path) = match create_test_repo() {
4633            Ok(repo) => repo,
4634            Err(_) => {
4635                println!("Skipping test due to git environment setup failure");
4636                return;
4637            }
4638        };
4639        // IMPORTANT: temp_dir must stay in scope to prevent early cleanup of test directory
4640        let _ = &temp_dir;
4641
4642        // Verify directory exists before changing to it
4643        if !repo_path.exists() {
4644            println!("Skipping test due to temporary directory creation issue");
4645            return;
4646        }
4647
4648        // Change to the test repository directory to ensure isolation
4649        let original_dir = match env::current_dir() {
4650            Ok(dir) => dir,
4651            Err(_) => {
4652                println!("Skipping test due to current directory access restrictions");
4653                return;
4654            }
4655        };
4656
4657        match env::set_current_dir(&repo_path) {
4658            Ok(_) => {
4659                // Test that submit_entry properly handles the case when no stack is active
4660                let result = submit_entry(
4661                    None,  // entry (should default to all unsubmitted)
4662                    None,  // title
4663                    None,  // description
4664                    None,  // range
4665                    false, // draft
4666                    true,  // open
4667                )
4668                .await;
4669
4670                // Restore original directory
4671                let _ = env::set_current_dir(original_dir);
4672
4673                // Should fail gracefully with appropriate error message when no stack is active
4674                match &result {
4675                    Err(e) => {
4676                        let error_msg = e.to_string();
4677                        // This is the expected behavior - no active stack should produce this error
4678                        assert!(
4679                            error_msg.contains("No active stack")
4680                                || error_msg.contains("config")
4681                                || error_msg.contains("current directory")
4682                                || error_msg.contains("Not a git repository")
4683                                || error_msg.contains("could not find repository"),
4684                            "Expected 'No active stack' or repository error, got: {error_msg}"
4685                        );
4686                    }
4687                    Ok(_) => {
4688                        // If it somehow succeeds, that's also fine (e.g., if environment is set up differently)
4689                        println!("Submit succeeded unexpectedly - test environment may have active stack");
4690                    }
4691                }
4692            }
4693            Err(_) => {
4694                // Skip test if we can't change directories (CI environment issue)
4695                println!("Skipping test due to directory access restrictions");
4696            }
4697        }
4698
4699        // Verify we can construct the command structure correctly
4700        let submit_action = StackAction::Submit {
4701            entry: None,
4702            title: None,
4703            description: None,
4704            range: None,
4705            draft: true, // Default changed to true
4706            open: true,
4707        };
4708
4709        assert!(matches!(
4710            submit_action,
4711            StackAction::Submit {
4712                entry: None,
4713                title: None,
4714                description: None,
4715                range: None,
4716                draft: true, // Default changed to true
4717                open: true
4718            }
4719        ));
4720    }
4721
4722    #[test]
4723    fn test_targeting_options_still_work() {
4724        // Test that specific targeting options still work correctly
4725
4726        // Test commit list parsing
4727        let commits = "abc123,def456,ghi789";
4728        let parsed: Vec<&str> = commits.split(',').map(|s| s.trim()).collect();
4729        assert_eq!(parsed.len(), 3);
4730        assert_eq!(parsed[0], "abc123");
4731        assert_eq!(parsed[1], "def456");
4732        assert_eq!(parsed[2], "ghi789");
4733
4734        // Test range parsing would work
4735        let range = "1-3";
4736        assert!(range.contains('-'));
4737        let parts: Vec<&str> = range.split('-').collect();
4738        assert_eq!(parts.len(), 2);
4739
4740        // Test since reference pattern
4741        let since_ref = "HEAD~3";
4742        assert!(since_ref.starts_with("HEAD"));
4743        assert!(since_ref.contains('~'));
4744    }
4745
4746    #[test]
4747    fn test_command_flow_logic() {
4748        // These just test the command structure exists
4749        assert!(matches!(
4750            StackAction::Push {
4751                branch: None,
4752                message: None,
4753                commit: None,
4754                since: None,
4755                commits: None,
4756                squash: None,
4757                squash_since: None,
4758                auto_branch: false,
4759                allow_base_branch: false,
4760                dry_run: false
4761            },
4762            StackAction::Push { .. }
4763        ));
4764
4765        assert!(matches!(
4766            StackAction::Submit {
4767                entry: None,
4768                title: None,
4769                description: None,
4770                range: None,
4771                draft: false,
4772                open: true
4773            },
4774            StackAction::Submit { .. }
4775        ));
4776    }
4777
4778    #[tokio::test]
4779    async fn test_deactivate_command_structure() {
4780        // Test that deactivate command structure exists and can be constructed
4781        let deactivate_action = StackAction::Deactivate { force: false };
4782
4783        // Verify it matches the expected pattern
4784        assert!(matches!(
4785            deactivate_action,
4786            StackAction::Deactivate { force: false }
4787        ));
4788
4789        // Test with force flag
4790        let force_deactivate = StackAction::Deactivate { force: true };
4791        assert!(matches!(
4792            force_deactivate,
4793            StackAction::Deactivate { force: true }
4794        ));
4795    }
4796}