cascade_cli/cli/commands/
stack.rs

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