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