cascade-cli 0.1.152

Stacked diffs CLI for Bitbucket Server
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
use crate::bitbucket::client::BitbucketClient;
use crate::bitbucket::pull_request::{
    CreatePullRequestRequest, Project, PullRequest, PullRequestManager, PullRequestRef,
    PullRequestState, Repository,
};
use crate::cli::output::Output;
use crate::config::CascadeConfig;
use crate::errors::{CascadeError, Result};
use crate::stack::{Stack, StackEntry, StackManager};
use std::collections::HashMap;
use tracing::{debug, error};
use uuid::Uuid;

/// High-level integration between stacks and Bitbucket
pub struct BitbucketIntegration {
    stack_manager: StackManager,
    pr_manager: PullRequestManager,
    config: CascadeConfig,
}

impl BitbucketIntegration {
    /// Create a new Bitbucket integration
    pub fn new(stack_manager: StackManager, config: CascadeConfig) -> Result<Self> {
        let bitbucket_config = config
            .bitbucket
            .as_ref()
            .ok_or_else(|| CascadeError::config("Bitbucket configuration not found"))?;

        let client = BitbucketClient::new(bitbucket_config)?;
        let pr_manager = PullRequestManager::new(client);

        Ok(Self {
            stack_manager,
            pr_manager,
            config,
        })
    }

    /// Update all PR descriptions in a stack with current hierarchy
    pub async fn update_all_pr_descriptions(&self, stack_id: &Uuid) -> Result<Vec<u64>> {
        let stack = self
            .stack_manager
            .get_stack(stack_id)
            .cloned()
            .ok_or_else(|| CascadeError::config(format!("Stack {stack_id} not found")))?;

        let mut updated_prs = Vec::new();

        // Update each PR with current stack hierarchy
        for entry in &stack.entries {
            if let Some(pr_id_str) = &entry.pull_request_id {
                if let Ok(pr_id) = pr_id_str.parse::<u64>() {
                    // Get current PR to get its version
                    match self.pr_manager.get_pull_request(pr_id).await {
                        Ok(pr) => {
                            // Generate updated description with current stack state
                            let updated_description = self.add_stack_hierarchy_footer(
                                pr.description.clone().and_then(|desc| {
                                    // Remove old stack hierarchy if present
                                    desc.split("---\n\n## 📚 Stack:")
                                        .next()
                                        .map(|s| s.trim().to_string())
                                }),
                                &stack,
                                entry,
                            )?;

                            // Update the PR description
                            match self
                                .pr_manager
                                .update_pull_request(
                                    pr_id,
                                    None, // Don't change title
                                    updated_description,
                                    pr.version,
                                )
                                .await
                            {
                                Ok(_) => {
                                    updated_prs.push(pr_id);
                                }
                                Err(e) => {
                                    // Suppress verbose error logging for benign 409 conflicts
                                    // These happen when PR was just created and version hasn't propagated
                                    let error_msg = e.to_string();
                                    if !error_msg.contains("409")
                                        && !error_msg.contains("out-of-date")
                                    {
                                        debug!(
                                            "Failed to update PR #{} description: {}",
                                            pr_id,
                                            error_msg.lines().next().unwrap_or("Unknown error")
                                        );
                                    }
                                }
                            }
                        }
                        Err(e) => {
                            tracing::debug!("Failed to get PR #{} for update: {}", pr_id, e);
                        }
                    }
                }
            }
        }

        Ok(updated_prs)
    }

