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