cascade_cli/cli/commands/
stack.rs

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