    /// Submit a single stack entry as a pull request
    pub async fn submit_entry(
        &mut self,
        stack_id: &Uuid,
        entry_id: &Uuid,
        title: Option<String>,
        description: Option<String>,
        draft: bool,
    ) -> Result<PullRequest> {
        let stack = {
            let stack_ref = self
                .stack_manager
                .get_stack(stack_id)
                .ok_or_else(|| CascadeError::config(format!("Stack {stack_id} not found")))?;
            stack_ref.clone()
        };

        let entry = stack
            .get_entry(entry_id)
            .ok_or_else(|| CascadeError::config(format!("Entry {entry_id} not found in stack")))?;

        // Submitting stack entry as pull request

        // 🆕 VALIDATE GIT INTEGRITY BEFORE SUBMISSION
        if let Err(integrity_error) = stack.validate_git_integrity(self.stack_manager.git_repo()) {
            return Err(CascadeError::validation(format!(
                "Cannot submit entry from corrupted stack '{}':\n{}",
                stack.name, integrity_error
            )));
        }

        // Push branch to remote
        let git_repo = self.stack_manager.git_repo();

        // Determine if we need force-push:
        // 1. Entry has a PR (was already submitted, may have been rebased)
        // 2. Branch exists on remote but no PR yet (edge case: pushed but PR creation failed)
        let branch_has_remote = git_repo.get_upstream_branch(&entry.branch)?.is_some();
        let needs_force_push = entry.pull_request_id.is_some() || branch_has_remote;

        if needs_force_push {
            // Force push for existing PRs or branches already on remote
            // Set env var to skip interactive confirmation during submit (user already confirmed submit action)
            std::env::set_var("FORCE_PUSH_NO_CONFIRM", "1");
            let result = git_repo.force_push_single_branch(&entry.branch);
            std::env::remove_var("FORCE_PUSH_NO_CONFIRM");
            result.map_err(|e| CascadeError::bitbucket(e.to_string()))?;
        } else {
            // Regular push for brand new submissions
            git_repo
                .push(&entry.branch)
                .map_err(|e| CascadeError::bitbucket(e.to_string()))?;
        }

        // Branch pushed successfully

        // Mark as pushed in metadata
        if let Some(commit_meta) = self
            .stack_manager
            .get_repository_metadata()
            .commits
            .get(&entry.commit_hash)
        {
            let mut updated_meta = commit_meta.clone();
            updated_meta.mark_pushed();
            // Note: This would require making mark_pushed public and updating the metadata
            // For now, we'll track this as a future enhancement
        }

        // Determine target branch (parent entry's branch or stack base)
        let target_branch = self.get_target_branch(&stack, entry)?;

        // Ensure target branch is also pushed to remote (if it's not the base branch)
        if target_branch != stack.base_branch {
            // Ensure target branch is pushed to remote

            // Push target branch - fail fast if this fails
            git_repo.push(&target_branch).map_err(|e| {
                CascadeError::bitbucket(format!(
                    "Failed to push target branch '{target_branch}': {e}. Cannot create PR without target branch. \
                    Try manually pushing with: git push origin {target_branch}"
                ))
            })?;

            // Target branch pushed successfully
        }

        // Create pull request
        let pr_request =
            self.create_pr_request(&stack, entry, &target_branch, title, description, draft)?;

        let pr = match self.pr_manager.create_pull_request(pr_request).await {
            Ok(pr) => pr,
            Err(e) => {
                return Err(CascadeError::bitbucket(format!(
                    "Failed to create pull request for branch '{}' -> '{}': {}. \
                    Ensure both branches exist in the remote repository. \
                    You can manually push with: git push origin {}",
                    entry.branch, target_branch, e, entry.branch
                )));
            }
        };

        // Update stack manager with PR information
        self.stack_manager
            .submit_entry(stack_id, entry_id, pr.id.to_string())?;

        // Pull request created for entry
        Ok(pr)
    }

