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