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