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