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