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