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