    /// Check the status of all pull requests in a stack
    pub async fn check_stack_status(&self, stack_id: &Uuid) -> Result<StackSubmissionStatus> {
        let stack = self
            .stack_manager
            .get_stack(stack_id)
            .ok_or_else(|| CascadeError::config(format!("Stack {stack_id} not found")))?;

        let mut status = StackSubmissionStatus {
            stack_name: stack.name.clone(),
            total_entries: stack.entries.len(),
            submitted_entries: 0,
            open_prs: 0,
            merged_prs: 0,
            declined_prs: 0,
            pull_requests: Vec::new(),
            enhanced_statuses: Vec::new(),
        };

        for entry in &stack.entries {
            if let Some(pr_id_str) = &entry.pull_request_id {
                status.submitted_entries += 1;

                if let Ok(pr_id) = pr_id_str.parse::<u64>() {
                    match self.pr_manager.get_pull_request(pr_id).await {
                        Ok(pr) => {
                            match pr.state {
                                PullRequestState::Open => status.open_prs += 1,
                                PullRequestState::Merged => status.merged_prs += 1,
                                PullRequestState::Declined => status.declined_prs += 1,
                            }
                            status.pull_requests.push(pr);
                        }
                        Err(e) => {
                            tracing::debug!("Failed to get pull request #{}: {}", pr_id, e);
                        }
                    }
                }
            }
        }

        Ok(status)
    }

    /// List all pull requests for the repository
    pub async fn list_pull_requests(
        &self,
        state: Option<PullRequestState>,
    ) -> Result<crate::bitbucket::pull_request::PullRequestPage> {
        self.pr_manager.list_pull_requests(state).await
    }

    /// Get the target branch for a stack entry
    fn get_target_branch(&self, stack: &Stack, entry: &StackEntry) -> Result<String> {
        // For the first entry (bottom of stack), target is the base branch
        if let Some(first_entry) = stack.entries.first() {
            if entry.id == first_entry.id {
                return Ok(stack.base_branch.clone());
            }
        }

        // For other entries, find the parent entry's branch
        let entry_index = stack
            .entries
            .iter()
            .position(|e| e.id == entry.id)
            .ok_or_else(|| CascadeError::config("Entry not found in stack"))?;

        if entry_index == 0 {
            Ok(stack.base_branch.clone())
        } else {
            Ok(stack.entries[entry_index - 1].branch.clone())
        }
    }

    /// Create a pull request request object
    fn create_pr_request(
        &self,
        stack: &Stack,
        entry: &StackEntry,
        target_branch: &str,
        title: Option<String>,
        description: Option<String>,
        draft: bool,
    ) -> Result<CreatePullRequestRequest> {
        let bitbucket_config = self.config.bitbucket.as_ref()
            .ok_or_else(|| CascadeError::config("Bitbucket configuration is missing. Run 'ca setup' to configure Bitbucket integration."))?;

        let repository = Repository {
            id: 0, // This will be filled by the API
            name: bitbucket_config.repo.clone(),
            slug: bitbucket_config.repo.clone(),
            scm_id: "git".to_string(),
            state: "AVAILABLE".to_string(),
            status_message: Some("Available".to_string()),
            forkable: true,
            project: Project {
                id: 0,
                key: bitbucket_config.project.clone(),
                name: bitbucket_config.project.clone(),
                description: None,
                public: false,
                project_type: "NORMAL".to_string(),
            },
            public: false,
        };

        let from_ref = PullRequestRef {
            id: format!("refs/heads/{}", entry.branch),
            display_id: entry.branch.clone(),
            latest_commit: entry.commit_hash.clone(),
            repository: repository.clone(),
        };

        let to_ref = PullRequestRef {
            id: format!("refs/heads/{target_branch}"),
            display_id: target_branch.to_string(),
            latest_commit: "".to_string(), // This will be filled by the API
            repository,
        };

        let mut title =
            title.unwrap_or_else(|| entry.message.lines().next().unwrap_or("").to_string());

        // Add [DRAFT] prefix for draft PRs
        if draft && !title.starts_with("[DRAFT]") {
            title = format!("[DRAFT] {title}");
        }

        let description = {
            // Priority order: 1) Template (if configured), 2) User description, 3) Commit message body, 4) None
            if let Some(template) = &self.config.cascade.pr_description_template {
                Some(template.clone()) // Always use template if configured
            } else if let Some(desc) = description {
                Some(desc) // Use provided description if no template
            } else if entry.message.lines().count() > 1 {
                // Fallback to commit message body if no template and no description
                Some(
                    entry
                        .message
                        .lines()
                        .skip(1)
                        .collect::<Vec<_>>()
                        .join("\n")
                        .trim()
                        .to_string(),
                )
            } else {
                None
            }
        };

        // Add stack hierarchy footer to description
        let description_with_footer = self.add_stack_hierarchy_footer(description, stack, entry)?;

        Ok(CreatePullRequestRequest {
            title,
            description: description_with_footer,
            from_ref,
            to_ref,
            draft, // Explicitly set true or false for Bitbucket Server
        })
    }

