cascade_cli/cli/commands/
stack.rs

1use crate::bitbucket::BitbucketIntegration;
2use crate::cli::output::Output;
3use crate::errors::{CascadeError, Result};
4use crate::git::{find_repository_root, GitRepository};
5use crate::stack::{StackManager, StackStatus};
6use clap::{Subcommand, ValueEnum};
7use indicatif::{ProgressBar, ProgressStyle};
8use std::env;
9use std::io::{self, Write};
10use tracing::{info, warn};
11
12/// CLI argument version of RebaseStrategy
13#[derive(ValueEnum, Clone, Debug)]
14pub enum RebaseStrategyArg {
15    /// Create new branches with version suffixes
16    BranchVersioning,
17    /// Use cherry-pick to apply commits
18    CherryPick,
19    /// Create merge commits
20    ThreeWayMerge,
21    /// Interactive rebase
22    Interactive,
23}
24
25#[derive(ValueEnum, Clone, Debug)]
26pub enum MergeStrategyArg {
27    /// Create a merge commit
28    Merge,
29    /// Squash all commits into one
30    Squash,
31    /// Fast-forward merge when possible
32    FastForward,
33}
34
35impl From<MergeStrategyArg> for crate::bitbucket::pull_request::MergeStrategy {
36    fn from(arg: MergeStrategyArg) -> Self {
37        match arg {
38            MergeStrategyArg::Merge => Self::Merge,
39            MergeStrategyArg::Squash => Self::Squash,
40            MergeStrategyArg::FastForward => Self::FastForward,
41        }
42    }
43}
44
45#[derive(Debug, Subcommand)]
46pub enum StackAction {
47    /// Create a new stack
48    Create {
49        /// Name of the stack
50        name: String,
51        /// Base branch for the stack
52        #[arg(long, short)]
53        base: Option<String>,
54        /// Description of the stack
55        #[arg(long, short)]
56        description: Option<String>,
57    },
58
59    /// List all stacks
60    List {
61        /// Show detailed information
62        #[arg(long, short)]
63        verbose: bool,
64        /// Show only active stack
65        #[arg(long)]
66        active: bool,
67        /// Output format (name, id, status)
68        #[arg(long)]
69        format: Option<String>,
70    },
71
72    /// Switch to a different stack
73    Switch {
74        /// Name of the stack to switch to
75        name: String,
76    },
77
78    /// Deactivate the current stack (turn off stack mode)
79    Deactivate {
80        /// Force deactivation without confirmation
81        #[arg(long)]
82        force: bool,
83    },
84
85    /// Show the current stack status  
86    Show {
87        /// Show detailed pull request information
88        #[arg(short, long)]
89        verbose: bool,
90        /// Show mergability status for all PRs
91        #[arg(short, long)]
92        mergeable: bool,
93    },
94
95    /// Push current commit to the top of the stack
96    Push {
97        /// Branch name for this commit
98        #[arg(long, short)]
99        branch: Option<String>,
100        /// Commit message (if creating a new commit)
101        #[arg(long, short)]
102        message: Option<String>,
103        /// Use specific commit hash instead of HEAD
104        #[arg(long)]
105        commit: Option<String>,
106        /// Push commits since this reference (e.g., HEAD~3)
107        #[arg(long)]
108        since: Option<String>,
109        /// Push multiple specific commits (comma-separated)
110        #[arg(long)]
111        commits: Option<String>,
112        /// Squash unpushed commits before pushing (optional: specify count)
113        #[arg(long, num_args = 0..=1, default_missing_value = "0")]
114        squash: Option<usize>,
115        /// Squash all commits since this reference (e.g., HEAD~5)
116        #[arg(long)]
117        squash_since: Option<String>,
118        /// Auto-create feature branch when pushing from base branch
119        #[arg(long)]
120        auto_branch: bool,
121        /// Allow pushing commits from base branch (not recommended)
122        #[arg(long)]
123        allow_base_branch: bool,
124        /// Show what would be pushed without actually pushing
125        #[arg(long)]
126        dry_run: bool,
127    },
128
129    /// Pop the top commit from the stack
130    Pop {
131        /// Keep the branch (don't delete it)
132        #[arg(long)]
133        keep_branch: bool,
134    },
135
136    /// Submit a stack entry for review
137    Submit {
138        /// Stack entry number (1-based, defaults to all unsubmitted)
139        entry: Option<usize>,
140        /// Pull request title
141        #[arg(long, short)]
142        title: Option<String>,
143        /// Pull request description
144        #[arg(long, short)]
145        description: Option<String>,
146        /// Submit range of entries (e.g., "1-3" or "2,4,6")
147        #[arg(long)]
148        range: Option<String>,
149        /// Create draft pull requests (can be edited later)
150        #[arg(long)]
151        draft: bool,
152    },
153
154    /// Check status of all pull requests in a stack
155    Status {
156        /// Name of the stack (defaults to active stack)
157        name: Option<String>,
158    },
159
160    /// List all pull requests for the repository
161    Prs {
162        /// Filter by state (open, merged, declined)
163        #[arg(long)]
164        state: Option<String>,
165        /// Show detailed information
166        #[arg(long, short)]
167        verbose: bool,
168    },
169
170    /// Check stack status with remote repository (read-only)
171    Check {
172        /// Force check even if there are issues
173        #[arg(long)]
174        force: bool,
175    },
176
177    /// Sync stack with remote repository (pull + rebase + cleanup)
178    Sync {
179        /// Force sync even if there are conflicts
180        #[arg(long)]
181        force: bool,
182        /// Skip cleanup of merged branches
183        #[arg(long)]
184        skip_cleanup: bool,
185        /// Interactive mode for conflict resolution
186        #[arg(long, short)]
187        interactive: bool,
188    },
189
190    /// Rebase stack on updated base branch
191    Rebase {
192        /// Interactive rebase
193        #[arg(long, short)]
194        interactive: bool,
195        /// Target base branch (defaults to stack's base branch)
196        #[arg(long)]
197        onto: Option<String>,
198        /// Rebase strategy to use
199        #[arg(long, value_enum)]
200        strategy: Option<RebaseStrategyArg>,
201    },
202
203    /// Continue an in-progress rebase after resolving conflicts
204    ContinueRebase,
205
206    /// Abort an in-progress rebase
207    AbortRebase,
208
209    /// Show rebase status and conflict resolution guidance
210    RebaseStatus,
211
212    /// Delete a stack
213    Delete {
214        /// Name of the stack to delete
215        name: String,
216        /// Force deletion without confirmation
217        #[arg(long)]
218        force: bool,
219    },
220
221    /// Validate stack integrity and handle branch modifications
222    ///
223    /// Checks that stack branches match their expected commit hashes.
224    /// Detects when branches have been manually modified (extra commits added).
225    ///
226    /// Available --fix modes:
227    /// • incorporate: Update stack entry to include extra commits
228    /// • split: Create new stack entry for extra commits  
229    /// • reset: Remove extra commits (DESTRUCTIVE - loses work)
230    ///
231    /// Without --fix, runs interactively asking for each modification.
232    Validate {
233        /// Name of the stack (defaults to active stack)
234        name: Option<String>,
235        /// Auto-fix mode: incorporate, split, or reset
236        #[arg(long)]
237        fix: Option<String>,
238    },
239
240    /// Land (merge) approved stack entries
241    Land {
242        /// Stack entry number to land (1-based index, optional)
243        entry: Option<usize>,
244        /// Force land even with blocking issues (dangerous)
245        #[arg(short, long)]
246        force: bool,
247        /// Dry run - show what would be landed without doing it
248        #[arg(short, long)]
249        dry_run: bool,
250        /// Use server-side validation (safer, checks approvals/builds)
251        #[arg(long)]
252        auto: bool,
253        /// Wait for builds to complete before merging
254        #[arg(long)]
255        wait_for_builds: bool,
256        /// Merge strategy to use
257        #[arg(long, value_enum, default_value = "squash")]
258        strategy: Option<MergeStrategyArg>,
259        /// Maximum time to wait for builds (seconds)
260        #[arg(long, default_value = "1800")]
261        build_timeout: u64,
262    },
263
264    /// Auto-land all ready PRs (shorthand for land --auto)
265    AutoLand {
266        /// Force land even with blocking issues (dangerous)
267        #[arg(short, long)]
268        force: bool,
269        /// Dry run - show what would be landed without doing it
270        #[arg(short, long)]
271        dry_run: bool,
272        /// Wait for builds to complete before merging
273        #[arg(long)]
274        wait_for_builds: bool,
275        /// Merge strategy to use
276        #[arg(long, value_enum, default_value = "squash")]
277        strategy: Option<MergeStrategyArg>,
278        /// Maximum time to wait for builds (seconds)
279        #[arg(long, default_value = "1800")]
280        build_timeout: u64,
281    },
282
283    /// List pull requests from Bitbucket
284    ListPrs {
285        /// Filter by state (open, merged, declined)
286        #[arg(short, long)]
287        state: Option<String>,
288        /// Show detailed information
289        #[arg(short, long)]
290        verbose: bool,
291    },
292
293    /// Continue an in-progress land operation after resolving conflicts
294    ContinueLand,
295
296    /// Abort an in-progress land operation  
297    AbortLand,
298
299    /// Show status of in-progress land operation
300    LandStatus,
301
302    /// Repair data consistency issues in stack metadata
303    Repair,
304}
305
306pub async fn run(action: StackAction) -> Result<()> {
307    match action {
308        StackAction::Create {
309            name,
310            base,
311            description,
312        } => create_stack(name, base, description).await,
313        StackAction::List {
314            verbose,
315            active,
316            format,
317        } => list_stacks(verbose, active, format).await,
318        StackAction::Switch { name } => switch_stack(name).await,
319        StackAction::Deactivate { force } => deactivate_stack(force).await,
320        StackAction::Show { verbose, mergeable } => show_stack(verbose, mergeable).await,
321        StackAction::Push {
322            branch,
323            message,
324            commit,
325            since,
326            commits,
327            squash,
328            squash_since,
329            auto_branch,
330            allow_base_branch,
331            dry_run,
332        } => {
333            push_to_stack(
334                branch,
335                message,
336                commit,
337                since,
338                commits,
339                squash,
340                squash_since,
341                auto_branch,
342                allow_base_branch,
343                dry_run,
344            )
345            .await
346        }
347        StackAction::Pop { keep_branch } => pop_from_stack(keep_branch).await,
348        StackAction::Submit {
349            entry,
350            title,
351            description,
352            range,
353            draft,
354        } => submit_entry(entry, title, description, range, draft).await,
355        StackAction::Status { name } => check_stack_status(name).await,
356        StackAction::Prs { state, verbose } => list_pull_requests(state, verbose).await,
357        StackAction::Check { force } => check_stack(force).await,
358        StackAction::Sync {
359            force,
360            skip_cleanup,
361            interactive,
362        } => sync_stack(force, skip_cleanup, interactive).await,
363        StackAction::Rebase {
364            interactive,
365            onto,
366            strategy,
367        } => rebase_stack(interactive, onto, strategy).await,
368        StackAction::ContinueRebase => continue_rebase().await,
369        StackAction::AbortRebase => abort_rebase().await,
370        StackAction::RebaseStatus => rebase_status().await,
371        StackAction::Delete { name, force } => delete_stack(name, force).await,
372        StackAction::Validate { name, fix } => validate_stack(name, fix).await,
373        StackAction::Land {
374            entry,
375            force,
376            dry_run,
377            auto,
378            wait_for_builds,
379            strategy,
380            build_timeout,
381        } => {
382            land_stack(
383                entry,
384                force,
385                dry_run,
386                auto,
387                wait_for_builds,
388                strategy,
389                build_timeout,
390            )
391            .await
392        }
393        StackAction::AutoLand {
394            force,
395            dry_run,
396            wait_for_builds,
397            strategy,
398            build_timeout,
399        } => auto_land_stack(force, dry_run, wait_for_builds, strategy, build_timeout).await,
400        StackAction::ListPrs { state, verbose } => list_pull_requests(state, verbose).await,
401        StackAction::ContinueLand => continue_land().await,
402        StackAction::AbortLand => abort_land().await,
403        StackAction::LandStatus => land_status().await,
404        StackAction::Repair => repair_stack_data().await,
405    }
406}
407
408// Public functions for shortcut commands
409pub async fn show(verbose: bool, mergeable: bool) -> Result<()> {
410    show_stack(verbose, mergeable).await
411}
412
413#[allow(clippy::too_many_arguments)]
414pub async fn push(
415    branch: Option<String>,
416    message: Option<String>,
417    commit: Option<String>,
418    since: Option<String>,
419    commits: Option<String>,
420    squash: Option<usize>,
421    squash_since: Option<String>,
422    auto_branch: bool,
423    allow_base_branch: bool,
424    dry_run: bool,
425) -> Result<()> {
426    push_to_stack(
427        branch,
428        message,
429        commit,
430        since,
431        commits,
432        squash,
433        squash_since,
434        auto_branch,
435        allow_base_branch,
436        dry_run,
437    )
438    .await
439}
440
441pub async fn pop(keep_branch: bool) -> Result<()> {
442    pop_from_stack(keep_branch).await
443}
444
445pub async fn land(
446    entry: Option<usize>,
447    force: bool,
448    dry_run: bool,
449    auto: bool,
450    wait_for_builds: bool,
451    strategy: Option<MergeStrategyArg>,
452    build_timeout: u64,
453) -> Result<()> {
454    land_stack(
455        entry,
456        force,
457        dry_run,
458        auto,
459        wait_for_builds,
460        strategy,
461        build_timeout,
462    )
463    .await
464}
465
466pub async fn autoland(
467    force: bool,
468    dry_run: bool,
469    wait_for_builds: bool,
470    strategy: Option<MergeStrategyArg>,
471    build_timeout: u64,
472) -> Result<()> {
473    auto_land_stack(force, dry_run, wait_for_builds, strategy, build_timeout).await
474}
475
476pub async fn sync(force: bool, skip_cleanup: bool, interactive: bool) -> Result<()> {
477    sync_stack(force, skip_cleanup, interactive).await
478}
479
480pub async fn rebase(
481    interactive: bool,
482    onto: Option<String>,
483    strategy: Option<RebaseStrategyArg>,
484) -> Result<()> {
485    rebase_stack(interactive, onto, strategy).await
486}
487
488pub async fn deactivate(force: bool) -> Result<()> {
489    deactivate_stack(force).await
490}
491
492pub async fn switch(name: String) -> Result<()> {
493    switch_stack(name).await
494}
495
496async fn create_stack(
497    name: String,
498    base: Option<String>,
499    description: Option<String>,
500) -> Result<()> {
501    let current_dir = env::current_dir()
502        .map_err(|e| CascadeError::config(format!("Could not get current directory: {e}")))?;
503
504    let repo_root = find_repository_root(&current_dir)
505        .map_err(|e| CascadeError::config(format!("Could not find git repository: {e}")))?;
506
507    let mut manager = StackManager::new(&repo_root)?;
508    let stack_id = manager.create_stack(name.clone(), base.clone(), description.clone())?;
509
510    // Get the created stack to check its working branch
511    let stack = manager
512        .get_stack(&stack_id)
513        .ok_or_else(|| CascadeError::config("Failed to get created stack"))?;
514
515    // Use the new output format
516    Output::stack_info(
517        &name,
518        &stack_id.to_string(),
519        &stack.base_branch,
520        stack.working_branch.as_deref(),
521        true, // is_active
522    );
523
524    if let Some(desc) = description {
525        Output::sub_item(format!("Description: {desc}"));
526    }
527
528    // Provide helpful guidance based on the working branch situation
529    if stack.working_branch.is_none() {
530        Output::warning(format!(
531            "You're currently on the base branch '{}'",
532            stack.base_branch
533        ));
534        Output::next_steps(&[
535            &format!("Create a feature branch: git checkout -b {name}"),
536            "Make changes and commit them",
537            "Run 'ca push' to add commits to this stack",
538        ]);
539    } else {
540        Output::next_steps(&[
541            "Make changes and commit them",
542            "Run 'ca push' to add commits to this stack",
543            "Use 'ca submit' when ready to create pull requests",
544        ]);
545    }
546
547    Ok(())
548}
549
550async fn list_stacks(verbose: bool, _active: bool, _format: Option<String>) -> Result<()> {
551    let current_dir = env::current_dir()
552        .map_err(|e| CascadeError::config(format!("Could not get current directory: {e}")))?;
553
554    let repo_root = find_repository_root(&current_dir)
555        .map_err(|e| CascadeError::config(format!("Could not find git repository: {e}")))?;
556
557    let manager = StackManager::new(&repo_root)?;
558    let stacks = manager.list_stacks();
559
560    if stacks.is_empty() {
561        Output::info("No stacks found. Create one with: ca stack create <name>");
562        return Ok(());
563    }
564
565    println!("📚 Stacks:");
566    for (stack_id, name, status, entry_count, active_marker) in stacks {
567        let status_icon = match status {
568            StackStatus::Clean => "✅",
569            StackStatus::Dirty => "🔄",
570            StackStatus::OutOfSync => "⚠️",
571            StackStatus::Conflicted => "❌",
572            StackStatus::Rebasing => "🔀",
573            StackStatus::NeedsSync => "🔄",
574            StackStatus::Corrupted => "💥",
575        };
576
577        let active_indicator = if active_marker.is_some() {
578            " (active)"
579        } else {
580            ""
581        };
582
583        // Get the actual stack object to access branch information
584        let stack = manager.get_stack(&stack_id);
585
586        if verbose {
587            println!("  {status_icon} {name} [{entry_count}]{active_indicator}");
588            println!("    ID: {stack_id}");
589            if let Some(stack_meta) = manager.get_stack_metadata(&stack_id) {
590                println!("    Base: {}", stack_meta.base_branch);
591                if let Some(desc) = &stack_meta.description {
592                    println!("    Description: {desc}");
593                }
594                println!(
595                    "    Commits: {} total, {} submitted",
596                    stack_meta.total_commits, stack_meta.submitted_commits
597                );
598                if stack_meta.has_conflicts {
599                    println!("    ⚠️  Has conflicts");
600                }
601            }
602
603            // Show branch information in verbose mode
604            if let Some(stack_obj) = stack {
605                if !stack_obj.entries.is_empty() {
606                    println!("    Branches:");
607                    for (i, entry) in stack_obj.entries.iter().enumerate() {
608                        let entry_num = i + 1;
609                        let submitted_indicator = if entry.is_submitted { "📤" } else { "📝" };
610                        let branch_name = &entry.branch;
611                        let short_message = if entry.message.len() > 40 {
612                            format!("{}...", &entry.message[..37])
613                        } else {
614                            entry.message.clone()
615                        };
616                        println!("      {entry_num}. {submitted_indicator} {branch_name} - {short_message}");
617                    }
618                }
619            }
620            println!();
621        } else {
622            // Show compact branch info in non-verbose mode
623            let branch_info = if let Some(stack_obj) = stack {
624                if stack_obj.entries.is_empty() {
625                    String::new()
626                } else if stack_obj.entries.len() == 1 {
627                    format!(" → {}", stack_obj.entries[0].branch)
628                } else {
629                    let first_branch = &stack_obj.entries[0].branch;
630                    let last_branch = &stack_obj.entries.last().unwrap().branch;
631                    format!(" → {first_branch} … {last_branch}")
632                }
633            } else {
634                String::new()
635            };
636
637            println!("  {status_icon} {name} [{entry_count}]{branch_info}{active_indicator}");
638        }
639    }
640
641    if !verbose {
642        println!("\nUse --verbose for more details");
643    }
644
645    Ok(())
646}
647
648async fn switch_stack(name: String) -> Result<()> {
649    let current_dir = env::current_dir()
650        .map_err(|e| CascadeError::config(format!("Could not get current directory: {e}")))?;
651
652    let repo_root = find_repository_root(&current_dir)
653        .map_err(|e| CascadeError::config(format!("Could not find git repository: {e}")))?;
654
655    let mut manager = StackManager::new(&repo_root)?;
656    let repo = GitRepository::open(&repo_root)?;
657
658    // Get stack information before switching
659    let stack = manager
660        .get_stack_by_name(&name)
661        .ok_or_else(|| CascadeError::config(format!("Stack '{name}' not found")))?;
662
663    // Determine the target branch and provide appropriate messaging
664    if let Some(working_branch) = &stack.working_branch {
665        // Stack has a working branch - try to switch to it
666        let current_branch = repo.get_current_branch().ok();
667
668        if current_branch.as_ref() != Some(working_branch) {
669            Output::progress(format!(
670                "Switching to stack working branch: {working_branch}"
671            ));
672
673            // Check if target branch exists
674            if repo.branch_exists(working_branch) {
675                match repo.checkout_branch(working_branch) {
676                    Ok(_) => {
677                        Output::success(format!("Checked out branch: {working_branch}"));
678                    }
679                    Err(e) => {
680                        Output::warning(format!("Failed to checkout '{working_branch}': {e}"));
681                        Output::sub_item("Stack activated but stayed on current branch");
682                        Output::sub_item(format!(
683                            "You can manually checkout with: git checkout {working_branch}"
684                        ));
685                    }
686                }
687            } else {
688                Output::warning(format!(
689                    "Stack working branch '{working_branch}' doesn't exist locally"
690                ));
691                Output::sub_item("Stack activated but stayed on current branch");
692                Output::sub_item(format!(
693                    "You may need to fetch from remote: git fetch origin {working_branch}"
694                ));
695            }
696        } else {
697            Output::success(format!("Already on stack working branch: {working_branch}"));
698        }
699    } else {
700        // No working branch - provide guidance
701        Output::warning(format!("Stack '{name}' has no working branch set"));
702        Output::sub_item(
703            "This typically happens when a stack was created while on the base branch",
704        );
705
706        Output::tip("To start working on this stack:");
707        Output::bullet(format!("Create a feature branch: git checkout -b {name}"));
708        Output::bullet("The stack will automatically track this as its working branch");
709        Output::bullet("Then use 'ca push' to add commits to the stack");
710
711        Output::sub_item(format!("Base branch: {}", stack.base_branch));
712    }
713
714    // Activate the stack (this will record the correct current branch)
715    manager.set_active_stack_by_name(&name)?;
716    Output::success(format!("Switched to stack '{name}'"));
717
718    Ok(())
719}
720
721async fn deactivate_stack(force: bool) -> Result<()> {
722    let current_dir = env::current_dir()
723        .map_err(|e| CascadeError::config(format!("Could not get current directory: {e}")))?;
724
725    let repo_root = find_repository_root(&current_dir)
726        .map_err(|e| CascadeError::config(format!("Could not find git repository: {e}")))?;
727
728    let mut manager = StackManager::new(&repo_root)?;
729
730    let active_stack = manager.get_active_stack();
731
732    if active_stack.is_none() {
733        Output::info("No active stack to deactivate");
734        return Ok(());
735    }
736
737    let stack_name = active_stack.unwrap().name.clone();
738
739    if !force {
740        Output::warning(format!(
741            "This will deactivate stack '{stack_name}' and return to normal Git workflow"
742        ));
743        Output::sub_item(format!(
744            "You can reactivate it later with 'ca stacks switch {stack_name}'"
745        ));
746        print!("   Continue? (y/N): ");
747
748        use std::io::{self, Write};
749        io::stdout().flush().unwrap();
750
751        let mut input = String::new();
752        io::stdin().read_line(&mut input).unwrap();
753
754        if !input.trim().to_lowercase().starts_with('y') {
755            Output::info("Cancelled deactivation");
756            return Ok(());
757        }
758    }
759
760    // Deactivate the stack
761    manager.set_active_stack(None)?;
762
763    Output::success(format!("Deactivated stack '{stack_name}'"));
764    Output::sub_item("Stack management is now OFF - you can use normal Git workflow");
765    Output::sub_item(format!("To reactivate: ca stacks switch {stack_name}"));
766
767    Ok(())
768}
769
770async fn show_stack(verbose: bool, show_mergeable: bool) -> Result<()> {
771    let current_dir = env::current_dir()
772        .map_err(|e| CascadeError::config(format!("Could not get current directory: {e}")))?;
773
774    let repo_root = find_repository_root(&current_dir)
775        .map_err(|e| CascadeError::config(format!("Could not find git repository: {e}")))?;
776
777    let stack_manager = StackManager::new(&repo_root)?;
778
779    // Get stack information first to avoid borrow conflicts
780    let (stack_id, stack_name, stack_base, stack_working, stack_entries) = {
781        let active_stack = stack_manager.get_active_stack().ok_or_else(|| {
782            CascadeError::config(
783                "No active stack. Use 'ca stacks create' or 'ca stacks switch' to select a stack"
784                    .to_string(),
785            )
786        })?;
787
788        (
789            active_stack.id,
790            active_stack.name.clone(),
791            active_stack.base_branch.clone(),
792            active_stack.working_branch.clone(),
793            active_stack.entries.clone(),
794        )
795    };
796
797    // 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    Output::progress(format!("Syncing stack '{stack_name}' with remote..."));
1933
1934    // Step 1: Pull latest changes from base branch
1935    Output::section(format!("Pulling latest changes from '{base_branch}'"));
1936
1937    // Checkout base branch first
1938    match git_repo.checkout_branch(&base_branch) {
1939        Ok(_) => {
1940            Output::sub_item(format!("Switched to '{base_branch}'"));
1941
1942            // Pull latest changes
1943            match git_repo.pull(&base_branch) {
1944                Ok(_) => {
1945                    Output::success("Successfully pulled latest changes");
1946                }
1947                Err(e) => {
1948                    if force {
1949                        Output::warning(format!("Pull failed: {e} (continuing due to --force)"));
1950                    } else {
1951                        Output::error(format!("Failed to pull latest changes: {e}"));
1952
1953                        // Provide diagnostic information for pull failures
1954                        Output::section("Sync Diagnostic Information");
1955
1956                        let error_str = e.to_string();
1957                        if error_str.contains("SSL") || error_str.contains("TLS") {
1958                            Output::bullet("SSL/TLS authentication issue detected");
1959                            Output::bullet("This is common with corporate Git servers");
1960                        }
1961
1962                        Output::tip("Solutions to try:");
1963                        Output::bullet("Test basic git authentication: git fetch origin");
1964                        Output::bullet("Use --force to skip pull and continue with rebase");
1965                        Output::bullet(format!(
1966                            "Try manual pull first: git pull origin {base_branch}"
1967                        ));
1968
1969                        Output::section("Quick Fix");
1970                        Output::command_example(
1971                            "ca sync --force    # Skip failed pull, continue with rebase",
1972                        );
1973
1974                        return Err(CascadeError::branch(format!(
1975                            "Failed to pull latest changes from '{base_branch}': {e}. Use --force to continue anyway."
1976                        )));
1977                    }
1978                }
1979            }
1980        }
1981        Err(e) => {
1982            if force {
1983                Output::warning(format!(
1984                    "Failed to checkout '{base_branch}': {e} (continuing due to --force)"
1985                ));
1986            } else {
1987                Output::error(format!(
1988                    "Failed to checkout base branch '{base_branch}': {e}"
1989                ));
1990                Output::tip("Use --force to bypass checkout issues and continue anyway");
1991                return Err(CascadeError::branch(format!(
1992                    "Failed to checkout base branch '{base_branch}': {e}. Use --force to continue anyway."
1993                )));
1994            }
1995        }
1996    }
1997
1998    // Step 2: Check if stack needs rebase
1999    Output::section("Checking if stack needs rebase");
2000
2001    let mut updated_stack_manager = StackManager::new(&repo_root)?;
2002    let stack_id = active_stack.id;
2003
2004    match updated_stack_manager.sync_stack(&stack_id) {
2005        Ok(_) => {
2006            // Check the updated status
2007            if let Some(updated_stack) = updated_stack_manager.get_stack(&stack_id) {
2008                match &updated_stack.status {
2009                    crate::stack::StackStatus::NeedsSync => {
2010                        Output::info(format!(
2011                            "Stack needs rebase due to new commits on '{base_branch}'"
2012                        ));
2013
2014                        // Step 3: Rebase the stack
2015                        Output::section(format!("Rebasing stack onto updated '{base_branch}'"));
2016
2017                        // Load configuration for Bitbucket integration
2018                        let config_dir = crate::config::get_repo_config_dir(&repo_root)?;
2019                        let config_path = config_dir.join("config.json");
2020                        let settings = crate::config::Settings::load_from_file(&config_path)?;
2021
2022                        let cascade_config = crate::config::CascadeConfig {
2023                            bitbucket: Some(settings.bitbucket.clone()),
2024                            git: settings.git.clone(),
2025                            auth: crate::config::AuthConfig::default(),
2026                            cascade: settings.cascade.clone(),
2027                        };
2028
2029                        // Use the existing rebase system
2030                        let options = crate::stack::RebaseOptions {
2031                            strategy: crate::stack::RebaseStrategy::BranchVersioning,
2032                            interactive,
2033                            target_base: Some(base_branch.clone()),
2034                            preserve_merges: true,
2035                            auto_resolve: !interactive,
2036                            max_retries: 3,
2037                            skip_pull: Some(true), // Skip pull since we already pulled above
2038                        };
2039
2040                        let mut rebase_manager = crate::stack::RebaseManager::new(
2041                            updated_stack_manager,
2042                            git_repo,
2043                            options,
2044                        );
2045
2046                        match rebase_manager.rebase_stack(&stack_id) {
2047                            Ok(result) => {
2048                                Output::success("Rebase completed successfully!");
2049
2050                                if !result.branch_mapping.is_empty() {
2051                                    Output::section("Updated branches:");
2052                                    for (old, new) in &result.branch_mapping {
2053                                        Output::bullet(format!("{old} → {new}"));
2054                                    }
2055
2056                                    // Update PRs if enabled
2057                                    if let Some(ref _bitbucket_config) = cascade_config.bitbucket {
2058                                        Output::progress("Updating pull requests...");
2059
2060                                        let integration_stack_manager =
2061                                            StackManager::new(&repo_root)?;
2062                                        let mut integration =
2063                                            crate::bitbucket::BitbucketIntegration::new(
2064                                                integration_stack_manager,
2065                                                cascade_config,
2066                                            )?;
2067
2068                                        match integration
2069                                            .update_prs_after_rebase(
2070                                                &stack_id,
2071                                                &result.branch_mapping,
2072                                            )
2073                                            .await
2074                                        {
2075                                            Ok(updated_prs) => {
2076                                                if !updated_prs.is_empty() {
2077                                                    Output::success(format!(
2078                                                        "Updated {} pull requests",
2079                                                        updated_prs.len()
2080                                                    ));
2081                                                }
2082                                            }
2083                                            Err(e) => {
2084                                                Output::warning(format!(
2085                                                    "Failed to update pull requests: {e}"
2086                                                ));
2087                                            }
2088                                        }
2089                                    }
2090                                }
2091                            }
2092                            Err(e) => {
2093                                Output::error(format!("Rebase failed: {e}"));
2094                                Output::tip("To resolve conflicts:");
2095                                Output::bullet("Fix conflicts in the affected files");
2096                                Output::bullet("Stage resolved files: git add <files>");
2097                                Output::bullet("Continue: ca stack continue-rebase");
2098                                return Err(e);
2099                            }
2100                        }
2101                    }
2102                    crate::stack::StackStatus::Clean => {
2103                        Output::success("Stack is already up to date");
2104                    }
2105                    other => {
2106                        Output::info(format!("Stack status: {other:?}"));
2107                    }
2108                }
2109            }
2110        }
2111        Err(e) => {
2112            if force {
2113                Output::warning(format!(
2114                    "Failed to check stack status: {e} (continuing due to --force)"
2115                ));
2116            } else {
2117                return Err(e);
2118            }
2119        }
2120    }
2121
2122    // Step 4: Cleanup merged branches (optional)
2123    if !skip_cleanup {
2124        Output::section("Checking for merged branches to clean up");
2125        // TODO: Implement merged branch cleanup
2126        // This would:
2127        // 1. Find branches that have been merged into base
2128        // 2. Ask user if they want to delete them
2129        // 3. Remove them from the stack metadata
2130        Output::info("Branch cleanup not yet implemented");
2131    } else {
2132        Output::info("Skipping branch cleanup");
2133    }
2134
2135    Output::success("Sync completed successfully!");
2136    Output::sub_item(format!("Base branch: {base_branch}"));
2137    Output::next_steps(&[
2138        "Review your updated stack: ca stack show",
2139        "Check PR status: ca stack status",
2140    ]);
2141
2142    Ok(())
2143}
2144
2145async fn rebase_stack(
2146    interactive: bool,
2147    onto: Option<String>,
2148    strategy: Option<RebaseStrategyArg>,
2149) -> Result<()> {
2150    let current_dir = env::current_dir()
2151        .map_err(|e| CascadeError::config(format!("Could not get current directory: {e}")))?;
2152
2153    let repo_root = find_repository_root(&current_dir)
2154        .map_err(|e| CascadeError::config(format!("Could not find git repository: {e}")))?;
2155
2156    let stack_manager = StackManager::new(&repo_root)?;
2157    let git_repo = GitRepository::open(&repo_root)?;
2158
2159    // Load configuration for potential Bitbucket integration
2160    let config_dir = crate::config::get_repo_config_dir(&repo_root)?;
2161    let config_path = config_dir.join("config.json");
2162    let settings = crate::config::Settings::load_from_file(&config_path)?;
2163
2164    // Create the main config structure
2165    let cascade_config = crate::config::CascadeConfig {
2166        bitbucket: Some(settings.bitbucket.clone()),
2167        git: settings.git.clone(),
2168        auth: crate::config::AuthConfig::default(),
2169        cascade: settings.cascade.clone(),
2170    };
2171
2172    // Get active stack
2173    let active_stack = stack_manager.get_active_stack().ok_or_else(|| {
2174        CascadeError::config("No active stack. Create a stack first with 'ca stack create'")
2175    })?;
2176    let stack_id = active_stack.id;
2177
2178    let active_stack = stack_manager
2179        .get_stack(&stack_id)
2180        .ok_or_else(|| CascadeError::config("Active stack not found"))?
2181        .clone();
2182
2183    if active_stack.entries.is_empty() {
2184        Output::info("Stack is empty. Nothing to rebase.");
2185        return Ok(());
2186    }
2187
2188    Output::progress(format!("Rebasing stack: {}", active_stack.name));
2189    Output::sub_item(format!("Base: {}", active_stack.base_branch));
2190
2191    // Determine rebase strategy
2192    let rebase_strategy = if let Some(cli_strategy) = strategy {
2193        match cli_strategy {
2194            RebaseStrategyArg::BranchVersioning => crate::stack::RebaseStrategy::BranchVersioning,
2195            RebaseStrategyArg::CherryPick => crate::stack::RebaseStrategy::CherryPick,
2196            RebaseStrategyArg::ThreeWayMerge => crate::stack::RebaseStrategy::ThreeWayMerge,
2197            RebaseStrategyArg::Interactive => crate::stack::RebaseStrategy::Interactive,
2198        }
2199    } else {
2200        // Use strategy from config
2201        match settings.cascade.default_sync_strategy.as_str() {
2202            "branch-versioning" => crate::stack::RebaseStrategy::BranchVersioning,
2203            "cherry-pick" => crate::stack::RebaseStrategy::CherryPick,
2204            "three-way-merge" => crate::stack::RebaseStrategy::ThreeWayMerge,
2205            "rebase" => crate::stack::RebaseStrategy::Interactive,
2206            _ => crate::stack::RebaseStrategy::BranchVersioning, // default fallback
2207        }
2208    };
2209
2210    // Create rebase options
2211    let options = crate::stack::RebaseOptions {
2212        strategy: rebase_strategy.clone(),
2213        interactive,
2214        target_base: onto,
2215        preserve_merges: true,
2216        auto_resolve: !interactive, // Auto-resolve unless interactive
2217        max_retries: 3,
2218        skip_pull: None, // Normal rebase should pull latest changes
2219    };
2220
2221    info!("   Strategy: {:?}", rebase_strategy);
2222    info!("   Interactive: {}", interactive);
2223    info!("   Target base: {:?}", options.target_base);
2224    info!("   Entries: {}", active_stack.entries.len());
2225
2226    // Check if there's already a rebase in progress
2227    let mut rebase_manager = crate::stack::RebaseManager::new(stack_manager, git_repo, options);
2228
2229    if rebase_manager.is_rebase_in_progress() {
2230        Output::warning("Rebase already in progress!");
2231        Output::tip("Use 'git status' to check the current state");
2232        Output::next_steps(&[
2233            "Run 'ca stack continue-rebase' to continue",
2234            "Run 'ca stack abort-rebase' to abort",
2235        ]);
2236        return Ok(());
2237    }
2238
2239    // Perform the rebase
2240    match rebase_manager.rebase_stack(&stack_id) {
2241        Ok(result) => {
2242            Output::success("Rebase completed!");
2243            Output::sub_item(result.get_summary());
2244
2245            if result.has_conflicts() {
2246                Output::warning(format!(
2247                    "{} conflicts were resolved",
2248                    result.conflicts.len()
2249                ));
2250                for conflict in &result.conflicts {
2251                    Output::bullet(&conflict[..8.min(conflict.len())]);
2252                }
2253            }
2254
2255            if !result.branch_mapping.is_empty() {
2256                Output::section("Branch mapping");
2257                for (old, new) in &result.branch_mapping {
2258                    Output::bullet(format!("{old} -> {new}"));
2259                }
2260
2261                // Handle PR updates if enabled
2262                if let Some(ref _bitbucket_config) = cascade_config.bitbucket {
2263                    // Create a new StackManager for the integration (since the original was moved)
2264                    let integration_stack_manager = StackManager::new(&repo_root)?;
2265                    let mut integration = BitbucketIntegration::new(
2266                        integration_stack_manager,
2267                        cascade_config.clone(),
2268                    )?;
2269
2270                    match integration
2271                        .update_prs_after_rebase(&stack_id, &result.branch_mapping)
2272                        .await
2273                    {
2274                        Ok(updated_prs) => {
2275                            if !updated_prs.is_empty() {
2276                                println!("   🔄 Preserved pull request history:");
2277                                for pr_update in updated_prs {
2278                                    println!("      ✅ {pr_update}");
2279                                }
2280                            }
2281                        }
2282                        Err(e) => {
2283                            eprintln!("   ⚠️  Failed to update pull requests: {e}");
2284                            eprintln!("      You may need to manually update PRs in Bitbucket");
2285                        }
2286                    }
2287                }
2288            }
2289
2290            println!(
2291                "   ✅ {} commits successfully rebased",
2292                result.success_count()
2293            );
2294
2295            // Show next steps
2296            if matches!(
2297                rebase_strategy,
2298                crate::stack::RebaseStrategy::BranchVersioning
2299            ) {
2300                println!("\n📝 Next steps:");
2301                if !result.branch_mapping.is_empty() {
2302                    println!("   1. ✅ New versioned branches have been created");
2303                    println!("   2. ✅ Pull requests have been updated automatically");
2304                    println!("   3. 🔍 Review the updated PRs in Bitbucket");
2305                    println!("   4. 🧪 Test your changes on the new branches");
2306                    println!(
2307                        "   5. 🗑️  Old branches are preserved for safety (can be deleted later)"
2308                    );
2309                } else {
2310                    println!("   1. Review the rebased stack");
2311                    println!("   2. Test your changes");
2312                    println!("   3. Submit new pull requests with 'ca stack submit'");
2313                }
2314            }
2315        }
2316        Err(e) => {
2317            warn!("❌ Rebase failed: {}", e);
2318            println!("💡 Tips for resolving rebase issues:");
2319            println!("   - Check for uncommitted changes with 'git status'");
2320            println!("   - Ensure base branch is up to date");
2321            println!("   - Try interactive mode: 'ca stack rebase --interactive'");
2322            return Err(e);
2323        }
2324    }
2325
2326    Ok(())
2327}
2328
2329async fn continue_rebase() -> Result<()> {
2330    let current_dir = env::current_dir()
2331        .map_err(|e| CascadeError::config(format!("Could not get current directory: {e}")))?;
2332
2333    let repo_root = find_repository_root(&current_dir)
2334        .map_err(|e| CascadeError::config(format!("Could not find git repository: {e}")))?;
2335
2336    let stack_manager = StackManager::new(&repo_root)?;
2337    let git_repo = crate::git::GitRepository::open(&repo_root)?;
2338    let options = crate::stack::RebaseOptions::default();
2339    let rebase_manager = crate::stack::RebaseManager::new(stack_manager, git_repo, options);
2340
2341    if !rebase_manager.is_rebase_in_progress() {
2342        println!("ℹ️  No rebase in progress");
2343        return Ok(());
2344    }
2345
2346    println!("🔄 Continuing rebase...");
2347    match rebase_manager.continue_rebase() {
2348        Ok(_) => {
2349            println!("✅ Rebase continued successfully");
2350            println!("   Check 'ca stack rebase-status' for current state");
2351        }
2352        Err(e) => {
2353            warn!("❌ Failed to continue rebase: {}", e);
2354            println!("💡 You may need to resolve conflicts first:");
2355            println!("   1. Edit conflicted files");
2356            println!("   2. Stage resolved files with 'git add'");
2357            println!("   3. Run 'ca stack continue-rebase' again");
2358        }
2359    }
2360
2361    Ok(())
2362}
2363
2364async fn abort_rebase() -> Result<()> {
2365    let current_dir = env::current_dir()
2366        .map_err(|e| CascadeError::config(format!("Could not get current directory: {e}")))?;
2367
2368    let repo_root = find_repository_root(&current_dir)
2369        .map_err(|e| CascadeError::config(format!("Could not find git repository: {e}")))?;
2370
2371    let stack_manager = StackManager::new(&repo_root)?;
2372    let git_repo = crate::git::GitRepository::open(&repo_root)?;
2373    let options = crate::stack::RebaseOptions::default();
2374    let rebase_manager = crate::stack::RebaseManager::new(stack_manager, git_repo, options);
2375
2376    if !rebase_manager.is_rebase_in_progress() {
2377        println!("ℹ️  No rebase in progress");
2378        return Ok(());
2379    }
2380
2381    println!("⚠️  Aborting rebase...");
2382    match rebase_manager.abort_rebase() {
2383        Ok(_) => {
2384            println!("✅ Rebase aborted successfully");
2385            println!("   Repository restored to pre-rebase state");
2386        }
2387        Err(e) => {
2388            warn!("❌ Failed to abort rebase: {}", e);
2389            println!("⚠️  You may need to manually clean up the repository state");
2390        }
2391    }
2392
2393    Ok(())
2394}
2395
2396async fn rebase_status() -> Result<()> {
2397    let current_dir = env::current_dir()
2398        .map_err(|e| CascadeError::config(format!("Could not get current directory: {e}")))?;
2399
2400    let repo_root = find_repository_root(&current_dir)
2401        .map_err(|e| CascadeError::config(format!("Could not find git repository: {e}")))?;
2402
2403    let stack_manager = StackManager::new(&repo_root)?;
2404    let git_repo = crate::git::GitRepository::open(&repo_root)?;
2405
2406    println!("📊 Rebase Status");
2407
2408    // Check if rebase is in progress by checking git state directly
2409    let git_dir = current_dir.join(".git");
2410    let rebase_in_progress = git_dir.join("REBASE_HEAD").exists()
2411        || git_dir.join("rebase-merge").exists()
2412        || git_dir.join("rebase-apply").exists();
2413
2414    if rebase_in_progress {
2415        println!("   Status: 🔄 Rebase in progress");
2416        println!(
2417            "   
2418📝 Actions available:"
2419        );
2420        println!("     - 'ca stack continue-rebase' to continue");
2421        println!("     - 'ca stack abort-rebase' to abort");
2422        println!("     - 'git status' to see conflicted files");
2423
2424        // Check for conflicts
2425        match git_repo.get_status() {
2426            Ok(statuses) => {
2427                let mut conflicts = Vec::new();
2428                for status in statuses.iter() {
2429                    if status.status().contains(git2::Status::CONFLICTED) {
2430                        if let Some(path) = status.path() {
2431                            conflicts.push(path.to_string());
2432                        }
2433                    }
2434                }
2435
2436                if !conflicts.is_empty() {
2437                    println!("   ⚠️  Conflicts in {} files:", conflicts.len());
2438                    for conflict in conflicts {
2439                        println!("      - {conflict}");
2440                    }
2441                    println!(
2442                        "   
2443💡 To resolve conflicts:"
2444                    );
2445                    println!("     1. Edit the conflicted files");
2446                    println!("     2. Stage resolved files: git add <file>");
2447                    println!("     3. Continue: ca stack continue-rebase");
2448                }
2449            }
2450            Err(e) => {
2451                warn!("Failed to get git status: {}", e);
2452            }
2453        }
2454    } else {
2455        println!("   Status: ✅ No rebase in progress");
2456
2457        // Show stack status instead
2458        if let Some(active_stack) = stack_manager.get_active_stack() {
2459            println!("   Active stack: {}", active_stack.name);
2460            println!("   Entries: {}", active_stack.entries.len());
2461            println!("   Base branch: {}", active_stack.base_branch);
2462        }
2463    }
2464
2465    Ok(())
2466}
2467
2468async fn delete_stack(name: String, force: bool) -> Result<()> {
2469    let current_dir = env::current_dir()
2470        .map_err(|e| CascadeError::config(format!("Could not get current directory: {e}")))?;
2471
2472    let repo_root = find_repository_root(&current_dir)
2473        .map_err(|e| CascadeError::config(format!("Could not find git repository: {e}")))?;
2474
2475    let mut manager = StackManager::new(&repo_root)?;
2476
2477    let stack = manager
2478        .get_stack_by_name(&name)
2479        .ok_or_else(|| CascadeError::config(format!("Stack '{name}' not found")))?;
2480    let stack_id = stack.id;
2481
2482    if !force && !stack.entries.is_empty() {
2483        return Err(CascadeError::config(format!(
2484            "Stack '{}' has {} entries. Use --force to delete anyway",
2485            name,
2486            stack.entries.len()
2487        )));
2488    }
2489
2490    let deleted = manager.delete_stack(&stack_id)?;
2491
2492    Output::success(format!("Deleted stack '{}'", deleted.name));
2493    if !deleted.entries.is_empty() {
2494        Output::warning(format!("{} entries were removed", deleted.entries.len()));
2495    }
2496
2497    Ok(())
2498}
2499
2500async fn validate_stack(name: Option<String>, fix_mode: Option<String>) -> Result<()> {
2501    let current_dir = env::current_dir()
2502        .map_err(|e| CascadeError::config(format!("Could not get current directory: {e}")))?;
2503
2504    let repo_root = find_repository_root(&current_dir)
2505        .map_err(|e| CascadeError::config(format!("Could not find git repository: {e}")))?;
2506
2507    let mut manager = StackManager::new(&repo_root)?;
2508
2509    if let Some(name) = name {
2510        // Validate specific stack
2511        let stack = manager
2512            .get_stack_by_name(&name)
2513            .ok_or_else(|| CascadeError::config(format!("Stack '{name}' not found")))?;
2514
2515        let stack_id = stack.id;
2516
2517        // Basic structure validation first
2518        match stack.validate() {
2519            Ok(message) => {
2520                println!("✅ Stack '{name}' structure validation: {message}");
2521            }
2522            Err(e) => {
2523                println!("❌ Stack '{name}' structure validation failed: {e}");
2524                return Err(CascadeError::config(e));
2525            }
2526        }
2527
2528        // Handle branch modifications (includes Git integrity checks)
2529        manager.handle_branch_modifications(&stack_id, fix_mode)?;
2530
2531        println!("🎉 Stack '{name}' validation completed");
2532        Ok(())
2533    } else {
2534        // Validate all stacks
2535        println!("🔍 Validating all stacks...");
2536
2537        // Get all stack IDs through public method
2538        let all_stacks = manager.get_all_stacks();
2539        let stack_ids: Vec<uuid::Uuid> = all_stacks.iter().map(|s| s.id).collect();
2540
2541        if stack_ids.is_empty() {
2542            println!("📭 No stacks found");
2543            return Ok(());
2544        }
2545
2546        let mut all_valid = true;
2547        for stack_id in stack_ids {
2548            let stack = manager.get_stack(&stack_id).unwrap();
2549            let stack_name = &stack.name;
2550
2551            println!("\n📋 Checking stack '{stack_name}':");
2552
2553            // Basic structure validation
2554            match stack.validate() {
2555                Ok(message) => {
2556                    println!("  ✅ Structure: {message}");
2557                }
2558                Err(e) => {
2559                    println!("  ❌ Structure: {e}");
2560                    all_valid = false;
2561                    continue;
2562                }
2563            }
2564
2565            // Handle branch modifications
2566            match manager.handle_branch_modifications(&stack_id, fix_mode.clone()) {
2567                Ok(_) => {
2568                    println!("  ✅ Git integrity: OK");
2569                }
2570                Err(e) => {
2571                    println!("  ❌ Git integrity: {e}");
2572                    all_valid = false;
2573                }
2574            }
2575        }
2576
2577        if all_valid {
2578            println!("\n🎉 All stacks passed validation");
2579        } else {
2580            println!("\n⚠️  Some stacks have validation issues");
2581            return Err(CascadeError::config("Stack validation failed".to_string()));
2582        }
2583
2584        Ok(())
2585    }
2586}
2587
2588/// Get commits that are not yet in any stack entry
2589#[allow(dead_code)]
2590fn get_unpushed_commits(repo: &GitRepository, stack: &crate::stack::Stack) -> Result<Vec<String>> {
2591    let mut unpushed = Vec::new();
2592    let head_commit = repo.get_head_commit()?;
2593    let mut current_commit = head_commit;
2594
2595    // Walk back from HEAD until we find a commit that's already in the stack
2596    loop {
2597        let commit_hash = current_commit.id().to_string();
2598        let already_in_stack = stack
2599            .entries
2600            .iter()
2601            .any(|entry| entry.commit_hash == commit_hash);
2602
2603        if already_in_stack {
2604            break;
2605        }
2606
2607        unpushed.push(commit_hash);
2608
2609        // Move to parent commit
2610        if let Some(parent) = current_commit.parents().next() {
2611            current_commit = parent;
2612        } else {
2613            break;
2614        }
2615    }
2616
2617    unpushed.reverse(); // Reverse to get chronological order
2618    Ok(unpushed)
2619}
2620
2621/// Squash the last N commits into a single commit
2622pub async fn squash_commits(
2623    repo: &GitRepository,
2624    count: usize,
2625    since_ref: Option<String>,
2626) -> Result<()> {
2627    if count <= 1 {
2628        return Ok(()); // Nothing to squash
2629    }
2630
2631    // Get the current branch
2632    let _current_branch = repo.get_current_branch()?;
2633
2634    // Determine the range for interactive rebase
2635    let rebase_range = if let Some(ref since) = since_ref {
2636        since.clone()
2637    } else {
2638        format!("HEAD~{count}")
2639    };
2640
2641    println!("   Analyzing {count} commits to create smart squash message...");
2642
2643    // Get the commits that will be squashed to create a smart message
2644    let head_commit = repo.get_head_commit()?;
2645    let mut commits_to_squash = Vec::new();
2646    let mut current = head_commit;
2647
2648    // Collect the last N commits
2649    for _ in 0..count {
2650        commits_to_squash.push(current.clone());
2651        if current.parent_count() > 0 {
2652            current = current.parent(0).map_err(CascadeError::Git)?;
2653        } else {
2654            break;
2655        }
2656    }
2657
2658    // Generate smart commit message from the squashed commits
2659    let smart_message = generate_squash_message(&commits_to_squash)?;
2660    println!(
2661        "   Smart message: {}",
2662        smart_message.lines().next().unwrap_or("")
2663    );
2664
2665    // Get the commit we want to reset to (the commit before our range)
2666    let reset_target = if since_ref.is_some() {
2667        // If squashing since a reference, reset to that reference
2668        format!("{rebase_range}~1")
2669    } else {
2670        // If squashing last N commits, reset to N commits before
2671        format!("HEAD~{count}")
2672    };
2673
2674    // Soft reset to preserve changes in staging area
2675    repo.reset_soft(&reset_target)?;
2676
2677    // Stage all changes (they should already be staged from the reset --soft)
2678    repo.stage_all()?;
2679
2680    // Create the new commit with the smart message
2681    let new_commit_hash = repo.commit(&smart_message)?;
2682
2683    println!(
2684        "   Created squashed commit: {} ({})",
2685        &new_commit_hash[..8],
2686        smart_message.lines().next().unwrap_or("")
2687    );
2688    println!("   💡 Tip: Use 'git commit --amend' to edit the commit message if needed");
2689
2690    Ok(())
2691}
2692
2693/// Generate a smart commit message from multiple commits being squashed
2694pub fn generate_squash_message(commits: &[git2::Commit]) -> Result<String> {
2695    if commits.is_empty() {
2696        return Ok("Squashed commits".to_string());
2697    }
2698
2699    // Get all commit messages
2700    let messages: Vec<String> = commits
2701        .iter()
2702        .map(|c| c.message().unwrap_or("").trim().to_string())
2703        .filter(|m| !m.is_empty())
2704        .collect();
2705
2706    if messages.is_empty() {
2707        return Ok("Squashed commits".to_string());
2708    }
2709
2710    // Strategy 1: If the last commit looks like a "Final:" commit, use it
2711    if let Some(last_msg) = messages.first() {
2712        // first() because we're in reverse chronological order
2713        if last_msg.starts_with("Final:") || last_msg.starts_with("final:") {
2714            return Ok(last_msg
2715                .trim_start_matches("Final:")
2716                .trim_start_matches("final:")
2717                .trim()
2718                .to_string());
2719        }
2720    }
2721
2722    // Strategy 2: If most commits are WIP, find the most descriptive non-WIP message
2723    let wip_count = messages
2724        .iter()
2725        .filter(|m| {
2726            m.to_lowercase().starts_with("wip") || m.to_lowercase().contains("work in progress")
2727        })
2728        .count();
2729
2730    if wip_count > messages.len() / 2 {
2731        // Mostly WIP commits, find the best non-WIP one or create a summary
2732        let non_wip: Vec<&String> = messages
2733            .iter()
2734            .filter(|m| {
2735                !m.to_lowercase().starts_with("wip")
2736                    && !m.to_lowercase().contains("work in progress")
2737            })
2738            .collect();
2739
2740        if let Some(best_msg) = non_wip.first() {
2741            return Ok(best_msg.to_string());
2742        }
2743
2744        // All are WIP, try to extract the feature being worked on
2745        let feature = extract_feature_from_wip(&messages);
2746        return Ok(feature);
2747    }
2748
2749    // Strategy 3: Use the last (most recent) commit message
2750    Ok(messages.first().unwrap().clone())
2751}
2752
2753/// Extract feature name from WIP commit messages
2754pub fn extract_feature_from_wip(messages: &[String]) -> String {
2755    // Look for patterns like "WIP: add authentication" -> "Add authentication"
2756    for msg in messages {
2757        // Check both case variations, but preserve original case
2758        if msg.to_lowercase().starts_with("wip:") {
2759            if let Some(rest) = msg
2760                .strip_prefix("WIP:")
2761                .or_else(|| msg.strip_prefix("wip:"))
2762            {
2763                let feature = rest.trim();
2764                if !feature.is_empty() && feature.len() > 3 {
2765                    // Capitalize first letter only, preserve rest
2766                    let mut chars: Vec<char> = feature.chars().collect();
2767                    if let Some(first) = chars.first_mut() {
2768                        *first = first.to_uppercase().next().unwrap_or(*first);
2769                    }
2770                    return chars.into_iter().collect();
2771                }
2772            }
2773        }
2774    }
2775
2776    // Fallback: Use the latest commit without WIP prefix
2777    if let Some(first) = messages.first() {
2778        let cleaned = first
2779            .trim_start_matches("WIP:")
2780            .trim_start_matches("wip:")
2781            .trim_start_matches("WIP")
2782            .trim_start_matches("wip")
2783            .trim();
2784
2785        if !cleaned.is_empty() {
2786            return format!("Implement {cleaned}");
2787        }
2788    }
2789
2790    format!("Squashed {} commits", messages.len())
2791}
2792
2793/// Count commits since a given reference
2794pub fn count_commits_since(repo: &GitRepository, since_commit_hash: &str) -> Result<usize> {
2795    let head_commit = repo.get_head_commit()?;
2796    let since_commit = repo.get_commit(since_commit_hash)?;
2797
2798    let mut count = 0;
2799    let mut current = head_commit;
2800
2801    // Walk backwards from HEAD until we reach the since commit
2802    loop {
2803        if current.id() == since_commit.id() {
2804            break;
2805        }
2806
2807        count += 1;
2808
2809        // Get parent commit
2810        if current.parent_count() == 0 {
2811            break; // Reached root commit
2812        }
2813
2814        current = current.parent(0).map_err(CascadeError::Git)?;
2815    }
2816
2817    Ok(count)
2818}
2819
2820/// Land (merge) approved stack entries
2821async fn land_stack(
2822    entry: Option<usize>,
2823    force: bool,
2824    dry_run: bool,
2825    auto: bool,
2826    wait_for_builds: bool,
2827    strategy: Option<MergeStrategyArg>,
2828    build_timeout: u64,
2829) -> Result<()> {
2830    let current_dir = env::current_dir()
2831        .map_err(|e| CascadeError::config(format!("Could not get current directory: {e}")))?;
2832
2833    let repo_root = find_repository_root(&current_dir)
2834        .map_err(|e| CascadeError::config(format!("Could not find git repository: {e}")))?;
2835
2836    let stack_manager = StackManager::new(&repo_root)?;
2837
2838    // Get stack ID and active stack before moving stack_manager
2839    let stack_id = stack_manager
2840        .get_active_stack()
2841        .map(|s| s.id)
2842        .ok_or_else(|| {
2843            CascadeError::config(
2844                "No active stack. Use 'ca stack create' or 'ca stack switch' to select a stack"
2845                    .to_string(),
2846            )
2847        })?;
2848
2849    let active_stack = stack_manager
2850        .get_active_stack()
2851        .cloned()
2852        .ok_or_else(|| CascadeError::config("No active stack found".to_string()))?;
2853
2854    // Load configuration and create Bitbucket integration
2855    let config_dir = crate::config::get_repo_config_dir(&repo_root)?;
2856    let config_path = config_dir.join("config.json");
2857    let settings = crate::config::Settings::load_from_file(&config_path)?;
2858
2859    let cascade_config = crate::config::CascadeConfig {
2860        bitbucket: Some(settings.bitbucket.clone()),
2861        git: settings.git.clone(),
2862        auth: crate::config::AuthConfig::default(),
2863        cascade: settings.cascade.clone(),
2864    };
2865
2866    let integration = crate::bitbucket::BitbucketIntegration::new(stack_manager, cascade_config)?;
2867
2868    // Get enhanced status
2869    let status = integration.check_enhanced_stack_status(&stack_id).await?;
2870
2871    if status.enhanced_statuses.is_empty() {
2872        println!("❌ No pull requests found to land");
2873        return Ok(());
2874    }
2875
2876    // Filter PRs that are ready to land
2877    let ready_prs: Vec<_> = status
2878        .enhanced_statuses
2879        .iter()
2880        .filter(|pr_status| {
2881            // If specific entry requested, only include that one
2882            if let Some(entry_num) = entry {
2883                // Find the corresponding stack entry for this PR
2884                if let Some(stack_entry) = active_stack.entries.get(entry_num.saturating_sub(1)) {
2885                    // Check if this PR corresponds to the requested entry
2886                    if pr_status.pr.from_ref.display_id != stack_entry.branch {
2887                        return false;
2888                    }
2889                } else {
2890                    return false; // Invalid entry number
2891                }
2892            }
2893
2894            if force {
2895                // If force is enabled, include any open PR
2896                pr_status.pr.state == crate::bitbucket::pull_request::PullRequestState::Open
2897            } else {
2898                pr_status.is_ready_to_land()
2899            }
2900        })
2901        .collect();
2902
2903    if ready_prs.is_empty() {
2904        if let Some(entry_num) = entry {
2905            println!("❌ Entry {entry_num} is not ready to land or doesn't exist");
2906        } else {
2907            println!("❌ No pull requests are ready to land");
2908        }
2909
2910        // Show what's blocking them
2911        println!("\n🚫 Blocking Issues:");
2912        for pr_status in &status.enhanced_statuses {
2913            if pr_status.pr.state == crate::bitbucket::pull_request::PullRequestState::Open {
2914                let blocking = pr_status.get_blocking_reasons();
2915                if !blocking.is_empty() {
2916                    println!("   PR #{}: {}", pr_status.pr.id, blocking.join(", "));
2917                }
2918            }
2919        }
2920
2921        if !force {
2922            println!("\n💡 Use --force to land PRs with blocking issues (dangerous!)");
2923        }
2924        return Ok(());
2925    }
2926
2927    if dry_run {
2928        if let Some(entry_num) = entry {
2929            println!("🏃 Dry Run - Entry {entry_num} that would be landed:");
2930        } else {
2931            println!("🏃 Dry Run - PRs that would be landed:");
2932        }
2933        for pr_status in &ready_prs {
2934            println!("   ✅ PR #{}: {}", pr_status.pr.id, pr_status.pr.title);
2935            if !pr_status.is_ready_to_land() && force {
2936                let blocking = pr_status.get_blocking_reasons();
2937                println!(
2938                    "      ⚠️  Would force land despite: {}",
2939                    blocking.join(", ")
2940                );
2941            }
2942        }
2943        return Ok(());
2944    }
2945
2946    // Default behavior: land all ready PRs (safest approach)
2947    // Only land specific entry if explicitly requested
2948    if entry.is_some() && ready_prs.len() > 1 {
2949        println!(
2950            "🎯 {} PRs are ready to land, but landing only entry #{}",
2951            ready_prs.len(),
2952            entry.unwrap()
2953        );
2954    }
2955
2956    // Setup auto-merge conditions
2957    let merge_strategy: crate::bitbucket::pull_request::MergeStrategy =
2958        strategy.unwrap_or(MergeStrategyArg::Squash).into();
2959    let auto_merge_conditions = crate::bitbucket::pull_request::AutoMergeConditions {
2960        merge_strategy: merge_strategy.clone(),
2961        wait_for_builds,
2962        build_timeout: std::time::Duration::from_secs(build_timeout),
2963        allowed_authors: None, // Allow all authors for now
2964    };
2965
2966    // Land the PRs
2967    println!(
2968        "🚀 Landing {} PR{}...",
2969        ready_prs.len(),
2970        if ready_prs.len() == 1 { "" } else { "s" }
2971    );
2972
2973    let pr_manager = crate::bitbucket::pull_request::PullRequestManager::new(
2974        crate::bitbucket::BitbucketClient::new(&settings.bitbucket)?,
2975    );
2976
2977    // Land PRs in dependency order
2978    let mut landed_count = 0;
2979    let mut failed_count = 0;
2980    let total_ready_prs = ready_prs.len();
2981
2982    for pr_status in ready_prs {
2983        let pr_id = pr_status.pr.id;
2984
2985        print!("🚀 Landing PR #{}: {}", pr_id, pr_status.pr.title);
2986
2987        let land_result = if auto {
2988            // Use auto-merge with conditions checking
2989            pr_manager
2990                .auto_merge_if_ready(pr_id, &auto_merge_conditions)
2991                .await
2992        } else {
2993            // Manual merge without auto-conditions
2994            pr_manager
2995                .merge_pull_request(pr_id, merge_strategy.clone())
2996                .await
2997                .map(
2998                    |pr| crate::bitbucket::pull_request::AutoMergeResult::Merged {
2999                        pr: Box::new(pr),
3000                        merge_strategy: merge_strategy.clone(),
3001                    },
3002                )
3003        };
3004
3005        match land_result {
3006            Ok(crate::bitbucket::pull_request::AutoMergeResult::Merged { .. }) => {
3007                println!(" ✅");
3008                landed_count += 1;
3009
3010                // 🔄 AUTO-RETARGETING: After each merge, retarget remaining PRs
3011                if landed_count < total_ready_prs {
3012                    println!("🔄 Retargeting remaining PRs to latest base...");
3013
3014                    // 1️⃣ CRITICAL: Update base branch to get latest merged state
3015                    let base_branch = active_stack.base_branch.clone();
3016                    let git_repo = crate::git::GitRepository::open(&repo_root)?;
3017
3018                    println!("   📥 Updating base branch: {base_branch}");
3019                    match git_repo.pull(&base_branch) {
3020                        Ok(_) => println!("   ✅ Base branch updated successfully"),
3021                        Err(e) => {
3022                            println!("   ⚠️  Warning: Failed to update base branch: {e}");
3023                            println!(
3024                                "   💡 You may want to manually run: git pull origin {base_branch}"
3025                            );
3026                        }
3027                    }
3028
3029                    // 2️⃣ Use rebase system to retarget remaining PRs
3030                    let mut rebase_manager = crate::stack::RebaseManager::new(
3031                        StackManager::new(&repo_root)?,
3032                        git_repo,
3033                        crate::stack::RebaseOptions {
3034                            strategy: crate::stack::RebaseStrategy::BranchVersioning,
3035                            target_base: Some(base_branch.clone()),
3036                            ..Default::default()
3037                        },
3038                    );
3039
3040                    match rebase_manager.rebase_stack(&stack_id) {
3041                        Ok(rebase_result) => {
3042                            if !rebase_result.branch_mapping.is_empty() {
3043                                // Update PRs using the rebase result
3044                                let retarget_config = crate::config::CascadeConfig {
3045                                    bitbucket: Some(settings.bitbucket.clone()),
3046                                    git: settings.git.clone(),
3047                                    auth: crate::config::AuthConfig::default(),
3048                                    cascade: settings.cascade.clone(),
3049                                };
3050                                let mut retarget_integration = BitbucketIntegration::new(
3051                                    StackManager::new(&repo_root)?,
3052                                    retarget_config,
3053                                )?;
3054
3055                                match retarget_integration
3056                                    .update_prs_after_rebase(
3057                                        &stack_id,
3058                                        &rebase_result.branch_mapping,
3059                                    )
3060                                    .await
3061                                {
3062                                    Ok(updated_prs) => {
3063                                        if !updated_prs.is_empty() {
3064                                            println!(
3065                                                "   ✅ Updated {} PRs with new targets",
3066                                                updated_prs.len()
3067                                            );
3068                                        }
3069                                    }
3070                                    Err(e) => {
3071                                        println!("   ⚠️  Failed to update remaining PRs: {e}");
3072                                        println!(
3073                                            "   💡 You may need to run: ca stack rebase --onto {base_branch}"
3074                                        );
3075                                    }
3076                                }
3077                            }
3078                        }
3079                        Err(e) => {
3080                            // 🚨 CONFLICTS DETECTED - Give clear next steps
3081                            println!("   ❌ Auto-retargeting conflicts detected!");
3082                            println!("   📝 To resolve conflicts and continue landing:");
3083                            println!("      1. Resolve conflicts in the affected files");
3084                            println!("      2. Stage resolved files: git add <files>");
3085                            println!("      3. Continue the process: ca stack continue-land");
3086                            println!("      4. Or abort the operation: ca stack abort-land");
3087                            println!();
3088                            println!("   💡 Check current status: ca stack land-status");
3089                            println!("   ⚠️  Error details: {e}");
3090
3091                            // Stop the land operation here - user needs to resolve conflicts
3092                            break;
3093                        }
3094                    }
3095                }
3096            }
3097            Ok(crate::bitbucket::pull_request::AutoMergeResult::NotReady { blocking_reasons }) => {
3098                println!(" ❌ Not ready: {}", blocking_reasons.join(", "));
3099                failed_count += 1;
3100                if !force {
3101                    break;
3102                }
3103            }
3104            Ok(crate::bitbucket::pull_request::AutoMergeResult::Failed { error }) => {
3105                println!(" ❌ Failed: {error}");
3106                failed_count += 1;
3107                if !force {
3108                    break;
3109                }
3110            }
3111            Err(e) => {
3112                println!(" ❌");
3113                eprintln!("Failed to land PR #{pr_id}: {e}");
3114                failed_count += 1;
3115
3116                if !force {
3117                    break;
3118                }
3119            }
3120        }
3121    }
3122
3123    // Show summary
3124    println!("\n🎯 Landing Summary:");
3125    println!("   ✅ Successfully landed: {landed_count}");
3126    if failed_count > 0 {
3127        println!("   ❌ Failed to land: {failed_count}");
3128    }
3129
3130    if landed_count > 0 {
3131        println!("✅ Landing operation completed!");
3132    } else {
3133        println!("❌ No PRs were successfully landed");
3134    }
3135
3136    Ok(())
3137}
3138
3139/// Auto-land all ready PRs (shorthand for land --auto)
3140async fn auto_land_stack(
3141    force: bool,
3142    dry_run: bool,
3143    wait_for_builds: bool,
3144    strategy: Option<MergeStrategyArg>,
3145    build_timeout: u64,
3146) -> Result<()> {
3147    // This is a shorthand for land with --auto
3148    land_stack(
3149        None,
3150        force,
3151        dry_run,
3152        true, // auto = true
3153        wait_for_builds,
3154        strategy,
3155        build_timeout,
3156    )
3157    .await
3158}
3159
3160async fn continue_land() -> Result<()> {
3161    let current_dir = env::current_dir()
3162        .map_err(|e| CascadeError::config(format!("Could not get current directory: {e}")))?;
3163
3164    let repo_root = find_repository_root(&current_dir)
3165        .map_err(|e| CascadeError::config(format!("Could not find git repository: {e}")))?;
3166
3167    let stack_manager = StackManager::new(&repo_root)?;
3168    let git_repo = crate::git::GitRepository::open(&repo_root)?;
3169    let options = crate::stack::RebaseOptions::default();
3170    let rebase_manager = crate::stack::RebaseManager::new(stack_manager, git_repo, options);
3171
3172    if !rebase_manager.is_rebase_in_progress() {
3173        println!("ℹ️  No rebase in progress");
3174        return Ok(());
3175    }
3176
3177    println!("🔄 Continuing land operation...");
3178    match rebase_manager.continue_rebase() {
3179        Ok(_) => {
3180            println!("✅ Land operation continued successfully");
3181            println!("   Check 'ca stack land-status' for current state");
3182        }
3183        Err(e) => {
3184            warn!("❌ Failed to continue land operation: {}", e);
3185            println!("💡 You may need to resolve conflicts first:");
3186            println!("   1. Edit conflicted files");
3187            println!("   2. Stage resolved files with 'git add'");
3188            println!("   3. Run 'ca stack continue-land' again");
3189        }
3190    }
3191
3192    Ok(())
3193}
3194
3195async fn abort_land() -> Result<()> {
3196    let current_dir = env::current_dir()
3197        .map_err(|e| CascadeError::config(format!("Could not get current directory: {e}")))?;
3198
3199    let repo_root = find_repository_root(&current_dir)
3200        .map_err(|e| CascadeError::config(format!("Could not find git repository: {e}")))?;
3201
3202    let stack_manager = StackManager::new(&repo_root)?;
3203    let git_repo = crate::git::GitRepository::open(&repo_root)?;
3204    let options = crate::stack::RebaseOptions::default();
3205    let rebase_manager = crate::stack::RebaseManager::new(stack_manager, git_repo, options);
3206
3207    if !rebase_manager.is_rebase_in_progress() {
3208        println!("ℹ️  No rebase in progress");
3209        return Ok(());
3210    }
3211
3212    println!("⚠️  Aborting land operation...");
3213    match rebase_manager.abort_rebase() {
3214        Ok(_) => {
3215            println!("✅ Land operation aborted successfully");
3216            println!("   Repository restored to pre-land state");
3217        }
3218        Err(e) => {
3219            warn!("❌ Failed to abort land operation: {}", e);
3220            println!("⚠️  You may need to manually clean up the repository state");
3221        }
3222    }
3223
3224    Ok(())
3225}
3226
3227async fn land_status() -> Result<()> {
3228    let current_dir = env::current_dir()
3229        .map_err(|e| CascadeError::config(format!("Could not get current directory: {e}")))?;
3230
3231    let repo_root = find_repository_root(&current_dir)
3232        .map_err(|e| CascadeError::config(format!("Could not find git repository: {e}")))?;
3233
3234    let stack_manager = StackManager::new(&repo_root)?;
3235    let git_repo = crate::git::GitRepository::open(&repo_root)?;
3236
3237    println!("📊 Land Status");
3238
3239    // Check if land operation is in progress by checking git state directly
3240    let git_dir = repo_root.join(".git");
3241    let land_in_progress = git_dir.join("REBASE_HEAD").exists()
3242        || git_dir.join("rebase-merge").exists()
3243        || git_dir.join("rebase-apply").exists();
3244
3245    if land_in_progress {
3246        println!("   Status: 🔄 Land operation in progress");
3247        println!(
3248            "   
3249📝 Actions available:"
3250        );
3251        println!("     - 'ca stack continue-land' to continue");
3252        println!("     - 'ca stack abort-land' to abort");
3253        println!("     - 'git status' to see conflicted files");
3254
3255        // Check for conflicts
3256        match git_repo.get_status() {
3257            Ok(statuses) => {
3258                let mut conflicts = Vec::new();
3259                for status in statuses.iter() {
3260                    if status.status().contains(git2::Status::CONFLICTED) {
3261                        if let Some(path) = status.path() {
3262                            conflicts.push(path.to_string());
3263                        }
3264                    }
3265                }
3266
3267                if !conflicts.is_empty() {
3268                    println!("   ⚠️  Conflicts in {} files:", conflicts.len());
3269                    for conflict in conflicts {
3270                        println!("      - {conflict}");
3271                    }
3272                    println!(
3273                        "   
3274💡 To resolve conflicts:"
3275                    );
3276                    println!("     1. Edit the conflicted files");
3277                    println!("     2. Stage resolved files: git add <file>");
3278                    println!("     3. Continue: ca stack continue-land");
3279                }
3280            }
3281            Err(e) => {
3282                warn!("Failed to get git status: {}", e);
3283            }
3284        }
3285    } else {
3286        println!("   Status: ✅ No land operation in progress");
3287
3288        // Show stack status instead
3289        if let Some(active_stack) = stack_manager.get_active_stack() {
3290            println!("   Active stack: {}", active_stack.name);
3291            println!("   Entries: {}", active_stack.entries.len());
3292            println!("   Base branch: {}", active_stack.base_branch);
3293        }
3294    }
3295
3296    Ok(())
3297}
3298
3299async fn repair_stack_data() -> Result<()> {
3300    let current_dir = env::current_dir()
3301        .map_err(|e| CascadeError::config(format!("Could not get current directory: {e}")))?;
3302
3303    let repo_root = find_repository_root(&current_dir)
3304        .map_err(|e| CascadeError::config(format!("Could not find git repository: {e}")))?;
3305
3306    let mut stack_manager = StackManager::new(&repo_root)?;
3307
3308    println!("🔧 Repairing stack data consistency...");
3309
3310    stack_manager.repair_all_stacks()?;
3311
3312    println!("✅ Stack data consistency repaired successfully!");
3313    println!("💡 Run 'ca stack --mergeable' to see updated status");
3314
3315    Ok(())
3316}
3317
3318/// Analyze commits for various safeguards before pushing
3319async fn analyze_commits_for_safeguards(
3320    commits_to_push: &[String],
3321    repo: &GitRepository,
3322    dry_run: bool,
3323) -> Result<()> {
3324    const LARGE_COMMIT_THRESHOLD: usize = 10;
3325    const WEEK_IN_SECONDS: i64 = 7 * 24 * 3600;
3326
3327    // 🛡️ SAFEGUARD 1: Large commit count warning
3328    if commits_to_push.len() > LARGE_COMMIT_THRESHOLD {
3329        println!(
3330            "⚠️  Warning: About to push {} commits to stack",
3331            commits_to_push.len()
3332        );
3333        println!("   This may indicate a merge commit issue or unexpected commit range.");
3334        println!("   Large commit counts often result from merging instead of rebasing.");
3335
3336        if !dry_run && !confirm_large_push(commits_to_push.len())? {
3337            return Err(CascadeError::config("Push cancelled by user"));
3338        }
3339    }
3340
3341    // Get commit objects for further analysis
3342    let commit_objects: Result<Vec<_>> = commits_to_push
3343        .iter()
3344        .map(|hash| repo.get_commit(hash))
3345        .collect();
3346    let commit_objects = commit_objects?;
3347
3348    // 🛡️ SAFEGUARD 2: Merge commit detection
3349    let merge_commits: Vec<_> = commit_objects
3350        .iter()
3351        .filter(|c| c.parent_count() > 1)
3352        .collect();
3353
3354    if !merge_commits.is_empty() {
3355        println!(
3356            "⚠️  Warning: {} merge commits detected in push",
3357            merge_commits.len()
3358        );
3359        println!("   This often indicates you merged instead of rebased.");
3360        println!("   Consider using 'ca sync' to rebase on the base branch.");
3361        println!("   Merge commits in stacks can cause confusion and duplicate work.");
3362    }
3363
3364    // 🛡️ SAFEGUARD 3: Commit age warning
3365    if commit_objects.len() > 1 {
3366        let oldest_commit_time = commit_objects.first().unwrap().time().seconds();
3367        let newest_commit_time = commit_objects.last().unwrap().time().seconds();
3368        let time_span = newest_commit_time - oldest_commit_time;
3369
3370        if time_span > WEEK_IN_SECONDS {
3371            let days = time_span / (24 * 3600);
3372            println!("⚠️  Warning: Commits span {days} days");
3373            println!("   This may indicate merged history rather than new work.");
3374            println!("   Recent work should typically span hours or days, not weeks.");
3375        }
3376    }
3377
3378    // 🛡️ SAFEGUARD 4: Better range detection suggestions
3379    if commits_to_push.len() > 5 {
3380        println!("💡 Tip: If you only want recent commits, use:");
3381        println!(
3382            "   ca push --since HEAD~{}  # pushes last {} commits",
3383            std::cmp::min(commits_to_push.len(), 5),
3384            std::cmp::min(commits_to_push.len(), 5)
3385        );
3386        println!("   ca push --commits <hash1>,<hash2>  # pushes specific commits");
3387        println!("   ca push --dry-run  # preview what would be pushed");
3388    }
3389
3390    // 🛡️ SAFEGUARD 5: Dry run mode
3391    if dry_run {
3392        println!("🔍 DRY RUN: Would push {} commits:", commits_to_push.len());
3393        for (i, (commit_hash, commit_obj)) in commits_to_push
3394            .iter()
3395            .zip(commit_objects.iter())
3396            .enumerate()
3397        {
3398            let summary = commit_obj.summary().unwrap_or("(no message)");
3399            let short_hash = &commit_hash[..std::cmp::min(commit_hash.len(), 7)];
3400            println!("  {}: {} ({})", i + 1, summary, short_hash);
3401        }
3402        println!("💡 Run without --dry-run to actually push these commits.");
3403    }
3404
3405    Ok(())
3406}
3407
3408/// Prompt user for confirmation when pushing large number of commits
3409fn confirm_large_push(count: usize) -> Result<bool> {
3410    print!("Do you want to continue pushing {count} commits? [y/N]: ");
3411    io::stdout()
3412        .flush()
3413        .map_err(|e| CascadeError::config(format!("Failed to flush stdout: {e}")))?;
3414
3415    let mut input = String::new();
3416    io::stdin()
3417        .read_line(&mut input)
3418        .map_err(|e| CascadeError::config(format!("Failed to read user input: {e}")))?;
3419
3420    let input = input.trim().to_lowercase();
3421    Ok(input == "y" || input == "yes")
3422}
3423
3424#[cfg(test)]
3425mod tests {
3426    use super::*;
3427    use std::process::Command;
3428    use tempfile::TempDir;
3429
3430    fn create_test_repo() -> Result<(TempDir, std::path::PathBuf)> {
3431        let temp_dir = TempDir::new()
3432            .map_err(|e| CascadeError::config(format!("Failed to create temp directory: {e}")))?;
3433        let repo_path = temp_dir.path().to_path_buf();
3434
3435        // Initialize git repository
3436        let output = Command::new("git")
3437            .args(["init"])
3438            .current_dir(&repo_path)
3439            .output()
3440            .map_err(|e| CascadeError::config(format!("Failed to run git init: {e}")))?;
3441        if !output.status.success() {
3442            return Err(CascadeError::config("Git init failed".to_string()));
3443        }
3444
3445        let output = Command::new("git")
3446            .args(["config", "user.name", "Test User"])
3447            .current_dir(&repo_path)
3448            .output()
3449            .map_err(|e| CascadeError::config(format!("Failed to run git config: {e}")))?;
3450        if !output.status.success() {
3451            return Err(CascadeError::config(
3452                "Git config user.name failed".to_string(),
3453            ));
3454        }
3455
3456        let output = Command::new("git")
3457            .args(["config", "user.email", "test@example.com"])
3458            .current_dir(&repo_path)
3459            .output()
3460            .map_err(|e| CascadeError::config(format!("Failed to run git config: {e}")))?;
3461        if !output.status.success() {
3462            return Err(CascadeError::config(
3463                "Git config user.email failed".to_string(),
3464            ));
3465        }
3466
3467        // Create initial commit
3468        std::fs::write(repo_path.join("README.md"), "# Test")
3469            .map_err(|e| CascadeError::config(format!("Failed to write file: {e}")))?;
3470        let output = Command::new("git")
3471            .args(["add", "."])
3472            .current_dir(&repo_path)
3473            .output()
3474            .map_err(|e| CascadeError::config(format!("Failed to run git add: {e}")))?;
3475        if !output.status.success() {
3476            return Err(CascadeError::config("Git add failed".to_string()));
3477        }
3478
3479        let output = Command::new("git")
3480            .args(["commit", "-m", "Initial commit"])
3481            .current_dir(&repo_path)
3482            .output()
3483            .map_err(|e| CascadeError::config(format!("Failed to run git commit: {e}")))?;
3484        if !output.status.success() {
3485            return Err(CascadeError::config("Git commit failed".to_string()));
3486        }
3487
3488        // Initialize cascade
3489        crate::config::initialize_repo(&repo_path, Some("https://test.bitbucket.com".to_string()))?;
3490
3491        Ok((temp_dir, repo_path))
3492    }
3493
3494    #[tokio::test]
3495    async fn test_create_stack() {
3496        let (temp_dir, repo_path) = match create_test_repo() {
3497            Ok(repo) => repo,
3498            Err(_) => {
3499                println!("Skipping test due to git environment setup failure");
3500                return;
3501            }
3502        };
3503        // IMPORTANT: temp_dir must stay in scope to prevent early cleanup of test directory
3504        let _ = &temp_dir;
3505
3506        // Note: create_test_repo() already initializes Cascade configuration
3507
3508        // Change to the repo directory (with proper error handling)
3509        let original_dir = env::current_dir().map_err(|_| "Failed to get current dir");
3510        match env::set_current_dir(&repo_path) {
3511            Ok(_) => {
3512                let result = create_stack(
3513                    "test-stack".to_string(),
3514                    None, // Use default branch
3515                    Some("Test description".to_string()),
3516                )
3517                .await;
3518
3519                // Restore original directory (best effort)
3520                if let Ok(orig) = original_dir {
3521                    let _ = env::set_current_dir(orig);
3522                }
3523
3524                assert!(
3525                    result.is_ok(),
3526                    "Stack creation should succeed in initialized repository"
3527                );
3528            }
3529            Err(_) => {
3530                // Skip test if we can't change directories (CI environment issue)
3531                println!("Skipping test due to directory access restrictions");
3532            }
3533        }
3534    }
3535
3536    #[tokio::test]
3537    async fn test_list_empty_stacks() {
3538        let (temp_dir, repo_path) = match create_test_repo() {
3539            Ok(repo) => repo,
3540            Err(_) => {
3541                println!("Skipping test due to git environment setup failure");
3542                return;
3543            }
3544        };
3545        // IMPORTANT: temp_dir must stay in scope to prevent early cleanup of test directory
3546        let _ = &temp_dir;
3547
3548        // Note: create_test_repo() already initializes Cascade configuration
3549
3550        // Change to the repo directory (with proper error handling)
3551        let original_dir = env::current_dir().map_err(|_| "Failed to get current dir");
3552        match env::set_current_dir(&repo_path) {
3553            Ok(_) => {
3554                let result = list_stacks(false, false, None).await;
3555
3556                // Restore original directory (best effort)
3557                if let Ok(orig) = original_dir {
3558                    let _ = env::set_current_dir(orig);
3559                }
3560
3561                assert!(
3562                    result.is_ok(),
3563                    "Listing stacks should succeed in initialized repository"
3564                );
3565            }
3566            Err(_) => {
3567                // Skip test if we can't change directories (CI environment issue)
3568                println!("Skipping test due to directory access restrictions");
3569            }
3570        }
3571    }
3572
3573    // Tests for squashing functionality
3574
3575    #[test]
3576    fn test_extract_feature_from_wip_basic() {
3577        let messages = vec![
3578            "WIP: add authentication".to_string(),
3579            "WIP: implement login flow".to_string(),
3580        ];
3581
3582        let result = extract_feature_from_wip(&messages);
3583        assert_eq!(result, "Add authentication");
3584    }
3585
3586    #[test]
3587    fn test_extract_feature_from_wip_capitalize() {
3588        let messages = vec!["WIP: fix user validation bug".to_string()];
3589
3590        let result = extract_feature_from_wip(&messages);
3591        assert_eq!(result, "Fix user validation bug");
3592    }
3593
3594    #[test]
3595    fn test_extract_feature_from_wip_fallback() {
3596        let messages = vec![
3597            "WIP user interface changes".to_string(),
3598            "wip: css styling".to_string(),
3599        ];
3600
3601        let result = extract_feature_from_wip(&messages);
3602        // Should create a fallback message since no "WIP:" prefix found
3603        assert!(result.contains("Implement") || result.contains("Squashed") || result.len() > 5);
3604    }
3605
3606    #[test]
3607    fn test_extract_feature_from_wip_empty() {
3608        let messages = vec![];
3609
3610        let result = extract_feature_from_wip(&messages);
3611        assert_eq!(result, "Squashed 0 commits");
3612    }
3613
3614    #[test]
3615    fn test_extract_feature_from_wip_short_message() {
3616        let messages = vec!["WIP: x".to_string()]; // Too short
3617
3618        let result = extract_feature_from_wip(&messages);
3619        assert!(result.starts_with("Implement") || result.contains("Squashed"));
3620    }
3621
3622    // Integration tests for squashing that don't require real git commits
3623
3624    #[test]
3625    fn test_squash_message_final_strategy() {
3626        // This test would need real git2::Commit objects, so we'll test the logic indirectly
3627        // through the extract_feature_from_wip function which handles the core logic
3628
3629        let messages = [
3630            "Final: implement user authentication system".to_string(),
3631            "WIP: add tests".to_string(),
3632            "WIP: fix validation".to_string(),
3633        ];
3634
3635        // Test that we can identify final commits
3636        assert!(messages[0].starts_with("Final:"));
3637
3638        // Test message extraction
3639        let extracted = messages[0].trim_start_matches("Final:").trim();
3640        assert_eq!(extracted, "implement user authentication system");
3641    }
3642
3643    #[test]
3644    fn test_squash_message_wip_detection() {
3645        let messages = [
3646            "WIP: start feature".to_string(),
3647            "WIP: continue work".to_string(),
3648            "WIP: almost done".to_string(),
3649            "Regular commit message".to_string(),
3650        ];
3651
3652        let wip_count = messages
3653            .iter()
3654            .filter(|m| {
3655                m.to_lowercase().starts_with("wip") || m.to_lowercase().contains("work in progress")
3656            })
3657            .count();
3658
3659        assert_eq!(wip_count, 3); // Should detect 3 WIP commits
3660        assert!(wip_count > messages.len() / 2); // Majority are WIP
3661
3662        // Should find the non-WIP message
3663        let non_wip: Vec<&String> = messages
3664            .iter()
3665            .filter(|m| {
3666                !m.to_lowercase().starts_with("wip")
3667                    && !m.to_lowercase().contains("work in progress")
3668            })
3669            .collect();
3670
3671        assert_eq!(non_wip.len(), 1);
3672        assert_eq!(non_wip[0], "Regular commit message");
3673    }
3674
3675    #[test]
3676    fn test_squash_message_all_wip() {
3677        let messages = vec![
3678            "WIP: add feature A".to_string(),
3679            "WIP: add feature B".to_string(),
3680            "WIP: finish implementation".to_string(),
3681        ];
3682
3683        let result = extract_feature_from_wip(&messages);
3684        // Should use the first message as the main feature
3685        assert_eq!(result, "Add feature A");
3686    }
3687
3688    #[test]
3689    fn test_squash_message_edge_cases() {
3690        // Test empty messages
3691        let empty_messages: Vec<String> = vec![];
3692        let result = extract_feature_from_wip(&empty_messages);
3693        assert_eq!(result, "Squashed 0 commits");
3694
3695        // Test messages with only whitespace
3696        let whitespace_messages = vec!["   ".to_string(), "\t\n".to_string()];
3697        let result = extract_feature_from_wip(&whitespace_messages);
3698        assert!(result.contains("Squashed") || result.contains("Implement"));
3699
3700        // Test case sensitivity
3701        let mixed_case = vec!["wip: Add Feature".to_string()];
3702        let result = extract_feature_from_wip(&mixed_case);
3703        assert_eq!(result, "Add Feature");
3704    }
3705
3706    // Tests for auto-land functionality
3707
3708    #[tokio::test]
3709    async fn test_auto_land_wrapper() {
3710        // Test that auto_land_stack correctly calls land_stack with auto=true
3711        let (temp_dir, repo_path) = match create_test_repo() {
3712            Ok(repo) => repo,
3713            Err(_) => {
3714                println!("Skipping test due to git environment setup failure");
3715                return;
3716            }
3717        };
3718        // IMPORTANT: temp_dir must stay in scope to prevent early cleanup of test directory
3719        let _ = &temp_dir;
3720
3721        // Initialize cascade in the test repo
3722        crate::config::initialize_repo(&repo_path, Some("https://test.bitbucket.com".to_string()))
3723            .expect("Failed to initialize Cascade in test repo");
3724
3725        let original_dir = env::current_dir().map_err(|_| "Failed to get current dir");
3726        match env::set_current_dir(&repo_path) {
3727            Ok(_) => {
3728                // Create a stack first
3729                let result = create_stack(
3730                    "test-stack".to_string(),
3731                    None,
3732                    Some("Test stack for auto-land".to_string()),
3733                )
3734                .await;
3735
3736                if let Ok(orig) = original_dir {
3737                    let _ = env::set_current_dir(orig);
3738                }
3739
3740                // For now, just test that the function can be called without panic
3741                // (It will fail due to missing Bitbucket config, but that's expected)
3742                assert!(
3743                    result.is_ok(),
3744                    "Stack creation should succeed in initialized repository"
3745                );
3746            }
3747            Err(_) => {
3748                println!("Skipping test due to directory access restrictions");
3749            }
3750        }
3751    }
3752
3753    #[test]
3754    fn test_auto_land_action_enum() {
3755        // Test that AutoLand action is properly defined
3756        use crate::cli::commands::stack::StackAction;
3757
3758        // This ensures the AutoLand variant exists and has the expected fields
3759        let _action = StackAction::AutoLand {
3760            force: false,
3761            dry_run: true,
3762            wait_for_builds: true,
3763            strategy: Some(MergeStrategyArg::Squash),
3764            build_timeout: 1800,
3765        };
3766
3767        // Test passes if we reach this point without errors
3768    }
3769
3770    #[test]
3771    fn test_merge_strategy_conversion() {
3772        // Test that MergeStrategyArg converts properly
3773        let squash_strategy = MergeStrategyArg::Squash;
3774        let merge_strategy: crate::bitbucket::pull_request::MergeStrategy = squash_strategy.into();
3775
3776        match merge_strategy {
3777            crate::bitbucket::pull_request::MergeStrategy::Squash => {
3778                // Correct conversion
3779            }
3780            _ => panic!("Expected Squash strategy"),
3781        }
3782
3783        let merge_strategy = MergeStrategyArg::Merge;
3784        let converted: crate::bitbucket::pull_request::MergeStrategy = merge_strategy.into();
3785
3786        match converted {
3787            crate::bitbucket::pull_request::MergeStrategy::Merge => {
3788                // Correct conversion
3789            }
3790            _ => panic!("Expected Merge strategy"),
3791        }
3792    }
3793
3794    #[test]
3795    fn test_auto_merge_conditions_structure() {
3796        // Test that AutoMergeConditions can be created with expected values
3797        use std::time::Duration;
3798
3799        let conditions = crate::bitbucket::pull_request::AutoMergeConditions {
3800            merge_strategy: crate::bitbucket::pull_request::MergeStrategy::Squash,
3801            wait_for_builds: true,
3802            build_timeout: Duration::from_secs(1800),
3803            allowed_authors: None,
3804        };
3805
3806        // Verify the conditions are set as expected for auto-land
3807        assert!(conditions.wait_for_builds);
3808        assert_eq!(conditions.build_timeout.as_secs(), 1800);
3809        assert!(conditions.allowed_authors.is_none());
3810        assert!(matches!(
3811            conditions.merge_strategy,
3812            crate::bitbucket::pull_request::MergeStrategy::Squash
3813        ));
3814    }
3815
3816    #[test]
3817    fn test_polling_constants() {
3818        // Test that polling frequency is documented and reasonable
3819        use std::time::Duration;
3820
3821        // The polling frequency should be 30 seconds as mentioned in documentation
3822        let expected_polling_interval = Duration::from_secs(30);
3823
3824        // Verify it's a reasonable value (not too frequent, not too slow)
3825        assert!(expected_polling_interval.as_secs() >= 10); // At least 10 seconds
3826        assert!(expected_polling_interval.as_secs() <= 60); // At most 1 minute
3827        assert_eq!(expected_polling_interval.as_secs(), 30); // Exactly 30 seconds
3828    }
3829
3830    #[test]
3831    fn test_build_timeout_defaults() {
3832        // Verify build timeout default is reasonable
3833        const DEFAULT_TIMEOUT: u64 = 1800; // 30 minutes
3834        assert_eq!(DEFAULT_TIMEOUT, 1800);
3835        // Test that our default timeout value is within reasonable bounds
3836        let timeout_value = 1800u64;
3837        assert!(timeout_value >= 300); // At least 5 minutes
3838        assert!(timeout_value <= 3600); // At most 1 hour
3839    }
3840
3841    #[test]
3842    fn test_scattered_commit_detection() {
3843        use std::collections::HashSet;
3844
3845        // Test scattered commit detection logic
3846        let mut source_branches = HashSet::new();
3847        source_branches.insert("feature-branch-1".to_string());
3848        source_branches.insert("feature-branch-2".to_string());
3849        source_branches.insert("feature-branch-3".to_string());
3850
3851        // Single branch should not trigger warning
3852        let single_branch = HashSet::from(["main".to_string()]);
3853        assert_eq!(single_branch.len(), 1);
3854
3855        // Multiple branches should trigger warning
3856        assert!(source_branches.len() > 1);
3857        assert_eq!(source_branches.len(), 3);
3858
3859        // Verify branch names are preserved correctly
3860        assert!(source_branches.contains("feature-branch-1"));
3861        assert!(source_branches.contains("feature-branch-2"));
3862        assert!(source_branches.contains("feature-branch-3"));
3863    }
3864
3865    #[test]
3866    fn test_source_branch_tracking() {
3867        // Test that source branch tracking correctly handles different scenarios
3868
3869        // Same branch should be consistent
3870        let branch_a = "feature-work";
3871        let branch_b = "feature-work";
3872        assert_eq!(branch_a, branch_b);
3873
3874        // Different branches should be detected
3875        let branch_1 = "feature-ui";
3876        let branch_2 = "feature-api";
3877        assert_ne!(branch_1, branch_2);
3878
3879        // Branch naming patterns
3880        assert!(branch_1.starts_with("feature-"));
3881        assert!(branch_2.starts_with("feature-"));
3882    }
3883
3884    // Tests for new default behavior (removing --all flag)
3885
3886    #[tokio::test]
3887    async fn test_push_default_behavior() {
3888        // Test the push_to_stack function structure and error handling in an isolated environment
3889        let (temp_dir, repo_path) = match create_test_repo() {
3890            Ok(repo) => repo,
3891            Err(_) => {
3892                println!("Skipping test due to git environment setup failure");
3893                return;
3894            }
3895        };
3896        // IMPORTANT: temp_dir must stay in scope to prevent early cleanup of test directory
3897        let _ = &temp_dir;
3898
3899        // Verify directory exists before changing to it
3900        if !repo_path.exists() {
3901            println!("Skipping test due to temporary directory creation issue");
3902            return;
3903        }
3904
3905        // Change to the test repository directory to ensure isolation
3906        let original_dir = env::current_dir().map_err(|_| "Failed to get current dir");
3907
3908        match env::set_current_dir(&repo_path) {
3909            Ok(_) => {
3910                // Test that push_to_stack properly handles the case when no stack is active
3911                let result = push_to_stack(
3912                    None,  // branch
3913                    None,  // message
3914                    None,  // commit
3915                    None,  // since
3916                    None,  // commits
3917                    None,  // squash
3918                    None,  // squash_since
3919                    false, // auto_branch
3920                    false, // allow_base_branch
3921                    false, // dry_run
3922                )
3923                .await;
3924
3925                // Restore original directory (best effort)
3926                if let Ok(orig) = original_dir {
3927                    let _ = env::set_current_dir(orig);
3928                }
3929
3930                // Should fail gracefully with appropriate error message when no stack is active
3931                match &result {
3932                    Err(e) => {
3933                        let error_msg = e.to_string();
3934                        // This is the expected behavior - no active stack should produce this error
3935                        assert!(
3936                            error_msg.contains("No active stack")
3937                                || error_msg.contains("config")
3938                                || error_msg.contains("current directory")
3939                                || error_msg.contains("Not a git repository")
3940                                || error_msg.contains("could not find repository"),
3941                            "Expected 'No active stack' or repository error, got: {error_msg}"
3942                        );
3943                    }
3944                    Ok(_) => {
3945                        // If it somehow succeeds, that's also fine (e.g., if environment is set up differently)
3946                        println!(
3947                            "Push succeeded unexpectedly - test environment may have active stack"
3948                        );
3949                    }
3950                }
3951            }
3952            Err(_) => {
3953                // Skip test if we can't change directories (CI environment issue)
3954                println!("Skipping test due to directory access restrictions");
3955            }
3956        }
3957
3958        // Verify we can construct the command structure correctly
3959        let push_action = StackAction::Push {
3960            branch: None,
3961            message: None,
3962            commit: None,
3963            since: None,
3964            commits: None,
3965            squash: None,
3966            squash_since: None,
3967            auto_branch: false,
3968            allow_base_branch: false,
3969            dry_run: false,
3970        };
3971
3972        assert!(matches!(
3973            push_action,
3974            StackAction::Push {
3975                branch: None,
3976                message: None,
3977                commit: None,
3978                since: None,
3979                commits: None,
3980                squash: None,
3981                squash_since: None,
3982                auto_branch: false,
3983                allow_base_branch: false,
3984                dry_run: false
3985            }
3986        ));
3987    }
3988
3989    #[tokio::test]
3990    async fn test_submit_default_behavior() {
3991        // Test the submit_entry function structure and error handling in an isolated environment
3992        let (temp_dir, repo_path) = match create_test_repo() {
3993            Ok(repo) => repo,
3994            Err(_) => {
3995                println!("Skipping test due to git environment setup failure");
3996                return;
3997            }
3998        };
3999        // IMPORTANT: temp_dir must stay in scope to prevent early cleanup of test directory
4000        let _ = &temp_dir;
4001
4002        // Verify directory exists before changing to it
4003        if !repo_path.exists() {
4004            println!("Skipping test due to temporary directory creation issue");
4005            return;
4006        }
4007
4008        // Change to the test repository directory to ensure isolation
4009        let original_dir = match env::current_dir() {
4010            Ok(dir) => dir,
4011            Err(_) => {
4012                println!("Skipping test due to current directory access restrictions");
4013                return;
4014            }
4015        };
4016
4017        match env::set_current_dir(&repo_path) {
4018            Ok(_) => {
4019                // Test that submit_entry properly handles the case when no stack is active
4020                let result = submit_entry(
4021                    None,  // entry (should default to all unsubmitted)
4022                    None,  // title
4023                    None,  // description
4024                    None,  // range
4025                    false, // draft
4026                )
4027                .await;
4028
4029                // Restore original directory
4030                let _ = env::set_current_dir(original_dir);
4031
4032                // Should fail gracefully with appropriate error message when no stack is active
4033                match &result {
4034                    Err(e) => {
4035                        let error_msg = e.to_string();
4036                        // This is the expected behavior - no active stack should produce this error
4037                        assert!(
4038                            error_msg.contains("No active stack")
4039                                || error_msg.contains("config")
4040                                || error_msg.contains("current directory")
4041                                || error_msg.contains("Not a git repository")
4042                                || error_msg.contains("could not find repository"),
4043                            "Expected 'No active stack' or repository error, got: {error_msg}"
4044                        );
4045                    }
4046                    Ok(_) => {
4047                        // If it somehow succeeds, that's also fine (e.g., if environment is set up differently)
4048                        println!("Submit succeeded unexpectedly - test environment may have active stack");
4049                    }
4050                }
4051            }
4052            Err(_) => {
4053                // Skip test if we can't change directories (CI environment issue)
4054                println!("Skipping test due to directory access restrictions");
4055            }
4056        }
4057
4058        // Verify we can construct the command structure correctly
4059        let submit_action = StackAction::Submit {
4060            entry: None,
4061            title: None,
4062            description: None,
4063            range: None,
4064            draft: false,
4065        };
4066
4067        assert!(matches!(
4068            submit_action,
4069            StackAction::Submit {
4070                entry: None,
4071                title: None,
4072                description: None,
4073                range: None,
4074                draft: false
4075            }
4076        ));
4077    }
4078
4079    #[test]
4080    fn test_targeting_options_still_work() {
4081        // Test that specific targeting options still work correctly
4082
4083        // Test commit list parsing
4084        let commits = "abc123,def456,ghi789";
4085        let parsed: Vec<&str> = commits.split(',').map(|s| s.trim()).collect();
4086        assert_eq!(parsed.len(), 3);
4087        assert_eq!(parsed[0], "abc123");
4088        assert_eq!(parsed[1], "def456");
4089        assert_eq!(parsed[2], "ghi789");
4090
4091        // Test range parsing would work
4092        let range = "1-3";
4093        assert!(range.contains('-'));
4094        let parts: Vec<&str> = range.split('-').collect();
4095        assert_eq!(parts.len(), 2);
4096
4097        // Test since reference pattern
4098        let since_ref = "HEAD~3";
4099        assert!(since_ref.starts_with("HEAD"));
4100        assert!(since_ref.contains('~'));
4101    }
4102
4103    #[test]
4104    fn test_command_flow_logic() {
4105        // These just test the command structure exists
4106        assert!(matches!(
4107            StackAction::Push {
4108                branch: None,
4109                message: None,
4110                commit: None,
4111                since: None,
4112                commits: None,
4113                squash: None,
4114                squash_since: None,
4115                auto_branch: false,
4116                allow_base_branch: false,
4117                dry_run: false
4118            },
4119            StackAction::Push { .. }
4120        ));
4121
4122        assert!(matches!(
4123            StackAction::Submit {
4124                entry: None,
4125                title: None,
4126                description: None,
4127                range: None,
4128                draft: false
4129            },
4130            StackAction::Submit { .. }
4131        ));
4132    }
4133
4134    #[tokio::test]
4135    async fn test_deactivate_command_structure() {
4136        // Test that deactivate command structure exists and can be constructed
4137        let deactivate_action = StackAction::Deactivate { force: false };
4138
4139        // Verify it matches the expected pattern
4140        assert!(matches!(
4141            deactivate_action,
4142            StackAction::Deactivate { force: false }
4143        ));
4144
4145        // Test with force flag
4146        let force_deactivate = StackAction::Deactivate { force: true };
4147        assert!(matches!(
4148            force_deactivate,
4149            StackAction::Deactivate { force: true }
4150        ));
4151    }
4152}