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!("      Author: {}", pr.author.user.display_name);
1861                    if let Some(url) = pr.web_url() {
1862                        println!("      URL: {url}");
1863                    }
1864                    if let Some(desc) = &pr.description {
1865                        if !desc.is_empty() {
1866                            println!("      Description: {desc}");
1867                        }
1868                    }
1869                    println!();
1870                }
1871            }
1872
1873            if !verbose {
1874                println!("\nUse --verbose for more details");
1875            }
1876        }
1877        Err(e) => {
1878            warn!("Failed to list pull requests: {}", e);
1879            return Err(e);
1880        }
1881    }
1882
1883    Ok(())
1884}
1885
1886async fn check_stack(_force: bool) -> Result<()> {
1887    let current_dir = env::current_dir()
1888        .map_err(|e| CascadeError::config(format!("Could not get current directory: {e}")))?;
1889
1890    let repo_root = find_repository_root(&current_dir)
1891        .map_err(|e| CascadeError::config(format!("Could not find git repository: {e}")))?;
1892
1893    let mut manager = StackManager::new(&repo_root)?;
1894
1895    let active_stack = manager
1896        .get_active_stack()
1897        .ok_or_else(|| CascadeError::config("No active stack"))?;
1898    let stack_id = active_stack.id;
1899
1900    manager.sync_stack(&stack_id)?;
1901
1902    Output::success("Stack check completed successfully");
1903
1904    Ok(())
1905}
1906
1907async fn sync_stack(force: bool, skip_cleanup: bool, interactive: bool) -> Result<()> {
1908    let current_dir = env::current_dir()
1909        .map_err(|e| CascadeError::config(format!("Could not get current directory: {e}")))?;
1910
1911    let repo_root = find_repository_root(&current_dir)
1912        .map_err(|e| CascadeError::config(format!("Could not find git repository: {e}")))?;
1913
1914    let stack_manager = StackManager::new(&repo_root)?;
1915    let git_repo = GitRepository::open(&repo_root)?;
1916
1917    // Get active stack
1918    let active_stack = stack_manager.get_active_stack().ok_or_else(|| {
1919        CascadeError::config("No active stack. Create a stack first with 'ca stack create'")
1920    })?;
1921
1922    let base_branch = active_stack.base_branch.clone();
1923    let stack_name = active_stack.name.clone();
1924
1925    Output::progress(format!("Syncing stack '{stack_name}' with remote..."));
1926
1927    // Step 1: Pull latest changes from base branch
1928    Output::section(format!("Pulling latest changes from '{base_branch}'"));
1929
1930    // Checkout base branch first
1931    match git_repo.checkout_branch(&base_branch) {
1932        Ok(_) => {
1933            Output::sub_item(format!("Switched to '{base_branch}'"));
1934
1935            // Pull latest changes
1936            match git_repo.pull(&base_branch) {
1937                Ok(_) => {
1938                    Output::sub_item("Successfully pulled latest changes");
1939                }
1940                Err(e) => {
1941                    if force {
1942                        Output::warning(format!("Failed to pull: {e} (continuing due to --force)"));
1943                    } else {
1944                        return Err(CascadeError::branch(format!(
1945                            "Failed to pull latest changes from '{base_branch}': {e}. Use --force to continue anyway."
1946                        )));
1947                    }
1948                }
1949            }
1950        }
1951        Err(e) => {
1952            if force {
1953                Output::warning(format!(
1954                    "Failed to checkout '{base_branch}': {e} (continuing due to --force)"
1955                ));
1956            } else {
1957                return Err(CascadeError::branch(format!(
1958                    "Failed to checkout base branch '{base_branch}': {e}. Use --force to continue anyway."
1959                )));
1960            }
1961        }
1962    }
1963
1964    // Step 2: Check if stack needs rebase
1965    Output::section("Checking if stack needs rebase");
1966
1967    let mut updated_stack_manager = StackManager::new(&repo_root)?;
1968    let stack_id = active_stack.id;
1969
1970    match updated_stack_manager.sync_stack(&stack_id) {
1971        Ok(_) => {
1972            // Check the updated status
1973            if let Some(updated_stack) = updated_stack_manager.get_stack(&stack_id) {
1974                match &updated_stack.status {
1975                    crate::stack::StackStatus::NeedsSync => {
1976                        Output::sub_item(format!(
1977                            "Stack needs rebase due to new commits on '{base_branch}'"
1978                        ));
1979
1980                        // Step 3: Rebase the stack
1981                        Output::section(format!("Rebasing stack onto updated '{base_branch}'"));
1982
1983                        // Load configuration for Bitbucket integration
1984                        let config_dir = crate::config::get_repo_config_dir(&repo_root)?;
1985                        let config_path = config_dir.join("config.json");
1986                        let settings = crate::config::Settings::load_from_file(&config_path)?;
1987
1988                        let cascade_config = crate::config::CascadeConfig {
1989                            bitbucket: Some(settings.bitbucket.clone()),
1990                            git: settings.git.clone(),
1991                            auth: crate::config::AuthConfig::default(),
1992                            cascade: settings.cascade.clone(),
1993                        };
1994
1995                        // Use the existing rebase system
1996                        let options = crate::stack::RebaseOptions {
1997                            strategy: crate::stack::RebaseStrategy::BranchVersioning,
1998                            interactive,
1999                            target_base: Some(base_branch.clone()),
2000                            preserve_merges: true,
2001                            auto_resolve: !interactive,
2002                            max_retries: 3,
2003                            skip_pull: Some(true), // Skip pull since we already pulled above
2004                        };
2005
2006                        let mut rebase_manager = crate::stack::RebaseManager::new(
2007                            updated_stack_manager,
2008                            git_repo,
2009                            options,
2010                        );
2011
2012                        match rebase_manager.rebase_stack(&stack_id) {
2013                            Ok(result) => {
2014                                Output::success("Rebase completed successfully!");
2015
2016                                if !result.branch_mapping.is_empty() {
2017                                    Output::section("Updated branches:");
2018                                    for (old, new) in &result.branch_mapping {
2019                                        Output::bullet(format!("{old} → {new}"));
2020                                    }
2021
2022                                    // Update PRs if enabled
2023                                    if let Some(ref _bitbucket_config) = cascade_config.bitbucket {
2024                                        Output::sub_item("Updating pull requests...");
2025
2026                                        let integration_stack_manager =
2027                                            StackManager::new(&repo_root)?;
2028                                        let mut integration =
2029                                            crate::bitbucket::BitbucketIntegration::new(
2030                                                integration_stack_manager,
2031                                                cascade_config,
2032                                            )?;
2033
2034                                        match integration
2035                                            .update_prs_after_rebase(
2036                                                &stack_id,
2037                                                &result.branch_mapping,
2038                                            )
2039                                            .await
2040                                        {
2041                                            Ok(updated_prs) => {
2042                                                if !updated_prs.is_empty() {
2043                                                    Output::sub_item(format!(
2044                                                        "Updated {} pull requests",
2045                                                        updated_prs.len()
2046                                                    ));
2047                                                }
2048                                            }
2049                                            Err(e) => {
2050                                                Output::warning(format!(
2051                                                    "Failed to update pull requests: {e}"
2052                                                ));
2053                                            }
2054                                        }
2055                                    }
2056                                }
2057                            }
2058                            Err(e) => {
2059                                Output::error(format!("Rebase failed: {e}"));
2060                                Output::tip("To resolve conflicts:");
2061                                Output::bullet("Fix conflicts in the affected files");
2062                                Output::bullet("Stage resolved files: git add <files>");
2063                                Output::bullet("Continue: ca stack continue-rebase");
2064                                return Err(e);
2065                            }
2066                        }
2067                    }
2068                    crate::stack::StackStatus::Clean => {
2069                        Output::success("Stack is already up to date");
2070                    }
2071                    other => {
2072                        Output::info(format!("Stack status: {other:?}"));
2073                    }
2074                }
2075            }
2076        }
2077        Err(e) => {
2078            if force {
2079                Output::warning(format!(
2080                    "Failed to check stack status: {e} (continuing due to --force)"
2081                ));
2082            } else {
2083                return Err(e);
2084            }
2085        }
2086    }
2087
2088    // Step 4: Cleanup merged branches (optional)
2089    if !skip_cleanup {
2090        Output::section("Checking for merged branches to clean up");
2091        // TODO: Implement merged branch cleanup
2092        // This would:
2093        // 1. Find branches that have been merged into base
2094        // 2. Ask user if they want to delete them
2095        // 3. Remove them from the stack metadata
2096        Output::info("Branch cleanup not yet implemented");
2097    } else {
2098        Output::info("Skipping branch cleanup");
2099    }
2100
2101    Output::success("Sync completed successfully!");
2102    Output::sub_item(format!("Base branch: {base_branch}"));
2103    Output::next_steps(&[
2104        "Review your updated stack: ca stack show",
2105        "Check PR status: ca stack status",
2106    ]);
2107
2108    Ok(())
2109}
2110
2111async fn rebase_stack(
2112    interactive: bool,
2113    onto: Option<String>,
2114    strategy: Option<RebaseStrategyArg>,
2115) -> Result<()> {
2116    let current_dir = env::current_dir()
2117        .map_err(|e| CascadeError::config(format!("Could not get current directory: {e}")))?;
2118
2119    let repo_root = find_repository_root(&current_dir)
2120        .map_err(|e| CascadeError::config(format!("Could not find git repository: {e}")))?;
2121
2122    let stack_manager = StackManager::new(&repo_root)?;
2123    let git_repo = GitRepository::open(&repo_root)?;
2124
2125    // Load configuration for potential Bitbucket integration
2126    let config_dir = crate::config::get_repo_config_dir(&repo_root)?;
2127    let config_path = config_dir.join("config.json");
2128    let settings = crate::config::Settings::load_from_file(&config_path)?;
2129
2130    // Create the main config structure
2131    let cascade_config = crate::config::CascadeConfig {
2132        bitbucket: Some(settings.bitbucket.clone()),
2133        git: settings.git.clone(),
2134        auth: crate::config::AuthConfig::default(),
2135        cascade: settings.cascade.clone(),
2136    };
2137
2138    // Get active stack
2139    let active_stack = stack_manager.get_active_stack().ok_or_else(|| {
2140        CascadeError::config("No active stack. Create a stack first with 'ca stack create'")
2141    })?;
2142    let stack_id = active_stack.id;
2143
2144    let active_stack = stack_manager
2145        .get_stack(&stack_id)
2146        .ok_or_else(|| CascadeError::config("Active stack not found"))?
2147        .clone();
2148
2149    if active_stack.entries.is_empty() {
2150        Output::info("Stack is empty. Nothing to rebase.");
2151        return Ok(());
2152    }
2153
2154    Output::progress(format!("Rebasing stack: {}", active_stack.name));
2155    Output::sub_item(format!("Base: {}", active_stack.base_branch));
2156
2157    // Determine rebase strategy
2158    let rebase_strategy = if let Some(cli_strategy) = strategy {
2159        match cli_strategy {
2160            RebaseStrategyArg::BranchVersioning => crate::stack::RebaseStrategy::BranchVersioning,
2161            RebaseStrategyArg::CherryPick => crate::stack::RebaseStrategy::CherryPick,
2162            RebaseStrategyArg::ThreeWayMerge => crate::stack::RebaseStrategy::ThreeWayMerge,
2163            RebaseStrategyArg::Interactive => crate::stack::RebaseStrategy::Interactive,
2164        }
2165    } else {
2166        // Use strategy from config
2167        match settings.cascade.default_sync_strategy.as_str() {
2168            "branch-versioning" => crate::stack::RebaseStrategy::BranchVersioning,
2169            "cherry-pick" => crate::stack::RebaseStrategy::CherryPick,
2170            "three-way-merge" => crate::stack::RebaseStrategy::ThreeWayMerge,
2171            "rebase" => crate::stack::RebaseStrategy::Interactive,
2172            _ => crate::stack::RebaseStrategy::BranchVersioning, // default fallback
2173        }
2174    };
2175
2176    // Create rebase options
2177    let options = crate::stack::RebaseOptions {
2178        strategy: rebase_strategy.clone(),
2179        interactive,
2180        target_base: onto,
2181        preserve_merges: true,
2182        auto_resolve: !interactive, // Auto-resolve unless interactive
2183        max_retries: 3,
2184        skip_pull: None, // Normal rebase should pull latest changes
2185    };
2186
2187    info!("   Strategy: {:?}", rebase_strategy);
2188    info!("   Interactive: {}", interactive);
2189    info!("   Target base: {:?}", options.target_base);
2190    info!("   Entries: {}", active_stack.entries.len());
2191
2192    // Check if there's already a rebase in progress
2193    let mut rebase_manager = crate::stack::RebaseManager::new(stack_manager, git_repo, options);
2194
2195    if rebase_manager.is_rebase_in_progress() {
2196        Output::warning("Rebase already in progress!");
2197        Output::tip("Use 'git status' to check the current state");
2198        Output::next_steps(&[
2199            "Run 'ca stack continue-rebase' to continue",
2200            "Run 'ca stack abort-rebase' to abort",
2201        ]);
2202        return Ok(());
2203    }
2204
2205    // Perform the rebase
2206    match rebase_manager.rebase_stack(&stack_id) {
2207        Ok(result) => {
2208            Output::success("Rebase completed!");
2209            Output::sub_item(result.get_summary());
2210
2211            if result.has_conflicts() {
2212                Output::warning(format!(
2213                    "{} conflicts were resolved",
2214                    result.conflicts.len()
2215                ));
2216                for conflict in &result.conflicts {
2217                    Output::bullet(&conflict[..8.min(conflict.len())]);
2218                }
2219            }
2220
2221            if !result.branch_mapping.is_empty() {
2222                Output::section("Branch mapping");
2223                for (old, new) in &result.branch_mapping {
2224                    Output::bullet(format!("{old} -> {new}"));
2225                }
2226
2227                // Handle PR updates if enabled
2228                if let Some(ref _bitbucket_config) = cascade_config.bitbucket {
2229                    // Create a new StackManager for the integration (since the original was moved)
2230                    let integration_stack_manager = StackManager::new(&repo_root)?;
2231                    let mut integration = BitbucketIntegration::new(
2232                        integration_stack_manager,
2233                        cascade_config.clone(),
2234                    )?;
2235
2236                    match integration
2237                        .update_prs_after_rebase(&stack_id, &result.branch_mapping)
2238                        .await
2239                    {
2240                        Ok(updated_prs) => {
2241                            if !updated_prs.is_empty() {
2242                                println!("   🔄 Preserved pull request history:");
2243                                for pr_update in updated_prs {
2244                                    println!("      ✅ {pr_update}");
2245                                }
2246                            }
2247                        }
2248                        Err(e) => {
2249                            eprintln!("   ⚠️  Failed to update pull requests: {e}");
2250                            eprintln!("      You may need to manually update PRs in Bitbucket");
2251                        }
2252                    }
2253                }
2254            }
2255
2256            println!(
2257                "   ✅ {} commits successfully rebased",
2258                result.success_count()
2259            );
2260
2261            // Show next steps
2262            if matches!(
2263                rebase_strategy,
2264                crate::stack::RebaseStrategy::BranchVersioning
2265            ) {
2266                println!("\n📝 Next steps:");
2267                if !result.branch_mapping.is_empty() {
2268                    println!("   1. ✅ New versioned branches have been created");
2269                    println!("   2. ✅ Pull requests have been updated automatically");
2270                    println!("   3. 🔍 Review the updated PRs in Bitbucket");
2271                    println!("   4. 🧪 Test your changes on the new branches");
2272                    println!(
2273                        "   5. 🗑️  Old branches are preserved for safety (can be deleted later)"
2274                    );
2275                } else {
2276                    println!("   1. Review the rebased stack");
2277                    println!("   2. Test your changes");
2278                    println!("   3. Submit new pull requests with 'ca stack submit'");
2279                }
2280            }
2281        }
2282        Err(e) => {
2283            warn!("❌ Rebase failed: {}", e);
2284            println!("💡 Tips for resolving rebase issues:");
2285            println!("   - Check for uncommitted changes with 'git status'");
2286            println!("   - Ensure base branch is up to date");
2287            println!("   - Try interactive mode: 'ca stack rebase --interactive'");
2288            return Err(e);
2289        }
2290    }
2291
2292    Ok(())
2293}
2294
2295async fn continue_rebase() -> Result<()> {
2296    let current_dir = env::current_dir()
2297        .map_err(|e| CascadeError::config(format!("Could not get current directory: {e}")))?;
2298
2299    let repo_root = find_repository_root(&current_dir)
2300        .map_err(|e| CascadeError::config(format!("Could not find git repository: {e}")))?;
2301
2302    let stack_manager = StackManager::new(&repo_root)?;
2303    let git_repo = crate::git::GitRepository::open(&repo_root)?;
2304    let options = crate::stack::RebaseOptions::default();
2305    let rebase_manager = crate::stack::RebaseManager::new(stack_manager, git_repo, options);
2306
2307    if !rebase_manager.is_rebase_in_progress() {
2308        println!("ℹ️  No rebase in progress");
2309        return Ok(());
2310    }
2311
2312    println!("🔄 Continuing rebase...");
2313    match rebase_manager.continue_rebase() {
2314        Ok(_) => {
2315            println!("✅ Rebase continued successfully");
2316            println!("   Check 'ca stack rebase-status' for current state");
2317        }
2318        Err(e) => {
2319            warn!("❌ Failed to continue rebase: {}", e);
2320            println!("💡 You may need to resolve conflicts first:");
2321            println!("   1. Edit conflicted files");
2322            println!("   2. Stage resolved files with 'git add'");
2323            println!("   3. Run 'ca stack continue-rebase' again");
2324        }
2325    }
2326
2327    Ok(())
2328}
2329
2330async fn abort_rebase() -> Result<()> {
2331    let current_dir = env::current_dir()
2332        .map_err(|e| CascadeError::config(format!("Could not get current directory: {e}")))?;
2333
2334    let repo_root = find_repository_root(&current_dir)
2335        .map_err(|e| CascadeError::config(format!("Could not find git repository: {e}")))?;
2336
2337    let stack_manager = StackManager::new(&repo_root)?;
2338    let git_repo = crate::git::GitRepository::open(&repo_root)?;
2339    let options = crate::stack::RebaseOptions::default();
2340    let rebase_manager = crate::stack::RebaseManager::new(stack_manager, git_repo, options);
2341
2342    if !rebase_manager.is_rebase_in_progress() {
2343        println!("ℹ️  No rebase in progress");
2344        return Ok(());
2345    }
2346
2347    println!("⚠️  Aborting rebase...");
2348    match rebase_manager.abort_rebase() {
2349        Ok(_) => {
2350            println!("✅ Rebase aborted successfully");
2351            println!("   Repository restored to pre-rebase state");
2352        }
2353        Err(e) => {
2354            warn!("❌ Failed to abort rebase: {}", e);
2355            println!("⚠️  You may need to manually clean up the repository state");
2356        }
2357    }
2358
2359    Ok(())
2360}
2361
2362async fn rebase_status() -> Result<()> {
2363    let current_dir = env::current_dir()
2364        .map_err(|e| CascadeError::config(format!("Could not get current directory: {e}")))?;
2365
2366    let repo_root = find_repository_root(&current_dir)
2367        .map_err(|e| CascadeError::config(format!("Could not find git repository: {e}")))?;
2368
2369    let stack_manager = StackManager::new(&repo_root)?;
2370    let git_repo = crate::git::GitRepository::open(&repo_root)?;
2371
2372    println!("📊 Rebase Status");
2373
2374    // Check if rebase is in progress by checking git state directly
2375    let git_dir = current_dir.join(".git");
2376    let rebase_in_progress = git_dir.join("REBASE_HEAD").exists()
2377        || git_dir.join("rebase-merge").exists()
2378        || git_dir.join("rebase-apply").exists();
2379
2380    if rebase_in_progress {
2381        println!("   Status: 🔄 Rebase in progress");
2382        println!(
2383            "   
2384📝 Actions available:"
2385        );
2386        println!("     - 'ca stack continue-rebase' to continue");
2387        println!("     - 'ca stack abort-rebase' to abort");
2388        println!("     - 'git status' to see conflicted files");
2389
2390        // Check for conflicts
2391        match git_repo.get_status() {
2392            Ok(statuses) => {
2393                let mut conflicts = Vec::new();
2394                for status in statuses.iter() {
2395                    if status.status().contains(git2::Status::CONFLICTED) {
2396                        if let Some(path) = status.path() {
2397                            conflicts.push(path.to_string());
2398                        }
2399                    }
2400                }
2401
2402                if !conflicts.is_empty() {
2403                    println!("   ⚠️  Conflicts in {} files:", conflicts.len());
2404                    for conflict in conflicts {
2405                        println!("      - {conflict}");
2406                    }
2407                    println!(
2408                        "   
2409💡 To resolve conflicts:"
2410                    );
2411                    println!("     1. Edit the conflicted files");
2412                    println!("     2. Stage resolved files: git add <file>");
2413                    println!("     3. Continue: ca stack continue-rebase");
2414                }
2415            }
2416            Err(e) => {
2417                warn!("Failed to get git status: {}", e);
2418            }
2419        }
2420    } else {
2421        println!("   Status: ✅ No rebase in progress");
2422
2423        // Show stack status instead
2424        if let Some(active_stack) = stack_manager.get_active_stack() {
2425            println!("   Active stack: {}", active_stack.name);
2426            println!("   Entries: {}", active_stack.entries.len());
2427            println!("   Base branch: {}", active_stack.base_branch);
2428        }
2429    }
2430
2431    Ok(())
2432}
2433
2434async fn delete_stack(name: String, force: bool) -> Result<()> {
2435    let current_dir = env::current_dir()
2436        .map_err(|e| CascadeError::config(format!("Could not get current directory: {e}")))?;
2437
2438    let repo_root = find_repository_root(&current_dir)
2439        .map_err(|e| CascadeError::config(format!("Could not find git repository: {e}")))?;
2440
2441    let mut manager = StackManager::new(&repo_root)?;
2442
2443    let stack = manager
2444        .get_stack_by_name(&name)
2445        .ok_or_else(|| CascadeError::config(format!("Stack '{name}' not found")))?;
2446    let stack_id = stack.id;
2447
2448    if !force && !stack.entries.is_empty() {
2449        return Err(CascadeError::config(format!(
2450            "Stack '{}' has {} entries. Use --force to delete anyway",
2451            name,
2452            stack.entries.len()
2453        )));
2454    }
2455
2456    let deleted = manager.delete_stack(&stack_id)?;
2457
2458    Output::success(format!("Deleted stack '{}'", deleted.name));
2459    if !deleted.entries.is_empty() {
2460        Output::warning(format!("{} entries were removed", deleted.entries.len()));
2461    }
2462
2463    Ok(())
2464}
2465
2466async fn validate_stack(name: Option<String>, fix_mode: Option<String>) -> Result<()> {
2467    let current_dir = env::current_dir()
2468        .map_err(|e| CascadeError::config(format!("Could not get current directory: {e}")))?;
2469
2470    let repo_root = find_repository_root(&current_dir)
2471        .map_err(|e| CascadeError::config(format!("Could not find git repository: {e}")))?;
2472
2473    let mut manager = StackManager::new(&repo_root)?;
2474
2475    if let Some(name) = name {
2476        // Validate specific stack
2477        let stack = manager
2478            .get_stack_by_name(&name)
2479            .ok_or_else(|| CascadeError::config(format!("Stack '{name}' not found")))?;
2480
2481        let stack_id = stack.id;
2482
2483        // Basic structure validation first
2484        match stack.validate() {
2485            Ok(message) => {
2486                println!("✅ Stack '{name}' structure validation: {message}");
2487            }
2488            Err(e) => {
2489                println!("❌ Stack '{name}' structure validation failed: {e}");
2490                return Err(CascadeError::config(e));
2491            }
2492        }
2493
2494        // Handle branch modifications (includes Git integrity checks)
2495        manager.handle_branch_modifications(&stack_id, fix_mode)?;
2496
2497        println!("🎉 Stack '{name}' validation completed");
2498        Ok(())
2499    } else {
2500        // Validate all stacks
2501        println!("🔍 Validating all stacks...");
2502
2503        // Get all stack IDs through public method
2504        let all_stacks = manager.get_all_stacks();
2505        let stack_ids: Vec<uuid::Uuid> = all_stacks.iter().map(|s| s.id).collect();
2506
2507        if stack_ids.is_empty() {
2508            println!("📭 No stacks found");
2509            return Ok(());
2510        }
2511
2512        let mut all_valid = true;
2513        for stack_id in stack_ids {
2514            let stack = manager.get_stack(&stack_id).unwrap();
2515            let stack_name = &stack.name;
2516
2517            println!("\n📋 Checking stack '{stack_name}':");
2518
2519            // Basic structure validation
2520            match stack.validate() {
2521                Ok(message) => {
2522                    println!("  ✅ Structure: {message}");
2523                }
2524                Err(e) => {
2525                    println!("  ❌ Structure: {e}");
2526                    all_valid = false;
2527                    continue;
2528                }
2529            }
2530
2531            // Handle branch modifications
2532            match manager.handle_branch_modifications(&stack_id, fix_mode.clone()) {
2533                Ok(_) => {
2534                    println!("  ✅ Git integrity: OK");
2535                }
2536                Err(e) => {
2537                    println!("  ❌ Git integrity: {e}");
2538                    all_valid = false;
2539                }
2540            }
2541        }
2542
2543        if all_valid {
2544            println!("\n🎉 All stacks passed validation");
2545        } else {
2546            println!("\n⚠️  Some stacks have validation issues");
2547            return Err(CascadeError::config("Stack validation failed".to_string()));
2548        }
2549
2550        Ok(())
2551    }
2552}
2553
2554/// Get commits that are not yet in any stack entry
2555#[allow(dead_code)]
2556fn get_unpushed_commits(repo: &GitRepository, stack: &crate::stack::Stack) -> Result<Vec<String>> {
2557    let mut unpushed = Vec::new();
2558    let head_commit = repo.get_head_commit()?;
2559    let mut current_commit = head_commit;
2560
2561    // Walk back from HEAD until we find a commit that's already in the stack
2562    loop {
2563        let commit_hash = current_commit.id().to_string();
2564        let already_in_stack = stack
2565            .entries
2566            .iter()
2567            .any(|entry| entry.commit_hash == commit_hash);
2568
2569        if already_in_stack {
2570            break;
2571        }
2572
2573        unpushed.push(commit_hash);
2574
2575        // Move to parent commit
2576        if let Some(parent) = current_commit.parents().next() {
2577            current_commit = parent;
2578        } else {
2579            break;
2580        }
2581    }
2582
2583    unpushed.reverse(); // Reverse to get chronological order
2584    Ok(unpushed)
2585}
2586
2587/// Squash the last N commits into a single commit
2588pub async fn squash_commits(
2589    repo: &GitRepository,
2590    count: usize,
2591    since_ref: Option<String>,
2592) -> Result<()> {
2593    if count <= 1 {
2594        return Ok(()); // Nothing to squash
2595    }
2596
2597    // Get the current branch
2598    let _current_branch = repo.get_current_branch()?;
2599
2600    // Determine the range for interactive rebase
2601    let rebase_range = if let Some(ref since) = since_ref {
2602        since.clone()
2603    } else {
2604        format!("HEAD~{count}")
2605    };
2606
2607    println!("   Analyzing {count} commits to create smart squash message...");
2608
2609    // Get the commits that will be squashed to create a smart message
2610    let head_commit = repo.get_head_commit()?;
2611    let mut commits_to_squash = Vec::new();
2612    let mut current = head_commit;
2613
2614    // Collect the last N commits
2615    for _ in 0..count {
2616        commits_to_squash.push(current.clone());
2617        if current.parent_count() > 0 {
2618            current = current.parent(0).map_err(CascadeError::Git)?;
2619        } else {
2620            break;
2621        }
2622    }
2623
2624    // Generate smart commit message from the squashed commits
2625    let smart_message = generate_squash_message(&commits_to_squash)?;
2626    println!(
2627        "   Smart message: {}",
2628        smart_message.lines().next().unwrap_or("")
2629    );
2630
2631    // Get the commit we want to reset to (the commit before our range)
2632    let reset_target = if since_ref.is_some() {
2633        // If squashing since a reference, reset to that reference
2634        format!("{rebase_range}~1")
2635    } else {
2636        // If squashing last N commits, reset to N commits before
2637        format!("HEAD~{count}")
2638    };
2639
2640    // Soft reset to preserve changes in staging area
2641    repo.reset_soft(&reset_target)?;
2642
2643    // Stage all changes (they should already be staged from the reset --soft)
2644    repo.stage_all()?;
2645
2646    // Create the new commit with the smart message
2647    let new_commit_hash = repo.commit(&smart_message)?;
2648
2649    println!(
2650        "   Created squashed commit: {} ({})",
2651        &new_commit_hash[..8],
2652        smart_message.lines().next().unwrap_or("")
2653    );
2654    println!("   💡 Tip: Use 'git commit --amend' to edit the commit message if needed");
2655
2656    Ok(())
2657}
2658
2659/// Generate a smart commit message from multiple commits being squashed
2660pub fn generate_squash_message(commits: &[git2::Commit]) -> Result<String> {
2661    if commits.is_empty() {
2662        return Ok("Squashed commits".to_string());
2663    }
2664
2665    // Get all commit messages
2666    let messages: Vec<String> = commits
2667        .iter()
2668        .map(|c| c.message().unwrap_or("").trim().to_string())
2669        .filter(|m| !m.is_empty())
2670        .collect();
2671
2672    if messages.is_empty() {
2673        return Ok("Squashed commits".to_string());
2674    }
2675
2676    // Strategy 1: If the last commit looks like a "Final:" commit, use it
2677    if let Some(last_msg) = messages.first() {
2678        // first() because we're in reverse chronological order
2679        if last_msg.starts_with("Final:") || last_msg.starts_with("final:") {
2680            return Ok(last_msg
2681                .trim_start_matches("Final:")
2682                .trim_start_matches("final:")
2683                .trim()
2684                .to_string());
2685        }
2686    }
2687
2688    // Strategy 2: If most commits are WIP, find the most descriptive non-WIP message
2689    let wip_count = messages
2690        .iter()
2691        .filter(|m| {
2692            m.to_lowercase().starts_with("wip") || m.to_lowercase().contains("work in progress")
2693        })
2694        .count();
2695
2696    if wip_count > messages.len() / 2 {
2697        // Mostly WIP commits, find the best non-WIP one or create a summary
2698        let non_wip: Vec<&String> = messages
2699            .iter()
2700            .filter(|m| {
2701                !m.to_lowercase().starts_with("wip")
2702                    && !m.to_lowercase().contains("work in progress")
2703            })
2704            .collect();
2705
2706        if let Some(best_msg) = non_wip.first() {
2707            return Ok(best_msg.to_string());
2708        }
2709
2710        // All are WIP, try to extract the feature being worked on
2711        let feature = extract_feature_from_wip(&messages);
2712        return Ok(feature);
2713    }
2714
2715    // Strategy 3: Use the last (most recent) commit message
2716    Ok(messages.first().unwrap().clone())
2717}
2718
2719/// Extract feature name from WIP commit messages
2720pub fn extract_feature_from_wip(messages: &[String]) -> String {
2721    // Look for patterns like "WIP: add authentication" -> "Add authentication"
2722    for msg in messages {
2723        // Check both case variations, but preserve original case
2724        if msg.to_lowercase().starts_with("wip:") {
2725            if let Some(rest) = msg
2726                .strip_prefix("WIP:")
2727                .or_else(|| msg.strip_prefix("wip:"))
2728            {
2729                let feature = rest.trim();
2730                if !feature.is_empty() && feature.len() > 3 {
2731                    // Capitalize first letter only, preserve rest
2732                    let mut chars: Vec<char> = feature.chars().collect();
2733                    if let Some(first) = chars.first_mut() {
2734                        *first = first.to_uppercase().next().unwrap_or(*first);
2735                    }
2736                    return chars.into_iter().collect();
2737                }
2738            }
2739        }
2740    }
2741
2742    // Fallback: Use the latest commit without WIP prefix
2743    if let Some(first) = messages.first() {
2744        let cleaned = first
2745            .trim_start_matches("WIP:")
2746            .trim_start_matches("wip:")
2747            .trim_start_matches("WIP")
2748            .trim_start_matches("wip")
2749            .trim();
2750
2751        if !cleaned.is_empty() {
2752            return format!("Implement {cleaned}");
2753        }
2754    }
2755
2756    format!("Squashed {} commits", messages.len())
2757}
2758
2759/// Count commits since a given reference
2760pub fn count_commits_since(repo: &GitRepository, since_commit_hash: &str) -> Result<usize> {
2761    let head_commit = repo.get_head_commit()?;
2762    let since_commit = repo.get_commit(since_commit_hash)?;
2763
2764    let mut count = 0;
2765    let mut current = head_commit;
2766
2767    // Walk backwards from HEAD until we reach the since commit
2768    loop {
2769        if current.id() == since_commit.id() {
2770            break;
2771        }
2772
2773        count += 1;
2774
2775        // Get parent commit
2776        if current.parent_count() == 0 {
2777            break; // Reached root commit
2778        }
2779
2780        current = current.parent(0).map_err(CascadeError::Git)?;
2781    }
2782
2783    Ok(count)
2784}
2785
2786/// Land (merge) approved stack entries
2787async fn land_stack(
2788    entry: Option<usize>,
2789    force: bool,
2790    dry_run: bool,
2791    auto: bool,
2792    wait_for_builds: bool,
2793    strategy: Option<MergeStrategyArg>,
2794    build_timeout: u64,
2795) -> Result<()> {
2796    let current_dir = env::current_dir()
2797        .map_err(|e| CascadeError::config(format!("Could not get current directory: {e}")))?;
2798
2799    let repo_root = find_repository_root(&current_dir)
2800        .map_err(|e| CascadeError::config(format!("Could not find git repository: {e}")))?;
2801
2802    let stack_manager = StackManager::new(&repo_root)?;
2803
2804    // Get stack ID and active stack before moving stack_manager
2805    let stack_id = stack_manager
2806        .get_active_stack()
2807        .map(|s| s.id)
2808        .ok_or_else(|| {
2809            CascadeError::config(
2810                "No active stack. Use 'ca stack create' or 'ca stack switch' to select a stack"
2811                    .to_string(),
2812            )
2813        })?;
2814
2815    let active_stack = stack_manager
2816        .get_active_stack()
2817        .cloned()
2818        .ok_or_else(|| CascadeError::config("No active stack found".to_string()))?;
2819
2820    // Load configuration and create Bitbucket integration
2821    let config_dir = crate::config::get_repo_config_dir(&repo_root)?;
2822    let config_path = config_dir.join("config.json");
2823    let settings = crate::config::Settings::load_from_file(&config_path)?;
2824
2825    let cascade_config = crate::config::CascadeConfig {
2826        bitbucket: Some(settings.bitbucket.clone()),
2827        git: settings.git.clone(),
2828        auth: crate::config::AuthConfig::default(),
2829        cascade: settings.cascade.clone(),
2830    };
2831
2832    let integration = crate::bitbucket::BitbucketIntegration::new(stack_manager, cascade_config)?;
2833
2834    // Get enhanced status
2835    let status = integration.check_enhanced_stack_status(&stack_id).await?;
2836
2837    if status.enhanced_statuses.is_empty() {
2838        println!("❌ No pull requests found to land");
2839        return Ok(());
2840    }
2841
2842    // Filter PRs that are ready to land
2843    let ready_prs: Vec<_> = status
2844        .enhanced_statuses
2845        .iter()
2846        .filter(|pr_status| {
2847            // If specific entry requested, only include that one
2848            if let Some(entry_num) = entry {
2849                // Find the corresponding stack entry for this PR
2850                if let Some(stack_entry) = active_stack.entries.get(entry_num.saturating_sub(1)) {
2851                    // Check if this PR corresponds to the requested entry
2852                    if pr_status.pr.from_ref.display_id != stack_entry.branch {
2853                        return false;
2854                    }
2855                } else {
2856                    return false; // Invalid entry number
2857                }
2858            }
2859
2860            if force {
2861                // If force is enabled, include any open PR
2862                pr_status.pr.state == crate::bitbucket::pull_request::PullRequestState::Open
2863            } else {
2864                pr_status.is_ready_to_land()
2865            }
2866        })
2867        .collect();
2868
2869    if ready_prs.is_empty() {
2870        if let Some(entry_num) = entry {
2871            println!("❌ Entry {entry_num} is not ready to land or doesn't exist");
2872        } else {
2873            println!("❌ No pull requests are ready to land");
2874        }
2875
2876        // Show what's blocking them
2877        println!("\n🚫 Blocking Issues:");
2878        for pr_status in &status.enhanced_statuses {
2879            if pr_status.pr.state == crate::bitbucket::pull_request::PullRequestState::Open {
2880                let blocking = pr_status.get_blocking_reasons();
2881                if !blocking.is_empty() {
2882                    println!("   PR #{}: {}", pr_status.pr.id, blocking.join(", "));
2883                }
2884            }
2885        }
2886
2887        if !force {
2888            println!("\n💡 Use --force to land PRs with blocking issues (dangerous!)");
2889        }
2890        return Ok(());
2891    }
2892
2893    if dry_run {
2894        if let Some(entry_num) = entry {
2895            println!("🏃 Dry Run - Entry {entry_num} that would be landed:");
2896        } else {
2897            println!("🏃 Dry Run - PRs that would be landed:");
2898        }
2899        for pr_status in &ready_prs {
2900            println!("   ✅ PR #{}: {}", pr_status.pr.id, pr_status.pr.title);
2901            if !pr_status.is_ready_to_land() && force {
2902                let blocking = pr_status.get_blocking_reasons();
2903                println!(
2904                    "      ⚠️  Would force land despite: {}",
2905                    blocking.join(", ")
2906                );
2907            }
2908        }
2909        return Ok(());
2910    }
2911
2912    // Default behavior: land all ready PRs (safest approach)
2913    // Only land specific entry if explicitly requested
2914    if entry.is_some() && ready_prs.len() > 1 {
2915        println!(
2916            "🎯 {} PRs are ready to land, but landing only entry #{}",
2917            ready_prs.len(),
2918            entry.unwrap()
2919        );
2920    }
2921
2922    // Setup auto-merge conditions
2923    let merge_strategy: crate::bitbucket::pull_request::MergeStrategy =
2924        strategy.unwrap_or(MergeStrategyArg::Squash).into();
2925    let auto_merge_conditions = crate::bitbucket::pull_request::AutoMergeConditions {
2926        merge_strategy: merge_strategy.clone(),
2927        wait_for_builds,
2928        build_timeout: std::time::Duration::from_secs(build_timeout),
2929        allowed_authors: None, // Allow all authors for now
2930    };
2931
2932    // Land the PRs
2933    println!(
2934        "🚀 Landing {} PR{}...",
2935        ready_prs.len(),
2936        if ready_prs.len() == 1 { "" } else { "s" }
2937    );
2938
2939    let pr_manager = crate::bitbucket::pull_request::PullRequestManager::new(
2940        crate::bitbucket::BitbucketClient::new(&settings.bitbucket)?,
2941    );
2942
2943    // Land PRs in dependency order
2944    let mut landed_count = 0;
2945    let mut failed_count = 0;
2946    let total_ready_prs = ready_prs.len();
2947
2948    for pr_status in ready_prs {
2949        let pr_id = pr_status.pr.id;
2950
2951        print!("🚀 Landing PR #{}: {}", pr_id, pr_status.pr.title);
2952
2953        let land_result = if auto {
2954            // Use auto-merge with conditions checking
2955            pr_manager
2956                .auto_merge_if_ready(pr_id, &auto_merge_conditions)
2957                .await
2958        } else {
2959            // Manual merge without auto-conditions
2960            pr_manager
2961                .merge_pull_request(pr_id, merge_strategy.clone())
2962                .await
2963                .map(
2964                    |pr| crate::bitbucket::pull_request::AutoMergeResult::Merged {
2965                        pr: Box::new(pr),
2966                        merge_strategy: merge_strategy.clone(),
2967                    },
2968                )
2969        };
2970
2971        match land_result {
2972            Ok(crate::bitbucket::pull_request::AutoMergeResult::Merged { .. }) => {
2973                println!(" ✅");
2974                landed_count += 1;
2975
2976                // 🔄 AUTO-RETARGETING: After each merge, retarget remaining PRs
2977                if landed_count < total_ready_prs {
2978                    println!("🔄 Retargeting remaining PRs to latest base...");
2979
2980                    // 1️⃣ CRITICAL: Update base branch to get latest merged state
2981                    let base_branch = active_stack.base_branch.clone();
2982                    let git_repo = crate::git::GitRepository::open(&repo_root)?;
2983
2984                    println!("   📥 Updating base branch: {base_branch}");
2985                    match git_repo.pull(&base_branch) {
2986                        Ok(_) => println!("   ✅ Base branch updated successfully"),
2987                        Err(e) => {
2988                            println!("   ⚠️  Warning: Failed to update base branch: {e}");
2989                            println!(
2990                                "   💡 You may want to manually run: git pull origin {base_branch}"
2991                            );
2992                        }
2993                    }
2994
2995                    // 2️⃣ Use rebase system to retarget remaining PRs
2996                    let mut rebase_manager = crate::stack::RebaseManager::new(
2997                        StackManager::new(&repo_root)?,
2998                        git_repo,
2999                        crate::stack::RebaseOptions {
3000                            strategy: crate::stack::RebaseStrategy::BranchVersioning,
3001                            target_base: Some(base_branch.clone()),
3002                            ..Default::default()
3003                        },
3004                    );
3005
3006                    match rebase_manager.rebase_stack(&stack_id) {
3007                        Ok(rebase_result) => {
3008                            if !rebase_result.branch_mapping.is_empty() {
3009                                // Update PRs using the rebase result
3010                                let retarget_config = crate::config::CascadeConfig {
3011                                    bitbucket: Some(settings.bitbucket.clone()),
3012                                    git: settings.git.clone(),
3013                                    auth: crate::config::AuthConfig::default(),
3014                                    cascade: settings.cascade.clone(),
3015                                };
3016                                let mut retarget_integration = BitbucketIntegration::new(
3017                                    StackManager::new(&repo_root)?,
3018                                    retarget_config,
3019                                )?;
3020
3021                                match retarget_integration
3022                                    .update_prs_after_rebase(
3023                                        &stack_id,
3024                                        &rebase_result.branch_mapping,
3025                                    )
3026                                    .await
3027                                {
3028                                    Ok(updated_prs) => {
3029                                        if !updated_prs.is_empty() {
3030                                            println!(
3031                                                "   ✅ Updated {} PRs with new targets",
3032                                                updated_prs.len()
3033                                            );
3034                                        }
3035                                    }
3036                                    Err(e) => {
3037                                        println!("   ⚠️  Failed to update remaining PRs: {e}");
3038                                        println!(
3039                                            "   💡 You may need to run: ca stack rebase --onto {base_branch}"
3040                                        );
3041                                    }
3042                                }
3043                            }
3044                        }
3045                        Err(e) => {
3046                            // 🚨 CONFLICTS DETECTED - Give clear next steps
3047                            println!("   ❌ Auto-retargeting conflicts detected!");
3048                            println!("   📝 To resolve conflicts and continue landing:");
3049                            println!("      1. Resolve conflicts in the affected files");
3050                            println!("      2. Stage resolved files: git add <files>");
3051                            println!("      3. Continue the process: ca stack continue-land");
3052                            println!("      4. Or abort the operation: ca stack abort-land");
3053                            println!();
3054                            println!("   💡 Check current status: ca stack land-status");
3055                            println!("   ⚠️  Error details: {e}");
3056
3057                            // Stop the land operation here - user needs to resolve conflicts
3058                            break;
3059                        }
3060                    }
3061                }
3062            }
3063            Ok(crate::bitbucket::pull_request::AutoMergeResult::NotReady { blocking_reasons }) => {
3064                println!(" ❌ Not ready: {}", blocking_reasons.join(", "));
3065                failed_count += 1;
3066                if !force {
3067                    break;
3068                }
3069            }
3070            Ok(crate::bitbucket::pull_request::AutoMergeResult::Failed { error }) => {
3071                println!(" ❌ Failed: {error}");
3072                failed_count += 1;
3073                if !force {
3074                    break;
3075                }
3076            }
3077            Err(e) => {
3078                println!(" ❌");
3079                eprintln!("Failed to land PR #{pr_id}: {e}");
3080                failed_count += 1;
3081
3082                if !force {
3083                    break;
3084                }
3085            }
3086        }
3087    }
3088
3089    // Show summary
3090    println!("\n🎯 Landing Summary:");
3091    println!("   ✅ Successfully landed: {landed_count}");
3092    if failed_count > 0 {
3093        println!("   ❌ Failed to land: {failed_count}");
3094    }
3095
3096    if landed_count > 0 {
3097        println!("✅ Landing operation completed!");
3098    } else {
3099        println!("❌ No PRs were successfully landed");
3100    }
3101
3102    Ok(())
3103}
3104
3105/// Auto-land all ready PRs (shorthand for land --auto)
3106async fn auto_land_stack(
3107    force: bool,
3108    dry_run: bool,
3109    wait_for_builds: bool,
3110    strategy: Option<MergeStrategyArg>,
3111    build_timeout: u64,
3112) -> Result<()> {
3113    // This is a shorthand for land with --auto
3114    land_stack(
3115        None,
3116        force,
3117        dry_run,
3118        true, // auto = true
3119        wait_for_builds,
3120        strategy,
3121        build_timeout,
3122    )
3123    .await
3124}
3125
3126async fn continue_land() -> Result<()> {
3127    let current_dir = env::current_dir()
3128        .map_err(|e| CascadeError::config(format!("Could not get current directory: {e}")))?;
3129
3130    let repo_root = find_repository_root(&current_dir)
3131        .map_err(|e| CascadeError::config(format!("Could not find git repository: {e}")))?;
3132
3133    let stack_manager = StackManager::new(&repo_root)?;
3134    let git_repo = crate::git::GitRepository::open(&repo_root)?;
3135    let options = crate::stack::RebaseOptions::default();
3136    let rebase_manager = crate::stack::RebaseManager::new(stack_manager, git_repo, options);
3137
3138    if !rebase_manager.is_rebase_in_progress() {
3139        println!("ℹ️  No rebase in progress");
3140        return Ok(());
3141    }
3142
3143    println!("🔄 Continuing land operation...");
3144    match rebase_manager.continue_rebase() {
3145        Ok(_) => {
3146            println!("✅ Land operation continued successfully");
3147            println!("   Check 'ca stack land-status' for current state");
3148        }
3149        Err(e) => {
3150            warn!("❌ Failed to continue land operation: {}", e);
3151            println!("💡 You may need to resolve conflicts first:");
3152            println!("   1. Edit conflicted files");
3153            println!("   2. Stage resolved files with 'git add'");
3154            println!("   3. Run 'ca stack continue-land' again");
3155        }
3156    }
3157
3158    Ok(())
3159}
3160
3161async fn abort_land() -> Result<()> {
3162    let current_dir = env::current_dir()
3163        .map_err(|e| CascadeError::config(format!("Could not get current directory: {e}")))?;
3164
3165    let repo_root = find_repository_root(&current_dir)
3166        .map_err(|e| CascadeError::config(format!("Could not find git repository: {e}")))?;
3167
3168    let stack_manager = StackManager::new(&repo_root)?;
3169    let git_repo = crate::git::GitRepository::open(&repo_root)?;
3170    let options = crate::stack::RebaseOptions::default();
3171    let rebase_manager = crate::stack::RebaseManager::new(stack_manager, git_repo, options);
3172
3173    if !rebase_manager.is_rebase_in_progress() {
3174        println!("ℹ️  No rebase in progress");
3175        return Ok(());
3176    }
3177
3178    println!("⚠️  Aborting land operation...");
3179    match rebase_manager.abort_rebase() {
3180        Ok(_) => {
3181            println!("✅ Land operation aborted successfully");
3182            println!("   Repository restored to pre-land state");
3183        }
3184        Err(e) => {
3185            warn!("❌ Failed to abort land operation: {}", e);
3186            println!("⚠️  You may need to manually clean up the repository state");
3187        }
3188    }
3189
3190    Ok(())
3191}
3192
3193async fn land_status() -> Result<()> {
3194    let current_dir = env::current_dir()
3195        .map_err(|e| CascadeError::config(format!("Could not get current directory: {e}")))?;
3196
3197    let repo_root = find_repository_root(&current_dir)
3198        .map_err(|e| CascadeError::config(format!("Could not find git repository: {e}")))?;
3199
3200    let stack_manager = StackManager::new(&repo_root)?;
3201    let git_repo = crate::git::GitRepository::open(&repo_root)?;
3202
3203    println!("📊 Land Status");
3204
3205    // Check if land operation is in progress by checking git state directly
3206    let git_dir = repo_root.join(".git");
3207    let land_in_progress = git_dir.join("REBASE_HEAD").exists()
3208        || git_dir.join("rebase-merge").exists()
3209        || git_dir.join("rebase-apply").exists();
3210
3211    if land_in_progress {
3212        println!("   Status: 🔄 Land operation in progress");
3213        println!(
3214            "   
3215📝 Actions available:"
3216        );
3217        println!("     - 'ca stack continue-land' to continue");
3218        println!("     - 'ca stack abort-land' to abort");
3219        println!("     - 'git status' to see conflicted files");
3220
3221        // Check for conflicts
3222        match git_repo.get_status() {
3223            Ok(statuses) => {
3224                let mut conflicts = Vec::new();
3225                for status in statuses.iter() {
3226                    if status.status().contains(git2::Status::CONFLICTED) {
3227                        if let Some(path) = status.path() {
3228                            conflicts.push(path.to_string());
3229                        }
3230                    }
3231                }
3232
3233                if !conflicts.is_empty() {
3234                    println!("   ⚠️  Conflicts in {} files:", conflicts.len());
3235                    for conflict in conflicts {
3236                        println!("      - {conflict}");
3237                    }
3238                    println!(
3239                        "   
3240💡 To resolve conflicts:"
3241                    );
3242                    println!("     1. Edit the conflicted files");
3243                    println!("     2. Stage resolved files: git add <file>");
3244                    println!("     3. Continue: ca stack continue-land");
3245                }
3246            }
3247            Err(e) => {
3248                warn!("Failed to get git status: {}", e);
3249            }
3250        }
3251    } else {
3252        println!("   Status: ✅ No land operation in progress");
3253
3254        // Show stack status instead
3255        if let Some(active_stack) = stack_manager.get_active_stack() {
3256            println!("   Active stack: {}", active_stack.name);
3257            println!("   Entries: {}", active_stack.entries.len());
3258            println!("   Base branch: {}", active_stack.base_branch);
3259        }
3260    }
3261
3262    Ok(())
3263}
3264
3265async fn repair_stack_data() -> Result<()> {
3266    let current_dir = env::current_dir()
3267        .map_err(|e| CascadeError::config(format!("Could not get current directory: {e}")))?;
3268
3269    let repo_root = find_repository_root(&current_dir)
3270        .map_err(|e| CascadeError::config(format!("Could not find git repository: {e}")))?;
3271
3272    let mut stack_manager = StackManager::new(&repo_root)?;
3273
3274    println!("🔧 Repairing stack data consistency...");
3275
3276    stack_manager.repair_all_stacks()?;
3277
3278    println!("✅ Stack data consistency repaired successfully!");
3279    println!("💡 Run 'ca stack --mergeable' to see updated status");
3280
3281    Ok(())
3282}
3283
3284/// Analyze commits for various safeguards before pushing
3285async fn analyze_commits_for_safeguards(
3286    commits_to_push: &[String],
3287    repo: &GitRepository,
3288    dry_run: bool,
3289) -> Result<()> {
3290    const LARGE_COMMIT_THRESHOLD: usize = 10;
3291    const WEEK_IN_SECONDS: i64 = 7 * 24 * 3600;
3292
3293    // 🛡️ SAFEGUARD 1: Large commit count warning
3294    if commits_to_push.len() > LARGE_COMMIT_THRESHOLD {
3295        println!(
3296            "⚠️  Warning: About to push {} commits to stack",
3297            commits_to_push.len()
3298        );
3299        println!("   This may indicate a merge commit issue or unexpected commit range.");
3300        println!("   Large commit counts often result from merging instead of rebasing.");
3301
3302        if !dry_run && !confirm_large_push(commits_to_push.len())? {
3303            return Err(CascadeError::config("Push cancelled by user"));
3304        }
3305    }
3306
3307    // Get commit objects for further analysis
3308    let commit_objects: Result<Vec<_>> = commits_to_push
3309        .iter()
3310        .map(|hash| repo.get_commit(hash))
3311        .collect();
3312    let commit_objects = commit_objects?;
3313
3314    // 🛡️ SAFEGUARD 2: Merge commit detection
3315    let merge_commits: Vec<_> = commit_objects
3316        .iter()
3317        .filter(|c| c.parent_count() > 1)
3318        .collect();
3319
3320    if !merge_commits.is_empty() {
3321        println!(
3322            "⚠️  Warning: {} merge commits detected in push",
3323            merge_commits.len()
3324        );
3325        println!("   This often indicates you merged instead of rebased.");
3326        println!("   Consider using 'ca sync' to rebase on the base branch.");
3327        println!("   Merge commits in stacks can cause confusion and duplicate work.");
3328    }
3329
3330    // 🛡️ SAFEGUARD 3: Commit age warning
3331    if commit_objects.len() > 1 {
3332        let oldest_commit_time = commit_objects.first().unwrap().time().seconds();
3333        let newest_commit_time = commit_objects.last().unwrap().time().seconds();
3334        let time_span = newest_commit_time - oldest_commit_time;
3335
3336        if time_span > WEEK_IN_SECONDS {
3337            let days = time_span / (24 * 3600);
3338            println!("⚠️  Warning: Commits span {days} days");
3339            println!("   This may indicate merged history rather than new work.");
3340            println!("   Recent work should typically span hours or days, not weeks.");
3341        }
3342    }
3343
3344    // 🛡️ SAFEGUARD 4: Better range detection suggestions
3345    if commits_to_push.len() > 5 {
3346        println!("💡 Tip: If you only want recent commits, use:");
3347        println!(
3348            "   ca push --since HEAD~{}  # pushes last {} commits",
3349            std::cmp::min(commits_to_push.len(), 5),
3350            std::cmp::min(commits_to_push.len(), 5)
3351        );
3352        println!("   ca push --commits <hash1>,<hash2>  # pushes specific commits");
3353        println!("   ca push --dry-run  # preview what would be pushed");
3354    }
3355
3356    // 🛡️ SAFEGUARD 5: Dry run mode
3357    if dry_run {
3358        println!("🔍 DRY RUN: Would push {} commits:", commits_to_push.len());
3359        for (i, (commit_hash, commit_obj)) in commits_to_push
3360            .iter()
3361            .zip(commit_objects.iter())
3362            .enumerate()
3363        {
3364            let summary = commit_obj.summary().unwrap_or("(no message)");
3365            let short_hash = &commit_hash[..std::cmp::min(commit_hash.len(), 7)];
3366            println!("  {}: {} ({})", i + 1, summary, short_hash);
3367        }
3368        println!("💡 Run without --dry-run to actually push these commits.");
3369    }
3370
3371    Ok(())
3372}
3373
3374/// Prompt user for confirmation when pushing large number of commits
3375fn confirm_large_push(count: usize) -> Result<bool> {
3376    print!("Do you want to continue pushing {count} commits? [y/N]: ");
3377    io::stdout()
3378        .flush()
3379        .map_err(|e| CascadeError::config(format!("Failed to flush stdout: {e}")))?;
3380
3381    let mut input = String::new();
3382    io::stdin()
3383        .read_line(&mut input)
3384        .map_err(|e| CascadeError::config(format!("Failed to read user input: {e}")))?;
3385
3386    let input = input.trim().to_lowercase();
3387    Ok(input == "y" || input == "yes")
3388}
3389
3390#[cfg(test)]
3391mod tests {
3392    use super::*;
3393    use std::process::Command;
3394    use tempfile::TempDir;
3395
3396    fn create_test_repo() -> Result<(TempDir, std::path::PathBuf)> {
3397        let temp_dir = TempDir::new()
3398            .map_err(|e| CascadeError::config(format!("Failed to create temp directory: {e}")))?;
3399        let repo_path = temp_dir.path().to_path_buf();
3400
3401        // Initialize git repository
3402        let output = Command::new("git")
3403            .args(["init"])
3404            .current_dir(&repo_path)
3405            .output()
3406            .map_err(|e| CascadeError::config(format!("Failed to run git init: {e}")))?;
3407        if !output.status.success() {
3408            return Err(CascadeError::config("Git init failed".to_string()));
3409        }
3410
3411        let output = Command::new("git")
3412            .args(["config", "user.name", "Test User"])
3413            .current_dir(&repo_path)
3414            .output()
3415            .map_err(|e| CascadeError::config(format!("Failed to run git config: {e}")))?;
3416        if !output.status.success() {
3417            return Err(CascadeError::config(
3418                "Git config user.name failed".to_string(),
3419            ));
3420        }
3421
3422        let output = Command::new("git")
3423            .args(["config", "user.email", "test@example.com"])
3424            .current_dir(&repo_path)
3425            .output()
3426            .map_err(|e| CascadeError::config(format!("Failed to run git config: {e}")))?;
3427        if !output.status.success() {
3428            return Err(CascadeError::config(
3429                "Git config user.email failed".to_string(),
3430            ));
3431        }
3432
3433        // Create initial commit
3434        std::fs::write(repo_path.join("README.md"), "# Test")
3435            .map_err(|e| CascadeError::config(format!("Failed to write file: {e}")))?;
3436        let output = Command::new("git")
3437            .args(["add", "."])
3438            .current_dir(&repo_path)
3439            .output()
3440            .map_err(|e| CascadeError::config(format!("Failed to run git add: {e}")))?;
3441        if !output.status.success() {
3442            return Err(CascadeError::config("Git add failed".to_string()));
3443        }
3444
3445        let output = Command::new("git")
3446            .args(["commit", "-m", "Initial commit"])
3447            .current_dir(&repo_path)
3448            .output()
3449            .map_err(|e| CascadeError::config(format!("Failed to run git commit: {e}")))?;
3450        if !output.status.success() {
3451            return Err(CascadeError::config("Git commit failed".to_string()));
3452        }
3453
3454        // Initialize cascade
3455        crate::config::initialize_repo(&repo_path, Some("https://test.bitbucket.com".to_string()))?;
3456
3457        Ok((temp_dir, repo_path))
3458    }
3459
3460    #[tokio::test]
3461    async fn test_create_stack() {
3462        let (temp_dir, repo_path) = match create_test_repo() {
3463            Ok(repo) => repo,
3464            Err(_) => {
3465                println!("Skipping test due to git environment setup failure");
3466                return;
3467            }
3468        };
3469        // IMPORTANT: temp_dir must stay in scope to prevent early cleanup of test directory
3470        let _ = &temp_dir;
3471
3472        // Note: create_test_repo() already initializes Cascade configuration
3473
3474        // Change to the repo directory (with proper error handling)
3475        let original_dir = env::current_dir().map_err(|_| "Failed to get current dir");
3476        match env::set_current_dir(&repo_path) {
3477            Ok(_) => {
3478                let result = create_stack(
3479                    "test-stack".to_string(),
3480                    None, // Use default branch
3481                    Some("Test description".to_string()),
3482                )
3483                .await;
3484
3485                // Restore original directory (best effort)
3486                if let Ok(orig) = original_dir {
3487                    let _ = env::set_current_dir(orig);
3488                }
3489
3490                assert!(
3491                    result.is_ok(),
3492                    "Stack creation should succeed in initialized repository"
3493                );
3494            }
3495            Err(_) => {
3496                // Skip test if we can't change directories (CI environment issue)
3497                println!("Skipping test due to directory access restrictions");
3498            }
3499        }
3500    }
3501
3502    #[tokio::test]
3503    async fn test_list_empty_stacks() {
3504        let (temp_dir, repo_path) = match create_test_repo() {
3505            Ok(repo) => repo,
3506            Err(_) => {
3507                println!("Skipping test due to git environment setup failure");
3508                return;
3509            }
3510        };
3511        // IMPORTANT: temp_dir must stay in scope to prevent early cleanup of test directory
3512        let _ = &temp_dir;
3513
3514        // Note: create_test_repo() already initializes Cascade configuration
3515
3516        // Change to the repo directory (with proper error handling)
3517        let original_dir = env::current_dir().map_err(|_| "Failed to get current dir");
3518        match env::set_current_dir(&repo_path) {
3519            Ok(_) => {
3520                let result = list_stacks(false, false, None).await;
3521
3522                // Restore original directory (best effort)
3523                if let Ok(orig) = original_dir {
3524                    let _ = env::set_current_dir(orig);
3525                }
3526
3527                assert!(
3528                    result.is_ok(),
3529                    "Listing stacks should succeed in initialized repository"
3530                );
3531            }
3532            Err(_) => {
3533                // Skip test if we can't change directories (CI environment issue)
3534                println!("Skipping test due to directory access restrictions");
3535            }
3536        }
3537    }
3538
3539    // Tests for squashing functionality
3540
3541    #[test]
3542    fn test_extract_feature_from_wip_basic() {
3543        let messages = vec![
3544            "WIP: add authentication".to_string(),
3545            "WIP: implement login flow".to_string(),
3546        ];
3547
3548        let result = extract_feature_from_wip(&messages);
3549        assert_eq!(result, "Add authentication");
3550    }
3551
3552    #[test]
3553    fn test_extract_feature_from_wip_capitalize() {
3554        let messages = vec!["WIP: fix user validation bug".to_string()];
3555
3556        let result = extract_feature_from_wip(&messages);
3557        assert_eq!(result, "Fix user validation bug");
3558    }
3559
3560    #[test]
3561    fn test_extract_feature_from_wip_fallback() {
3562        let messages = vec![
3563            "WIP user interface changes".to_string(),
3564            "wip: css styling".to_string(),
3565        ];
3566
3567        let result = extract_feature_from_wip(&messages);
3568        // Should create a fallback message since no "WIP:" prefix found
3569        assert!(result.contains("Implement") || result.contains("Squashed") || result.len() > 5);
3570    }
3571
3572    #[test]
3573    fn test_extract_feature_from_wip_empty() {
3574        let messages = vec![];
3575
3576        let result = extract_feature_from_wip(&messages);
3577        assert_eq!(result, "Squashed 0 commits");
3578    }
3579
3580    #[test]
3581    fn test_extract_feature_from_wip_short_message() {
3582        let messages = vec!["WIP: x".to_string()]; // Too short
3583
3584        let result = extract_feature_from_wip(&messages);
3585        assert!(result.starts_with("Implement") || result.contains("Squashed"));
3586    }
3587
3588    // Integration tests for squashing that don't require real git commits
3589
3590    #[test]
3591    fn test_squash_message_final_strategy() {
3592        // This test would need real git2::Commit objects, so we'll test the logic indirectly
3593        // through the extract_feature_from_wip function which handles the core logic
3594
3595        let messages = [
3596            "Final: implement user authentication system".to_string(),
3597            "WIP: add tests".to_string(),
3598            "WIP: fix validation".to_string(),
3599        ];
3600
3601        // Test that we can identify final commits
3602        assert!(messages[0].starts_with("Final:"));
3603
3604        // Test message extraction
3605        let extracted = messages[0].trim_start_matches("Final:").trim();
3606        assert_eq!(extracted, "implement user authentication system");
3607    }
3608
3609    #[test]
3610    fn test_squash_message_wip_detection() {
3611        let messages = [
3612            "WIP: start feature".to_string(),
3613            "WIP: continue work".to_string(),
3614            "WIP: almost done".to_string(),
3615            "Regular commit message".to_string(),
3616        ];
3617
3618        let wip_count = messages
3619            .iter()
3620            .filter(|m| {
3621                m.to_lowercase().starts_with("wip") || m.to_lowercase().contains("work in progress")
3622            })
3623            .count();
3624
3625        assert_eq!(wip_count, 3); // Should detect 3 WIP commits
3626        assert!(wip_count > messages.len() / 2); // Majority are WIP
3627
3628        // Should find the non-WIP message
3629        let non_wip: Vec<&String> = messages
3630            .iter()
3631            .filter(|m| {
3632                !m.to_lowercase().starts_with("wip")
3633                    && !m.to_lowercase().contains("work in progress")
3634            })
3635            .collect();
3636
3637        assert_eq!(non_wip.len(), 1);
3638        assert_eq!(non_wip[0], "Regular commit message");
3639    }
3640
3641    #[test]
3642    fn test_squash_message_all_wip() {
3643        let messages = vec![
3644            "WIP: add feature A".to_string(),
3645            "WIP: add feature B".to_string(),
3646            "WIP: finish implementation".to_string(),
3647        ];
3648
3649        let result = extract_feature_from_wip(&messages);
3650        // Should use the first message as the main feature
3651        assert_eq!(result, "Add feature A");
3652    }
3653
3654    #[test]
3655    fn test_squash_message_edge_cases() {
3656        // Test empty messages
3657        let empty_messages: Vec<String> = vec![];
3658        let result = extract_feature_from_wip(&empty_messages);
3659        assert_eq!(result, "Squashed 0 commits");
3660
3661        // Test messages with only whitespace
3662        let whitespace_messages = vec!["   ".to_string(), "\t\n".to_string()];
3663        let result = extract_feature_from_wip(&whitespace_messages);
3664        assert!(result.contains("Squashed") || result.contains("Implement"));
3665
3666        // Test case sensitivity
3667        let mixed_case = vec!["wip: Add Feature".to_string()];
3668        let result = extract_feature_from_wip(&mixed_case);
3669        assert_eq!(result, "Add Feature");
3670    }
3671
3672    // Tests for auto-land functionality
3673
3674    #[tokio::test]
3675    async fn test_auto_land_wrapper() {
3676        // Test that auto_land_stack correctly calls land_stack with auto=true
3677        let (temp_dir, repo_path) = match create_test_repo() {
3678            Ok(repo) => repo,
3679            Err(_) => {
3680                println!("Skipping test due to git environment setup failure");
3681                return;
3682            }
3683        };
3684        // IMPORTANT: temp_dir must stay in scope to prevent early cleanup of test directory
3685        let _ = &temp_dir;
3686
3687        // Initialize cascade in the test repo
3688        crate::config::initialize_repo(&repo_path, Some("https://test.bitbucket.com".to_string()))
3689            .expect("Failed to initialize Cascade in test repo");
3690
3691        let original_dir = env::current_dir().map_err(|_| "Failed to get current dir");
3692        match env::set_current_dir(&repo_path) {
3693            Ok(_) => {
3694                // Create a stack first
3695                let result = create_stack(
3696                    "test-stack".to_string(),
3697                    None,
3698                    Some("Test stack for auto-land".to_string()),
3699                )
3700                .await;
3701
3702                if let Ok(orig) = original_dir {
3703                    let _ = env::set_current_dir(orig);
3704                }
3705
3706                // For now, just test that the function can be called without panic
3707                // (It will fail due to missing Bitbucket config, but that's expected)
3708                assert!(
3709                    result.is_ok(),
3710                    "Stack creation should succeed in initialized repository"
3711                );
3712            }
3713            Err(_) => {
3714                println!("Skipping test due to directory access restrictions");
3715            }
3716        }
3717    }
3718
3719    #[test]
3720    fn test_auto_land_action_enum() {
3721        // Test that AutoLand action is properly defined
3722        use crate::cli::commands::stack::StackAction;
3723
3724        // This ensures the AutoLand variant exists and has the expected fields
3725        let _action = StackAction::AutoLand {
3726            force: false,
3727            dry_run: true,
3728            wait_for_builds: true,
3729            strategy: Some(MergeStrategyArg::Squash),
3730            build_timeout: 1800,
3731        };
3732
3733        // Test passes if we reach this point without errors
3734    }
3735
3736    #[test]
3737    fn test_merge_strategy_conversion() {
3738        // Test that MergeStrategyArg converts properly
3739        let squash_strategy = MergeStrategyArg::Squash;
3740        let merge_strategy: crate::bitbucket::pull_request::MergeStrategy = squash_strategy.into();
3741
3742        match merge_strategy {
3743            crate::bitbucket::pull_request::MergeStrategy::Squash => {
3744                // Correct conversion
3745            }
3746            _ => panic!("Expected Squash strategy"),
3747        }
3748
3749        let merge_strategy = MergeStrategyArg::Merge;
3750        let converted: crate::bitbucket::pull_request::MergeStrategy = merge_strategy.into();
3751
3752        match converted {
3753            crate::bitbucket::pull_request::MergeStrategy::Merge => {
3754                // Correct conversion
3755            }
3756            _ => panic!("Expected Merge strategy"),
3757        }
3758    }
3759
3760    #[test]
3761    fn test_auto_merge_conditions_structure() {
3762        // Test that AutoMergeConditions can be created with expected values
3763        use std::time::Duration;
3764
3765        let conditions = crate::bitbucket::pull_request::AutoMergeConditions {
3766            merge_strategy: crate::bitbucket::pull_request::MergeStrategy::Squash,
3767            wait_for_builds: true,
3768            build_timeout: Duration::from_secs(1800),
3769            allowed_authors: None,
3770        };
3771
3772        // Verify the conditions are set as expected for auto-land
3773        assert!(conditions.wait_for_builds);
3774        assert_eq!(conditions.build_timeout.as_secs(), 1800);
3775        assert!(conditions.allowed_authors.is_none());
3776        assert!(matches!(
3777            conditions.merge_strategy,
3778            crate::bitbucket::pull_request::MergeStrategy::Squash
3779        ));
3780    }
3781
3782    #[test]
3783    fn test_polling_constants() {
3784        // Test that polling frequency is documented and reasonable
3785        use std::time::Duration;
3786
3787        // The polling frequency should be 30 seconds as mentioned in documentation
3788        let expected_polling_interval = Duration::from_secs(30);
3789
3790        // Verify it's a reasonable value (not too frequent, not too slow)
3791        assert!(expected_polling_interval.as_secs() >= 10); // At least 10 seconds
3792        assert!(expected_polling_interval.as_secs() <= 60); // At most 1 minute
3793        assert_eq!(expected_polling_interval.as_secs(), 30); // Exactly 30 seconds
3794    }
3795
3796    #[test]
3797    fn test_build_timeout_defaults() {
3798        // Verify build timeout default is reasonable
3799        const DEFAULT_TIMEOUT: u64 = 1800; // 30 minutes
3800        assert_eq!(DEFAULT_TIMEOUT, 1800);
3801        // Test that our default timeout value is within reasonable bounds
3802        let timeout_value = 1800u64;
3803        assert!(timeout_value >= 300); // At least 5 minutes
3804        assert!(timeout_value <= 3600); // At most 1 hour
3805    }
3806
3807    #[test]
3808    fn test_scattered_commit_detection() {
3809        use std::collections::HashSet;
3810
3811        // Test scattered commit detection logic
3812        let mut source_branches = HashSet::new();
3813        source_branches.insert("feature-branch-1".to_string());
3814        source_branches.insert("feature-branch-2".to_string());
3815        source_branches.insert("feature-branch-3".to_string());
3816
3817        // Single branch should not trigger warning
3818        let single_branch = HashSet::from(["main".to_string()]);
3819        assert_eq!(single_branch.len(), 1);
3820
3821        // Multiple branches should trigger warning
3822        assert!(source_branches.len() > 1);
3823        assert_eq!(source_branches.len(), 3);
3824
3825        // Verify branch names are preserved correctly
3826        assert!(source_branches.contains("feature-branch-1"));
3827        assert!(source_branches.contains("feature-branch-2"));
3828        assert!(source_branches.contains("feature-branch-3"));
3829    }
3830
3831    #[test]
3832    fn test_source_branch_tracking() {
3833        // Test that source branch tracking correctly handles different scenarios
3834
3835        // Same branch should be consistent
3836        let branch_a = "feature-work";
3837        let branch_b = "feature-work";
3838        assert_eq!(branch_a, branch_b);
3839
3840        // Different branches should be detected
3841        let branch_1 = "feature-ui";
3842        let branch_2 = "feature-api";
3843        assert_ne!(branch_1, branch_2);
3844
3845        // Branch naming patterns
3846        assert!(branch_1.starts_with("feature-"));
3847        assert!(branch_2.starts_with("feature-"));
3848    }
3849
3850    // Tests for new default behavior (removing --all flag)
3851
3852    #[tokio::test]
3853    async fn test_push_default_behavior() {
3854        // Test the push_to_stack function structure and error handling in an isolated environment
3855        let (temp_dir, repo_path) = match create_test_repo() {
3856            Ok(repo) => repo,
3857            Err(_) => {
3858                println!("Skipping test due to git environment setup failure");
3859                return;
3860            }
3861        };
3862        // IMPORTANT: temp_dir must stay in scope to prevent early cleanup of test directory
3863        let _ = &temp_dir;
3864
3865        // Verify directory exists before changing to it
3866        if !repo_path.exists() {
3867            println!("Skipping test due to temporary directory creation issue");
3868            return;
3869        }
3870
3871        // Change to the test repository directory to ensure isolation
3872        let original_dir = env::current_dir().map_err(|_| "Failed to get current dir");
3873
3874        match env::set_current_dir(&repo_path) {
3875            Ok(_) => {
3876                // Test that push_to_stack properly handles the case when no stack is active
3877                let result = push_to_stack(
3878                    None,  // branch
3879                    None,  // message
3880                    None,  // commit
3881                    None,  // since
3882                    None,  // commits
3883                    None,  // squash
3884                    None,  // squash_since
3885                    false, // auto_branch
3886                    false, // allow_base_branch
3887                    false, // dry_run
3888                )
3889                .await;
3890
3891                // Restore original directory (best effort)
3892                if let Ok(orig) = original_dir {
3893                    let _ = env::set_current_dir(orig);
3894                }
3895
3896                // Should fail gracefully with appropriate error message when no stack is active
3897                match &result {
3898                    Err(e) => {
3899                        let error_msg = e.to_string();
3900                        // This is the expected behavior - no active stack should produce this error
3901                        assert!(
3902                            error_msg.contains("No active stack")
3903                                || error_msg.contains("config")
3904                                || error_msg.contains("current directory")
3905                                || error_msg.contains("Not a git repository")
3906                                || error_msg.contains("could not find repository"),
3907                            "Expected 'No active stack' or repository error, got: {error_msg}"
3908                        );
3909                    }
3910                    Ok(_) => {
3911                        // If it somehow succeeds, that's also fine (e.g., if environment is set up differently)
3912                        println!(
3913                            "Push succeeded unexpectedly - test environment may have active stack"
3914                        );
3915                    }
3916                }
3917            }
3918            Err(_) => {
3919                // Skip test if we can't change directories (CI environment issue)
3920                println!("Skipping test due to directory access restrictions");
3921            }
3922        }
3923
3924        // Verify we can construct the command structure correctly
3925        let push_action = StackAction::Push {
3926            branch: None,
3927            message: None,
3928            commit: None,
3929            since: None,
3930            commits: None,
3931            squash: None,
3932            squash_since: None,
3933            auto_branch: false,
3934            allow_base_branch: false,
3935            dry_run: false,
3936        };
3937
3938        assert!(matches!(
3939            push_action,
3940            StackAction::Push {
3941                branch: None,
3942                message: None,
3943                commit: None,
3944                since: None,
3945                commits: None,
3946                squash: None,
3947                squash_since: None,
3948                auto_branch: false,
3949                allow_base_branch: false,
3950                dry_run: false
3951            }
3952        ));
3953    }
3954
3955    #[tokio::test]
3956    async fn test_submit_default_behavior() {
3957        // Test the submit_entry function structure and error handling in an isolated environment
3958        let (temp_dir, repo_path) = match create_test_repo() {
3959            Ok(repo) => repo,
3960            Err(_) => {
3961                println!("Skipping test due to git environment setup failure");
3962                return;
3963            }
3964        };
3965        // IMPORTANT: temp_dir must stay in scope to prevent early cleanup of test directory
3966        let _ = &temp_dir;
3967
3968        // Verify directory exists before changing to it
3969        if !repo_path.exists() {
3970            println!("Skipping test due to temporary directory creation issue");
3971            return;
3972        }
3973
3974        // Change to the test repository directory to ensure isolation
3975        let original_dir = match env::current_dir() {
3976            Ok(dir) => dir,
3977            Err(_) => {
3978                println!("Skipping test due to current directory access restrictions");
3979                return;
3980            }
3981        };
3982
3983        match env::set_current_dir(&repo_path) {
3984            Ok(_) => {
3985                // Test that submit_entry properly handles the case when no stack is active
3986                let result = submit_entry(
3987                    None,  // entry (should default to all unsubmitted)
3988                    None,  // title
3989                    None,  // description
3990                    None,  // range
3991                    false, // draft
3992                )
3993                .await;
3994
3995                // Restore original directory
3996                let _ = env::set_current_dir(original_dir);
3997
3998                // Should fail gracefully with appropriate error message when no stack is active
3999                match &result {
4000                    Err(e) => {
4001                        let error_msg = e.to_string();
4002                        // This is the expected behavior - no active stack should produce this error
4003                        assert!(
4004                            error_msg.contains("No active stack")
4005                                || error_msg.contains("config")
4006                                || error_msg.contains("current directory")
4007                                || error_msg.contains("Not a git repository")
4008                                || error_msg.contains("could not find repository"),
4009                            "Expected 'No active stack' or repository error, got: {error_msg}"
4010                        );
4011                    }
4012                    Ok(_) => {
4013                        // If it somehow succeeds, that's also fine (e.g., if environment is set up differently)
4014                        println!("Submit succeeded unexpectedly - test environment may have active stack");
4015                    }
4016                }
4017            }
4018            Err(_) => {
4019                // Skip test if we can't change directories (CI environment issue)
4020                println!("Skipping test due to directory access restrictions");
4021            }
4022        }
4023
4024        // Verify we can construct the command structure correctly
4025        let submit_action = StackAction::Submit {
4026            entry: None,
4027            title: None,
4028            description: None,
4029            range: None,
4030            draft: false,
4031        };
4032
4033        assert!(matches!(
4034            submit_action,
4035            StackAction::Submit {
4036                entry: None,
4037                title: None,
4038                description: None,
4039                range: None,
4040                draft: false
4041            }
4042        ));
4043    }
4044
4045    #[test]
4046    fn test_targeting_options_still_work() {
4047        // Test that specific targeting options still work correctly
4048
4049        // Test commit list parsing
4050        let commits = "abc123,def456,ghi789";
4051        let parsed: Vec<&str> = commits.split(',').map(|s| s.trim()).collect();
4052        assert_eq!(parsed.len(), 3);
4053        assert_eq!(parsed[0], "abc123");
4054        assert_eq!(parsed[1], "def456");
4055        assert_eq!(parsed[2], "ghi789");
4056
4057        // Test range parsing would work
4058        let range = "1-3";
4059        assert!(range.contains('-'));
4060        let parts: Vec<&str> = range.split('-').collect();
4061        assert_eq!(parts.len(), 2);
4062
4063        // Test since reference pattern
4064        let since_ref = "HEAD~3";
4065        assert!(since_ref.starts_with("HEAD"));
4066        assert!(since_ref.contains('~'));
4067    }
4068
4069    #[test]
4070    fn test_command_flow_logic() {
4071        // These just test the command structure exists
4072        assert!(matches!(
4073            StackAction::Push {
4074                branch: None,
4075                message: None,
4076                commit: None,
4077                since: None,
4078                commits: None,
4079                squash: None,
4080                squash_since: None,
4081                auto_branch: false,
4082                allow_base_branch: false,
4083                dry_run: false
4084            },
4085            StackAction::Push { .. }
4086        ));
4087
4088        assert!(matches!(
4089            StackAction::Submit {
4090                entry: None,
4091                title: None,
4092                description: None,
4093                range: None,
4094                draft: false
4095            },
4096            StackAction::Submit { .. }
4097        ));
4098    }
4099
4100    #[tokio::test]
4101    async fn test_deactivate_command_structure() {
4102        // Test that deactivate command structure exists and can be constructed
4103        let deactivate_action = StackAction::Deactivate { force: false };
4104
4105        // Verify it matches the expected pattern
4106        assert!(matches!(
4107            deactivate_action,
4108            StackAction::Deactivate { force: false }
4109        ));
4110
4111        // Test with force flag
4112        let force_deactivate = StackAction::Deactivate { force: true };
4113        assert!(matches!(
4114            force_deactivate,
4115            StackAction::Deactivate { force: true }
4116        ));
4117    }
4118}