    /// Generate a beautiful stack hierarchy footer for PR descriptions
    fn add_stack_hierarchy_footer(
        &self,
        description: Option<String>,
        stack: &Stack,
        current_entry: &StackEntry,
    ) -> Result<Option<String>> {
        let hierarchy = self.generate_stack_hierarchy(stack, current_entry)?;

        let footer = format!("\n\n---\n\n## 📚 Stack: {}\n\n{}", stack.name, hierarchy);

        match description {
            Some(desc) => Ok(Some(format!("{desc}{footer}"))),
            None => Ok(Some(footer.trim_start_matches('\n').to_string())),
        }
    }

    /// Generate a visual hierarchy showing the stack structure
    fn generate_stack_hierarchy(
        &self,
        stack: &Stack,
        current_entry: &StackEntry,
    ) -> Result<String> {
        let mut hierarchy = String::new();

        // Add visual tree directly without redundant info
        hierarchy.push_str("### Stack Hierarchy\n\n");
        hierarchy.push_str("```\n");

        // Base branch
        hierarchy.push_str(&format!("📍 {} (base)\n", stack.base_branch));

        // Stack entries with visual connections
        for (index, entry) in stack.entries.iter().enumerate() {
            let is_current = entry.id == current_entry.id;
            let is_last = index == stack.entries.len() - 1;

            // Visual tree connector
            let connector = if is_last { "└── " } else { "├── " };

            // Entry indicator
            let indicator = if is_current {
                "← current"
            } else if entry.pull_request_id.is_some() {
                ""
            } else {
                "(pending)"
            };

            // PR link if available
            let pr_info = if let Some(pr_id) = &entry.pull_request_id {
                format!(" (PR #{pr_id})")
            } else {
                String::new()
            };

            hierarchy.push_str(&format!(
                "{}{}{} {}\n",
                connector, entry.branch, pr_info, indicator
            ));
        }

        hierarchy.push_str("```\n\n");

        // Add position context
        if let Some(current_index) = stack.entries.iter().position(|e| e.id == current_entry.id) {
            let position = current_index + 1;
            let total = stack.entries.len();
            hierarchy.push_str(&format!("**Position:** {position} of {total} in stack"));
        }

        Ok(hierarchy)
    }

