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