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