    /// Update pull requests after a rebase using smart force push strategy
    /// This preserves all review history by updating existing branches instead of creating new ones
    pub async fn update_prs_after_rebase(
        &mut self,
        stack_id: &Uuid,
        branch_mapping: &HashMap<String, String>,
    ) -> Result<Vec<String>> {
        debug!(
            "Updating pull requests after rebase for stack {} using smart force push",
            stack_id
        );

        let stack = self
            .stack_manager
            .get_stack(stack_id)
            .ok_or_else(|| CascadeError::config(format!("Stack {stack_id} not found")))?
            .clone();

        let mut updated_branches = Vec::new();

        for entry in &stack.entries {
            // Check if this entry has an existing PR and was remapped to a new branch
            if let (Some(pr_id_str), Some(new_branch)) =
                (&entry.pull_request_id, branch_mapping.get(&entry.branch))
            {
                if let Ok(pr_id) = pr_id_str.parse::<u64>() {
                    debug!(
                        "Found existing PR #{} for entry {}, updating branch {} -> {}",
                        pr_id, entry.id, entry.branch, new_branch
                    );

                    // Get the existing PR to understand its current state
                    match self.pr_manager.get_pull_request_status(pr_id).await {
                        Ok(pr_status) => {
                            match pr_status.pr.state {
                                crate::bitbucket::pull_request::PullRequestState::Merged => {
                                    if let Err(e) = self
                                        .stack_manager
                                        .set_entry_merged(&stack.id, &entry.id, true)
                                    {
                                        tracing::warn!(
                                            "Failed to persist merged state for entry {}: {}",
                                            entry.id,
                                            e
                                        );
                                    }
                                    debug!(
                                        "Skipping PR #{} update because it is already merged",
                                        pr_id
                                    );
                                    continue;
                                }
                                crate::bitbucket::pull_request::PullRequestState::Declined => {
                                    if let Err(e) = self
                                        .stack_manager
                                        .set_entry_merged(&stack.id, &entry.id, false)
                                    {
                                        tracing::warn!(
                                            "Failed to persist merged state for entry {}: {}",
                                            entry.id,
                                            e
                                        );
                                    }
                                    debug!("Skipping PR #{} update because it is declined", pr_id);
                                    continue;
                                }
                                crate::bitbucket::pull_request::PullRequestState::Open => {
                                    if let Err(e) = self
                                        .stack_manager
                                        .set_entry_merged(&stack.id, &entry.id, false)
                                    {
                                        tracing::warn!(
                                            "Failed to persist merged state for entry {}: {}",
                                            entry.id,
                                            e
                                        );
                                    }
                                }
                            }

                            // Ensure local branch head matches recorded commit before updating PR
                            // If they don't match, auto-reconcile since we just finished a rebase
                            if let Ok(local_head) =
                                self.stack_manager.git_repo().get_branch_head(&entry.branch)
                            {
                                if local_head != entry.commit_hash {
                                    tracing::debug!(
                                        "Branch '{}' HEAD ({}) doesn't match metadata ({}), reconciling...",
                                        entry.branch,
                                        &local_head[..8],
                                        &entry.commit_hash[..8]
                                    );

                                    // Auto-reconcile: update metadata to match current branch HEAD
                                    // This is safe during PR updates after a rebase since we know the branch was just updated
                                    if let Some(stack) = self.stack_manager.get_stack_mut(&stack.id)
                                    {
                                        if let Err(e) = stack
                                            .update_entry_commit_hash(&entry.id, local_head.clone())
                                        {
                                            Output::warning(format!(
                                                "Could not reconcile metadata for PR #{}: {}",
                                                pr_id, e
                                            ));
                                            continue;
                                        }
                                        // Save reconciled metadata
                                        if let Err(e) = self.stack_manager.save_to_disk() {
                                            Output::warning(format!(
                                                "Could not save reconciled metadata: {}",
                                                e
                                            ));
                                        }
                                    }
                                }
                            }

                            // Validate that the new branch contains cumulative changes
                            if let Err(validation_error) =
                                self.validate_cumulative_changes(&entry.branch, new_branch)
                            {
                                Output::error(format!(
                                    "❌ Validation failed for PR #{pr_id}: {validation_error}"
                                ));
                                Output::warning("Skipping force push to prevent data loss");
                                continue;
                            }

                            // Force push the new branch content to the old branch name
                            // This preserves the PR while updating its contents
                            match self
                                .stack_manager
                                .git_repo()
                                .force_push_branch(&entry.branch, new_branch)
                            {
                                Ok(_) => {
                                    debug!(
                                        "Successfully force-pushed {} to preserve PR #{}",
                                        entry.branch, pr_id
                                    );

                                    // Add a comment explaining the rebase
                                    let rebase_comment = format!(
                                        "🔄 **Automatic rebase completed**\n\n\
                                        This PR has been automatically rebased onto the latest `{}`.\n\
                                        - Updated commit: `{}`\n\
                                        - All review history and comments are preserved",
                                        stack.base_branch,
                                        &entry.commit_hash[..8]
                                    );

                                    if let Err(e) =
                                        self.pr_manager.add_comment(pr_id, &rebase_comment).await
                                    {
                                        tracing::debug!(
                                            "Failed to add rebase comment to PR #{}: {}",
                                            pr_id,
                                            e
                                        );
                                    }

                                    updated_branches.push(format!(
                                        "PR #{}: {} (preserved)",
                                        pr_id, entry.branch
                                    ));
                                }
                                Err(e) => {
                                    error!("Failed to force push {}: {}", entry.branch, e);
                                    // Fall back to creating a comment about the issue
                                    let error_comment = format!(
                                        "⚠️ **Rebase Update Issue**\n\n\
                                        The automatic rebase completed, but updating this PR failed.\n\
                                        You may need to manually update this branch.\n\
                                        Error: {e}"
                                    );

                                    if let Err(e2) =
                                        self.pr_manager.add_comment(pr_id, &error_comment).await
                                    {
                                        tracing::debug!(
                                            "Failed to add error comment to PR #{}: {}",
                                            pr_id,
                                            e2
                                        );
                                    }
                                }
                            }
                        }
                        Err(e) => {
                            tracing::debug!("Could not retrieve PR #{}: {}", pr_id, e);
                        }
                    }
                }
            } else if branch_mapping.contains_key(&entry.branch) {
                // This entry was remapped but doesn't have a PR yet
                debug!(
                    "Entry {} was remapped but has no PR - no action needed",
                    entry.id
                );
            }
        }

        if !updated_branches.is_empty() {
            debug!(
                "Successfully updated {} PRs using smart force push strategy",
                updated_branches.len()
            );
        }

        Ok(updated_branches)
    }

