cascade_cli/git/
repository.rs

1use crate::cli::output::Output;
2use crate::errors::{CascadeError, Result};
3use chrono;
4use dialoguer::{theme::ColorfulTheme, Confirm, Select};
5use git2::{Oid, Repository, Signature};
6use std::path::{Path, PathBuf};
7use tracing::{debug, info, warn};
8
9/// Repository information
10#[derive(Debug, Clone)]
11pub struct RepositoryInfo {
12    pub path: PathBuf,
13    pub head_branch: Option<String>,
14    pub head_commit: Option<String>,
15    pub is_dirty: bool,
16    pub untracked_files: Vec<String>,
17}
18
19/// Backup information for force push operations
20#[derive(Debug, Clone)]
21struct ForceBackupInfo {
22    pub backup_branch_name: String,
23    pub remote_commit_id: String,
24    #[allow(dead_code)] // Used for logging/display purposes
25    pub commits_that_would_be_lost: usize,
26}
27
28/// Safety information for branch deletion operations
29#[derive(Debug, Clone)]
30struct BranchDeletionSafety {
31    pub unpushed_commits: Vec<String>,
32    pub remote_tracking_branch: Option<String>,
33    pub is_merged_to_main: bool,
34    pub main_branch_name: String,
35}
36
37/// Safety information for checkout operations
38#[derive(Debug, Clone)]
39struct CheckoutSafety {
40    #[allow(dead_code)] // Used in confirmation dialogs and future features
41    pub has_uncommitted_changes: bool,
42    pub modified_files: Vec<String>,
43    pub staged_files: Vec<String>,
44    pub untracked_files: Vec<String>,
45    #[allow(dead_code)] // Reserved for future automatic stashing implementation
46    pub stash_created: Option<String>,
47    #[allow(dead_code)] // Used for context in confirmation dialogs
48    pub current_branch: Option<String>,
49}
50
51/// SSL configuration for git operations
52#[derive(Debug, Clone)]
53pub struct GitSslConfig {
54    pub accept_invalid_certs: bool,
55    pub ca_bundle_path: Option<String>,
56}
57
58/// Summary of git repository status
59#[derive(Debug, Clone)]
60pub struct GitStatusSummary {
61    staged_files: usize,
62    unstaged_files: usize,
63    untracked_files: usize,
64}
65
66impl GitStatusSummary {
67    pub fn is_clean(&self) -> bool {
68        self.staged_files == 0 && self.unstaged_files == 0 && self.untracked_files == 0
69    }
70
71    pub fn has_staged_changes(&self) -> bool {
72        self.staged_files > 0
73    }
74
75    pub fn has_unstaged_changes(&self) -> bool {
76        self.unstaged_files > 0
77    }
78
79    pub fn has_untracked_files(&self) -> bool {
80        self.untracked_files > 0
81    }
82
83    pub fn staged_count(&self) -> usize {
84        self.staged_files
85    }
86
87    pub fn unstaged_count(&self) -> usize {
88        self.unstaged_files
89    }
90
91    pub fn untracked_count(&self) -> usize {
92        self.untracked_files
93    }
94}
95
96/// Wrapper around git2::Repository with safe operations
97///
98/// For thread safety, use the async variants (e.g., fetch_async, pull_async)
99/// which automatically handle threading using tokio::spawn_blocking.
100/// The async methods create new repository instances in background threads.
101pub struct GitRepository {
102    repo: Repository,
103    path: PathBuf,
104    ssl_config: Option<GitSslConfig>,
105    bitbucket_credentials: Option<BitbucketCredentials>,
106}
107
108#[derive(Debug, Clone)]
109struct BitbucketCredentials {
110    username: Option<String>,
111    token: Option<String>,
112}
113
114impl GitRepository {
115    /// Open a Git repository at the given path
116    /// Automatically loads SSL configuration from cascade config if available
117    pub fn open(path: &Path) -> Result<Self> {
118        let repo = Repository::discover(path)
119            .map_err(|e| CascadeError::config(format!("Not a git repository: {e}")))?;
120
121        let workdir = repo
122            .workdir()
123            .ok_or_else(|| CascadeError::config("Repository has no working directory"))?
124            .to_path_buf();
125
126        // Try to load SSL configuration from cascade config
127        let ssl_config = Self::load_ssl_config_from_cascade(&workdir);
128        let bitbucket_credentials = Self::load_bitbucket_credentials_from_cascade(&workdir);
129
130        Ok(Self {
131            repo,
132            path: workdir,
133            ssl_config,
134            bitbucket_credentials,
135        })
136    }
137
138    /// Load SSL configuration from cascade config file if it exists
139    fn load_ssl_config_from_cascade(repo_path: &Path) -> Option<GitSslConfig> {
140        // Try to load cascade configuration
141        let config_dir = crate::config::get_repo_config_dir(repo_path).ok()?;
142        let config_path = config_dir.join("config.json");
143        let settings = crate::config::Settings::load_from_file(&config_path).ok()?;
144
145        // Convert BitbucketConfig to GitSslConfig if SSL settings exist
146        if settings.bitbucket.accept_invalid_certs.is_some()
147            || settings.bitbucket.ca_bundle_path.is_some()
148        {
149            Some(GitSslConfig {
150                accept_invalid_certs: settings.bitbucket.accept_invalid_certs.unwrap_or(false),
151                ca_bundle_path: settings.bitbucket.ca_bundle_path,
152            })
153        } else {
154            None
155        }
156    }
157
158    /// Load Bitbucket credentials from cascade config file if it exists
159    fn load_bitbucket_credentials_from_cascade(repo_path: &Path) -> Option<BitbucketCredentials> {
160        // Try to load cascade configuration
161        let config_dir = crate::config::get_repo_config_dir(repo_path).ok()?;
162        let config_path = config_dir.join("config.json");
163        let settings = crate::config::Settings::load_from_file(&config_path).ok()?;
164
165        // Return credentials if any are configured
166        if settings.bitbucket.username.is_some() || settings.bitbucket.token.is_some() {
167            Some(BitbucketCredentials {
168                username: settings.bitbucket.username.clone(),
169                token: settings.bitbucket.token.clone(),
170            })
171        } else {
172            None
173        }
174    }
175
176    /// Get repository information
177    pub fn get_info(&self) -> Result<RepositoryInfo> {
178        let head_branch = self.get_current_branch().ok();
179        let head_commit = self.get_head_commit_hash().ok();
180        let is_dirty = self.is_dirty()?;
181        let untracked_files = self.get_untracked_files()?;
182
183        Ok(RepositoryInfo {
184            path: self.path.clone(),
185            head_branch,
186            head_commit,
187            is_dirty,
188            untracked_files,
189        })
190    }
191
192    /// Get the current branch name
193    pub fn get_current_branch(&self) -> Result<String> {
194        let head = self
195            .repo
196            .head()
197            .map_err(|e| CascadeError::branch(format!("Could not get HEAD: {e}")))?;
198
199        if let Some(name) = head.shorthand() {
200            Ok(name.to_string())
201        } else {
202            // Detached HEAD - return commit hash
203            let commit = head
204                .peel_to_commit()
205                .map_err(|e| CascadeError::branch(format!("Could not get HEAD commit: {e}")))?;
206            Ok(format!("HEAD@{}", commit.id()))
207        }
208    }
209
210    /// Get the HEAD commit hash
211    pub fn get_head_commit_hash(&self) -> Result<String> {
212        let head = self
213            .repo
214            .head()
215            .map_err(|e| CascadeError::branch(format!("Could not get HEAD: {e}")))?;
216
217        let commit = head
218            .peel_to_commit()
219            .map_err(|e| CascadeError::branch(format!("Could not get HEAD commit: {e}")))?;
220
221        Ok(commit.id().to_string())
222    }
223
224    /// Check if the working directory is dirty (has uncommitted changes)
225    pub fn is_dirty(&self) -> Result<bool> {
226        let statuses = self.repo.statuses(None).map_err(CascadeError::Git)?;
227
228        for status in statuses.iter() {
229            let flags = status.status();
230
231            // Check for any modifications, additions, or deletions
232            if flags.intersects(
233                git2::Status::INDEX_MODIFIED
234                    | git2::Status::INDEX_NEW
235                    | git2::Status::INDEX_DELETED
236                    | git2::Status::WT_MODIFIED
237                    | git2::Status::WT_NEW
238                    | git2::Status::WT_DELETED,
239            ) {
240                return Ok(true);
241            }
242        }
243
244        Ok(false)
245    }
246
247    /// Get list of untracked files
248    pub fn get_untracked_files(&self) -> Result<Vec<String>> {
249        let statuses = self.repo.statuses(None).map_err(CascadeError::Git)?;
250
251        let mut untracked = Vec::new();
252        for status in statuses.iter() {
253            if status.status().contains(git2::Status::WT_NEW) {
254                if let Some(path) = status.path() {
255                    untracked.push(path.to_string());
256                }
257            }
258        }
259
260        Ok(untracked)
261    }
262
263    /// Create a new branch
264    pub fn create_branch(&self, name: &str, target: Option<&str>) -> Result<()> {
265        let target_commit = if let Some(target) = target {
266            // Find the specified target commit/branch
267            let target_obj = self.repo.revparse_single(target).map_err(|e| {
268                CascadeError::branch(format!("Could not find target '{target}': {e}"))
269            })?;
270            target_obj.peel_to_commit().map_err(|e| {
271                CascadeError::branch(format!("Target '{target}' is not a commit: {e}"))
272            })?
273        } else {
274            // Use current HEAD
275            let head = self
276                .repo
277                .head()
278                .map_err(|e| CascadeError::branch(format!("Could not get HEAD: {e}")))?;
279            head.peel_to_commit()
280                .map_err(|e| CascadeError::branch(format!("Could not get HEAD commit: {e}")))?
281        };
282
283        self.repo
284            .branch(name, &target_commit, false)
285            .map_err(|e| CascadeError::branch(format!("Could not create branch '{name}': {e}")))?;
286
287        // Branch creation logging is handled by the caller for clean output
288        Ok(())
289    }
290
291    /// Update a branch to point to a specific commit (local operation only)
292    /// Creates the branch if it doesn't exist, updates it if it does
293    pub fn update_branch_to_commit(&self, branch_name: &str, commit_id: &str) -> Result<()> {
294        let commit_oid = Oid::from_str(commit_id).map_err(|e| {
295            CascadeError::branch(format!("Invalid commit ID '{}': {}", commit_id, e))
296        })?;
297
298        let commit = self.repo.find_commit(commit_oid).map_err(|e| {
299            CascadeError::branch(format!("Commit '{}' not found: {}", commit_id, e))
300        })?;
301
302        // Try to find existing branch
303        if self
304            .repo
305            .find_branch(branch_name, git2::BranchType::Local)
306            .is_ok()
307        {
308            // Update existing branch to point to new commit
309            let refname = format!("refs/heads/{}", branch_name);
310            self.repo
311                .reference(
312                    &refname,
313                    commit_oid,
314                    true,
315                    "update branch to rebased commit",
316                )
317                .map_err(|e| {
318                    CascadeError::branch(format!(
319                        "Failed to update branch '{}': {}",
320                        branch_name, e
321                    ))
322                })?;
323        } else {
324            // Create new branch
325            self.repo.branch(branch_name, &commit, false).map_err(|e| {
326                CascadeError::branch(format!("Failed to create branch '{}': {}", branch_name, e))
327            })?;
328        }
329
330        Ok(())
331    }
332
333    /// Force-push a single branch to remote (simpler version for when branch is already updated locally)
334    pub fn force_push_single_branch(&self, branch_name: &str) -> Result<()> {
335        // Fetch first to ensure we have latest remote state for safety checks
336        if let Err(e) = self.fetch() {
337            tracing::warn!("Could not fetch before force push: {}", e);
338        }
339
340        // Check safety and create backup if needed
341        let safety_result = self.check_force_push_safety_enhanced(branch_name)?;
342        if let Some(backup_info) = safety_result {
343            self.create_backup_branch(branch_name, &backup_info.remote_commit_id)?;
344        }
345
346        // Force push using git CLI (more reliable than git2 for TLS)
347        let output = std::process::Command::new("git")
348            .args(["push", "--force", "origin", branch_name])
349            .current_dir(&self.path)
350            .output()
351            .map_err(|e| CascadeError::branch(format!("Failed to execute git push: {}", e)))?;
352
353        if !output.status.success() {
354            let stderr = String::from_utf8_lossy(&output.stderr);
355            return Err(CascadeError::branch(format!(
356                "Force push failed for '{}': {}",
357                branch_name, stderr
358            )));
359        }
360
361        Ok(())
362    }
363
364    /// Switch to a branch with safety checks
365    pub fn checkout_branch(&self, name: &str) -> Result<()> {
366        self.checkout_branch_with_options(name, false)
367    }
368
369    /// Switch to a branch with force option to bypass safety checks
370    pub fn checkout_branch_unsafe(&self, name: &str) -> Result<()> {
371        self.checkout_branch_with_options(name, true)
372    }
373
374    /// Internal branch checkout implementation with safety options
375    fn checkout_branch_with_options(&self, name: &str, force_unsafe: bool) -> Result<()> {
376        debug!("Attempting to checkout branch: {}", name);
377
378        // Enhanced safety check: Detect uncommitted work before checkout
379        if !force_unsafe {
380            let safety_result = self.check_checkout_safety(name)?;
381            if let Some(safety_info) = safety_result {
382                // Repository has uncommitted changes, get user confirmation
383                self.handle_checkout_confirmation(name, &safety_info)?;
384            }
385        }
386
387        // Find the branch
388        let branch = self
389            .repo
390            .find_branch(name, git2::BranchType::Local)
391            .map_err(|e| CascadeError::branch(format!("Could not find branch '{name}': {e}")))?;
392
393        let branch_ref = branch.get();
394        let tree = branch_ref.peel_to_tree().map_err(|e| {
395            CascadeError::branch(format!("Could not get tree for branch '{name}': {e}"))
396        })?;
397
398        // Checkout the tree
399        self.repo
400            .checkout_tree(tree.as_object(), None)
401            .map_err(|e| {
402                CascadeError::branch(format!("Could not checkout branch '{name}': {e}"))
403            })?;
404
405        // Update HEAD
406        self.repo
407            .set_head(&format!("refs/heads/{name}"))
408            .map_err(|e| CascadeError::branch(format!("Could not update HEAD to '{name}': {e}")))?;
409
410        Output::success(format!("Switched to branch '{name}'"));
411        Ok(())
412    }
413
414    /// Checkout a specific commit (detached HEAD) with safety checks
415    pub fn checkout_commit(&self, commit_hash: &str) -> Result<()> {
416        self.checkout_commit_with_options(commit_hash, false)
417    }
418
419    /// Checkout a specific commit with force option to bypass safety checks
420    pub fn checkout_commit_unsafe(&self, commit_hash: &str) -> Result<()> {
421        self.checkout_commit_with_options(commit_hash, true)
422    }
423
424    /// Internal commit checkout implementation with safety options
425    fn checkout_commit_with_options(&self, commit_hash: &str, force_unsafe: bool) -> Result<()> {
426        debug!("Attempting to checkout commit: {}", commit_hash);
427
428        // Enhanced safety check: Detect uncommitted work before checkout
429        if !force_unsafe {
430            let safety_result = self.check_checkout_safety(&format!("commit:{commit_hash}"))?;
431            if let Some(safety_info) = safety_result {
432                // Repository has uncommitted changes, get user confirmation
433                self.handle_checkout_confirmation(&format!("commit {commit_hash}"), &safety_info)?;
434            }
435        }
436
437        let oid = Oid::from_str(commit_hash).map_err(CascadeError::Git)?;
438
439        let commit = self.repo.find_commit(oid).map_err(|e| {
440            CascadeError::branch(format!("Could not find commit '{commit_hash}': {e}"))
441        })?;
442
443        let tree = commit.tree().map_err(|e| {
444            CascadeError::branch(format!(
445                "Could not get tree for commit '{commit_hash}': {e}"
446            ))
447        })?;
448
449        // Checkout the tree
450        self.repo
451            .checkout_tree(tree.as_object(), None)
452            .map_err(|e| {
453                CascadeError::branch(format!("Could not checkout commit '{commit_hash}': {e}"))
454            })?;
455
456        // Update HEAD to the commit (detached HEAD)
457        self.repo.set_head_detached(oid).map_err(|e| {
458            CascadeError::branch(format!(
459                "Could not update HEAD to commit '{commit_hash}': {e}"
460            ))
461        })?;
462
463        Output::success(format!(
464            "Checked out commit '{commit_hash}' (detached HEAD)"
465        ));
466        Ok(())
467    }
468
469    /// Check if a branch exists
470    pub fn branch_exists(&self, name: &str) -> bool {
471        self.repo.find_branch(name, git2::BranchType::Local).is_ok()
472    }
473
474    /// Check if a branch exists locally, and if not, attempt to fetch it from remote
475    pub fn branch_exists_or_fetch(&self, name: &str) -> Result<bool> {
476        // 1. Check if branch exists locally first
477        if self.repo.find_branch(name, git2::BranchType::Local).is_ok() {
478            return Ok(true);
479        }
480
481        // 2. Try to fetch it from remote
482        println!("🔍 Branch '{name}' not found locally, trying to fetch from remote...");
483
484        use std::process::Command;
485
486        // Try: git fetch origin release/12.34:release/12.34
487        let fetch_result = Command::new("git")
488            .args(["fetch", "origin", &format!("{name}:{name}")])
489            .current_dir(&self.path)
490            .output();
491
492        match fetch_result {
493            Ok(output) => {
494                if output.status.success() {
495                    println!("✅ Successfully fetched '{name}' from origin");
496                    // 3. Check again locally after fetch
497                    return Ok(self.repo.find_branch(name, git2::BranchType::Local).is_ok());
498                } else {
499                    let stderr = String::from_utf8_lossy(&output.stderr);
500                    tracing::debug!("Failed to fetch branch '{name}': {stderr}");
501                }
502            }
503            Err(e) => {
504                tracing::debug!("Git fetch command failed: {e}");
505            }
506        }
507
508        // 4. Try alternative fetch patterns for common branch naming
509        if name.contains('/') {
510            println!("🔍 Trying alternative fetch patterns...");
511
512            // Try: git fetch origin (to get all refs, then checkout locally)
513            let fetch_all_result = Command::new("git")
514                .args(["fetch", "origin"])
515                .current_dir(&self.path)
516                .output();
517
518            if let Ok(output) = fetch_all_result {
519                if output.status.success() {
520                    // Try to create local branch from remote
521                    let checkout_result = Command::new("git")
522                        .args(["checkout", "-b", name, &format!("origin/{name}")])
523                        .current_dir(&self.path)
524                        .output();
525
526                    if let Ok(checkout_output) = checkout_result {
527                        if checkout_output.status.success() {
528                            println!(
529                                "✅ Successfully created local branch '{name}' from origin/{name}"
530                            );
531                            return Ok(true);
532                        }
533                    }
534                }
535            }
536        }
537
538        // 5. Only fail if it doesn't exist anywhere
539        Ok(false)
540    }
541
542    /// Get the commit hash for a specific branch without switching branches
543    pub fn get_branch_commit_hash(&self, branch_name: &str) -> Result<String> {
544        let branch = self
545            .repo
546            .find_branch(branch_name, git2::BranchType::Local)
547            .map_err(|e| {
548                CascadeError::branch(format!("Could not find branch '{branch_name}': {e}"))
549            })?;
550
551        let commit = branch.get().peel_to_commit().map_err(|e| {
552            CascadeError::branch(format!(
553                "Could not get commit for branch '{branch_name}': {e}"
554            ))
555        })?;
556
557        Ok(commit.id().to_string())
558    }
559
560    /// List all local branches
561    pub fn list_branches(&self) -> Result<Vec<String>> {
562        let branches = self
563            .repo
564            .branches(Some(git2::BranchType::Local))
565            .map_err(CascadeError::Git)?;
566
567        let mut branch_names = Vec::new();
568        for branch in branches {
569            let (branch, _) = branch.map_err(CascadeError::Git)?;
570            if let Some(name) = branch.name().map_err(CascadeError::Git)? {
571                branch_names.push(name.to_string());
572            }
573        }
574
575        Ok(branch_names)
576    }
577
578    /// Get the upstream branch for a local branch
579    pub fn get_upstream_branch(&self, branch_name: &str) -> Result<Option<String>> {
580        // Try to get the upstream from git config
581        let config = self.repo.config().map_err(CascadeError::Git)?;
582
583        // Check for branch.{branch_name}.remote and branch.{branch_name}.merge
584        let remote_key = format!("branch.{branch_name}.remote");
585        let merge_key = format!("branch.{branch_name}.merge");
586
587        if let (Ok(remote), Ok(merge_ref)) = (
588            config.get_string(&remote_key),
589            config.get_string(&merge_key),
590        ) {
591            // Parse the merge ref (e.g., "refs/heads/feature-auth" -> "feature-auth")
592            if let Some(branch_part) = merge_ref.strip_prefix("refs/heads/") {
593                return Ok(Some(format!("{remote}/{branch_part}")));
594            }
595        }
596
597        // Fallback: check if there's a remote tracking branch with the same name
598        let potential_upstream = format!("origin/{branch_name}");
599        if self
600            .repo
601            .find_reference(&format!("refs/remotes/{potential_upstream}"))
602            .is_ok()
603        {
604            return Ok(Some(potential_upstream));
605        }
606
607        Ok(None)
608    }
609
610    /// Get ahead/behind counts compared to upstream
611    pub fn get_ahead_behind_counts(
612        &self,
613        local_branch: &str,
614        upstream_branch: &str,
615    ) -> Result<(usize, usize)> {
616        // Get the commit objects for both branches
617        let local_ref = self
618            .repo
619            .find_reference(&format!("refs/heads/{local_branch}"))
620            .map_err(|_| {
621                CascadeError::config(format!("Local branch '{local_branch}' not found"))
622            })?;
623        let local_commit = local_ref.peel_to_commit().map_err(CascadeError::Git)?;
624
625        let upstream_ref = self
626            .repo
627            .find_reference(&format!("refs/remotes/{upstream_branch}"))
628            .map_err(|_| {
629                CascadeError::config(format!("Upstream branch '{upstream_branch}' not found"))
630            })?;
631        let upstream_commit = upstream_ref.peel_to_commit().map_err(CascadeError::Git)?;
632
633        // Use git2's graph_ahead_behind to calculate the counts
634        let (ahead, behind) = self
635            .repo
636            .graph_ahead_behind(local_commit.id(), upstream_commit.id())
637            .map_err(CascadeError::Git)?;
638
639        Ok((ahead, behind))
640    }
641
642    /// Set upstream tracking for a branch
643    pub fn set_upstream(&self, branch_name: &str, remote: &str, remote_branch: &str) -> Result<()> {
644        let mut config = self.repo.config().map_err(CascadeError::Git)?;
645
646        // Set branch.{branch_name}.remote = remote
647        let remote_key = format!("branch.{branch_name}.remote");
648        config
649            .set_str(&remote_key, remote)
650            .map_err(CascadeError::Git)?;
651
652        // Set branch.{branch_name}.merge = refs/heads/{remote_branch}
653        let merge_key = format!("branch.{branch_name}.merge");
654        let merge_value = format!("refs/heads/{remote_branch}");
655        config
656            .set_str(&merge_key, &merge_value)
657            .map_err(CascadeError::Git)?;
658
659        Ok(())
660    }
661
662    /// Create a commit with all staged changes
663    pub fn commit(&self, message: &str) -> Result<String> {
664        // Validate git user configuration before attempting commit operations
665        self.validate_git_user_config()?;
666
667        let signature = self.get_signature()?;
668        let tree_id = self.get_index_tree()?;
669        let tree = self.repo.find_tree(tree_id).map_err(CascadeError::Git)?;
670
671        // Get parent commits
672        let head = self.repo.head().map_err(CascadeError::Git)?;
673        let parent_commit = head.peel_to_commit().map_err(CascadeError::Git)?;
674
675        let commit_id = self
676            .repo
677            .commit(
678                Some("HEAD"),
679                &signature,
680                &signature,
681                message,
682                &tree,
683                &[&parent_commit],
684            )
685            .map_err(CascadeError::Git)?;
686
687        Output::success(format!("Created commit: {commit_id} - {message}"));
688        Ok(commit_id.to_string())
689    }
690
691    /// Commit any staged changes with a default message
692    pub fn commit_staged_changes(&self, default_message: &str) -> Result<Option<String>> {
693        // Check if there are staged changes
694        let staged_files = self.get_staged_files()?;
695        if staged_files.is_empty() {
696            tracing::debug!("No staged changes to commit");
697            return Ok(None);
698        }
699
700        tracing::info!("Committing {} staged files", staged_files.len());
701        let commit_hash = self.commit(default_message)?;
702        Ok(Some(commit_hash))
703    }
704
705    /// Stage all changes
706    pub fn stage_all(&self) -> Result<()> {
707        let mut index = self.repo.index().map_err(CascadeError::Git)?;
708
709        index
710            .add_all(["*"].iter(), git2::IndexAddOption::DEFAULT, None)
711            .map_err(CascadeError::Git)?;
712
713        index.write().map_err(CascadeError::Git)?;
714
715        tracing::debug!("Staged all changes");
716        Ok(())
717    }
718
719    /// Stage only specific files (safer than stage_all during rebase)
720    pub fn stage_files(&self, file_paths: &[&str]) -> Result<()> {
721        if file_paths.is_empty() {
722            tracing::debug!("No files to stage");
723            return Ok(());
724        }
725
726        let mut index = self.repo.index().map_err(CascadeError::Git)?;
727
728        for file_path in file_paths {
729            index
730                .add_path(std::path::Path::new(file_path))
731                .map_err(CascadeError::Git)?;
732        }
733
734        index.write().map_err(CascadeError::Git)?;
735
736        tracing::debug!(
737            "Staged {} specific files: {:?}",
738            file_paths.len(),
739            file_paths
740        );
741        Ok(())
742    }
743
744    /// Stage only files that had conflicts (safer for rebase operations)
745    pub fn stage_conflict_resolved_files(&self) -> Result<()> {
746        let conflicted_files = self.get_conflicted_files()?;
747        if conflicted_files.is_empty() {
748            tracing::debug!("No conflicted files to stage");
749            return Ok(());
750        }
751
752        let file_paths: Vec<&str> = conflicted_files.iter().map(|s| s.as_str()).collect();
753        self.stage_files(&file_paths)?;
754
755        tracing::debug!("Staged {} conflict-resolved files", conflicted_files.len());
756        Ok(())
757    }
758
759    /// Get repository path
760    pub fn path(&self) -> &Path {
761        &self.path
762    }
763
764    /// Check if a commit exists
765    pub fn commit_exists(&self, commit_hash: &str) -> Result<bool> {
766        match Oid::from_str(commit_hash) {
767            Ok(oid) => match self.repo.find_commit(oid) {
768                Ok(_) => Ok(true),
769                Err(_) => Ok(false),
770            },
771            Err(_) => Ok(false),
772        }
773    }
774
775    /// Get the HEAD commit object
776    pub fn get_head_commit(&self) -> Result<git2::Commit<'_>> {
777        let head = self
778            .repo
779            .head()
780            .map_err(|e| CascadeError::branch(format!("Could not get HEAD: {e}")))?;
781        head.peel_to_commit()
782            .map_err(|e| CascadeError::branch(format!("Could not get HEAD commit: {e}")))
783    }
784
785    /// Get a commit object by hash
786    pub fn get_commit(&self, commit_hash: &str) -> Result<git2::Commit<'_>> {
787        let oid = Oid::from_str(commit_hash).map_err(CascadeError::Git)?;
788
789        self.repo.find_commit(oid).map_err(CascadeError::Git)
790    }
791
792    /// Get the commit hash at the head of a branch
793    pub fn get_branch_head(&self, branch_name: &str) -> Result<String> {
794        let branch = self
795            .repo
796            .find_branch(branch_name, git2::BranchType::Local)
797            .map_err(|e| {
798                CascadeError::branch(format!("Could not find branch '{branch_name}': {e}"))
799            })?;
800
801        let commit = branch.get().peel_to_commit().map_err(|e| {
802            CascadeError::branch(format!(
803                "Could not get commit for branch '{branch_name}': {e}"
804            ))
805        })?;
806
807        Ok(commit.id().to_string())
808    }
809
810    /// Validate git user configuration is properly set
811    pub fn validate_git_user_config(&self) -> Result<()> {
812        if let Ok(config) = self.repo.config() {
813            let name_result = config.get_string("user.name");
814            let email_result = config.get_string("user.email");
815
816            if let (Ok(name), Ok(email)) = (name_result, email_result) {
817                if !name.trim().is_empty() && !email.trim().is_empty() {
818                    tracing::debug!("Git user config validated: {} <{}>", name, email);
819                    return Ok(());
820                }
821            }
822        }
823
824        // Check if this is a CI environment where validation can be skipped
825        let is_ci = std::env::var("CI").is_ok();
826
827        if is_ci {
828            tracing::debug!("CI environment - skipping git user config validation");
829            return Ok(());
830        }
831
832        Output::warning("Git user configuration missing or incomplete");
833        Output::info("This can cause cherry-pick and commit operations to fail");
834        Output::info("Please configure git user information:");
835        Output::bullet("git config user.name \"Your Name\"".to_string());
836        Output::bullet("git config user.email \"your.email@example.com\"".to_string());
837        Output::info("Or set globally with the --global flag");
838
839        // Don't fail - let operations continue with fallback signature
840        // This preserves backward compatibility while providing guidance
841        Ok(())
842    }
843
844    /// Get a signature for commits with comprehensive fallback and validation
845    fn get_signature(&self) -> Result<Signature<'_>> {
846        // Try to get signature from Git config first
847        if let Ok(config) = self.repo.config() {
848            // Try global/system config first
849            let name_result = config.get_string("user.name");
850            let email_result = config.get_string("user.email");
851
852            if let (Ok(name), Ok(email)) = (name_result, email_result) {
853                if !name.trim().is_empty() && !email.trim().is_empty() {
854                    tracing::debug!("Using git config: {} <{}>", name, email);
855                    return Signature::now(&name, &email).map_err(CascadeError::Git);
856                }
857            } else {
858                tracing::debug!("Git user config incomplete or missing");
859            }
860        }
861
862        // Check if this is a CI environment where fallback is acceptable
863        let is_ci = std::env::var("CI").is_ok();
864
865        if is_ci {
866            tracing::debug!("CI environment detected, using fallback signature");
867            return Signature::now("Cascade CLI", "cascade@example.com").map_err(CascadeError::Git);
868        }
869
870        // Interactive environment - provide helpful guidance
871        tracing::warn!("Git user configuration missing - this can cause commit operations to fail");
872
873        // Try fallback signature, but warn about the issue
874        match Signature::now("Cascade CLI", "cascade@example.com") {
875            Ok(sig) => {
876                Output::warning("Git user not configured - using fallback signature");
877                Output::info("For better git history, run:");
878                Output::bullet("git config user.name \"Your Name\"".to_string());
879                Output::bullet("git config user.email \"your.email@example.com\"".to_string());
880                Output::info("Or set it globally with --global flag");
881                Ok(sig)
882            }
883            Err(e) => {
884                Err(CascadeError::branch(format!(
885                    "Cannot create git signature: {e}. Please configure git user with:\n  git config user.name \"Your Name\"\n  git config user.email \"your.email@example.com\""
886                )))
887            }
888        }
889    }
890
891    /// Configure remote callbacks with SSL settings
892    /// Priority: Cascade SSL config > Git config > Default
893    fn configure_remote_callbacks(&self) -> Result<git2::RemoteCallbacks<'_>> {
894        self.configure_remote_callbacks_with_fallback(false)
895    }
896
897    /// Determine if we should retry with DefaultCredentials based on git2 error classification
898    fn should_retry_with_default_credentials(&self, error: &git2::Error) -> bool {
899        match error.class() {
900            // Authentication errors that might be resolved with DefaultCredentials
901            git2::ErrorClass::Http => {
902                // HTTP errors often indicate authentication issues in corporate environments
903                match error.code() {
904                    git2::ErrorCode::Auth => true,
905                    _ => {
906                        // Check for specific HTTP authentication replay errors
907                        let error_string = error.to_string();
908                        error_string.contains("too many redirects")
909                            || error_string.contains("authentication replays")
910                            || error_string.contains("authentication required")
911                    }
912                }
913            }
914            git2::ErrorClass::Net => {
915                // Network errors that might be authentication-related
916                let error_string = error.to_string();
917                error_string.contains("authentication")
918                    || error_string.contains("unauthorized")
919                    || error_string.contains("forbidden")
920            }
921            _ => false,
922        }
923    }
924
925    /// Determine if we should fallback to git CLI based on git2 error classification
926    fn should_fallback_to_git_cli(&self, error: &git2::Error) -> bool {
927        match error.class() {
928            // SSL/TLS errors that git CLI handles better
929            git2::ErrorClass::Ssl => true,
930
931            // Certificate errors
932            git2::ErrorClass::Http if error.code() == git2::ErrorCode::Certificate => true,
933
934            // SSH errors that might need git CLI
935            git2::ErrorClass::Ssh => {
936                let error_string = error.to_string();
937                error_string.contains("no callback set")
938                    || error_string.contains("authentication required")
939            }
940
941            // Network errors that might be proxy/firewall related
942            git2::ErrorClass::Net => {
943                let error_string = error.to_string();
944                error_string.contains("TLS stream")
945                    || error_string.contains("SSL")
946                    || error_string.contains("proxy")
947                    || error_string.contains("firewall")
948            }
949
950            // General HTTP errors not handled by DefaultCredentials retry
951            git2::ErrorClass::Http => {
952                let error_string = error.to_string();
953                error_string.contains("TLS stream")
954                    || error_string.contains("SSL")
955                    || error_string.contains("proxy")
956            }
957
958            _ => false,
959        }
960    }
961
962    fn configure_remote_callbacks_with_fallback(
963        &self,
964        use_default_first: bool,
965    ) -> Result<git2::RemoteCallbacks<'_>> {
966        let mut callbacks = git2::RemoteCallbacks::new();
967
968        // Configure authentication with comprehensive credential support
969        let bitbucket_credentials = self.bitbucket_credentials.clone();
970        callbacks.credentials(move |url, username_from_url, allowed_types| {
971            tracing::debug!(
972                "Authentication requested for URL: {}, username: {:?}, allowed_types: {:?}",
973                url,
974                username_from_url,
975                allowed_types
976            );
977
978            // For SSH URLs with username
979            if allowed_types.contains(git2::CredentialType::SSH_KEY) {
980                if let Some(username) = username_from_url {
981                    tracing::debug!("Trying SSH key authentication for user: {}", username);
982                    return git2::Cred::ssh_key_from_agent(username);
983                }
984            }
985
986            // For HTTPS URLs, try multiple authentication methods in sequence
987            if allowed_types.contains(git2::CredentialType::USER_PASS_PLAINTEXT) {
988                // If we're in corporate network fallback mode, try DefaultCredentials first
989                if use_default_first {
990                    tracing::debug!("Corporate network mode: trying DefaultCredentials first");
991                    return git2::Cred::default();
992                }
993
994                if url.contains("bitbucket") {
995                    if let Some(creds) = &bitbucket_credentials {
996                        // Method 1: Username + Token (common for Bitbucket)
997                        if let (Some(username), Some(token)) = (&creds.username, &creds.token) {
998                            tracing::debug!("Trying Bitbucket username + token authentication");
999                            return git2::Cred::userpass_plaintext(username, token);
1000                        }
1001
1002                        // Method 2: Token as username, empty password (alternate Bitbucket format)
1003                        if let Some(token) = &creds.token {
1004                            tracing::debug!("Trying Bitbucket token-as-username authentication");
1005                            return git2::Cred::userpass_plaintext(token, "");
1006                        }
1007
1008                        // Method 3: Just username (will prompt for password or use credential helper)
1009                        if let Some(username) = &creds.username {
1010                            tracing::debug!("Trying Bitbucket username authentication (will use credential helper)");
1011                            return git2::Cred::username(username);
1012                        }
1013                    }
1014                }
1015
1016                // Method 4: Default credential helper for all HTTPS URLs
1017                tracing::debug!("Trying default credential helper for HTTPS authentication");
1018                return git2::Cred::default();
1019            }
1020
1021            // Fallback to default for any other cases
1022            tracing::debug!("Using default credential fallback");
1023            git2::Cred::default()
1024        });
1025
1026        // Configure SSL certificate checking with system certificates by default
1027        // This matches what tools like Graphite, Sapling, and Phabricator do
1028        // Priority: 1. Use system certificates (default), 2. Manual overrides only if needed
1029
1030        let mut ssl_configured = false;
1031
1032        // Check for manual SSL overrides first (only when user explicitly needs them)
1033        if let Some(ssl_config) = &self.ssl_config {
1034            if ssl_config.accept_invalid_certs {
1035                Output::warning(
1036                    "SSL certificate verification DISABLED via Cascade config - this is insecure!",
1037                );
1038                callbacks.certificate_check(|_cert, _host| {
1039                    tracing::debug!("⚠️  Accepting invalid certificate for host: {}", _host);
1040                    Ok(git2::CertificateCheckStatus::CertificateOk)
1041                });
1042                ssl_configured = true;
1043            } else if let Some(ca_path) = &ssl_config.ca_bundle_path {
1044                Output::info(format!(
1045                    "Using custom CA bundle from Cascade config: {ca_path}"
1046                ));
1047                callbacks.certificate_check(|_cert, host| {
1048                    tracing::debug!("Using custom CA bundle for host: {}", host);
1049                    Ok(git2::CertificateCheckStatus::CertificateOk)
1050                });
1051                ssl_configured = true;
1052            }
1053        }
1054
1055        // Check git config for manual overrides
1056        if !ssl_configured {
1057            if let Ok(config) = self.repo.config() {
1058                let ssl_verify = config.get_bool("http.sslVerify").unwrap_or(true);
1059
1060                if !ssl_verify {
1061                    Output::warning(
1062                        "SSL certificate verification DISABLED via git config - this is insecure!",
1063                    );
1064                    callbacks.certificate_check(|_cert, host| {
1065                        tracing::debug!("⚠️  Bypassing SSL verification for host: {}", host);
1066                        Ok(git2::CertificateCheckStatus::CertificateOk)
1067                    });
1068                    ssl_configured = true;
1069                } else if let Ok(ca_path) = config.get_string("http.sslCAInfo") {
1070                    Output::info(format!("Using custom CA bundle from git config: {ca_path}"));
1071                    callbacks.certificate_check(|_cert, host| {
1072                        tracing::debug!("Using git config CA bundle for host: {}", host);
1073                        Ok(git2::CertificateCheckStatus::CertificateOk)
1074                    });
1075                    ssl_configured = true;
1076                }
1077            }
1078        }
1079
1080        // DEFAULT BEHAVIOR: Use system certificates (like git CLI and other modern tools)
1081        // This should work out-of-the-box in corporate environments
1082        if !ssl_configured {
1083            tracing::debug!(
1084                "Using system certificate store for SSL verification (default behavior)"
1085            );
1086
1087            // For macOS with SecureTransport backend, try default certificate validation first
1088            if cfg!(target_os = "macos") {
1089                tracing::debug!("macOS detected - using default certificate validation");
1090                // Don't set any certificate callback - let git2 use its default behavior
1091                // This often works better with SecureTransport backend on macOS
1092            } else {
1093                // Use CertificatePassthrough for other platforms
1094                callbacks.certificate_check(|_cert, host| {
1095                    tracing::debug!("System certificate validation for host: {}", host);
1096                    Ok(git2::CertificateCheckStatus::CertificatePassthrough)
1097                });
1098            }
1099        }
1100
1101        Ok(callbacks)
1102    }
1103
1104    /// Get the tree ID from the current index
1105    fn get_index_tree(&self) -> Result<Oid> {
1106        let mut index = self.repo.index().map_err(CascadeError::Git)?;
1107
1108        index.write_tree().map_err(CascadeError::Git)
1109    }
1110
1111    /// Get repository status
1112    pub fn get_status(&self) -> Result<git2::Statuses<'_>> {
1113        self.repo.statuses(None).map_err(CascadeError::Git)
1114    }
1115
1116    /// Get a summary of repository status
1117    pub fn get_status_summary(&self) -> Result<GitStatusSummary> {
1118        let statuses = self.get_status()?;
1119
1120        let mut staged_files = 0;
1121        let mut unstaged_files = 0;
1122        let mut untracked_files = 0;
1123
1124        for status in statuses.iter() {
1125            let flags = status.status();
1126
1127            if flags.intersects(
1128                git2::Status::INDEX_MODIFIED
1129                    | git2::Status::INDEX_NEW
1130                    | git2::Status::INDEX_DELETED
1131                    | git2::Status::INDEX_RENAMED
1132                    | git2::Status::INDEX_TYPECHANGE,
1133            ) {
1134                staged_files += 1;
1135            }
1136
1137            if flags.intersects(
1138                git2::Status::WT_MODIFIED
1139                    | git2::Status::WT_DELETED
1140                    | git2::Status::WT_TYPECHANGE
1141                    | git2::Status::WT_RENAMED,
1142            ) {
1143                unstaged_files += 1;
1144            }
1145
1146            if flags.intersects(git2::Status::WT_NEW) {
1147                untracked_files += 1;
1148            }
1149        }
1150
1151        Ok(GitStatusSummary {
1152            staged_files,
1153            unstaged_files,
1154            untracked_files,
1155        })
1156    }
1157
1158    /// Get the current commit hash (alias for get_head_commit_hash)
1159    pub fn get_current_commit_hash(&self) -> Result<String> {
1160        self.get_head_commit_hash()
1161    }
1162
1163    /// Get the count of commits between two commits
1164    pub fn get_commit_count_between(&self, from_commit: &str, to_commit: &str) -> Result<usize> {
1165        let from_oid = git2::Oid::from_str(from_commit).map_err(CascadeError::Git)?;
1166        let to_oid = git2::Oid::from_str(to_commit).map_err(CascadeError::Git)?;
1167
1168        let mut revwalk = self.repo.revwalk().map_err(CascadeError::Git)?;
1169        revwalk.push(to_oid).map_err(CascadeError::Git)?;
1170        revwalk.hide(from_oid).map_err(CascadeError::Git)?;
1171
1172        Ok(revwalk.count())
1173    }
1174
1175    /// Get remote URL for a given remote name
1176    pub fn get_remote_url(&self, name: &str) -> Result<String> {
1177        let remote = self.repo.find_remote(name).map_err(CascadeError::Git)?;
1178        Ok(remote.url().unwrap_or("unknown").to_string())
1179    }
1180
1181    /// Cherry-pick a specific commit to the current branch
1182    pub fn cherry_pick(&self, commit_hash: &str) -> Result<String> {
1183        tracing::debug!("Cherry-picking commit {}", commit_hash);
1184
1185        // Validate git user configuration before attempting commit operations
1186        self.validate_git_user_config()?;
1187
1188        let oid = Oid::from_str(commit_hash).map_err(CascadeError::Git)?;
1189        let commit = self.repo.find_commit(oid).map_err(CascadeError::Git)?;
1190
1191        // Get the commit's tree
1192        let commit_tree = commit.tree().map_err(CascadeError::Git)?;
1193
1194        // Get parent tree for merge base
1195        let parent_commit = if commit.parent_count() > 0 {
1196            commit.parent(0).map_err(CascadeError::Git)?
1197        } else {
1198            // Root commit - use empty tree
1199            let empty_tree_oid = self.repo.treebuilder(None)?.write()?;
1200            let empty_tree = self.repo.find_tree(empty_tree_oid)?;
1201            let sig = self.get_signature()?;
1202            return self
1203                .repo
1204                .commit(
1205                    Some("HEAD"),
1206                    &sig,
1207                    &sig,
1208                    commit.message().unwrap_or("Cherry-picked commit"),
1209                    &empty_tree,
1210                    &[],
1211                )
1212                .map(|oid| oid.to_string())
1213                .map_err(CascadeError::Git);
1214        };
1215
1216        let parent_tree = parent_commit.tree().map_err(CascadeError::Git)?;
1217
1218        // Get current HEAD tree for 3-way merge
1219        let head_commit = self.get_head_commit()?;
1220        let head_tree = head_commit.tree().map_err(CascadeError::Git)?;
1221
1222        // Perform 3-way merge
1223        let mut index = self
1224            .repo
1225            .merge_trees(&parent_tree, &head_tree, &commit_tree, None)
1226            .map_err(CascadeError::Git)?;
1227
1228        // Check for conflicts
1229        if index.has_conflicts() {
1230            return Err(CascadeError::branch(format!(
1231                "Cherry-pick of {commit_hash} has conflicts that need manual resolution"
1232            )));
1233        }
1234
1235        // Write merged tree
1236        let merged_tree_oid = index.write_tree_to(&self.repo).map_err(CascadeError::Git)?;
1237        let merged_tree = self
1238            .repo
1239            .find_tree(merged_tree_oid)
1240            .map_err(CascadeError::Git)?;
1241
1242        // Create new commit
1243        let signature = self.get_signature()?;
1244        let message = format!("Cherry-pick: {}", commit.message().unwrap_or(""));
1245
1246        let new_commit_oid = self
1247            .repo
1248            .commit(
1249                Some("HEAD"),
1250                &signature,
1251                &signature,
1252                &message,
1253                &merged_tree,
1254                &[&head_commit],
1255            )
1256            .map_err(CascadeError::Git)?;
1257
1258        // Update working directory to reflect the new commit
1259        let new_commit = self
1260            .repo
1261            .find_commit(new_commit_oid)
1262            .map_err(CascadeError::Git)?;
1263        let new_tree = new_commit.tree().map_err(CascadeError::Git)?;
1264
1265        self.repo
1266            .checkout_tree(
1267                new_tree.as_object(),
1268                Some(git2::build::CheckoutBuilder::new().force()),
1269            )
1270            .map_err(CascadeError::Git)?;
1271
1272        tracing::info!("Cherry-picked {} -> {}", commit_hash, new_commit_oid);
1273        Ok(new_commit_oid.to_string())
1274    }
1275
1276    /// Check for merge conflicts in the index
1277    pub fn has_conflicts(&self) -> Result<bool> {
1278        let index = self.repo.index().map_err(CascadeError::Git)?;
1279        Ok(index.has_conflicts())
1280    }
1281
1282    /// Get list of conflicted files
1283    pub fn get_conflicted_files(&self) -> Result<Vec<String>> {
1284        let index = self.repo.index().map_err(CascadeError::Git)?;
1285
1286        let mut conflicts = Vec::new();
1287
1288        // Iterate through index conflicts
1289        let conflict_iter = index.conflicts().map_err(CascadeError::Git)?;
1290
1291        for conflict in conflict_iter {
1292            let conflict = conflict.map_err(CascadeError::Git)?;
1293            if let Some(our) = conflict.our {
1294                if let Ok(path) = std::str::from_utf8(&our.path) {
1295                    conflicts.push(path.to_string());
1296                }
1297            } else if let Some(their) = conflict.their {
1298                if let Ok(path) = std::str::from_utf8(&their.path) {
1299                    conflicts.push(path.to_string());
1300                }
1301            }
1302        }
1303
1304        Ok(conflicts)
1305    }
1306
1307    /// Fetch from remote origin
1308    pub fn fetch(&self) -> Result<()> {
1309        tracing::debug!("Fetching from origin");
1310
1311        let mut remote = self
1312            .repo
1313            .find_remote("origin")
1314            .map_err(|e| CascadeError::branch(format!("No remote 'origin' found: {e}")))?;
1315
1316        // Configure callbacks with SSL settings from git config
1317        let callbacks = self.configure_remote_callbacks()?;
1318
1319        // Fetch options with authentication and SSL config
1320        let mut fetch_options = git2::FetchOptions::new();
1321        fetch_options.remote_callbacks(callbacks);
1322
1323        // Fetch with authentication
1324        match remote.fetch::<&str>(&[], Some(&mut fetch_options), None) {
1325            Ok(_) => {
1326                tracing::debug!("Fetch completed successfully");
1327                Ok(())
1328            }
1329            Err(e) => {
1330                if self.should_retry_with_default_credentials(&e) {
1331                    tracing::debug!(
1332                        "Authentication error detected (class: {:?}, code: {:?}): {}, retrying with DefaultCredentials",
1333                        e.class(), e.code(), e
1334                    );
1335
1336                    // Retry with DefaultCredentials for corporate networks
1337                    let callbacks = self.configure_remote_callbacks_with_fallback(true)?;
1338                    let mut fetch_options = git2::FetchOptions::new();
1339                    fetch_options.remote_callbacks(callbacks);
1340
1341                    match remote.fetch::<&str>(&[], Some(&mut fetch_options), None) {
1342                        Ok(_) => {
1343                            tracing::debug!("Fetch succeeded with DefaultCredentials");
1344                            return Ok(());
1345                        }
1346                        Err(retry_error) => {
1347                            tracing::debug!(
1348                                "DefaultCredentials retry failed: {}, falling back to git CLI",
1349                                retry_error
1350                            );
1351                            return self.fetch_with_git_cli();
1352                        }
1353                    }
1354                }
1355
1356                if self.should_fallback_to_git_cli(&e) {
1357                    tracing::debug!(
1358                        "Network/SSL error detected (class: {:?}, code: {:?}): {}, falling back to git CLI for fetch operation",
1359                        e.class(), e.code(), e
1360                    );
1361                    return self.fetch_with_git_cli();
1362                }
1363                Err(CascadeError::Git(e))
1364            }
1365        }
1366    }
1367
1368    /// Pull changes from remote (fetch + merge)
1369    pub fn pull(&self, branch: &str) -> Result<()> {
1370        tracing::debug!("Pulling branch: {}", branch);
1371
1372        // First fetch - this now includes TLS fallback
1373        match self.fetch() {
1374            Ok(_) => {}
1375            Err(e) => {
1376                // If fetch failed even with CLI fallback, try full git pull as last resort
1377                let error_string = e.to_string();
1378                if error_string.contains("TLS stream") || error_string.contains("SSL") {
1379                    tracing::warn!(
1380                        "git2 error detected: {}, falling back to git CLI for pull operation",
1381                        e
1382                    );
1383                    return self.pull_with_git_cli(branch);
1384                }
1385                return Err(e);
1386            }
1387        }
1388
1389        // Get remote tracking branch
1390        let remote_branch_name = format!("origin/{branch}");
1391        let remote_oid = self
1392            .repo
1393            .refname_to_id(&format!("refs/remotes/{remote_branch_name}"))
1394            .map_err(|e| {
1395                CascadeError::branch(format!("Remote branch {remote_branch_name} not found: {e}"))
1396            })?;
1397
1398        let remote_commit = self
1399            .repo
1400            .find_commit(remote_oid)
1401            .map_err(CascadeError::Git)?;
1402
1403        // Get current HEAD
1404        let head_commit = self.get_head_commit()?;
1405
1406        // Check if already up to date
1407        if head_commit.id() == remote_commit.id() {
1408            tracing::debug!("Already up to date");
1409            return Ok(());
1410        }
1411
1412        // Check if we can fast-forward (local is ancestor of remote)
1413        let merge_base_oid = self
1414            .repo
1415            .merge_base(head_commit.id(), remote_commit.id())
1416            .map_err(CascadeError::Git)?;
1417
1418        if merge_base_oid == head_commit.id() {
1419            // Fast-forward: local is direct ancestor of remote, just move pointer
1420            tracing::debug!("Fast-forwarding {} to {}", branch, remote_commit.id());
1421
1422            // Update the branch reference to point to remote commit
1423            let refname = format!("refs/heads/{}", branch);
1424            self.repo
1425                .reference(&refname, remote_oid, true, "pull: Fast-forward")
1426                .map_err(CascadeError::Git)?;
1427
1428            // Update HEAD to point to the new commit
1429            self.repo.set_head(&refname).map_err(CascadeError::Git)?;
1430
1431            // Checkout the new commit (update working directory)
1432            self.repo
1433                .checkout_head(Some(
1434                    git2::build::CheckoutBuilder::new()
1435                        .force()
1436                        .remove_untracked(false),
1437                ))
1438                .map_err(CascadeError::Git)?;
1439
1440            tracing::debug!("Fast-forwarded to {}", remote_commit.id());
1441            return Ok(());
1442        }
1443
1444        // If we can't fast-forward, the local branch has diverged
1445        // This should NOT happen on protected branches!
1446        Err(CascadeError::branch(format!(
1447            "Branch '{}' has diverged from remote. Local has commits not in remote. \
1448             Protected branches should not have local commits. \
1449             Try: git reset --hard origin/{}",
1450            branch, branch
1451        )))
1452    }
1453
1454    /// Push current branch to remote
1455    pub fn push(&self, branch: &str) -> Result<()> {
1456        // Pushing branch to remote
1457
1458        let mut remote = self
1459            .repo
1460            .find_remote("origin")
1461            .map_err(|e| CascadeError::branch(format!("No remote 'origin' found: {e}")))?;
1462
1463        let remote_url = remote.url().unwrap_or("unknown").to_string();
1464        tracing::debug!("Remote URL: {}", remote_url);
1465
1466        let refspec = format!("refs/heads/{branch}:refs/heads/{branch}");
1467        tracing::debug!("Push refspec: {}", refspec);
1468
1469        // Configure callbacks with enhanced SSL settings and error handling
1470        let mut callbacks = self.configure_remote_callbacks()?;
1471
1472        // Add enhanced progress and error callbacks for better debugging
1473        callbacks.push_update_reference(|refname, status| {
1474            if let Some(msg) = status {
1475                tracing::error!("Push failed for ref {}: {}", refname, msg);
1476                return Err(git2::Error::from_str(&format!("Push failed: {msg}")));
1477            }
1478            tracing::debug!("Push succeeded for ref: {}", refname);
1479            Ok(())
1480        });
1481
1482        // Push options with authentication and SSL config
1483        let mut push_options = git2::PushOptions::new();
1484        push_options.remote_callbacks(callbacks);
1485
1486        // Attempt push with enhanced error reporting
1487        match remote.push(&[&refspec], Some(&mut push_options)) {
1488            Ok(_) => {
1489                tracing::info!("Push completed successfully for branch: {}", branch);
1490                Ok(())
1491            }
1492            Err(e) => {
1493                tracing::debug!(
1494                    "git2 push error: {} (class: {:?}, code: {:?})",
1495                    e,
1496                    e.class(),
1497                    e.code()
1498                );
1499
1500                if self.should_retry_with_default_credentials(&e) {
1501                    tracing::debug!(
1502                        "Authentication error detected (class: {:?}, code: {:?}): {}, retrying with DefaultCredentials",
1503                        e.class(), e.code(), e
1504                    );
1505
1506                    // Retry with DefaultCredentials for corporate networks
1507                    let callbacks = self.configure_remote_callbacks_with_fallback(true)?;
1508                    let mut push_options = git2::PushOptions::new();
1509                    push_options.remote_callbacks(callbacks);
1510
1511                    match remote.push(&[&refspec], Some(&mut push_options)) {
1512                        Ok(_) => {
1513                            tracing::debug!("Push succeeded with DefaultCredentials");
1514                            return Ok(());
1515                        }
1516                        Err(retry_error) => {
1517                            tracing::debug!(
1518                                "DefaultCredentials retry failed: {}, falling back to git CLI",
1519                                retry_error
1520                            );
1521                            return self.push_with_git_cli(branch);
1522                        }
1523                    }
1524                }
1525
1526                if self.should_fallback_to_git_cli(&e) {
1527                    tracing::debug!(
1528                        "Network/SSL error detected (class: {:?}, code: {:?}): {}, falling back to git CLI for push operation",
1529                        e.class(), e.code(), e
1530                    );
1531                    return self.push_with_git_cli(branch);
1532                }
1533
1534                // Create concise error message
1535                let error_msg = if e.to_string().contains("authentication") {
1536                    format!(
1537                        "Authentication failed for branch '{branch}'. Try: git push origin {branch}"
1538                    )
1539                } else {
1540                    format!("Failed to push branch '{branch}': {e}")
1541                };
1542
1543                tracing::error!("{}", error_msg);
1544                Err(CascadeError::branch(error_msg))
1545            }
1546        }
1547    }
1548
1549    /// Fallback push method using git CLI instead of git2
1550    /// This is used when git2 has TLS/SSL or auth issues but git CLI works fine
1551    fn push_with_git_cli(&self, branch: &str) -> Result<()> {
1552        let output = std::process::Command::new("git")
1553            .args(["push", "origin", branch])
1554            .current_dir(&self.path)
1555            .output()
1556            .map_err(|e| CascadeError::branch(format!("Failed to execute git command: {e}")))?;
1557
1558        if output.status.success() {
1559            // Silent success - no need to log when fallback works
1560            Ok(())
1561        } else {
1562            let stderr = String::from_utf8_lossy(&output.stderr);
1563            let _stdout = String::from_utf8_lossy(&output.stdout);
1564            // Extract the most relevant error message
1565            let error_msg = if stderr.contains("SSL_connect") || stderr.contains("SSL_ERROR") {
1566                "Network error: Unable to connect to repository (VPN may be required)".to_string()
1567            } else if stderr.contains("repository") && stderr.contains("not found") {
1568                "Repository not found - check your Bitbucket configuration".to_string()
1569            } else if stderr.contains("authentication") || stderr.contains("403") {
1570                "Authentication failed - check your credentials".to_string()
1571            } else {
1572                // For other errors, just show the stderr without the verbose prefix
1573                stderr.trim().to_string()
1574            };
1575            tracing::error!("{}", error_msg);
1576            Err(CascadeError::branch(error_msg))
1577        }
1578    }
1579
1580    /// Fallback fetch method using git CLI instead of git2
1581    /// This is used when git2 has TLS/SSL issues but git CLI works fine
1582    fn fetch_with_git_cli(&self) -> Result<()> {
1583        tracing::debug!("Using git CLI fallback for fetch operation");
1584
1585        let output = std::process::Command::new("git")
1586            .args(["fetch", "origin"])
1587            .current_dir(&self.path)
1588            .output()
1589            .map_err(|e| {
1590                CascadeError::Git(git2::Error::from_str(&format!(
1591                    "Failed to execute git command: {e}"
1592                )))
1593            })?;
1594
1595        if output.status.success() {
1596            tracing::debug!("Git CLI fetch succeeded");
1597            Ok(())
1598        } else {
1599            let stderr = String::from_utf8_lossy(&output.stderr);
1600            let stdout = String::from_utf8_lossy(&output.stdout);
1601            let error_msg = format!(
1602                "Git CLI fetch failed: {}\nStdout: {}\nStderr: {}",
1603                output.status, stdout, stderr
1604            );
1605            tracing::error!("{}", error_msg);
1606            Err(CascadeError::Git(git2::Error::from_str(&error_msg)))
1607        }
1608    }
1609
1610    /// Fallback pull method using git CLI instead of git2
1611    /// This is used when git2 has TLS/SSL issues but git CLI works fine
1612    fn pull_with_git_cli(&self, branch: &str) -> Result<()> {
1613        tracing::debug!("Using git CLI fallback for pull operation: {}", branch);
1614
1615        let output = std::process::Command::new("git")
1616            .args(["pull", "origin", branch])
1617            .current_dir(&self.path)
1618            .output()
1619            .map_err(|e| {
1620                CascadeError::Git(git2::Error::from_str(&format!(
1621                    "Failed to execute git command: {e}"
1622                )))
1623            })?;
1624
1625        if output.status.success() {
1626            tracing::info!("✅ Git CLI pull succeeded for branch: {}", branch);
1627            Ok(())
1628        } else {
1629            let stderr = String::from_utf8_lossy(&output.stderr);
1630            let stdout = String::from_utf8_lossy(&output.stdout);
1631            let error_msg = format!(
1632                "Git CLI pull failed for branch '{}': {}\nStdout: {}\nStderr: {}",
1633                branch, output.status, stdout, stderr
1634            );
1635            tracing::error!("{}", error_msg);
1636            Err(CascadeError::Git(git2::Error::from_str(&error_msg)))
1637        }
1638    }
1639
1640    /// Fallback force push method using git CLI instead of git2
1641    /// This is used when git2 has TLS/SSL issues but git CLI works fine
1642    fn force_push_with_git_cli(&self, branch: &str) -> Result<()> {
1643        tracing::debug!(
1644            "Using git CLI fallback for force push operation: {}",
1645            branch
1646        );
1647
1648        let output = std::process::Command::new("git")
1649            .args(["push", "--force", "origin", branch])
1650            .current_dir(&self.path)
1651            .output()
1652            .map_err(|e| CascadeError::branch(format!("Failed to execute git command: {e}")))?;
1653
1654        if output.status.success() {
1655            tracing::info!("✅ Git CLI force push succeeded for branch: {}", branch);
1656            Ok(())
1657        } else {
1658            let stderr = String::from_utf8_lossy(&output.stderr);
1659            let stdout = String::from_utf8_lossy(&output.stdout);
1660            let error_msg = format!(
1661                "Git CLI force push failed for branch '{}': {}\nStdout: {}\nStderr: {}",
1662                branch, output.status, stdout, stderr
1663            );
1664            tracing::error!("{}", error_msg);
1665            Err(CascadeError::branch(error_msg))
1666        }
1667    }
1668
1669    /// Delete a local branch
1670    pub fn delete_branch(&self, name: &str) -> Result<()> {
1671        self.delete_branch_with_options(name, false)
1672    }
1673
1674    /// Delete a local branch with force option to bypass safety checks
1675    pub fn delete_branch_unsafe(&self, name: &str) -> Result<()> {
1676        self.delete_branch_with_options(name, true)
1677    }
1678
1679    /// Internal branch deletion implementation with safety options
1680    fn delete_branch_with_options(&self, name: &str, force_unsafe: bool) -> Result<()> {
1681        debug!("Attempting to delete branch: {}", name);
1682
1683        // Enhanced safety check: Detect unpushed commits before deletion
1684        if !force_unsafe {
1685            let safety_result = self.check_branch_deletion_safety(name)?;
1686            if let Some(safety_info) = safety_result {
1687                // Branch has unpushed commits, get user confirmation
1688                self.handle_branch_deletion_confirmation(name, &safety_info)?;
1689            }
1690        }
1691
1692        let mut branch = self
1693            .repo
1694            .find_branch(name, git2::BranchType::Local)
1695            .map_err(|e| CascadeError::branch(format!("Could not find branch '{name}': {e}")))?;
1696
1697        branch
1698            .delete()
1699            .map_err(|e| CascadeError::branch(format!("Could not delete branch '{name}': {e}")))?;
1700
1701        debug!("Successfully deleted branch '{}'", name);
1702        Ok(())
1703    }
1704
1705    /// Get commits between two references
1706    pub fn get_commits_between(&self, from: &str, to: &str) -> Result<Vec<git2::Commit<'_>>> {
1707        let from_oid = self
1708            .repo
1709            .refname_to_id(&format!("refs/heads/{from}"))
1710            .or_else(|_| Oid::from_str(from))
1711            .map_err(|e| CascadeError::branch(format!("Invalid from reference '{from}': {e}")))?;
1712
1713        let to_oid = self
1714            .repo
1715            .refname_to_id(&format!("refs/heads/{to}"))
1716            .or_else(|_| Oid::from_str(to))
1717            .map_err(|e| CascadeError::branch(format!("Invalid to reference '{to}': {e}")))?;
1718
1719        let mut revwalk = self.repo.revwalk().map_err(CascadeError::Git)?;
1720
1721        revwalk.push(to_oid).map_err(CascadeError::Git)?;
1722        revwalk.hide(from_oid).map_err(CascadeError::Git)?;
1723
1724        let mut commits = Vec::new();
1725        for oid in revwalk {
1726            let oid = oid.map_err(CascadeError::Git)?;
1727            let commit = self.repo.find_commit(oid).map_err(CascadeError::Git)?;
1728            commits.push(commit);
1729        }
1730
1731        Ok(commits)
1732    }
1733
1734    /// Force push one branch's content to another branch name
1735    /// This is used to preserve PR history while updating branch contents after rebase
1736    pub fn force_push_branch(&self, target_branch: &str, source_branch: &str) -> Result<()> {
1737        self.force_push_branch_with_options(target_branch, source_branch, false)
1738    }
1739
1740    /// Force push with explicit force flag to bypass safety checks
1741    pub fn force_push_branch_unsafe(&self, target_branch: &str, source_branch: &str) -> Result<()> {
1742        self.force_push_branch_with_options(target_branch, source_branch, true)
1743    }
1744
1745    /// Internal force push implementation with safety options
1746    fn force_push_branch_with_options(
1747        &self,
1748        target_branch: &str,
1749        source_branch: &str,
1750        force_unsafe: bool,
1751    ) -> Result<()> {
1752        info!(
1753            "Force pushing {} content to {} to preserve PR history",
1754            source_branch, target_branch
1755        );
1756
1757        // Enhanced safety check: Detect potential data loss and get user confirmation
1758        if !force_unsafe {
1759            let safety_result = self.check_force_push_safety_enhanced(target_branch)?;
1760            if let Some(backup_info) = safety_result {
1761                // Create backup branch before force push
1762                self.create_backup_branch(target_branch, &backup_info.remote_commit_id)?;
1763                info!(
1764                    "✅ Created backup branch: {}",
1765                    backup_info.backup_branch_name
1766                );
1767            }
1768        }
1769
1770        // First, ensure we have the latest changes for the source branch
1771        let source_ref = self
1772            .repo
1773            .find_reference(&format!("refs/heads/{source_branch}"))
1774            .map_err(|e| {
1775                CascadeError::config(format!("Failed to find source branch {source_branch}: {e}"))
1776            })?;
1777        let _source_commit = source_ref.peel_to_commit().map_err(|e| {
1778            CascadeError::config(format!(
1779                "Failed to get commit for source branch {source_branch}: {e}"
1780            ))
1781        })?;
1782
1783        // Force push to remote without modifying local target branch
1784        let mut remote = self
1785            .repo
1786            .find_remote("origin")
1787            .map_err(|e| CascadeError::config(format!("Failed to find origin remote: {e}")))?;
1788
1789        // Push source branch content to remote target branch
1790        let refspec = format!("+refs/heads/{source_branch}:refs/heads/{target_branch}");
1791
1792        // Configure callbacks with SSL settings from git config
1793        let callbacks = self.configure_remote_callbacks()?;
1794
1795        // Push options for force push with SSL config
1796        let mut push_options = git2::PushOptions::new();
1797        push_options.remote_callbacks(callbacks);
1798
1799        match remote.push(&[&refspec], Some(&mut push_options)) {
1800            Ok(_) => {}
1801            Err(e) => {
1802                if self.should_retry_with_default_credentials(&e) {
1803                    tracing::debug!(
1804                        "Authentication error detected (class: {:?}, code: {:?}): {}, retrying with DefaultCredentials",
1805                        e.class(), e.code(), e
1806                    );
1807
1808                    // Retry with DefaultCredentials for corporate networks
1809                    let callbacks = self.configure_remote_callbacks_with_fallback(true)?;
1810                    let mut push_options = git2::PushOptions::new();
1811                    push_options.remote_callbacks(callbacks);
1812
1813                    match remote.push(&[&refspec], Some(&mut push_options)) {
1814                        Ok(_) => {
1815                            tracing::debug!("Force push succeeded with DefaultCredentials");
1816                            // Success - continue to normal success path
1817                        }
1818                        Err(retry_error) => {
1819                            tracing::debug!(
1820                                "DefaultCredentials retry failed: {}, falling back to git CLI",
1821                                retry_error
1822                            );
1823                            return self.force_push_with_git_cli(target_branch);
1824                        }
1825                    }
1826                } else if self.should_fallback_to_git_cli(&e) {
1827                    tracing::debug!(
1828                        "Network/SSL error detected (class: {:?}, code: {:?}): {}, falling back to git CLI for force push operation",
1829                        e.class(), e.code(), e
1830                    );
1831                    return self.force_push_with_git_cli(target_branch);
1832                } else {
1833                    return Err(CascadeError::config(format!(
1834                        "Failed to force push {target_branch}: {e}"
1835                    )));
1836                }
1837            }
1838        }
1839
1840        info!(
1841            "✅ Successfully force pushed {} to preserve PR history",
1842            target_branch
1843        );
1844        Ok(())
1845    }
1846
1847    /// Enhanced safety check for force push operations with user confirmation
1848    /// Returns backup info if data would be lost and user confirms
1849    fn check_force_push_safety_enhanced(
1850        &self,
1851        target_branch: &str,
1852    ) -> Result<Option<ForceBackupInfo>> {
1853        // First fetch latest remote changes to ensure we have up-to-date information
1854        match self.fetch() {
1855            Ok(_) => {}
1856            Err(e) => {
1857                // If fetch fails, warn but don't block the operation
1858                warn!("Could not fetch latest changes for safety check: {}", e);
1859            }
1860        }
1861
1862        // Check if there are commits on the remote that would be lost
1863        let remote_ref = format!("refs/remotes/origin/{target_branch}");
1864        let local_ref = format!("refs/heads/{target_branch}");
1865
1866        // Try to find both local and remote references
1867        let local_commit = match self.repo.find_reference(&local_ref) {
1868            Ok(reference) => reference.peel_to_commit().ok(),
1869            Err(_) => None,
1870        };
1871
1872        let remote_commit = match self.repo.find_reference(&remote_ref) {
1873            Ok(reference) => reference.peel_to_commit().ok(),
1874            Err(_) => None,
1875        };
1876
1877        // If we have both commits, check for divergence
1878        if let (Some(local), Some(remote)) = (local_commit, remote_commit) {
1879            if local.id() != remote.id() {
1880                // Check if the remote has commits that the local doesn't have
1881                let merge_base_oid = self
1882                    .repo
1883                    .merge_base(local.id(), remote.id())
1884                    .map_err(|e| CascadeError::config(format!("Failed to find merge base: {e}")))?;
1885
1886                // If merge base != remote commit, remote has commits that would be lost
1887                if merge_base_oid != remote.id() {
1888                    let commits_to_lose = self.count_commits_between(
1889                        &merge_base_oid.to_string(),
1890                        &remote.id().to_string(),
1891                    )?;
1892
1893                    // Create backup branch name with timestamp
1894                    let timestamp = chrono::Utc::now().format("%Y%m%d_%H%M%S");
1895                    let backup_branch_name = format!("{target_branch}_backup_{timestamp}");
1896
1897                    debug!(
1898                        "Force push to '{}' would overwrite {} commits on remote",
1899                        target_branch, commits_to_lose
1900                    );
1901
1902                    // Check if we're in a non-interactive environment (CI/testing)
1903                    if std::env::var("CI").is_ok() || std::env::var("FORCE_PUSH_NO_CONFIRM").is_ok()
1904                    {
1905                        info!(
1906                            "Non-interactive environment detected, proceeding with backup creation"
1907                        );
1908                        return Ok(Some(ForceBackupInfo {
1909                            backup_branch_name,
1910                            remote_commit_id: remote.id().to_string(),
1911                            commits_that_would_be_lost: commits_to_lose,
1912                        }));
1913                    }
1914
1915                    // Interactive confirmation
1916                    println!("\n⚠️  FORCE PUSH WARNING ⚠️");
1917                    println!("Force push to '{target_branch}' would overwrite {commits_to_lose} commits on remote:");
1918
1919                    // Show the commits that would be lost
1920                    match self
1921                        .get_commits_between(&merge_base_oid.to_string(), &remote.id().to_string())
1922                    {
1923                        Ok(commits) => {
1924                            println!("\nCommits that would be lost:");
1925                            for (i, commit) in commits.iter().take(5).enumerate() {
1926                                let short_hash = &commit.id().to_string()[..8];
1927                                let summary = commit.summary().unwrap_or("<no message>");
1928                                println!("  {}. {} - {}", i + 1, short_hash, summary);
1929                            }
1930                            if commits.len() > 5 {
1931                                println!("  ... and {} more commits", commits.len() - 5);
1932                            }
1933                        }
1934                        Err(_) => {
1935                            println!("  (Unable to retrieve commit details)");
1936                        }
1937                    }
1938
1939                    println!("\nA backup branch '{backup_branch_name}' will be created before proceeding.");
1940
1941                    let confirmed = Confirm::with_theme(&ColorfulTheme::default())
1942                        .with_prompt("Do you want to proceed with the force push?")
1943                        .default(false)
1944                        .interact()
1945                        .map_err(|e| {
1946                            CascadeError::config(format!("Failed to get user confirmation: {e}"))
1947                        })?;
1948
1949                    if !confirmed {
1950                        return Err(CascadeError::config(
1951                            "Force push cancelled by user. Use --force to bypass this check."
1952                                .to_string(),
1953                        ));
1954                    }
1955
1956                    return Ok(Some(ForceBackupInfo {
1957                        backup_branch_name,
1958                        remote_commit_id: remote.id().to_string(),
1959                        commits_that_would_be_lost: commits_to_lose,
1960                    }));
1961                }
1962            }
1963        }
1964
1965        Ok(None)
1966    }
1967
1968    /// Create a backup branch pointing to the remote commit that would be lost
1969    fn create_backup_branch(&self, original_branch: &str, remote_commit_id: &str) -> Result<()> {
1970        let timestamp = chrono::Utc::now().format("%Y%m%d_%H%M%S");
1971        let backup_branch_name = format!("{original_branch}_backup_{timestamp}");
1972
1973        // Parse the commit ID
1974        let commit_oid = Oid::from_str(remote_commit_id).map_err(|e| {
1975            CascadeError::config(format!("Invalid commit ID {remote_commit_id}: {e}"))
1976        })?;
1977
1978        // Find the commit
1979        let commit = self.repo.find_commit(commit_oid).map_err(|e| {
1980            CascadeError::config(format!("Failed to find commit {remote_commit_id}: {e}"))
1981        })?;
1982
1983        // Create the backup branch
1984        self.repo
1985            .branch(&backup_branch_name, &commit, false)
1986            .map_err(|e| {
1987                CascadeError::config(format!(
1988                    "Failed to create backup branch {backup_branch_name}: {e}"
1989                ))
1990            })?;
1991
1992        info!(
1993            "✅ Created backup branch '{}' pointing to {}",
1994            backup_branch_name,
1995            &remote_commit_id[..8]
1996        );
1997        Ok(())
1998    }
1999
2000    /// Check if branch deletion is safe by detecting unpushed commits
2001    /// Returns safety info if there are concerns that need user attention
2002    fn check_branch_deletion_safety(
2003        &self,
2004        branch_name: &str,
2005    ) -> Result<Option<BranchDeletionSafety>> {
2006        // First, try to fetch latest remote changes
2007        match self.fetch() {
2008            Ok(_) => {}
2009            Err(e) => {
2010                warn!(
2011                    "Could not fetch latest changes for branch deletion safety check: {}",
2012                    e
2013                );
2014            }
2015        }
2016
2017        // Find the branch
2018        let branch = self
2019            .repo
2020            .find_branch(branch_name, git2::BranchType::Local)
2021            .map_err(|e| {
2022                CascadeError::branch(format!("Could not find branch '{branch_name}': {e}"))
2023            })?;
2024
2025        let _branch_commit = branch.get().peel_to_commit().map_err(|e| {
2026            CascadeError::branch(format!(
2027                "Could not get commit for branch '{branch_name}': {e}"
2028            ))
2029        })?;
2030
2031        // Determine the main branch (try common names)
2032        let main_branch_name = self.detect_main_branch()?;
2033
2034        // Check if branch is merged to main
2035        let is_merged_to_main = self.is_branch_merged_to_main(branch_name, &main_branch_name)?;
2036
2037        // Find the upstream/remote tracking branch
2038        let remote_tracking_branch = self.get_remote_tracking_branch(branch_name);
2039
2040        let mut unpushed_commits = Vec::new();
2041
2042        // Check for unpushed commits compared to remote tracking branch
2043        if let Some(ref remote_branch) = remote_tracking_branch {
2044            match self.get_commits_between(remote_branch, branch_name) {
2045                Ok(commits) => {
2046                    unpushed_commits = commits.iter().map(|c| c.id().to_string()).collect();
2047                }
2048                Err(_) => {
2049                    // If we can't compare with remote, check against main branch
2050                    if !is_merged_to_main {
2051                        if let Ok(commits) =
2052                            self.get_commits_between(&main_branch_name, branch_name)
2053                        {
2054                            unpushed_commits = commits.iter().map(|c| c.id().to_string()).collect();
2055                        }
2056                    }
2057                }
2058            }
2059        } else if !is_merged_to_main {
2060            // No remote tracking branch, check against main
2061            if let Ok(commits) = self.get_commits_between(&main_branch_name, branch_name) {
2062                unpushed_commits = commits.iter().map(|c| c.id().to_string()).collect();
2063            }
2064        }
2065
2066        // If there are concerns, return safety info
2067        if !unpushed_commits.is_empty() || (!is_merged_to_main && remote_tracking_branch.is_none())
2068        {
2069            Ok(Some(BranchDeletionSafety {
2070                unpushed_commits,
2071                remote_tracking_branch,
2072                is_merged_to_main,
2073                main_branch_name,
2074            }))
2075        } else {
2076            Ok(None)
2077        }
2078    }
2079
2080    /// Handle user confirmation for branch deletion with safety concerns
2081    fn handle_branch_deletion_confirmation(
2082        &self,
2083        branch_name: &str,
2084        safety_info: &BranchDeletionSafety,
2085    ) -> Result<()> {
2086        // Check if we're in a non-interactive environment
2087        if std::env::var("CI").is_ok() || std::env::var("BRANCH_DELETE_NO_CONFIRM").is_ok() {
2088            return Err(CascadeError::branch(
2089                format!(
2090                    "Branch '{branch_name}' has {} unpushed commits and cannot be deleted in non-interactive mode. Use --force to override.",
2091                    safety_info.unpushed_commits.len()
2092                )
2093            ));
2094        }
2095
2096        // Interactive warning and confirmation
2097        println!("\n⚠️  BRANCH DELETION WARNING ⚠️");
2098        println!("Branch '{branch_name}' has potential issues:");
2099
2100        if !safety_info.unpushed_commits.is_empty() {
2101            println!(
2102                "\n🔍 Unpushed commits ({} total):",
2103                safety_info.unpushed_commits.len()
2104            );
2105
2106            // Show details of unpushed commits
2107            for (i, commit_id) in safety_info.unpushed_commits.iter().take(5).enumerate() {
2108                if let Ok(oid) = Oid::from_str(commit_id) {
2109                    if let Ok(commit) = self.repo.find_commit(oid) {
2110                        let short_hash = &commit_id[..8];
2111                        let summary = commit.summary().unwrap_or("<no message>");
2112                        println!("  {}. {} - {}", i + 1, short_hash, summary);
2113                    }
2114                }
2115            }
2116
2117            if safety_info.unpushed_commits.len() > 5 {
2118                println!(
2119                    "  ... and {} more commits",
2120                    safety_info.unpushed_commits.len() - 5
2121                );
2122            }
2123        }
2124
2125        if !safety_info.is_merged_to_main {
2126            println!("\n📋 Branch status:");
2127            println!("  • Not merged to '{}'", safety_info.main_branch_name);
2128            if let Some(ref remote) = safety_info.remote_tracking_branch {
2129                println!("  • Remote tracking branch: {remote}");
2130            } else {
2131                println!("  • No remote tracking branch");
2132            }
2133        }
2134
2135        println!("\n💡 Safer alternatives:");
2136        if !safety_info.unpushed_commits.is_empty() {
2137            if let Some(ref _remote) = safety_info.remote_tracking_branch {
2138                println!("  • Push commits first: git push origin {branch_name}");
2139            } else {
2140                println!("  • Create and push to remote: git push -u origin {branch_name}");
2141            }
2142        }
2143        if !safety_info.is_merged_to_main {
2144            println!(
2145                "  • Merge to {} first: git checkout {} && git merge {branch_name}",
2146                safety_info.main_branch_name, safety_info.main_branch_name
2147            );
2148        }
2149
2150        let confirmed = Confirm::with_theme(&ColorfulTheme::default())
2151            .with_prompt("Do you want to proceed with deleting this branch?")
2152            .default(false)
2153            .interact()
2154            .map_err(|e| CascadeError::branch(format!("Failed to get user confirmation: {e}")))?;
2155
2156        if !confirmed {
2157            return Err(CascadeError::branch(
2158                "Branch deletion cancelled by user. Use --force to bypass this check.".to_string(),
2159            ));
2160        }
2161
2162        Ok(())
2163    }
2164
2165    /// Detect the main branch name (main, master, develop)
2166    pub fn detect_main_branch(&self) -> Result<String> {
2167        let main_candidates = ["main", "master", "develop", "trunk"];
2168
2169        for candidate in &main_candidates {
2170            if self
2171                .repo
2172                .find_branch(candidate, git2::BranchType::Local)
2173                .is_ok()
2174            {
2175                return Ok(candidate.to_string());
2176            }
2177        }
2178
2179        // Fallback to HEAD's target if it's a symbolic reference
2180        if let Ok(head) = self.repo.head() {
2181            if let Some(name) = head.shorthand() {
2182                return Ok(name.to_string());
2183            }
2184        }
2185
2186        // Final fallback
2187        Ok("main".to_string())
2188    }
2189
2190    /// Check if a branch is merged to the main branch
2191    fn is_branch_merged_to_main(&self, branch_name: &str, main_branch: &str) -> Result<bool> {
2192        // Get the commits between main and the branch
2193        match self.get_commits_between(main_branch, branch_name) {
2194            Ok(commits) => Ok(commits.is_empty()),
2195            Err(_) => {
2196                // If we can't determine, assume not merged for safety
2197                Ok(false)
2198            }
2199        }
2200    }
2201
2202    /// Get the remote tracking branch for a local branch
2203    fn get_remote_tracking_branch(&self, branch_name: &str) -> Option<String> {
2204        // Try common remote tracking branch patterns
2205        let remote_candidates = [
2206            format!("origin/{branch_name}"),
2207            format!("remotes/origin/{branch_name}"),
2208        ];
2209
2210        for candidate in &remote_candidates {
2211            if self
2212                .repo
2213                .find_reference(&format!(
2214                    "refs/remotes/{}",
2215                    candidate.replace("remotes/", "")
2216                ))
2217                .is_ok()
2218            {
2219                return Some(candidate.clone());
2220            }
2221        }
2222
2223        None
2224    }
2225
2226    /// Check if checkout operation is safe
2227    fn check_checkout_safety(&self, _target: &str) -> Result<Option<CheckoutSafety>> {
2228        // Check if there are uncommitted changes
2229        let is_dirty = self.is_dirty()?;
2230        if !is_dirty {
2231            // No uncommitted changes, checkout is safe
2232            return Ok(None);
2233        }
2234
2235        // Get current branch for context
2236        let current_branch = self.get_current_branch().ok();
2237
2238        // Get detailed information about uncommitted changes
2239        let modified_files = self.get_modified_files()?;
2240        let staged_files = self.get_staged_files()?;
2241        let untracked_files = self.get_untracked_files()?;
2242
2243        let has_uncommitted_changes = !modified_files.is_empty() || !staged_files.is_empty();
2244
2245        if has_uncommitted_changes || !untracked_files.is_empty() {
2246            return Ok(Some(CheckoutSafety {
2247                has_uncommitted_changes,
2248                modified_files,
2249                staged_files,
2250                untracked_files,
2251                stash_created: None,
2252                current_branch,
2253            }));
2254        }
2255
2256        Ok(None)
2257    }
2258
2259    /// Handle user confirmation for checkout operations with uncommitted changes
2260    fn handle_checkout_confirmation(
2261        &self,
2262        target: &str,
2263        safety_info: &CheckoutSafety,
2264    ) -> Result<()> {
2265        // Check if we're in a non-interactive environment FIRST (before any output)
2266        let is_ci = std::env::var("CI").is_ok();
2267        let no_confirm = std::env::var("CHECKOUT_NO_CONFIRM").is_ok();
2268        let is_non_interactive = is_ci || no_confirm;
2269
2270        if is_non_interactive {
2271            return Err(CascadeError::branch(
2272                format!(
2273                    "Cannot checkout '{target}' with uncommitted changes in non-interactive mode. Commit your changes or use stash first."
2274                )
2275            ));
2276        }
2277
2278        // Interactive warning and confirmation
2279        println!("\n⚠️  CHECKOUT WARNING ⚠️");
2280        println!("You have uncommitted changes that could be lost:");
2281
2282        if !safety_info.modified_files.is_empty() {
2283            println!(
2284                "\n📝 Modified files ({}):",
2285                safety_info.modified_files.len()
2286            );
2287            for file in safety_info.modified_files.iter().take(10) {
2288                println!("   - {file}");
2289            }
2290            if safety_info.modified_files.len() > 10 {
2291                println!("   ... and {} more", safety_info.modified_files.len() - 10);
2292            }
2293        }
2294
2295        if !safety_info.staged_files.is_empty() {
2296            println!("\n📁 Staged files ({}):", safety_info.staged_files.len());
2297            for file in safety_info.staged_files.iter().take(10) {
2298                println!("   - {file}");
2299            }
2300            if safety_info.staged_files.len() > 10 {
2301                println!("   ... and {} more", safety_info.staged_files.len() - 10);
2302            }
2303        }
2304
2305        if !safety_info.untracked_files.is_empty() {
2306            println!(
2307                "\n❓ Untracked files ({}):",
2308                safety_info.untracked_files.len()
2309            );
2310            for file in safety_info.untracked_files.iter().take(5) {
2311                println!("   - {file}");
2312            }
2313            if safety_info.untracked_files.len() > 5 {
2314                println!("   ... and {} more", safety_info.untracked_files.len() - 5);
2315            }
2316        }
2317
2318        println!("\n🔄 Options:");
2319        println!("1. Stash changes and checkout (recommended)");
2320        println!("2. Force checkout (WILL LOSE UNCOMMITTED CHANGES)");
2321        println!("3. Cancel checkout");
2322
2323        // Use proper selection dialog instead of y/n confirmation
2324        let selection = Select::with_theme(&ColorfulTheme::default())
2325            .with_prompt("Choose an action")
2326            .items(&[
2327                "Stash changes and checkout (recommended)",
2328                "Force checkout (WILL LOSE UNCOMMITTED CHANGES)",
2329                "Cancel checkout",
2330            ])
2331            .default(0)
2332            .interact()
2333            .map_err(|e| CascadeError::branch(format!("Could not get user selection: {e}")))?;
2334
2335        match selection {
2336            0 => {
2337                // Option 1: Stash changes and checkout
2338                let stash_message = format!(
2339                    "Auto-stash before checkout to {} at {}",
2340                    target,
2341                    chrono::Utc::now().format("%Y-%m-%d %H:%M:%S UTC")
2342                );
2343
2344                match self.create_stash(&stash_message) {
2345                    Ok(stash_id) => {
2346                        println!("✅ Created stash: {stash_message} ({stash_id})");
2347                        println!("💡 You can restore with: git stash pop");
2348                    }
2349                    Err(e) => {
2350                        println!("❌ Failed to create stash: {e}");
2351
2352                        // If stash failed, provide better options
2353                        use dialoguer::Select;
2354                        let stash_failed_options = vec![
2355                            "Commit staged changes and proceed",
2356                            "Force checkout (WILL LOSE CHANGES)",
2357                            "Cancel and handle manually",
2358                        ];
2359
2360                        let stash_selection = Select::with_theme(&ColorfulTheme::default())
2361                            .with_prompt("Stash failed. What would you like to do?")
2362                            .items(&stash_failed_options)
2363                            .default(0)
2364                            .interact()
2365                            .map_err(|e| {
2366                                CascadeError::branch(format!("Could not get user selection: {e}"))
2367                            })?;
2368
2369                        match stash_selection {
2370                            0 => {
2371                                // Try to commit staged changes
2372                                let staged_files = self.get_staged_files()?;
2373                                if !staged_files.is_empty() {
2374                                    println!(
2375                                        "📝 Committing {} staged files...",
2376                                        staged_files.len()
2377                                    );
2378                                    match self
2379                                        .commit_staged_changes("WIP: Auto-commit before checkout")
2380                                    {
2381                                        Ok(Some(commit_hash)) => {
2382                                            println!(
2383                                                "✅ Committed staged changes as {}",
2384                                                &commit_hash[..8]
2385                                            );
2386                                            println!("💡 You can undo with: git reset HEAD~1");
2387                                        }
2388                                        Ok(None) => {
2389                                            println!("ℹ️  No staged changes found to commit");
2390                                        }
2391                                        Err(commit_err) => {
2392                                            println!(
2393                                                "❌ Failed to commit staged changes: {commit_err}"
2394                                            );
2395                                            return Err(CascadeError::branch(
2396                                                "Could not commit staged changes".to_string(),
2397                                            ));
2398                                        }
2399                                    }
2400                                } else {
2401                                    println!("ℹ️  No staged changes to commit");
2402                                }
2403                            }
2404                            1 => {
2405                                // Force checkout anyway
2406                                println!("⚠️  Proceeding with force checkout - uncommitted changes will be lost!");
2407                            }
2408                            2 => {
2409                                // Cancel
2410                                return Err(CascadeError::branch(
2411                                    "Checkout cancelled. Please handle changes manually and try again.".to_string(),
2412                                ));
2413                            }
2414                            _ => unreachable!(),
2415                        }
2416                    }
2417                }
2418            }
2419            1 => {
2420                // Option 2: Force checkout (lose changes)
2421                println!("⚠️  Proceeding with force checkout - uncommitted changes will be lost!");
2422            }
2423            2 => {
2424                // Option 3: Cancel
2425                return Err(CascadeError::branch(
2426                    "Checkout cancelled by user".to_string(),
2427                ));
2428            }
2429            _ => unreachable!(),
2430        }
2431
2432        Ok(())
2433    }
2434
2435    /// Create a stash with uncommitted changes
2436    fn create_stash(&self, message: &str) -> Result<String> {
2437        tracing::info!("Creating stash: {}", message);
2438
2439        // Use git CLI for stashing since git2 stashing is complex and unreliable
2440        let output = std::process::Command::new("git")
2441            .args(["stash", "push", "-m", message])
2442            .current_dir(&self.path)
2443            .output()
2444            .map_err(|e| {
2445                CascadeError::branch(format!("Failed to execute git stash command: {e}"))
2446            })?;
2447
2448        if output.status.success() {
2449            let stdout = String::from_utf8_lossy(&output.stdout);
2450
2451            // Extract stash hash if available (git stash outputs like "Saved working directory and index state WIP on branch: message")
2452            let stash_id = if stdout.contains("Saved working directory") {
2453                // Get the most recent stash ID
2454                let stash_list_output = std::process::Command::new("git")
2455                    .args(["stash", "list", "-n", "1", "--format=%H"])
2456                    .current_dir(&self.path)
2457                    .output()
2458                    .map_err(|e| CascadeError::branch(format!("Failed to get stash ID: {e}")))?;
2459
2460                if stash_list_output.status.success() {
2461                    String::from_utf8_lossy(&stash_list_output.stdout)
2462                        .trim()
2463                        .to_string()
2464                } else {
2465                    "stash@{0}".to_string() // fallback
2466                }
2467            } else {
2468                "stash@{0}".to_string() // fallback
2469            };
2470
2471            tracing::info!("✅ Created stash: {} ({})", message, stash_id);
2472            Ok(stash_id)
2473        } else {
2474            let stderr = String::from_utf8_lossy(&output.stderr);
2475            let stdout = String::from_utf8_lossy(&output.stdout);
2476
2477            // Check for common stash failure reasons
2478            if stderr.contains("No local changes to save")
2479                || stdout.contains("No local changes to save")
2480            {
2481                return Err(CascadeError::branch("No local changes to save".to_string()));
2482            }
2483
2484            Err(CascadeError::branch(format!(
2485                "Failed to create stash: {}\nStderr: {}\nStdout: {}",
2486                output.status, stderr, stdout
2487            )))
2488        }
2489    }
2490
2491    /// Get modified files in working directory
2492    fn get_modified_files(&self) -> Result<Vec<String>> {
2493        let mut opts = git2::StatusOptions::new();
2494        opts.include_untracked(false).include_ignored(false);
2495
2496        let statuses = self
2497            .repo
2498            .statuses(Some(&mut opts))
2499            .map_err(|e| CascadeError::branch(format!("Could not get repository status: {e}")))?;
2500
2501        let mut modified_files = Vec::new();
2502        for status in statuses.iter() {
2503            let flags = status.status();
2504            if flags.contains(git2::Status::WT_MODIFIED) || flags.contains(git2::Status::WT_DELETED)
2505            {
2506                if let Some(path) = status.path() {
2507                    modified_files.push(path.to_string());
2508                }
2509            }
2510        }
2511
2512        Ok(modified_files)
2513    }
2514
2515    /// Get staged files in index
2516    pub fn get_staged_files(&self) -> Result<Vec<String>> {
2517        let mut opts = git2::StatusOptions::new();
2518        opts.include_untracked(false).include_ignored(false);
2519
2520        let statuses = self
2521            .repo
2522            .statuses(Some(&mut opts))
2523            .map_err(|e| CascadeError::branch(format!("Could not get repository status: {e}")))?;
2524
2525        let mut staged_files = Vec::new();
2526        for status in statuses.iter() {
2527            let flags = status.status();
2528            if flags.contains(git2::Status::INDEX_MODIFIED)
2529                || flags.contains(git2::Status::INDEX_NEW)
2530                || flags.contains(git2::Status::INDEX_DELETED)
2531            {
2532                if let Some(path) = status.path() {
2533                    staged_files.push(path.to_string());
2534                }
2535            }
2536        }
2537
2538        Ok(staged_files)
2539    }
2540
2541    /// Count commits between two references
2542    fn count_commits_between(&self, from: &str, to: &str) -> Result<usize> {
2543        let commits = self.get_commits_between(from, to)?;
2544        Ok(commits.len())
2545    }
2546
2547    /// Resolve a reference (branch name, tag, or commit hash) to a commit
2548    pub fn resolve_reference(&self, reference: &str) -> Result<git2::Commit<'_>> {
2549        // Try to parse as commit hash first
2550        if let Ok(oid) = Oid::from_str(reference) {
2551            if let Ok(commit) = self.repo.find_commit(oid) {
2552                return Ok(commit);
2553            }
2554        }
2555
2556        // Try to resolve as a reference (branch, tag, etc.)
2557        let obj = self.repo.revparse_single(reference).map_err(|e| {
2558            CascadeError::branch(format!("Could not resolve reference '{reference}': {e}"))
2559        })?;
2560
2561        obj.peel_to_commit().map_err(|e| {
2562            CascadeError::branch(format!(
2563                "Reference '{reference}' does not point to a commit: {e}"
2564            ))
2565        })
2566    }
2567
2568    /// Reset HEAD to a specific reference (soft reset)
2569    pub fn reset_soft(&self, target_ref: &str) -> Result<()> {
2570        let target_commit = self.resolve_reference(target_ref)?;
2571
2572        self.repo
2573            .reset(target_commit.as_object(), git2::ResetType::Soft, None)
2574            .map_err(CascadeError::Git)?;
2575
2576        Ok(())
2577    }
2578
2579    /// Reset working directory and index to match HEAD (hard reset)
2580    /// This clears all uncommitted changes and staged files
2581    pub fn reset_to_head(&self) -> Result<()> {
2582        tracing::debug!("Resetting working directory and index to HEAD");
2583
2584        let head = self.repo.head().map_err(CascadeError::Git)?;
2585        let head_commit = head.peel_to_commit().map_err(CascadeError::Git)?;
2586
2587        // Hard reset: resets index and working tree
2588        let mut checkout_builder = git2::build::CheckoutBuilder::new();
2589        checkout_builder.force(); // Force checkout to overwrite any local changes
2590        checkout_builder.remove_untracked(false); // Don't remove untracked files
2591
2592        self.repo
2593            .reset(
2594                head_commit.as_object(),
2595                git2::ResetType::Hard,
2596                Some(&mut checkout_builder),
2597            )
2598            .map_err(CascadeError::Git)?;
2599
2600        tracing::debug!("Successfully reset working directory to HEAD");
2601        Ok(())
2602    }
2603
2604    /// Find which branch contains a specific commit
2605    pub fn find_branch_containing_commit(&self, commit_hash: &str) -> Result<String> {
2606        let oid = Oid::from_str(commit_hash).map_err(|e| {
2607            CascadeError::branch(format!("Invalid commit hash '{commit_hash}': {e}"))
2608        })?;
2609
2610        // Get all local branches
2611        let branches = self
2612            .repo
2613            .branches(Some(git2::BranchType::Local))
2614            .map_err(CascadeError::Git)?;
2615
2616        for branch_result in branches {
2617            let (branch, _) = branch_result.map_err(CascadeError::Git)?;
2618
2619            if let Some(branch_name) = branch.name().map_err(CascadeError::Git)? {
2620                // Check if this branch contains the commit
2621                if let Ok(branch_head) = branch.get().peel_to_commit() {
2622                    // Walk the commit history from this branch's HEAD
2623                    let mut revwalk = self.repo.revwalk().map_err(CascadeError::Git)?;
2624                    revwalk.push(branch_head.id()).map_err(CascadeError::Git)?;
2625
2626                    for commit_oid in revwalk {
2627                        let commit_oid = commit_oid.map_err(CascadeError::Git)?;
2628                        if commit_oid == oid {
2629                            return Ok(branch_name.to_string());
2630                        }
2631                    }
2632                }
2633            }
2634        }
2635
2636        // If not found in any branch, might be on current HEAD
2637        Err(CascadeError::branch(format!(
2638            "Commit {commit_hash} not found in any local branch"
2639        )))
2640    }
2641
2642    // Async wrappers for potentially blocking operations
2643
2644    /// Fetch from remote origin (async)
2645    pub async fn fetch_async(&self) -> Result<()> {
2646        let repo_path = self.path.clone();
2647        crate::utils::async_ops::run_git_operation(move || {
2648            let repo = GitRepository::open(&repo_path)?;
2649            repo.fetch()
2650        })
2651        .await
2652    }
2653
2654    /// Pull changes from remote (async)
2655    pub async fn pull_async(&self, branch: &str) -> Result<()> {
2656        let repo_path = self.path.clone();
2657        let branch_name = branch.to_string();
2658        crate::utils::async_ops::run_git_operation(move || {
2659            let repo = GitRepository::open(&repo_path)?;
2660            repo.pull(&branch_name)
2661        })
2662        .await
2663    }
2664
2665    /// Push branch to remote (async)
2666    pub async fn push_branch_async(&self, branch_name: &str) -> Result<()> {
2667        let repo_path = self.path.clone();
2668        let branch = branch_name.to_string();
2669        crate::utils::async_ops::run_git_operation(move || {
2670            let repo = GitRepository::open(&repo_path)?;
2671            repo.push(&branch)
2672        })
2673        .await
2674    }
2675
2676    /// Cherry-pick commit (async)
2677    pub async fn cherry_pick_commit_async(&self, commit_hash: &str) -> Result<String> {
2678        let repo_path = self.path.clone();
2679        let hash = commit_hash.to_string();
2680        crate::utils::async_ops::run_git_operation(move || {
2681            let repo = GitRepository::open(&repo_path)?;
2682            repo.cherry_pick(&hash)
2683        })
2684        .await
2685    }
2686
2687    /// Get commit hashes between two refs (async)
2688    pub async fn get_commit_hashes_between_async(
2689        &self,
2690        from: &str,
2691        to: &str,
2692    ) -> Result<Vec<String>> {
2693        let repo_path = self.path.clone();
2694        let from_str = from.to_string();
2695        let to_str = to.to_string();
2696        crate::utils::async_ops::run_git_operation(move || {
2697            let repo = GitRepository::open(&repo_path)?;
2698            let commits = repo.get_commits_between(&from_str, &to_str)?;
2699            Ok(commits.into_iter().map(|c| c.id().to_string()).collect())
2700        })
2701        .await
2702    }
2703
2704    /// Reset a branch to point to a specific commit
2705    pub fn reset_branch_to_commit(&self, branch_name: &str, commit_hash: &str) -> Result<()> {
2706        info!(
2707            "Resetting branch '{}' to commit {}",
2708            branch_name,
2709            &commit_hash[..8]
2710        );
2711
2712        // Find the target commit
2713        let target_oid = git2::Oid::from_str(commit_hash).map_err(|e| {
2714            CascadeError::branch(format!("Invalid commit hash '{commit_hash}': {e}"))
2715        })?;
2716
2717        let _target_commit = self.repo.find_commit(target_oid).map_err(|e| {
2718            CascadeError::branch(format!("Could not find commit '{commit_hash}': {e}"))
2719        })?;
2720
2721        // Find the branch
2722        let _branch = self
2723            .repo
2724            .find_branch(branch_name, git2::BranchType::Local)
2725            .map_err(|e| {
2726                CascadeError::branch(format!("Could not find branch '{branch_name}': {e}"))
2727            })?;
2728
2729        // Update the branch reference to point to the target commit
2730        let branch_ref_name = format!("refs/heads/{branch_name}");
2731        self.repo
2732            .reference(
2733                &branch_ref_name,
2734                target_oid,
2735                true,
2736                &format!("Reset {branch_name} to {commit_hash}"),
2737            )
2738            .map_err(|e| {
2739                CascadeError::branch(format!(
2740                    "Could not reset branch '{branch_name}' to commit '{commit_hash}': {e}"
2741                ))
2742            })?;
2743
2744        tracing::info!(
2745            "Successfully reset branch '{}' to commit {}",
2746            branch_name,
2747            &commit_hash[..8]
2748        );
2749        Ok(())
2750    }
2751
2752    /// Detect the parent branch of the current branch using multiple strategies
2753    pub fn detect_parent_branch(&self) -> Result<Option<String>> {
2754        let current_branch = self.get_current_branch()?;
2755
2756        // Strategy 1: Check if current branch has an upstream tracking branch
2757        if let Ok(Some(upstream)) = self.get_upstream_branch(&current_branch) {
2758            // Extract the branch name from "origin/branch-name" format
2759            if let Some(branch_name) = upstream.split('/').nth(1) {
2760                if self.branch_exists(branch_name) {
2761                    tracing::debug!(
2762                        "Detected parent branch '{}' from upstream tracking",
2763                        branch_name
2764                    );
2765                    return Ok(Some(branch_name.to_string()));
2766                }
2767            }
2768        }
2769
2770        // Strategy 2: Use git's default branch detection
2771        if let Ok(default_branch) = self.detect_main_branch() {
2772            // Don't suggest the current branch as its own parent
2773            if current_branch != default_branch {
2774                tracing::debug!(
2775                    "Detected parent branch '{}' as repository default",
2776                    default_branch
2777                );
2778                return Ok(Some(default_branch));
2779            }
2780        }
2781
2782        // Strategy 3: Find the branch with the most recent common ancestor
2783        // Get all local branches and find the one with the shortest commit distance
2784        if let Ok(branches) = self.list_branches() {
2785            let current_commit = self.get_head_commit()?;
2786            let current_commit_hash = current_commit.id().to_string();
2787            let current_oid = current_commit.id();
2788
2789            let mut best_candidate = None;
2790            let mut best_distance = usize::MAX;
2791
2792            for branch in branches {
2793                // Skip the current branch and any branches that look like version branches
2794                if branch == current_branch
2795                    || branch.contains("-v")
2796                    || branch.ends_with("-v2")
2797                    || branch.ends_with("-v3")
2798                {
2799                    continue;
2800                }
2801
2802                if let Ok(base_commit_hash) = self.get_branch_commit_hash(&branch) {
2803                    if let Ok(base_oid) = git2::Oid::from_str(&base_commit_hash) {
2804                        // Find merge base between current branch and this branch
2805                        if let Ok(merge_base_oid) = self.repo.merge_base(current_oid, base_oid) {
2806                            // Count commits from merge base to current head
2807                            if let Ok(distance) = self.count_commits_between(
2808                                &merge_base_oid.to_string(),
2809                                &current_commit_hash,
2810                            ) {
2811                                // Prefer branches with shorter distances (more recent common ancestor)
2812                                // Also prefer branches that look like base branches
2813                                let is_likely_base = self.is_likely_base_branch(&branch);
2814                                let adjusted_distance = if is_likely_base {
2815                                    distance
2816                                } else {
2817                                    distance + 1000
2818                                };
2819
2820                                if adjusted_distance < best_distance {
2821                                    best_distance = adjusted_distance;
2822                                    best_candidate = Some(branch.clone());
2823                                }
2824                            }
2825                        }
2826                    }
2827                }
2828            }
2829
2830            if let Some(ref candidate) = best_candidate {
2831                tracing::debug!(
2832                    "Detected parent branch '{}' with distance {}",
2833                    candidate,
2834                    best_distance
2835                );
2836            }
2837
2838            return Ok(best_candidate);
2839        }
2840
2841        tracing::debug!("Could not detect parent branch for '{}'", current_branch);
2842        Ok(None)
2843    }
2844
2845    /// Check if a branch name looks like a typical base branch
2846    fn is_likely_base_branch(&self, branch_name: &str) -> bool {
2847        let base_patterns = [
2848            "main",
2849            "master",
2850            "develop",
2851            "dev",
2852            "development",
2853            "staging",
2854            "stage",
2855            "release",
2856            "production",
2857            "prod",
2858        ];
2859
2860        base_patterns.contains(&branch_name)
2861    }
2862}
2863
2864#[cfg(test)]
2865mod tests {
2866    use super::*;
2867    use std::process::Command;
2868    use tempfile::TempDir;
2869
2870    fn create_test_repo() -> (TempDir, PathBuf) {
2871        let temp_dir = TempDir::new().unwrap();
2872        let repo_path = temp_dir.path().to_path_buf();
2873
2874        // Initialize git repository
2875        Command::new("git")
2876            .args(["init"])
2877            .current_dir(&repo_path)
2878            .output()
2879            .unwrap();
2880        Command::new("git")
2881            .args(["config", "user.name", "Test"])
2882            .current_dir(&repo_path)
2883            .output()
2884            .unwrap();
2885        Command::new("git")
2886            .args(["config", "user.email", "test@test.com"])
2887            .current_dir(&repo_path)
2888            .output()
2889            .unwrap();
2890
2891        // Create initial commit
2892        std::fs::write(repo_path.join("README.md"), "# Test").unwrap();
2893        Command::new("git")
2894            .args(["add", "."])
2895            .current_dir(&repo_path)
2896            .output()
2897            .unwrap();
2898        Command::new("git")
2899            .args(["commit", "-m", "Initial commit"])
2900            .current_dir(&repo_path)
2901            .output()
2902            .unwrap();
2903
2904        (temp_dir, repo_path)
2905    }
2906
2907    fn create_commit(repo_path: &PathBuf, message: &str, filename: &str) {
2908        let file_path = repo_path.join(filename);
2909        std::fs::write(&file_path, format!("Content for {filename}\n")).unwrap();
2910
2911        Command::new("git")
2912            .args(["add", filename])
2913            .current_dir(repo_path)
2914            .output()
2915            .unwrap();
2916        Command::new("git")
2917            .args(["commit", "-m", message])
2918            .current_dir(repo_path)
2919            .output()
2920            .unwrap();
2921    }
2922
2923    #[test]
2924    fn test_repository_info() {
2925        let (_temp_dir, repo_path) = create_test_repo();
2926        let repo = GitRepository::open(&repo_path).unwrap();
2927
2928        let info = repo.get_info().unwrap();
2929        assert!(!info.is_dirty); // Should be clean after commit
2930        assert!(
2931            info.head_branch == Some("master".to_string())
2932                || info.head_branch == Some("main".to_string()),
2933            "Expected default branch to be 'master' or 'main', got {:?}",
2934            info.head_branch
2935        );
2936        assert!(info.head_commit.is_some()); // Just check it exists
2937        assert!(info.untracked_files.is_empty()); // Should be empty after commit
2938    }
2939
2940    #[test]
2941    fn test_force_push_branch_basic() {
2942        let (_temp_dir, repo_path) = create_test_repo();
2943        let repo = GitRepository::open(&repo_path).unwrap();
2944
2945        // Get the actual default branch name
2946        let default_branch = repo.get_current_branch().unwrap();
2947
2948        // Create source branch with commits
2949        create_commit(&repo_path, "Feature commit 1", "feature1.rs");
2950        Command::new("git")
2951            .args(["checkout", "-b", "source-branch"])
2952            .current_dir(&repo_path)
2953            .output()
2954            .unwrap();
2955        create_commit(&repo_path, "Feature commit 2", "feature2.rs");
2956
2957        // Create target branch
2958        Command::new("git")
2959            .args(["checkout", &default_branch])
2960            .current_dir(&repo_path)
2961            .output()
2962            .unwrap();
2963        Command::new("git")
2964            .args(["checkout", "-b", "target-branch"])
2965            .current_dir(&repo_path)
2966            .output()
2967            .unwrap();
2968        create_commit(&repo_path, "Target commit", "target.rs");
2969
2970        // Test force push from source to target
2971        let result = repo.force_push_branch("target-branch", "source-branch");
2972
2973        // Should succeed in test environment (even though it doesn't actually push to remote)
2974        // The important thing is that the function doesn't panic and handles the git2 operations
2975        assert!(result.is_ok() || result.is_err()); // Either is acceptable for unit test
2976    }
2977
2978    #[test]
2979    fn test_force_push_branch_nonexistent_branches() {
2980        let (_temp_dir, repo_path) = create_test_repo();
2981        let repo = GitRepository::open(&repo_path).unwrap();
2982
2983        // Get the actual default branch name
2984        let default_branch = repo.get_current_branch().unwrap();
2985
2986        // Test force push with nonexistent source branch
2987        let result = repo.force_push_branch("target", "nonexistent-source");
2988        assert!(result.is_err());
2989
2990        // Test force push with nonexistent target branch
2991        let result = repo.force_push_branch("nonexistent-target", &default_branch);
2992        assert!(result.is_err());
2993    }
2994
2995    #[test]
2996    fn test_force_push_workflow_simulation() {
2997        let (_temp_dir, repo_path) = create_test_repo();
2998        let repo = GitRepository::open(&repo_path).unwrap();
2999
3000        // Simulate the smart force push workflow:
3001        // 1. Original branch exists with PR
3002        Command::new("git")
3003            .args(["checkout", "-b", "feature-auth"])
3004            .current_dir(&repo_path)
3005            .output()
3006            .unwrap();
3007        create_commit(&repo_path, "Add authentication", "auth.rs");
3008
3009        // 2. Rebase creates versioned branch
3010        Command::new("git")
3011            .args(["checkout", "-b", "feature-auth-v2"])
3012            .current_dir(&repo_path)
3013            .output()
3014            .unwrap();
3015        create_commit(&repo_path, "Fix auth validation", "auth.rs");
3016
3017        // 3. Smart force push: update original branch from versioned branch
3018        let result = repo.force_push_branch("feature-auth", "feature-auth-v2");
3019
3020        // Verify the operation is handled properly (success or expected error)
3021        match result {
3022            Ok(_) => {
3023                // Force push succeeded - verify branch state if possible
3024                Command::new("git")
3025                    .args(["checkout", "feature-auth"])
3026                    .current_dir(&repo_path)
3027                    .output()
3028                    .unwrap();
3029                let log_output = Command::new("git")
3030                    .args(["log", "--oneline", "-2"])
3031                    .current_dir(&repo_path)
3032                    .output()
3033                    .unwrap();
3034                let log_str = String::from_utf8_lossy(&log_output.stdout);
3035                assert!(
3036                    log_str.contains("Fix auth validation")
3037                        || log_str.contains("Add authentication")
3038                );
3039            }
3040            Err(_) => {
3041                // Expected in test environment without remote - that's fine
3042                // The important thing is we tested the code path without panicking
3043            }
3044        }
3045    }
3046
3047    #[test]
3048    fn test_branch_operations() {
3049        let (_temp_dir, repo_path) = create_test_repo();
3050        let repo = GitRepository::open(&repo_path).unwrap();
3051
3052        // Test get current branch - accept either main or master
3053        let current = repo.get_current_branch().unwrap();
3054        assert!(
3055            current == "master" || current == "main",
3056            "Expected default branch to be 'master' or 'main', got '{current}'"
3057        );
3058
3059        // Test create branch
3060        Command::new("git")
3061            .args(["checkout", "-b", "test-branch"])
3062            .current_dir(&repo_path)
3063            .output()
3064            .unwrap();
3065        let current = repo.get_current_branch().unwrap();
3066        assert_eq!(current, "test-branch");
3067    }
3068
3069    #[test]
3070    fn test_commit_operations() {
3071        let (_temp_dir, repo_path) = create_test_repo();
3072        let repo = GitRepository::open(&repo_path).unwrap();
3073
3074        // Test get head commit
3075        let head = repo.get_head_commit().unwrap();
3076        assert_eq!(head.message().unwrap().trim(), "Initial commit");
3077
3078        // Test get commit by hash
3079        let hash = head.id().to_string();
3080        let same_commit = repo.get_commit(&hash).unwrap();
3081        assert_eq!(head.id(), same_commit.id());
3082    }
3083
3084    #[test]
3085    fn test_checkout_safety_clean_repo() {
3086        let (_temp_dir, repo_path) = create_test_repo();
3087        let repo = GitRepository::open(&repo_path).unwrap();
3088
3089        // Create a test branch
3090        create_commit(&repo_path, "Second commit", "test.txt");
3091        Command::new("git")
3092            .args(["checkout", "-b", "test-branch"])
3093            .current_dir(&repo_path)
3094            .output()
3095            .unwrap();
3096
3097        // Test checkout safety with clean repo
3098        let safety_result = repo.check_checkout_safety("main");
3099        assert!(safety_result.is_ok());
3100        assert!(safety_result.unwrap().is_none()); // Clean repo should return None
3101    }
3102
3103    #[test]
3104    fn test_checkout_safety_with_modified_files() {
3105        let (_temp_dir, repo_path) = create_test_repo();
3106        let repo = GitRepository::open(&repo_path).unwrap();
3107
3108        // Create a test branch
3109        Command::new("git")
3110            .args(["checkout", "-b", "test-branch"])
3111            .current_dir(&repo_path)
3112            .output()
3113            .unwrap();
3114
3115        // Modify a file to create uncommitted changes
3116        std::fs::write(repo_path.join("README.md"), "Modified content").unwrap();
3117
3118        // Test checkout safety with modified files
3119        let safety_result = repo.check_checkout_safety("main");
3120        assert!(safety_result.is_ok());
3121        let safety_info = safety_result.unwrap();
3122        assert!(safety_info.is_some());
3123
3124        let info = safety_info.unwrap();
3125        assert!(!info.modified_files.is_empty());
3126        assert!(info.modified_files.contains(&"README.md".to_string()));
3127    }
3128
3129    #[test]
3130    fn test_unsafe_checkout_methods() {
3131        let (_temp_dir, repo_path) = create_test_repo();
3132        let repo = GitRepository::open(&repo_path).unwrap();
3133
3134        // Create a test branch
3135        create_commit(&repo_path, "Second commit", "test.txt");
3136        Command::new("git")
3137            .args(["checkout", "-b", "test-branch"])
3138            .current_dir(&repo_path)
3139            .output()
3140            .unwrap();
3141
3142        // Modify a file to create uncommitted changes
3143        std::fs::write(repo_path.join("README.md"), "Modified content").unwrap();
3144
3145        // Test unsafe checkout methods bypass safety checks
3146        let _result = repo.checkout_branch_unsafe("main");
3147        // Note: This might still fail due to git2 restrictions, but shouldn't hit our safety code
3148        // The important thing is that it doesn't trigger our safety confirmation
3149
3150        // Test unsafe commit checkout
3151        let head_commit = repo.get_head_commit().unwrap();
3152        let commit_hash = head_commit.id().to_string();
3153        let _result = repo.checkout_commit_unsafe(&commit_hash);
3154        // Similar to above - testing that safety is bypassed
3155    }
3156
3157    #[test]
3158    fn test_get_modified_files() {
3159        let (_temp_dir, repo_path) = create_test_repo();
3160        let repo = GitRepository::open(&repo_path).unwrap();
3161
3162        // Initially should have no modified files
3163        let modified = repo.get_modified_files().unwrap();
3164        assert!(modified.is_empty());
3165
3166        // Modify a file
3167        std::fs::write(repo_path.join("README.md"), "Modified content").unwrap();
3168
3169        // Should now detect the modified file
3170        let modified = repo.get_modified_files().unwrap();
3171        assert_eq!(modified.len(), 1);
3172        assert!(modified.contains(&"README.md".to_string()));
3173    }
3174
3175    #[test]
3176    fn test_get_staged_files() {
3177        let (_temp_dir, repo_path) = create_test_repo();
3178        let repo = GitRepository::open(&repo_path).unwrap();
3179
3180        // Initially should have no staged files
3181        let staged = repo.get_staged_files().unwrap();
3182        assert!(staged.is_empty());
3183
3184        // Create and stage a new file
3185        std::fs::write(repo_path.join("staged.txt"), "Staged content").unwrap();
3186        Command::new("git")
3187            .args(["add", "staged.txt"])
3188            .current_dir(&repo_path)
3189            .output()
3190            .unwrap();
3191
3192        // Should now detect the staged file
3193        let staged = repo.get_staged_files().unwrap();
3194        assert_eq!(staged.len(), 1);
3195        assert!(staged.contains(&"staged.txt".to_string()));
3196    }
3197
3198    #[test]
3199    fn test_create_stash_fallback() {
3200        let (_temp_dir, repo_path) = create_test_repo();
3201        let repo = GitRepository::open(&repo_path).unwrap();
3202
3203        // Test stash creation - newer git versions allow empty stashes
3204        let result = repo.create_stash("test stash");
3205
3206        // Either succeeds (newer git with empty stash) or fails with helpful message
3207        match result {
3208            Ok(stash_id) => {
3209                // Modern git allows empty stashes, verify we got a stash ID
3210                assert!(!stash_id.is_empty());
3211                assert!(stash_id.contains("stash") || stash_id.len() >= 7); // SHA or stash@{n}
3212            }
3213            Err(error) => {
3214                // Older git should fail with helpful message
3215                let error_msg = error.to_string();
3216                assert!(
3217                    error_msg.contains("No local changes to save")
3218                        || error_msg.contains("git stash push")
3219                );
3220            }
3221        }
3222    }
3223
3224    #[test]
3225    fn test_delete_branch_unsafe() {
3226        let (_temp_dir, repo_path) = create_test_repo();
3227        let repo = GitRepository::open(&repo_path).unwrap();
3228
3229        // Create a test branch
3230        create_commit(&repo_path, "Second commit", "test.txt");
3231        Command::new("git")
3232            .args(["checkout", "-b", "test-branch"])
3233            .current_dir(&repo_path)
3234            .output()
3235            .unwrap();
3236
3237        // Add another commit to the test branch to make it different from main
3238        create_commit(&repo_path, "Branch-specific commit", "branch.txt");
3239
3240        // Go back to main
3241        Command::new("git")
3242            .args(["checkout", "main"])
3243            .current_dir(&repo_path)
3244            .output()
3245            .unwrap();
3246
3247        // Test unsafe delete bypasses safety checks
3248        // Note: This may still fail if the branch has unpushed commits, but it should bypass our safety confirmation
3249        let result = repo.delete_branch_unsafe("test-branch");
3250        // Even if it fails, the key is that it didn't prompt for user confirmation
3251        // So we just check that it attempted the operation without interactive prompts
3252        let _ = result; // Don't assert success since delete may fail for git reasons
3253    }
3254
3255    #[test]
3256    fn test_force_push_unsafe() {
3257        let (_temp_dir, repo_path) = create_test_repo();
3258        let repo = GitRepository::open(&repo_path).unwrap();
3259
3260        // Create a test branch
3261        create_commit(&repo_path, "Second commit", "test.txt");
3262        Command::new("git")
3263            .args(["checkout", "-b", "test-branch"])
3264            .current_dir(&repo_path)
3265            .output()
3266            .unwrap();
3267
3268        // Test unsafe force push bypasses safety checks
3269        // Note: This will likely fail due to no remote, but it tests the safety bypass
3270        let _result = repo.force_push_branch_unsafe("test-branch", "test-branch");
3271        // The key is that it doesn't trigger safety confirmation dialogs
3272    }
3273
3274    #[test]
3275    fn test_cherry_pick_basic() {
3276        let (_temp_dir, repo_path) = create_test_repo();
3277        let repo = GitRepository::open(&repo_path).unwrap();
3278
3279        // Create a branch with a commit to cherry-pick
3280        repo.create_branch("source", None).unwrap();
3281        repo.checkout_branch("source").unwrap();
3282
3283        std::fs::write(repo_path.join("cherry.txt"), "Cherry content").unwrap();
3284        Command::new("git")
3285            .args(["add", "."])
3286            .current_dir(&repo_path)
3287            .output()
3288            .unwrap();
3289
3290        Command::new("git")
3291            .args(["commit", "-m", "Cherry commit"])
3292            .current_dir(&repo_path)
3293            .output()
3294            .unwrap();
3295
3296        let cherry_commit = repo.get_head_commit_hash().unwrap();
3297
3298        // Switch back to previous branch (where source was created from)
3299        // Using `git checkout -` is environment-agnostic
3300        Command::new("git")
3301            .args(["checkout", "-"])
3302            .current_dir(&repo_path)
3303            .output()
3304            .unwrap();
3305
3306        repo.create_branch("target", None).unwrap();
3307        repo.checkout_branch("target").unwrap();
3308
3309        // Cherry-pick the commit
3310        let new_commit = repo.cherry_pick(&cherry_commit).unwrap();
3311
3312        // Verify new commit exists and is different
3313        assert_ne!(new_commit, cherry_commit, "Should create new commit hash");
3314
3315        // Verify file exists on target branch
3316        assert!(
3317            repo_path.join("cherry.txt").exists(),
3318            "Cherry-picked file should exist"
3319        );
3320
3321        // Verify source branch is unchanged
3322        repo.checkout_branch("source").unwrap();
3323        let source_head = repo.get_head_commit_hash().unwrap();
3324        assert_eq!(
3325            source_head, cherry_commit,
3326            "Source branch should be unchanged"
3327        );
3328    }
3329
3330    #[test]
3331    fn test_cherry_pick_preserves_commit_message() {
3332        let (_temp_dir, repo_path) = create_test_repo();
3333        let repo = GitRepository::open(&repo_path).unwrap();
3334
3335        // Create commit with specific message
3336        repo.create_branch("msg-test", None).unwrap();
3337        repo.checkout_branch("msg-test").unwrap();
3338
3339        std::fs::write(repo_path.join("msg.txt"), "Content").unwrap();
3340        Command::new("git")
3341            .args(["add", "."])
3342            .current_dir(&repo_path)
3343            .output()
3344            .unwrap();
3345
3346        let commit_msg = "Test: Special commit message\n\nWith body";
3347        Command::new("git")
3348            .args(["commit", "-m", commit_msg])
3349            .current_dir(&repo_path)
3350            .output()
3351            .unwrap();
3352
3353        let original_commit = repo.get_head_commit_hash().unwrap();
3354
3355        // Cherry-pick to another branch (use previous branch via git checkout -)
3356        Command::new("git")
3357            .args(["checkout", "-"])
3358            .current_dir(&repo_path)
3359            .output()
3360            .unwrap();
3361        let new_commit = repo.cherry_pick(&original_commit).unwrap();
3362
3363        // Get commit message of new commit
3364        let output = Command::new("git")
3365            .args(["log", "-1", "--format=%B", &new_commit])
3366            .current_dir(&repo_path)
3367            .output()
3368            .unwrap();
3369
3370        let new_msg = String::from_utf8_lossy(&output.stdout);
3371        assert!(
3372            new_msg.contains("Special commit message"),
3373            "Should preserve commit message"
3374        );
3375    }
3376
3377    #[test]
3378    fn test_cherry_pick_handles_conflicts() {
3379        let (_temp_dir, repo_path) = create_test_repo();
3380        let repo = GitRepository::open(&repo_path).unwrap();
3381
3382        // Create conflicting content
3383        std::fs::write(repo_path.join("conflict.txt"), "Original").unwrap();
3384        Command::new("git")
3385            .args(["add", "."])
3386            .current_dir(&repo_path)
3387            .output()
3388            .unwrap();
3389
3390        Command::new("git")
3391            .args(["commit", "-m", "Add conflict file"])
3392            .current_dir(&repo_path)
3393            .output()
3394            .unwrap();
3395
3396        // Create branch with different content
3397        repo.create_branch("conflict-branch", None).unwrap();
3398        repo.checkout_branch("conflict-branch").unwrap();
3399
3400        std::fs::write(repo_path.join("conflict.txt"), "Modified").unwrap();
3401        Command::new("git")
3402            .args(["add", "."])
3403            .current_dir(&repo_path)
3404            .output()
3405            .unwrap();
3406
3407        Command::new("git")
3408            .args(["commit", "-m", "Modify conflict file"])
3409            .current_dir(&repo_path)
3410            .output()
3411            .unwrap();
3412
3413        let conflict_commit = repo.get_head_commit_hash().unwrap();
3414
3415        // Try to cherry-pick (should fail due to conflict)
3416        // Go back to previous branch
3417        Command::new("git")
3418            .args(["checkout", "-"])
3419            .current_dir(&repo_path)
3420            .output()
3421            .unwrap();
3422        std::fs::write(repo_path.join("conflict.txt"), "Different").unwrap();
3423        Command::new("git")
3424            .args(["add", "."])
3425            .current_dir(&repo_path)
3426            .output()
3427            .unwrap();
3428
3429        Command::new("git")
3430            .args(["commit", "-m", "Different change"])
3431            .current_dir(&repo_path)
3432            .output()
3433            .unwrap();
3434
3435        // Cherry-pick should fail with conflict
3436        let result = repo.cherry_pick(&conflict_commit);
3437        assert!(result.is_err(), "Cherry-pick with conflict should fail");
3438    }
3439
3440    #[test]
3441    fn test_reset_to_head_clears_staged_files() {
3442        let (_temp_dir, repo_path) = create_test_repo();
3443        let repo = GitRepository::open(&repo_path).unwrap();
3444
3445        // Create and stage some files
3446        std::fs::write(repo_path.join("staged1.txt"), "Content 1").unwrap();
3447        std::fs::write(repo_path.join("staged2.txt"), "Content 2").unwrap();
3448
3449        Command::new("git")
3450            .args(["add", "staged1.txt", "staged2.txt"])
3451            .current_dir(&repo_path)
3452            .output()
3453            .unwrap();
3454
3455        // Verify files are staged
3456        let staged_before = repo.get_staged_files().unwrap();
3457        assert_eq!(staged_before.len(), 2, "Should have 2 staged files");
3458
3459        // Reset to HEAD
3460        repo.reset_to_head().unwrap();
3461
3462        // Verify no files are staged after reset
3463        let staged_after = repo.get_staged_files().unwrap();
3464        assert_eq!(
3465            staged_after.len(),
3466            0,
3467            "Should have no staged files after reset"
3468        );
3469    }
3470
3471    #[test]
3472    fn test_reset_to_head_clears_modified_files() {
3473        let (_temp_dir, repo_path) = create_test_repo();
3474        let repo = GitRepository::open(&repo_path).unwrap();
3475
3476        // Modify an existing file
3477        std::fs::write(repo_path.join("README.md"), "# Modified content").unwrap();
3478
3479        // Stage the modification
3480        Command::new("git")
3481            .args(["add", "README.md"])
3482            .current_dir(&repo_path)
3483            .output()
3484            .unwrap();
3485
3486        // Verify file is modified and staged
3487        assert!(repo.is_dirty().unwrap(), "Repo should be dirty");
3488
3489        // Reset to HEAD
3490        repo.reset_to_head().unwrap();
3491
3492        // Verify repo is clean
3493        assert!(
3494            !repo.is_dirty().unwrap(),
3495            "Repo should be clean after reset"
3496        );
3497
3498        // Verify file content is restored
3499        let content = std::fs::read_to_string(repo_path.join("README.md")).unwrap();
3500        assert_eq!(
3501            content, "# Test",
3502            "File should be restored to original content"
3503        );
3504    }
3505
3506    #[test]
3507    fn test_reset_to_head_preserves_untracked_files() {
3508        let (_temp_dir, repo_path) = create_test_repo();
3509        let repo = GitRepository::open(&repo_path).unwrap();
3510
3511        // Create untracked file
3512        std::fs::write(repo_path.join("untracked.txt"), "Untracked content").unwrap();
3513
3514        // Stage some other file
3515        std::fs::write(repo_path.join("staged.txt"), "Staged content").unwrap();
3516        Command::new("git")
3517            .args(["add", "staged.txt"])
3518            .current_dir(&repo_path)
3519            .output()
3520            .unwrap();
3521
3522        // Reset to HEAD
3523        repo.reset_to_head().unwrap();
3524
3525        // Verify untracked file still exists
3526        assert!(
3527            repo_path.join("untracked.txt").exists(),
3528            "Untracked file should be preserved"
3529        );
3530
3531        // Verify staged file was removed (since it was never committed)
3532        assert!(
3533            !repo_path.join("staged.txt").exists(),
3534            "Staged but uncommitted file should be removed"
3535        );
3536    }
3537
3538    #[test]
3539    fn test_cherry_pick_does_not_modify_source() {
3540        let (_temp_dir, repo_path) = create_test_repo();
3541        let repo = GitRepository::open(&repo_path).unwrap();
3542
3543        // Create source branch with multiple commits
3544        repo.create_branch("feature", None).unwrap();
3545        repo.checkout_branch("feature").unwrap();
3546
3547        // Add multiple commits
3548        for i in 1..=3 {
3549            std::fs::write(
3550                repo_path.join(format!("file{i}.txt")),
3551                format!("Content {i}"),
3552            )
3553            .unwrap();
3554            Command::new("git")
3555                .args(["add", "."])
3556                .current_dir(&repo_path)
3557                .output()
3558                .unwrap();
3559
3560            Command::new("git")
3561                .args(["commit", "-m", &format!("Commit {i}")])
3562                .current_dir(&repo_path)
3563                .output()
3564                .unwrap();
3565        }
3566
3567        // Get source branch state
3568        let source_commits = Command::new("git")
3569            .args(["log", "--format=%H", "feature"])
3570            .current_dir(&repo_path)
3571            .output()
3572            .unwrap();
3573        let source_state = String::from_utf8_lossy(&source_commits.stdout).to_string();
3574
3575        // Cherry-pick middle commit to another branch
3576        let commits: Vec<&str> = source_state.lines().collect();
3577        let middle_commit = commits[1];
3578
3579        // Go back to previous branch
3580        Command::new("git")
3581            .args(["checkout", "-"])
3582            .current_dir(&repo_path)
3583            .output()
3584            .unwrap();
3585        repo.create_branch("target", None).unwrap();
3586        repo.checkout_branch("target").unwrap();
3587
3588        repo.cherry_pick(middle_commit).unwrap();
3589
3590        // Verify source branch is completely unchanged
3591        let after_commits = Command::new("git")
3592            .args(["log", "--format=%H", "feature"])
3593            .current_dir(&repo_path)
3594            .output()
3595            .unwrap();
3596        let after_state = String::from_utf8_lossy(&after_commits.stdout).to_string();
3597
3598        assert_eq!(
3599            source_state, after_state,
3600            "Source branch should be completely unchanged after cherry-pick"
3601        );
3602    }
3603
3604    #[test]
3605    fn test_detect_parent_branch() {
3606        let (_temp_dir, repo_path) = create_test_repo();
3607        let repo = GitRepository::open(&repo_path).unwrap();
3608
3609        // Create a custom base branch (not just main/master)
3610        repo.create_branch("dev123", None).unwrap();
3611        repo.checkout_branch("dev123").unwrap();
3612        create_commit(&repo_path, "Base commit on dev123", "base.txt");
3613
3614        // Create feature branch from dev123
3615        repo.create_branch("feature-branch", None).unwrap();
3616        repo.checkout_branch("feature-branch").unwrap();
3617        create_commit(&repo_path, "Feature commit", "feature.txt");
3618
3619        // Should detect dev123 as parent since it's the most recent common ancestor
3620        let detected_parent = repo.detect_parent_branch().unwrap();
3621
3622        // The algorithm should find dev123 through either Strategy 2 (default branch)
3623        // or Strategy 3 (common ancestor analysis)
3624        assert!(detected_parent.is_some(), "Should detect a parent branch");
3625
3626        // Since we can't guarantee which strategy will work in the test environment,
3627        // just verify it returns something reasonable
3628        let parent = detected_parent.unwrap();
3629        assert!(
3630            parent == "dev123" || parent == "main" || parent == "master",
3631            "Parent should be dev123, main, or master, got: {parent}"
3632        );
3633    }
3634}