cascade_cli/git/
repository.rs

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