    /// Validate that the new branch contains cumulative changes from the base
    /// This prevents data loss during force push operations
    fn validate_cumulative_changes(&self, original_branch: &str, new_branch: &str) -> Result<()> {
        let git_repo = self.stack_manager.git_repo();

        // Get the stack that contains this branch
        let stack = self
            .stack_manager
            .get_all_stacks()
            .into_iter()
            .find(|s| s.entries.iter().any(|e| e.branch == original_branch))
            .ok_or_else(|| {
                CascadeError::config(format!(
                    "No stack found containing branch '{original_branch}'"
                ))
            })?;

        let _base_branch = &stack.base_branch;

        // Ensure the updated branch exists locally
        let new_head = git_repo.get_branch_head(new_branch).map_err(|e| {
            CascadeError::validation(format!("Could not get HEAD for branch '{new_branch}': {e}"))
        })?;

        // If a remote counterpart exists, ensure the new head is a descendant before overwriting
        match git_repo.get_remote_branch_head(original_branch) {
            Ok(remote_head) => {
                if remote_head != new_head && !git_repo.is_descendant_of(&new_head, &remote_head)? {
                    tracing::debug!(
                        "Stack sync: '{}' rewrote remote history ({} -> {}). This is expected after rebase.",
                        new_branch,
                        &remote_head[..8],
                        &new_head[..8]
                    );
                } else {
                    tracing::debug!(
                        "Validated ancestry for '{}': {} descends from {}",
                        new_branch,
                        &new_head[..8],
                        &remote_head[..8]
                    );
                }
            }
            Err(_) => {
                tracing::debug!(
                    "No remote tracking branch for '{}' - skipping ancestor validation",
                    original_branch
                );
            }
        }

        Ok(())
    }

