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