cascade_cli/cli/commands/
stack.rs

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