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