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