    /// Check the enhanced status of all pull requests in a stack
    pub async fn check_enhanced_stack_status(
        &mut self,
        stack_id: &Uuid,
    ) -> Result<StackSubmissionStatus> {
        let stack = self
            .stack_manager
            .get_stack(stack_id)
            .cloned()
            .ok_or_else(|| CascadeError::config(format!("Stack {stack_id} not found")))?;

        let stack_uuid = stack.id;

        let mut status = StackSubmissionStatus {
            stack_name: stack.name.clone(),
            total_entries: stack.entries.len(),
            submitted_entries: 0,
            open_prs: 0,
            merged_prs: 0,
            declined_prs: 0,
            pull_requests: Vec::new(),
            enhanced_statuses: Vec::new(),
        };

        let mut merged_updates: Vec<(Uuid, bool)> = Vec::new();

        for entry in &stack.entries {
            if let Some(pr_id_str) = &entry.pull_request_id {
                status.submitted_entries += 1;

                if let Ok(pr_id) = pr_id_str.parse::<u64>() {
                    // Get enhanced status instead of basic PR
                    match self.pr_manager.get_pull_request_status(pr_id).await {
                        Ok(enhanced_status) => {
                            match enhanced_status.pr.state {
                                crate::bitbucket::pull_request::PullRequestState::Open => {
                                    status.open_prs += 1;
                                    merged_updates.push((entry.id, false));
                                }
                                crate::bitbucket::pull_request::PullRequestState::Merged => {
                                    status.merged_prs += 1;
                                    merged_updates.push((entry.id, true));
                                }
                                crate::bitbucket::pull_request::PullRequestState::Declined => {
                                    status.declined_prs += 1;
                                    merged_updates.push((entry.id, false));
                                }
                            }
                            status.pull_requests.push(enhanced_status.pr.clone());
                            status.enhanced_statuses.push(enhanced_status);
                        }
                        Err(e) => {
                            tracing::debug!(
                                "Failed to get enhanced status for PR #{}: {}",
                                pr_id,
                                e
                            );
                            // Fallback to basic PR info
                            match self.pr_manager.get_pull_request(pr_id).await {
                                Ok(pr) => {
                                    match pr.state {
                                        crate::bitbucket::pull_request::PullRequestState::Open => {
                                            status.open_prs += 1;
                                            merged_updates.push((entry.id, false));
                                        }
                                        crate::bitbucket::pull_request::PullRequestState::Merged => {
                                            status.merged_prs += 1;
                                            merged_updates.push((entry.id, true));
                                        }
                                        crate::bitbucket::pull_request::PullRequestState::Declined => {
                                            status.declined_prs += 1;
                                            merged_updates.push((entry.id, false));
                                        }
                                    }
                                    status.pull_requests.push(pr);
                                }
                                Err(e2) => {
                                    tracing::debug!("Failed to get basic PR #{}: {}", pr_id, e2);
                                }
                            }
                        }
                    }
                }
            }
        }

        drop(stack);

        if !merged_updates.is_empty() {
            for (entry_id, merged) in merged_updates {
                if let Err(e) = self
                    .stack_manager
                    .set_entry_merged(&stack_uuid, &entry_id, merged)
                {
                    tracing::warn!(
                        "Failed to persist merged state for entry {}: {}",
                        entry_id,
                        e
                    );
                }
            }
        }

        Ok(status)
    }
}

/// Status of stack submission with enhanced mergability information
#[derive(Debug)]
pub struct StackSubmissionStatus {
    pub stack_name: String,
    pub total_entries: usize,
    pub submitted_entries: usize,
    pub open_prs: usize,
    pub merged_prs: usize,
    pub declined_prs: usize,
    pub pull_requests: Vec<PullRequest>,
    pub enhanced_statuses: Vec<crate::bitbucket::pull_request::PullRequestStatus>,
}

impl StackSubmissionStatus {
    /// Calculate completion percentage (merged PRs / submitted PRs)
    ///
    /// Measures completion of submitted work, not total stack entries.
    /// This changed from `total_entries` to `submitted_entries` as divisor
    /// to provide a more accurate measure of review progress.
    pub fn completion_percentage(&self) -> f64 {
        if self.submitted_entries == 0 {
            0.0
        } else {
            (self.merged_prs as f64 / self.submitted_entries as f64) * 100.0
        }
    }

    /// Check if all entries are submitted
    pub fn all_submitted(&self) -> bool {
        self.submitted_entries == self.total_entries
    }

    /// Check if all PRs are merged
    pub fn all_merged(&self) -> bool {
        self.submitted_entries > 0 && self.merged_prs == self.submitted_entries
    }
}