cascade_cli/cli/commands/
stack.rs

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