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