cascade_cli/cli/commands/
stack.rs

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