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, true)
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            tracing::warn!(
1303                "Cherry-pick has conflicts - writing conflicted state to disk for resolution"
1304            );
1305            
1306            // Write the in-memory merge index to the repository's index
1307            // This makes the conflicts visible to Git commands and our auto-resolver
1308            index.write().map_err(CascadeError::Git)?;
1309            
1310            // Checkout the conflicted files to working directory with conflict markers
1311            self.repo
1312                .checkout_index(
1313                    Some(&mut index),
1314                    Some(
1315                        git2::build::CheckoutBuilder::new()
1316                            .allow_conflicts(true)
1317                            .conflict_style_merge(true)
1318                            .force(),
1319                    ),
1320                )
1321                .map_err(CascadeError::Git)?;
1322            
1323            tracing::warn!("Conflicted state written - auto-resolve can now process conflicts");
1324            
1325            return Err(CascadeError::branch(format!(
1326                "Cherry-pick of {commit_hash} has conflicts that need manual resolution"
1327            )));
1328        }
1329
1330        // Write merged tree
1331        let merged_tree_oid = index.write_tree_to(&self.repo).map_err(CascadeError::Git)?;
1332        let merged_tree = self
1333            .repo
1334            .find_tree(merged_tree_oid)
1335            .map_err(CascadeError::Git)?;
1336
1337        // Create new commit with original message (preserve it exactly)
1338        let signature = self.get_signature()?;
1339        let message = commit.message().unwrap_or("Cherry-picked commit");
1340
1341        let new_commit_oid = self
1342            .repo
1343            .commit(
1344                Some("HEAD"),
1345                &signature,
1346                &signature,
1347                message,
1348                &merged_tree,
1349                &[&head_commit],
1350            )
1351            .map_err(CascadeError::Git)?;
1352
1353        // Update working directory to reflect the new commit
1354        let new_commit = self
1355            .repo
1356            .find_commit(new_commit_oid)
1357            .map_err(CascadeError::Git)?;
1358        let new_tree = new_commit.tree().map_err(CascadeError::Git)?;
1359
1360        self.repo
1361            .checkout_tree(
1362                new_tree.as_object(),
1363                Some(git2::build::CheckoutBuilder::new().force()),
1364            )
1365            .map_err(CascadeError::Git)?;
1366
1367        tracing::debug!("Cherry-picked {} -> {}", commit_hash, new_commit_oid);
1368        Ok(new_commit_oid.to_string())
1369    }
1370
1371    /// Check for merge conflicts in the index
1372    pub fn has_conflicts(&self) -> Result<bool> {
1373        let index = self.repo.index().map_err(CascadeError::Git)?;
1374        Ok(index.has_conflicts())
1375    }
1376
1377    /// Get list of conflicted files
1378    pub fn get_conflicted_files(&self) -> Result<Vec<String>> {
1379        let index = self.repo.index().map_err(CascadeError::Git)?;
1380
1381        let mut conflicts = Vec::new();
1382
1383        // Iterate through index conflicts
1384        let conflict_iter = index.conflicts().map_err(CascadeError::Git)?;
1385
1386        for conflict in conflict_iter {
1387            let conflict = conflict.map_err(CascadeError::Git)?;
1388            if let Some(our) = conflict.our {
1389                if let Ok(path) = std::str::from_utf8(&our.path) {
1390                    conflicts.push(path.to_string());
1391                }
1392            } else if let Some(their) = conflict.their {
1393                if let Ok(path) = std::str::from_utf8(&their.path) {
1394                    conflicts.push(path.to_string());
1395                }
1396            }
1397        }
1398
1399        Ok(conflicts)
1400    }
1401
1402    /// Fetch from remote origin
1403    pub fn fetch(&self) -> Result<()> {
1404        tracing::debug!("Fetching from origin");
1405
1406        let mut remote = self
1407            .repo
1408            .find_remote("origin")
1409            .map_err(|e| CascadeError::branch(format!("No remote 'origin' found: {e}")))?;
1410
1411        // Configure callbacks with SSL settings from git config
1412        let callbacks = self.configure_remote_callbacks()?;
1413
1414        // Fetch options with authentication and SSL config
1415        let mut fetch_options = git2::FetchOptions::new();
1416        fetch_options.remote_callbacks(callbacks);
1417
1418        // Fetch with authentication
1419        match remote.fetch::<&str>(&[], Some(&mut fetch_options), None) {
1420            Ok(_) => {
1421                tracing::debug!("Fetch completed successfully");
1422                Ok(())
1423            }
1424            Err(e) => {
1425                if self.should_retry_with_default_credentials(&e) {
1426                    tracing::debug!(
1427                        "Authentication error detected (class: {:?}, code: {:?}): {}, retrying with DefaultCredentials",
1428                        e.class(), e.code(), e
1429                    );
1430
1431                    // Retry with DefaultCredentials for corporate networks
1432                    let callbacks = self.configure_remote_callbacks_with_fallback(true)?;
1433                    let mut fetch_options = git2::FetchOptions::new();
1434                    fetch_options.remote_callbacks(callbacks);
1435
1436                    match remote.fetch::<&str>(&[], Some(&mut fetch_options), None) {
1437                        Ok(_) => {
1438                            tracing::debug!("Fetch succeeded with DefaultCredentials");
1439                            return Ok(());
1440                        }
1441                        Err(retry_error) => {
1442                            tracing::debug!(
1443                                "DefaultCredentials retry failed: {}, falling back to git CLI",
1444                                retry_error
1445                            );
1446                            return self.fetch_with_git_cli();
1447                        }
1448                    }
1449                }
1450
1451                if self.should_fallback_to_git_cli(&e) {
1452                    tracing::debug!(
1453                        "Network/SSL error detected (class: {:?}, code: {:?}): {}, falling back to git CLI for fetch operation",
1454                        e.class(), e.code(), e
1455                    );
1456                    return self.fetch_with_git_cli();
1457                }
1458                Err(CascadeError::Git(e))
1459            }
1460        }
1461    }
1462
1463    /// Pull changes from remote (fetch + merge)
1464    pub fn pull(&self, branch: &str) -> Result<()> {
1465        tracing::debug!("Pulling branch: {}", branch);
1466
1467        // First fetch - this now includes TLS fallback
1468        match self.fetch() {
1469            Ok(_) => {}
1470            Err(e) => {
1471                // If fetch failed even with CLI fallback, try full git pull as last resort
1472                let error_string = e.to_string();
1473                if error_string.contains("TLS stream") || error_string.contains("SSL") {
1474                    tracing::warn!(
1475                        "git2 error detected: {}, falling back to git CLI for pull operation",
1476                        e
1477                    );
1478                    return self.pull_with_git_cli(branch);
1479                }
1480                return Err(e);
1481            }
1482        }
1483
1484        // Get remote tracking branch
1485        let remote_branch_name = format!("origin/{branch}");
1486        let remote_oid = self
1487            .repo
1488            .refname_to_id(&format!("refs/remotes/{remote_branch_name}"))
1489            .map_err(|e| {
1490                CascadeError::branch(format!("Remote branch {remote_branch_name} not found: {e}"))
1491            })?;
1492
1493        let remote_commit = self
1494            .repo
1495            .find_commit(remote_oid)
1496            .map_err(CascadeError::Git)?;
1497
1498        // Get current HEAD
1499        let head_commit = self.get_head_commit()?;
1500
1501        // Check if already up to date
1502        if head_commit.id() == remote_commit.id() {
1503            tracing::debug!("Already up to date");
1504            return Ok(());
1505        }
1506
1507        // Check if we can fast-forward (local is ancestor of remote)
1508        let merge_base_oid = self
1509            .repo
1510            .merge_base(head_commit.id(), remote_commit.id())
1511            .map_err(CascadeError::Git)?;
1512
1513        if merge_base_oid == head_commit.id() {
1514            // Fast-forward: local is direct ancestor of remote, just move pointer
1515            tracing::debug!("Fast-forwarding {} to {}", branch, remote_commit.id());
1516
1517            // Update the branch reference to point to remote commit
1518            let refname = format!("refs/heads/{}", branch);
1519            self.repo
1520                .reference(&refname, remote_oid, true, "pull: Fast-forward")
1521                .map_err(CascadeError::Git)?;
1522
1523            // Update HEAD to point to the new commit
1524            self.repo.set_head(&refname).map_err(CascadeError::Git)?;
1525
1526            // Checkout the new commit (update working directory)
1527            self.repo
1528                .checkout_head(Some(
1529                    git2::build::CheckoutBuilder::new()
1530                        .force()
1531                        .remove_untracked(false),
1532                ))
1533                .map_err(CascadeError::Git)?;
1534
1535            tracing::debug!("Fast-forwarded to {}", remote_commit.id());
1536            return Ok(());
1537        }
1538
1539        // If we can't fast-forward, the local branch has diverged
1540        // This should NOT happen on protected branches!
1541        Err(CascadeError::branch(format!(
1542            "Branch '{}' has diverged from remote. Local has commits not in remote. \
1543             Protected branches should not have local commits. \
1544             Try: git reset --hard origin/{}",
1545            branch, branch
1546        )))
1547    }
1548
1549    /// Push current branch to remote
1550    pub fn push(&self, branch: &str) -> Result<()> {
1551        // Pushing branch to remote
1552
1553        let mut remote = self
1554            .repo
1555            .find_remote("origin")
1556            .map_err(|e| CascadeError::branch(format!("No remote 'origin' found: {e}")))?;
1557
1558        let remote_url = remote.url().unwrap_or("unknown").to_string();
1559        tracing::debug!("Remote URL: {}", remote_url);
1560
1561        let refspec = format!("refs/heads/{branch}:refs/heads/{branch}");
1562        tracing::debug!("Push refspec: {}", refspec);
1563
1564        // Configure callbacks with enhanced SSL settings and error handling
1565        let mut callbacks = self.configure_remote_callbacks()?;
1566
1567        // Add enhanced progress and error callbacks for better debugging
1568        callbacks.push_update_reference(|refname, status| {
1569            if let Some(msg) = status {
1570                tracing::error!("Push failed for ref {}: {}", refname, msg);
1571                return Err(git2::Error::from_str(&format!("Push failed: {msg}")));
1572            }
1573            tracing::debug!("Push succeeded for ref: {}", refname);
1574            Ok(())
1575        });
1576
1577        // Push options with authentication and SSL config
1578        let mut push_options = git2::PushOptions::new();
1579        push_options.remote_callbacks(callbacks);
1580
1581        // Attempt push with enhanced error reporting
1582        match remote.push(&[&refspec], Some(&mut push_options)) {
1583            Ok(_) => {
1584                tracing::info!("Push completed successfully for branch: {}", branch);
1585                Ok(())
1586            }
1587            Err(e) => {
1588                tracing::debug!(
1589                    "git2 push error: {} (class: {:?}, code: {:?})",
1590                    e,
1591                    e.class(),
1592                    e.code()
1593                );
1594
1595                if self.should_retry_with_default_credentials(&e) {
1596                    tracing::debug!(
1597                        "Authentication error detected (class: {:?}, code: {:?}): {}, retrying with DefaultCredentials",
1598                        e.class(), e.code(), e
1599                    );
1600
1601                    // Retry with DefaultCredentials for corporate networks
1602                    let callbacks = self.configure_remote_callbacks_with_fallback(true)?;
1603                    let mut push_options = git2::PushOptions::new();
1604                    push_options.remote_callbacks(callbacks);
1605
1606                    match remote.push(&[&refspec], Some(&mut push_options)) {
1607                        Ok(_) => {
1608                            tracing::debug!("Push succeeded with DefaultCredentials");
1609                            return Ok(());
1610                        }
1611                        Err(retry_error) => {
1612                            tracing::debug!(
1613                                "DefaultCredentials retry failed: {}, falling back to git CLI",
1614                                retry_error
1615                            );
1616                            return self.push_with_git_cli(branch);
1617                        }
1618                    }
1619                }
1620
1621                if self.should_fallback_to_git_cli(&e) {
1622                    tracing::debug!(
1623                        "Network/SSL error detected (class: {:?}, code: {:?}): {}, falling back to git CLI for push operation",
1624                        e.class(), e.code(), e
1625                    );
1626                    return self.push_with_git_cli(branch);
1627                }
1628
1629                // Create concise error message
1630                let error_msg = if e.to_string().contains("authentication") {
1631                    format!(
1632                        "Authentication failed for branch '{branch}'. Try: git push origin {branch}"
1633                    )
1634                } else {
1635                    format!("Failed to push branch '{branch}': {e}")
1636                };
1637
1638                tracing::error!("{}", error_msg);
1639                Err(CascadeError::branch(error_msg))
1640            }
1641        }
1642    }
1643
1644    /// Fallback push method using git CLI instead of git2
1645    /// This is used when git2 has TLS/SSL or auth issues but git CLI works fine
1646    fn push_with_git_cli(&self, branch: &str) -> Result<()> {
1647        // Ensure index is closed before CLI command
1648        self.ensure_index_closed()?;
1649
1650        let output = std::process::Command::new("git")
1651            .args(["push", "origin", branch])
1652            .current_dir(&self.path)
1653            .output()
1654            .map_err(|e| CascadeError::branch(format!("Failed to execute git command: {e}")))?;
1655
1656        if output.status.success() {
1657            // Silent success - no need to log when fallback works
1658            Ok(())
1659        } else {
1660            let stderr = String::from_utf8_lossy(&output.stderr);
1661            let _stdout = String::from_utf8_lossy(&output.stdout);
1662            // Extract the most relevant error message
1663            let error_msg = if stderr.contains("SSL_connect") || stderr.contains("SSL_ERROR") {
1664                "Network error: Unable to connect to repository (VPN may be required)".to_string()
1665            } else if stderr.contains("repository") && stderr.contains("not found") {
1666                "Repository not found - check your Bitbucket configuration".to_string()
1667            } else if stderr.contains("authentication") || stderr.contains("403") {
1668                "Authentication failed - check your credentials".to_string()
1669            } else {
1670                // For other errors, just show the stderr without the verbose prefix
1671                stderr.trim().to_string()
1672            };
1673            tracing::error!("{}", error_msg);
1674            Err(CascadeError::branch(error_msg))
1675        }
1676    }
1677
1678    /// Fallback fetch method using git CLI instead of git2
1679    /// This is used when git2 has TLS/SSL issues but git CLI works fine
1680    fn fetch_with_git_cli(&self) -> Result<()> {
1681        tracing::debug!("Using git CLI fallback for fetch operation");
1682
1683        // Ensure index is closed before CLI command
1684        self.ensure_index_closed()?;
1685
1686        let output = std::process::Command::new("git")
1687            .args(["fetch", "origin"])
1688            .current_dir(&self.path)
1689            .output()
1690            .map_err(|e| {
1691                CascadeError::Git(git2::Error::from_str(&format!(
1692                    "Failed to execute git command: {e}"
1693                )))
1694            })?;
1695
1696        if output.status.success() {
1697            tracing::debug!("Git CLI fetch succeeded");
1698            Ok(())
1699        } else {
1700            let stderr = String::from_utf8_lossy(&output.stderr);
1701            let stdout = String::from_utf8_lossy(&output.stdout);
1702            let error_msg = format!(
1703                "Git CLI fetch failed: {}\nStdout: {}\nStderr: {}",
1704                output.status, stdout, stderr
1705            );
1706            tracing::error!("{}", error_msg);
1707            Err(CascadeError::Git(git2::Error::from_str(&error_msg)))
1708        }
1709    }
1710
1711    /// Fallback pull method using git CLI instead of git2
1712    /// This is used when git2 has TLS/SSL issues but git CLI works fine
1713    fn pull_with_git_cli(&self, branch: &str) -> Result<()> {
1714        tracing::debug!("Using git CLI fallback for pull operation: {}", branch);
1715
1716        // Ensure index is closed before CLI command
1717        self.ensure_index_closed()?;
1718
1719        let output = std::process::Command::new("git")
1720            .args(["pull", "origin", branch])
1721            .current_dir(&self.path)
1722            .output()
1723            .map_err(|e| {
1724                CascadeError::Git(git2::Error::from_str(&format!(
1725                    "Failed to execute git command: {e}"
1726                )))
1727            })?;
1728
1729        if output.status.success() {
1730            tracing::info!("✅ Git CLI pull succeeded for branch: {}", branch);
1731            Ok(())
1732        } else {
1733            let stderr = String::from_utf8_lossy(&output.stderr);
1734            let stdout = String::from_utf8_lossy(&output.stdout);
1735            let error_msg = format!(
1736                "Git CLI pull failed for branch '{}': {}\nStdout: {}\nStderr: {}",
1737                branch, output.status, stdout, stderr
1738            );
1739            tracing::error!("{}", error_msg);
1740            Err(CascadeError::Git(git2::Error::from_str(&error_msg)))
1741        }
1742    }
1743
1744    /// Fallback force push method using git CLI instead of git2
1745    /// This is used when git2 has TLS/SSL issues but git CLI works fine
1746    fn force_push_with_git_cli(&self, branch: &str) -> Result<()> {
1747        tracing::debug!(
1748            "Using git CLI fallback for force push operation: {}",
1749            branch
1750        );
1751
1752        let output = std::process::Command::new("git")
1753            .args(["push", "--force", "origin", branch])
1754            .current_dir(&self.path)
1755            .output()
1756            .map_err(|e| CascadeError::branch(format!("Failed to execute git command: {e}")))?;
1757
1758        if output.status.success() {
1759            tracing::debug!("Git CLI force push succeeded for branch: {}", branch);
1760            Ok(())
1761        } else {
1762            let stderr = String::from_utf8_lossy(&output.stderr);
1763            let stdout = String::from_utf8_lossy(&output.stdout);
1764            let error_msg = format!(
1765                "Git CLI force push failed for branch '{}': {}\nStdout: {}\nStderr: {}",
1766                branch, output.status, stdout, stderr
1767            );
1768            tracing::error!("{}", error_msg);
1769            Err(CascadeError::branch(error_msg))
1770        }
1771    }
1772
1773    /// Delete a local branch
1774    pub fn delete_branch(&self, name: &str) -> Result<()> {
1775        self.delete_branch_with_options(name, false)
1776    }
1777
1778    /// Delete a local branch with force option to bypass safety checks
1779    pub fn delete_branch_unsafe(&self, name: &str) -> Result<()> {
1780        self.delete_branch_with_options(name, true)
1781    }
1782
1783    /// Internal branch deletion implementation with safety options
1784    fn delete_branch_with_options(&self, name: &str, force_unsafe: bool) -> Result<()> {
1785        debug!("Attempting to delete branch: {}", name);
1786
1787        // Enhanced safety check: Detect unpushed commits before deletion
1788        if !force_unsafe {
1789            let safety_result = self.check_branch_deletion_safety(name)?;
1790            if let Some(safety_info) = safety_result {
1791                // Branch has unpushed commits, get user confirmation
1792                self.handle_branch_deletion_confirmation(name, &safety_info)?;
1793            }
1794        }
1795
1796        let mut branch = self
1797            .repo
1798            .find_branch(name, git2::BranchType::Local)
1799            .map_err(|e| CascadeError::branch(format!("Could not find branch '{name}': {e}")))?;
1800
1801        branch
1802            .delete()
1803            .map_err(|e| CascadeError::branch(format!("Could not delete branch '{name}': {e}")))?;
1804
1805        debug!("Successfully deleted branch '{}'", name);
1806        Ok(())
1807    }
1808
1809    /// Get commits between two references
1810    pub fn get_commits_between(&self, from: &str, to: &str) -> Result<Vec<git2::Commit<'_>>> {
1811        let from_oid = self
1812            .repo
1813            .refname_to_id(&format!("refs/heads/{from}"))
1814            .or_else(|_| Oid::from_str(from))
1815            .map_err(|e| CascadeError::branch(format!("Invalid from reference '{from}': {e}")))?;
1816
1817        let to_oid = self
1818            .repo
1819            .refname_to_id(&format!("refs/heads/{to}"))
1820            .or_else(|_| Oid::from_str(to))
1821            .map_err(|e| CascadeError::branch(format!("Invalid to reference '{to}': {e}")))?;
1822
1823        let mut revwalk = self.repo.revwalk().map_err(CascadeError::Git)?;
1824
1825        revwalk.push(to_oid).map_err(CascadeError::Git)?;
1826        revwalk.hide(from_oid).map_err(CascadeError::Git)?;
1827
1828        let mut commits = Vec::new();
1829        for oid in revwalk {
1830            let oid = oid.map_err(CascadeError::Git)?;
1831            let commit = self.repo.find_commit(oid).map_err(CascadeError::Git)?;
1832            commits.push(commit);
1833        }
1834
1835        Ok(commits)
1836    }
1837
1838    /// Force push one branch's content to another branch name
1839    /// This is used to preserve PR history while updating branch contents after rebase
1840    pub fn force_push_branch(&self, target_branch: &str, source_branch: &str) -> Result<()> {
1841        self.force_push_branch_with_options(target_branch, source_branch, false)
1842    }
1843
1844    /// Force push with explicit force flag to bypass safety checks
1845    pub fn force_push_branch_unsafe(&self, target_branch: &str, source_branch: &str) -> Result<()> {
1846        self.force_push_branch_with_options(target_branch, source_branch, true)
1847    }
1848
1849    /// Internal force push implementation with safety options
1850    fn force_push_branch_with_options(
1851        &self,
1852        target_branch: &str,
1853        source_branch: &str,
1854        force_unsafe: bool,
1855    ) -> Result<()> {
1856        debug!(
1857            "Force pushing {} content to {} to preserve PR history",
1858            source_branch, target_branch
1859        );
1860
1861        // Enhanced safety check: Detect potential data loss and get user confirmation
1862        if !force_unsafe {
1863            let safety_result = self.check_force_push_safety_enhanced(target_branch)?;
1864            if let Some(backup_info) = safety_result {
1865                // Create backup branch before force push
1866                self.create_backup_branch(target_branch, &backup_info.remote_commit_id)?;
1867                debug!("Created backup branch: {}", backup_info.backup_branch_name);
1868            }
1869        }
1870
1871        // First, ensure we have the latest changes for the source branch
1872        let source_ref = self
1873            .repo
1874            .find_reference(&format!("refs/heads/{source_branch}"))
1875            .map_err(|e| {
1876                CascadeError::config(format!("Failed to find source branch {source_branch}: {e}"))
1877            })?;
1878        let _source_commit = source_ref.peel_to_commit().map_err(|e| {
1879            CascadeError::config(format!(
1880                "Failed to get commit for source branch {source_branch}: {e}"
1881            ))
1882        })?;
1883
1884        // Force push to remote without modifying local target branch
1885        let mut remote = self
1886            .repo
1887            .find_remote("origin")
1888            .map_err(|e| CascadeError::config(format!("Failed to find origin remote: {e}")))?;
1889
1890        // Push source branch content to remote target branch
1891        let refspec = format!("+refs/heads/{source_branch}:refs/heads/{target_branch}");
1892
1893        // Configure callbacks with SSL settings from git config
1894        let callbacks = self.configure_remote_callbacks()?;
1895
1896        // Push options for force push with SSL config
1897        let mut push_options = git2::PushOptions::new();
1898        push_options.remote_callbacks(callbacks);
1899
1900        match remote.push(&[&refspec], Some(&mut push_options)) {
1901            Ok(_) => {}
1902            Err(e) => {
1903                if self.should_retry_with_default_credentials(&e) {
1904                    tracing::debug!(
1905                        "Authentication error detected (class: {:?}, code: {:?}): {}, retrying with DefaultCredentials",
1906                        e.class(), e.code(), e
1907                    );
1908
1909                    // Retry with DefaultCredentials for corporate networks
1910                    let callbacks = self.configure_remote_callbacks_with_fallback(true)?;
1911                    let mut push_options = git2::PushOptions::new();
1912                    push_options.remote_callbacks(callbacks);
1913
1914                    match remote.push(&[&refspec], Some(&mut push_options)) {
1915                        Ok(_) => {
1916                            tracing::debug!("Force push succeeded with DefaultCredentials");
1917                            // Success - continue to normal success path
1918                        }
1919                        Err(retry_error) => {
1920                            tracing::debug!(
1921                                "DefaultCredentials retry failed: {}, falling back to git CLI",
1922                                retry_error
1923                            );
1924                            return self.force_push_with_git_cli(target_branch);
1925                        }
1926                    }
1927                } else if self.should_fallback_to_git_cli(&e) {
1928                    tracing::debug!(
1929                        "Network/SSL error detected (class: {:?}, code: {:?}): {}, falling back to git CLI for force push operation",
1930                        e.class(), e.code(), e
1931                    );
1932                    return self.force_push_with_git_cli(target_branch);
1933                } else {
1934                    return Err(CascadeError::config(format!(
1935                        "Failed to force push {target_branch}: {e}"
1936                    )));
1937                }
1938            }
1939        }
1940
1941        info!(
1942            "✅ Successfully force pushed {} to preserve PR history",
1943            target_branch
1944        );
1945        Ok(())
1946    }
1947
1948    /// Enhanced safety check for force push operations with user confirmation
1949    /// Returns backup info if data would be lost and user confirms
1950    fn check_force_push_safety_enhanced(
1951        &self,
1952        target_branch: &str,
1953    ) -> Result<Option<ForceBackupInfo>> {
1954        // First fetch latest remote changes to ensure we have up-to-date information
1955        match self.fetch() {
1956            Ok(_) => {}
1957            Err(e) => {
1958                // If fetch fails, warn but don't block the operation
1959                warn!("Could not fetch latest changes for safety check: {}", e);
1960            }
1961        }
1962
1963        // Check if there are commits on the remote that would be lost
1964        let remote_ref = format!("refs/remotes/origin/{target_branch}");
1965        let local_ref = format!("refs/heads/{target_branch}");
1966
1967        // Try to find both local and remote references
1968        let local_commit = match self.repo.find_reference(&local_ref) {
1969            Ok(reference) => reference.peel_to_commit().ok(),
1970            Err(_) => None,
1971        };
1972
1973        let remote_commit = match self.repo.find_reference(&remote_ref) {
1974            Ok(reference) => reference.peel_to_commit().ok(),
1975            Err(_) => None,
1976        };
1977
1978        // If we have both commits, check for divergence
1979        if let (Some(local), Some(remote)) = (local_commit, remote_commit) {
1980            if local.id() != remote.id() {
1981                // Check if the remote has commits that the local doesn't have
1982                let merge_base_oid = self
1983                    .repo
1984                    .merge_base(local.id(), remote.id())
1985                    .map_err(|e| CascadeError::config(format!("Failed to find merge base: {e}")))?;
1986
1987                // If merge base != remote commit, remote has commits that would be lost
1988                if merge_base_oid != remote.id() {
1989                    let commits_to_lose = self.count_commits_between(
1990                        &merge_base_oid.to_string(),
1991                        &remote.id().to_string(),
1992                    )?;
1993
1994                    // Create backup branch name with timestamp
1995                    let timestamp = chrono::Utc::now().format("%Y%m%d_%H%M%S");
1996                    let backup_branch_name = format!("{target_branch}_backup_{timestamp}");
1997
1998                    debug!(
1999                        "Force push to '{}' would overwrite {} commits on remote",
2000                        target_branch, commits_to_lose
2001                    );
2002
2003                    // Check if we're in a non-interactive environment (CI/testing)
2004                    if std::env::var("CI").is_ok() || std::env::var("FORCE_PUSH_NO_CONFIRM").is_ok()
2005                    {
2006                        info!(
2007                            "Non-interactive environment detected, proceeding with backup creation"
2008                        );
2009                        return Ok(Some(ForceBackupInfo {
2010                            backup_branch_name,
2011                            remote_commit_id: remote.id().to_string(),
2012                            commits_that_would_be_lost: commits_to_lose,
2013                        }));
2014                    }
2015
2016                    // Interactive confirmation
2017                    println!();
2018                    Output::warning("FORCE PUSH WARNING");
2019                    println!("Force push to '{target_branch}' would overwrite {commits_to_lose} commits on remote:");
2020
2021                    // Show the commits that would be lost
2022                    match self
2023                        .get_commits_between(&merge_base_oid.to_string(), &remote.id().to_string())
2024                    {
2025                        Ok(commits) => {
2026                            println!();
2027                            println!("Commits that would be lost:");
2028                            for (i, commit) in commits.iter().take(5).enumerate() {
2029                                let short_hash = &commit.id().to_string()[..8];
2030                                let summary = commit.summary().unwrap_or("<no message>");
2031                                println!("  {}. {} - {}", i + 1, short_hash, summary);
2032                            }
2033                            if commits.len() > 5 {
2034                                println!("  ... and {} more commits", commits.len() - 5);
2035                            }
2036                        }
2037                        Err(_) => {
2038                            println!("  (Unable to retrieve commit details)");
2039                        }
2040                    }
2041
2042                    println!();
2043                    Output::info(format!(
2044                        "A backup branch '{backup_branch_name}' will be created before proceeding."
2045                    ));
2046
2047                    let confirmed = Confirm::with_theme(&ColorfulTheme::default())
2048                        .with_prompt("Do you want to proceed with the force push?")
2049                        .default(false)
2050                        .interact()
2051                        .map_err(|e| {
2052                            CascadeError::config(format!("Failed to get user confirmation: {e}"))
2053                        })?;
2054
2055                    if !confirmed {
2056                        return Err(CascadeError::config(
2057                            "Force push cancelled by user. Use --force to bypass this check."
2058                                .to_string(),
2059                        ));
2060                    }
2061
2062                    return Ok(Some(ForceBackupInfo {
2063                        backup_branch_name,
2064                        remote_commit_id: remote.id().to_string(),
2065                        commits_that_would_be_lost: commits_to_lose,
2066                    }));
2067                }
2068            }
2069        }
2070
2071        Ok(None)
2072    }
2073
2074    /// Check if two commit histories represent a rebase scenario
2075    /// Returns true if the commit messages match, indicating content is preserved
2076    fn is_likely_rebase_scenario(&self, local_oid: &str, remote_oid: &str) -> bool {
2077        // Get commits from both branches
2078        let local_oid_parsed = match git2::Oid::from_str(local_oid) {
2079            Ok(oid) => oid,
2080            Err(_) => return false,
2081        };
2082
2083        let remote_oid_parsed = match git2::Oid::from_str(remote_oid) {
2084            Ok(oid) => oid,
2085            Err(_) => return false,
2086        };
2087
2088        let local_commit = match self.repo.find_commit(local_oid_parsed) {
2089            Ok(c) => c,
2090            Err(_) => return false,
2091        };
2092
2093        let remote_commit = match self.repo.find_commit(remote_oid_parsed) {
2094            Ok(c) => c,
2095            Err(_) => return false,
2096        };
2097
2098        // Compare commit messages - if they match, it's likely a rebase
2099        let local_msg = local_commit.message().unwrap_or("");
2100        let remote_msg = remote_commit.message().unwrap_or("");
2101
2102        // If the top commit messages match, this is very likely a rebase
2103        if local_msg == remote_msg {
2104            return true;
2105        }
2106
2107        // Also check if local has same number of commits with matching messages
2108        // This handles multi-commit rebases
2109        let local_count = local_commit.parent_count();
2110        let remote_count = remote_commit.parent_count();
2111
2112        if local_count == remote_count && local_count > 0 {
2113            // Walk back and compare messages
2114            let mut local_walker = match self.repo.revwalk() {
2115                Ok(w) => w,
2116                Err(_) => return false,
2117            };
2118            let mut remote_walker = match self.repo.revwalk() {
2119                Ok(w) => w,
2120                Err(_) => return false,
2121            };
2122
2123            if local_walker.push(local_commit.id()).is_err() {
2124                return false;
2125            }
2126            if remote_walker.push(remote_commit.id()).is_err() {
2127                return false;
2128            }
2129
2130            let local_messages: Vec<String> = local_walker
2131                .take(5) // Check first 5 commits
2132                .filter_map(|oid| {
2133                    self.repo
2134                        .find_commit(oid.ok()?)
2135                        .ok()?
2136                        .message()
2137                        .map(|s| s.to_string())
2138                })
2139                .collect();
2140
2141            let remote_messages: Vec<String> = remote_walker
2142                .take(5)
2143                .filter_map(|oid| {
2144                    self.repo
2145                        .find_commit(oid.ok()?)
2146                        .ok()?
2147                        .message()
2148                        .map(|s| s.to_string())
2149                })
2150                .collect();
2151
2152            // If most messages match, it's a rebase
2153            let matches = local_messages
2154                .iter()
2155                .zip(remote_messages.iter())
2156                .filter(|(l, r)| l == r)
2157                .count();
2158
2159            return matches >= local_messages.len() / 2;
2160        }
2161
2162        false
2163    }
2164
2165    /// Check force push safety without user confirmation (auto-creates backup)
2166    /// Used for automated operations like sync where user already confirmed the operation
2167    fn check_force_push_safety_auto(&self, target_branch: &str) -> Result<Option<ForceBackupInfo>> {
2168        // First fetch latest remote changes to ensure we have up-to-date information
2169        match self.fetch() {
2170            Ok(_) => {}
2171            Err(e) => {
2172                warn!("Could not fetch latest changes for safety check: {}", e);
2173            }
2174        }
2175
2176        // Check if there are commits on the remote that would be lost
2177        let remote_ref = format!("refs/remotes/origin/{target_branch}");
2178        let local_ref = format!("refs/heads/{target_branch}");
2179
2180        // Try to find both local and remote references
2181        let local_commit = match self.repo.find_reference(&local_ref) {
2182            Ok(reference) => reference.peel_to_commit().ok(),
2183            Err(_) => None,
2184        };
2185
2186        let remote_commit = match self.repo.find_reference(&remote_ref) {
2187            Ok(reference) => reference.peel_to_commit().ok(),
2188            Err(_) => None,
2189        };
2190
2191        // If we have both commits, check for divergence
2192        if let (Some(local), Some(remote)) = (local_commit, remote_commit) {
2193            if local.id() != remote.id() {
2194                // Check if the remote has commits that the local doesn't have
2195                let merge_base_oid = self
2196                    .repo
2197                    .merge_base(local.id(), remote.id())
2198                    .map_err(|e| CascadeError::config(format!("Failed to find merge base: {e}")))?;
2199
2200                // If merge base != remote commit, remote has commits that would be lost
2201                if merge_base_oid != remote.id() {
2202                    // Check if this is a rebase scenario (same commit messages, different hashes)
2203                    // This is the expected behavior for stacked diffs and doesn't need scary warnings
2204                    let is_likely_rebase = self.is_likely_rebase_scenario(
2205                        &local.id().to_string(),
2206                        &remote.id().to_string(),
2207                    );
2208
2209                    if is_likely_rebase {
2210                        debug!(
2211                            "Detected rebase scenario for '{}' - skipping backup (commit content preserved)",
2212                            target_branch
2213                        );
2214                        // No backup needed - this is a normal rebase with preserved content
2215                        return Ok(None);
2216                    }
2217
2218                    let commits_to_lose = self.count_commits_between(
2219                        &merge_base_oid.to_string(),
2220                        &remote.id().to_string(),
2221                    )?;
2222
2223                    // Create backup branch name with timestamp
2224                    let timestamp = chrono::Utc::now().format("%Y%m%d_%H%M%S");
2225                    let backup_branch_name = format!("{target_branch}_backup_{timestamp}");
2226
2227                    debug!(
2228                        "Auto-creating backup for force push to '{}' (would overwrite {} commits)",
2229                        target_branch, commits_to_lose
2230                    );
2231
2232                    // Automatically create backup without confirmation
2233                    return Ok(Some(ForceBackupInfo {
2234                        backup_branch_name,
2235                        remote_commit_id: remote.id().to_string(),
2236                        commits_that_would_be_lost: commits_to_lose,
2237                    }));
2238                }
2239            }
2240        }
2241
2242        Ok(None)
2243    }
2244
2245    /// Create a backup branch pointing to the remote commit that would be lost
2246    fn create_backup_branch(&self, original_branch: &str, remote_commit_id: &str) -> Result<()> {
2247        let timestamp = chrono::Utc::now().format("%Y%m%d_%H%M%S");
2248        let backup_branch_name = format!("{original_branch}_backup_{timestamp}");
2249
2250        // Parse the commit ID
2251        let commit_oid = Oid::from_str(remote_commit_id).map_err(|e| {
2252            CascadeError::config(format!("Invalid commit ID {remote_commit_id}: {e}"))
2253        })?;
2254
2255        // Find the commit
2256        let commit = self.repo.find_commit(commit_oid).map_err(|e| {
2257            CascadeError::config(format!("Failed to find commit {remote_commit_id}: {e}"))
2258        })?;
2259
2260        // Create the backup branch
2261        self.repo
2262            .branch(&backup_branch_name, &commit, false)
2263            .map_err(|e| {
2264                CascadeError::config(format!(
2265                    "Failed to create backup branch {backup_branch_name}: {e}"
2266                ))
2267            })?;
2268
2269        debug!(
2270            "Created backup branch '{}' pointing to {}",
2271            backup_branch_name,
2272            &remote_commit_id[..8]
2273        );
2274        Ok(())
2275    }
2276
2277    /// Check if branch deletion is safe by detecting unpushed commits
2278    /// Returns safety info if there are concerns that need user attention
2279    fn check_branch_deletion_safety(
2280        &self,
2281        branch_name: &str,
2282    ) -> Result<Option<BranchDeletionSafety>> {
2283        // First, try to fetch latest remote changes
2284        match self.fetch() {
2285            Ok(_) => {}
2286            Err(e) => {
2287                warn!(
2288                    "Could not fetch latest changes for branch deletion safety check: {}",
2289                    e
2290                );
2291            }
2292        }
2293
2294        // Find the branch
2295        let branch = self
2296            .repo
2297            .find_branch(branch_name, git2::BranchType::Local)
2298            .map_err(|e| {
2299                CascadeError::branch(format!("Could not find branch '{branch_name}': {e}"))
2300            })?;
2301
2302        let _branch_commit = branch.get().peel_to_commit().map_err(|e| {
2303            CascadeError::branch(format!(
2304                "Could not get commit for branch '{branch_name}': {e}"
2305            ))
2306        })?;
2307
2308        // Determine the main branch (try common names)
2309        let main_branch_name = self.detect_main_branch()?;
2310
2311        // Check if branch is merged to main
2312        let is_merged_to_main = self.is_branch_merged_to_main(branch_name, &main_branch_name)?;
2313
2314        // Find the upstream/remote tracking branch
2315        let remote_tracking_branch = self.get_remote_tracking_branch(branch_name);
2316
2317        let mut unpushed_commits = Vec::new();
2318
2319        // Check for unpushed commits compared to remote tracking branch
2320        if let Some(ref remote_branch) = remote_tracking_branch {
2321            match self.get_commits_between(remote_branch, branch_name) {
2322                Ok(commits) => {
2323                    unpushed_commits = commits.iter().map(|c| c.id().to_string()).collect();
2324                }
2325                Err(_) => {
2326                    // If we can't compare with remote, check against main branch
2327                    if !is_merged_to_main {
2328                        if let Ok(commits) =
2329                            self.get_commits_between(&main_branch_name, branch_name)
2330                        {
2331                            unpushed_commits = commits.iter().map(|c| c.id().to_string()).collect();
2332                        }
2333                    }
2334                }
2335            }
2336        } else if !is_merged_to_main {
2337            // No remote tracking branch, check against main
2338            if let Ok(commits) = self.get_commits_between(&main_branch_name, branch_name) {
2339                unpushed_commits = commits.iter().map(|c| c.id().to_string()).collect();
2340            }
2341        }
2342
2343        // If there are concerns, return safety info
2344        if !unpushed_commits.is_empty() || (!is_merged_to_main && remote_tracking_branch.is_none())
2345        {
2346            Ok(Some(BranchDeletionSafety {
2347                unpushed_commits,
2348                remote_tracking_branch,
2349                is_merged_to_main,
2350                main_branch_name,
2351            }))
2352        } else {
2353            Ok(None)
2354        }
2355    }
2356
2357    /// Handle user confirmation for branch deletion with safety concerns
2358    fn handle_branch_deletion_confirmation(
2359        &self,
2360        branch_name: &str,
2361        safety_info: &BranchDeletionSafety,
2362    ) -> Result<()> {
2363        // Check if we're in a non-interactive environment
2364        if std::env::var("CI").is_ok() || std::env::var("BRANCH_DELETE_NO_CONFIRM").is_ok() {
2365            return Err(CascadeError::branch(
2366                format!(
2367                    "Branch '{branch_name}' has {} unpushed commits and cannot be deleted in non-interactive mode. Use --force to override.",
2368                    safety_info.unpushed_commits.len()
2369                )
2370            ));
2371        }
2372
2373        // Interactive warning and confirmation
2374        println!();
2375        Output::warning("BRANCH DELETION WARNING");
2376        println!("Branch '{branch_name}' has potential issues:");
2377
2378        if !safety_info.unpushed_commits.is_empty() {
2379            println!(
2380                "\n🔍 Unpushed commits ({} total):",
2381                safety_info.unpushed_commits.len()
2382            );
2383
2384            // Show details of unpushed commits
2385            for (i, commit_id) in safety_info.unpushed_commits.iter().take(5).enumerate() {
2386                if let Ok(oid) = Oid::from_str(commit_id) {
2387                    if let Ok(commit) = self.repo.find_commit(oid) {
2388                        let short_hash = &commit_id[..8];
2389                        let summary = commit.summary().unwrap_or("<no message>");
2390                        println!("  {}. {} - {}", i + 1, short_hash, summary);
2391                    }
2392                }
2393            }
2394
2395            if safety_info.unpushed_commits.len() > 5 {
2396                println!(
2397                    "  ... and {} more commits",
2398                    safety_info.unpushed_commits.len() - 5
2399                );
2400            }
2401        }
2402
2403        if !safety_info.is_merged_to_main {
2404            println!("\n📋 Branch status:");
2405            println!("  • Not merged to '{}'", safety_info.main_branch_name);
2406            if let Some(ref remote) = safety_info.remote_tracking_branch {
2407                println!("  • Remote tracking branch: {remote}");
2408            } else {
2409                println!("  • No remote tracking branch");
2410            }
2411        }
2412
2413        println!("\n💡 Safer alternatives:");
2414        if !safety_info.unpushed_commits.is_empty() {
2415            if let Some(ref _remote) = safety_info.remote_tracking_branch {
2416                println!("  • Push commits first: git push origin {branch_name}");
2417            } else {
2418                println!("  • Create and push to remote: git push -u origin {branch_name}");
2419            }
2420        }
2421        if !safety_info.is_merged_to_main {
2422            println!(
2423                "  • Merge to {} first: git checkout {} && git merge {branch_name}",
2424                safety_info.main_branch_name, safety_info.main_branch_name
2425            );
2426        }
2427
2428        let confirmed = Confirm::with_theme(&ColorfulTheme::default())
2429            .with_prompt("Do you want to proceed with deleting this branch?")
2430            .default(false)
2431            .interact()
2432            .map_err(|e| CascadeError::branch(format!("Failed to get user confirmation: {e}")))?;
2433
2434        if !confirmed {
2435            return Err(CascadeError::branch(
2436                "Branch deletion cancelled by user. Use --force to bypass this check.".to_string(),
2437            ));
2438        }
2439
2440        Ok(())
2441    }
2442
2443    /// Detect the main branch name (main, master, develop)
2444    pub fn detect_main_branch(&self) -> Result<String> {
2445        let main_candidates = ["main", "master", "develop", "trunk"];
2446
2447        for candidate in &main_candidates {
2448            if self
2449                .repo
2450                .find_branch(candidate, git2::BranchType::Local)
2451                .is_ok()
2452            {
2453                return Ok(candidate.to_string());
2454            }
2455        }
2456
2457        // Fallback to HEAD's target if it's a symbolic reference
2458        if let Ok(head) = self.repo.head() {
2459            if let Some(name) = head.shorthand() {
2460                return Ok(name.to_string());
2461            }
2462        }
2463
2464        // Final fallback
2465        Ok("main".to_string())
2466    }
2467
2468    /// Check if a branch is merged to the main branch
2469    fn is_branch_merged_to_main(&self, branch_name: &str, main_branch: &str) -> Result<bool> {
2470        // Get the commits between main and the branch
2471        match self.get_commits_between(main_branch, branch_name) {
2472            Ok(commits) => Ok(commits.is_empty()),
2473            Err(_) => {
2474                // If we can't determine, assume not merged for safety
2475                Ok(false)
2476            }
2477        }
2478    }
2479
2480    /// Get the remote tracking branch for a local branch
2481    fn get_remote_tracking_branch(&self, branch_name: &str) -> Option<String> {
2482        // Try common remote tracking branch patterns
2483        let remote_candidates = [
2484            format!("origin/{branch_name}"),
2485            format!("remotes/origin/{branch_name}"),
2486        ];
2487
2488        for candidate in &remote_candidates {
2489            if self
2490                .repo
2491                .find_reference(&format!(
2492                    "refs/remotes/{}",
2493                    candidate.replace("remotes/", "")
2494                ))
2495                .is_ok()
2496            {
2497                return Some(candidate.clone());
2498            }
2499        }
2500
2501        None
2502    }
2503
2504    /// Check if checkout operation is safe
2505    fn check_checkout_safety(&self, _target: &str) -> Result<Option<CheckoutSafety>> {
2506        // Check if there are uncommitted changes
2507        let is_dirty = self.is_dirty()?;
2508        if !is_dirty {
2509            // No uncommitted changes, checkout is safe
2510            return Ok(None);
2511        }
2512
2513        // Get current branch for context
2514        let current_branch = self.get_current_branch().ok();
2515
2516        // Get detailed information about uncommitted changes
2517        let modified_files = self.get_modified_files()?;
2518        let staged_files = self.get_staged_files()?;
2519        let untracked_files = self.get_untracked_files()?;
2520
2521        let has_uncommitted_changes = !modified_files.is_empty() || !staged_files.is_empty();
2522
2523        if has_uncommitted_changes || !untracked_files.is_empty() {
2524            return Ok(Some(CheckoutSafety {
2525                has_uncommitted_changes,
2526                modified_files,
2527                staged_files,
2528                untracked_files,
2529                stash_created: None,
2530                current_branch,
2531            }));
2532        }
2533
2534        Ok(None)
2535    }
2536
2537    /// Handle user confirmation for checkout operations with uncommitted changes
2538    fn handle_checkout_confirmation(
2539        &self,
2540        target: &str,
2541        safety_info: &CheckoutSafety,
2542    ) -> Result<()> {
2543        // Check if we're in a non-interactive environment FIRST (before any output)
2544        let is_ci = std::env::var("CI").is_ok();
2545        let no_confirm = std::env::var("CHECKOUT_NO_CONFIRM").is_ok();
2546        let is_non_interactive = is_ci || no_confirm;
2547
2548        if is_non_interactive {
2549            return Err(CascadeError::branch(
2550                format!(
2551                    "Cannot checkout '{target}' with uncommitted changes in non-interactive mode. Commit your changes or use stash first."
2552                )
2553            ));
2554        }
2555
2556        // Interactive warning and confirmation
2557        println!("\nCHECKOUT WARNING");
2558        println!("Attempting to checkout: {}", target);
2559        println!("You have uncommitted changes that could be lost:");
2560
2561        if !safety_info.modified_files.is_empty() {
2562            println!("\nModified files ({}):", safety_info.modified_files.len());
2563            for file in safety_info.modified_files.iter().take(10) {
2564                println!("   - {file}");
2565            }
2566            if safety_info.modified_files.len() > 10 {
2567                println!("   ... and {} more", safety_info.modified_files.len() - 10);
2568            }
2569        }
2570
2571        if !safety_info.staged_files.is_empty() {
2572            println!("\nStaged files ({}):", safety_info.staged_files.len());
2573            for file in safety_info.staged_files.iter().take(10) {
2574                println!("   - {file}");
2575            }
2576            if safety_info.staged_files.len() > 10 {
2577                println!("   ... and {} more", safety_info.staged_files.len() - 10);
2578            }
2579        }
2580
2581        if !safety_info.untracked_files.is_empty() {
2582            println!("\nUntracked files ({}):", safety_info.untracked_files.len());
2583            for file in safety_info.untracked_files.iter().take(5) {
2584                println!("   - {file}");
2585            }
2586            if safety_info.untracked_files.len() > 5 {
2587                println!("   ... and {} more", safety_info.untracked_files.len() - 5);
2588            }
2589        }
2590
2591        println!("\nOptions:");
2592        println!("1. Stash changes and checkout (recommended)");
2593        println!("2. Force checkout (WILL LOSE UNCOMMITTED CHANGES)");
2594        println!("3. Cancel checkout");
2595
2596        // Use proper selection dialog instead of y/n confirmation
2597        let selection = Select::with_theme(&ColorfulTheme::default())
2598            .with_prompt("Choose an action")
2599            .items(&[
2600                "Stash changes and checkout (recommended)",
2601                "Force checkout (WILL LOSE UNCOMMITTED CHANGES)",
2602                "Cancel checkout",
2603            ])
2604            .default(0)
2605            .interact()
2606            .map_err(|e| CascadeError::branch(format!("Could not get user selection: {e}")))?;
2607
2608        match selection {
2609            0 => {
2610                // Option 1: Stash changes and checkout
2611                let stash_message = format!(
2612                    "Auto-stash before checkout to {} at {}",
2613                    target,
2614                    chrono::Utc::now().format("%Y-%m-%d %H:%M:%S UTC")
2615                );
2616
2617                match self.create_stash(&stash_message) {
2618                    Ok(stash_id) => {
2619                        println!("✅ Created stash: {stash_message} ({stash_id})");
2620                        println!("💡 You can restore with: git stash pop");
2621                    }
2622                    Err(e) => {
2623                        println!("❌ Failed to create stash: {e}");
2624
2625                        // If stash failed, provide better options
2626                        use dialoguer::Select;
2627                        let stash_failed_options = vec![
2628                            "Commit staged changes and proceed",
2629                            "Force checkout (WILL LOSE CHANGES)",
2630                            "Cancel and handle manually",
2631                        ];
2632
2633                        let stash_selection = Select::with_theme(&ColorfulTheme::default())
2634                            .with_prompt("Stash failed. What would you like to do?")
2635                            .items(&stash_failed_options)
2636                            .default(0)
2637                            .interact()
2638                            .map_err(|e| {
2639                                CascadeError::branch(format!("Could not get user selection: {e}"))
2640                            })?;
2641
2642                        match stash_selection {
2643                            0 => {
2644                                // Try to commit staged changes
2645                                let staged_files = self.get_staged_files()?;
2646                                if !staged_files.is_empty() {
2647                                    println!(
2648                                        "📝 Committing {} staged files...",
2649                                        staged_files.len()
2650                                    );
2651                                    match self
2652                                        .commit_staged_changes("WIP: Auto-commit before checkout")
2653                                    {
2654                                        Ok(Some(commit_hash)) => {
2655                                            println!(
2656                                                "✅ Committed staged changes as {}",
2657                                                &commit_hash[..8]
2658                                            );
2659                                            println!("💡 You can undo with: git reset HEAD~1");
2660                                        }
2661                                        Ok(None) => {
2662                                            println!("ℹ️  No staged changes found to commit");
2663                                        }
2664                                        Err(commit_err) => {
2665                                            println!(
2666                                                "❌ Failed to commit staged changes: {commit_err}"
2667                                            );
2668                                            return Err(CascadeError::branch(
2669                                                "Could not commit staged changes".to_string(),
2670                                            ));
2671                                        }
2672                                    }
2673                                } else {
2674                                    println!("ℹ️  No staged changes to commit");
2675                                }
2676                            }
2677                            1 => {
2678                                // Force checkout anyway
2679                                Output::warning("Proceeding with force checkout - uncommitted changes will be lost!");
2680                            }
2681                            2 => {
2682                                // Cancel
2683                                return Err(CascadeError::branch(
2684                                    "Checkout cancelled. Please handle changes manually and try again.".to_string(),
2685                                ));
2686                            }
2687                            _ => unreachable!(),
2688                        }
2689                    }
2690                }
2691            }
2692            1 => {
2693                // Option 2: Force checkout (lose changes)
2694                Output::warning(
2695                    "Proceeding with force checkout - uncommitted changes will be lost!",
2696                );
2697            }
2698            2 => {
2699                // Option 3: Cancel
2700                return Err(CascadeError::branch(
2701                    "Checkout cancelled by user".to_string(),
2702                ));
2703            }
2704            _ => unreachable!(),
2705        }
2706
2707        Ok(())
2708    }
2709
2710    /// Create a stash with uncommitted changes
2711    fn create_stash(&self, message: &str) -> Result<String> {
2712        tracing::info!("Creating stash: {}", message);
2713
2714        // Use git CLI for stashing since git2 stashing is complex and unreliable
2715        let output = std::process::Command::new("git")
2716            .args(["stash", "push", "-m", message])
2717            .current_dir(&self.path)
2718            .output()
2719            .map_err(|e| {
2720                CascadeError::branch(format!("Failed to execute git stash command: {e}"))
2721            })?;
2722
2723        if output.status.success() {
2724            let stdout = String::from_utf8_lossy(&output.stdout);
2725
2726            // Extract stash hash if available (git stash outputs like "Saved working directory and index state WIP on branch: message")
2727            let stash_id = if stdout.contains("Saved working directory") {
2728                // Get the most recent stash ID
2729                let stash_list_output = std::process::Command::new("git")
2730                    .args(["stash", "list", "-n", "1", "--format=%H"])
2731                    .current_dir(&self.path)
2732                    .output()
2733                    .map_err(|e| CascadeError::branch(format!("Failed to get stash ID: {e}")))?;
2734
2735                if stash_list_output.status.success() {
2736                    String::from_utf8_lossy(&stash_list_output.stdout)
2737                        .trim()
2738                        .to_string()
2739                } else {
2740                    "stash@{0}".to_string() // fallback
2741                }
2742            } else {
2743                "stash@{0}".to_string() // fallback
2744            };
2745
2746            tracing::info!("✅ Created stash: {} ({})", message, stash_id);
2747            Ok(stash_id)
2748        } else {
2749            let stderr = String::from_utf8_lossy(&output.stderr);
2750            let stdout = String::from_utf8_lossy(&output.stdout);
2751
2752            // Check for common stash failure reasons
2753            if stderr.contains("No local changes to save")
2754                || stdout.contains("No local changes to save")
2755            {
2756                return Err(CascadeError::branch("No local changes to save".to_string()));
2757            }
2758
2759            Err(CascadeError::branch(format!(
2760                "Failed to create stash: {}\nStderr: {}\nStdout: {}",
2761                output.status, stderr, stdout
2762            )))
2763        }
2764    }
2765
2766    /// Get modified files in working directory
2767    fn get_modified_files(&self) -> Result<Vec<String>> {
2768        let mut opts = git2::StatusOptions::new();
2769        opts.include_untracked(false).include_ignored(false);
2770
2771        let statuses = self
2772            .repo
2773            .statuses(Some(&mut opts))
2774            .map_err(|e| CascadeError::branch(format!("Could not get repository status: {e}")))?;
2775
2776        let mut modified_files = Vec::new();
2777        for status in statuses.iter() {
2778            let flags = status.status();
2779            if flags.contains(git2::Status::WT_MODIFIED) || flags.contains(git2::Status::WT_DELETED)
2780            {
2781                if let Some(path) = status.path() {
2782                    modified_files.push(path.to_string());
2783                }
2784            }
2785        }
2786
2787        Ok(modified_files)
2788    }
2789
2790    /// Get staged files in index
2791    pub fn get_staged_files(&self) -> Result<Vec<String>> {
2792        let mut opts = git2::StatusOptions::new();
2793        opts.include_untracked(false).include_ignored(false);
2794
2795        let statuses = self
2796            .repo
2797            .statuses(Some(&mut opts))
2798            .map_err(|e| CascadeError::branch(format!("Could not get repository status: {e}")))?;
2799
2800        let mut staged_files = Vec::new();
2801        for status in statuses.iter() {
2802            let flags = status.status();
2803            if flags.contains(git2::Status::INDEX_MODIFIED)
2804                || flags.contains(git2::Status::INDEX_NEW)
2805                || flags.contains(git2::Status::INDEX_DELETED)
2806            {
2807                if let Some(path) = status.path() {
2808                    staged_files.push(path.to_string());
2809                }
2810            }
2811        }
2812
2813        Ok(staged_files)
2814    }
2815
2816    /// Count commits between two references
2817    fn count_commits_between(&self, from: &str, to: &str) -> Result<usize> {
2818        let commits = self.get_commits_between(from, to)?;
2819        Ok(commits.len())
2820    }
2821
2822    /// Resolve a reference (branch name, tag, or commit hash) to a commit
2823    pub fn resolve_reference(&self, reference: &str) -> Result<git2::Commit<'_>> {
2824        // Try to parse as commit hash first
2825        if let Ok(oid) = Oid::from_str(reference) {
2826            if let Ok(commit) = self.repo.find_commit(oid) {
2827                return Ok(commit);
2828            }
2829        }
2830
2831        // Try to resolve as a reference (branch, tag, etc.)
2832        let obj = self.repo.revparse_single(reference).map_err(|e| {
2833            CascadeError::branch(format!("Could not resolve reference '{reference}': {e}"))
2834        })?;
2835
2836        obj.peel_to_commit().map_err(|e| {
2837            CascadeError::branch(format!(
2838                "Reference '{reference}' does not point to a commit: {e}"
2839            ))
2840        })
2841    }
2842
2843    /// Reset HEAD to a specific reference (soft reset)
2844    pub fn reset_soft(&self, target_ref: &str) -> Result<()> {
2845        let target_commit = self.resolve_reference(target_ref)?;
2846
2847        self.repo
2848            .reset(target_commit.as_object(), git2::ResetType::Soft, None)
2849            .map_err(CascadeError::Git)?;
2850
2851        Ok(())
2852    }
2853
2854    /// Reset working directory and index to match HEAD (hard reset)
2855    /// This clears all uncommitted changes and staged files
2856    pub fn reset_to_head(&self) -> Result<()> {
2857        tracing::debug!("Resetting working directory and index to HEAD");
2858
2859        let head = self.repo.head().map_err(CascadeError::Git)?;
2860        let head_commit = head.peel_to_commit().map_err(CascadeError::Git)?;
2861
2862        // Hard reset: resets index and working tree
2863        let mut checkout_builder = git2::build::CheckoutBuilder::new();
2864        checkout_builder.force(); // Force checkout to overwrite any local changes
2865        checkout_builder.remove_untracked(false); // Don't remove untracked files
2866
2867        self.repo
2868            .reset(
2869                head_commit.as_object(),
2870                git2::ResetType::Hard,
2871                Some(&mut checkout_builder),
2872            )
2873            .map_err(CascadeError::Git)?;
2874
2875        tracing::debug!("Successfully reset working directory to HEAD");
2876        Ok(())
2877    }
2878
2879    /// Find which branch contains a specific commit
2880    pub fn find_branch_containing_commit(&self, commit_hash: &str) -> Result<String> {
2881        let oid = Oid::from_str(commit_hash).map_err(|e| {
2882            CascadeError::branch(format!("Invalid commit hash '{commit_hash}': {e}"))
2883        })?;
2884
2885        // Get all local branches
2886        let branches = self
2887            .repo
2888            .branches(Some(git2::BranchType::Local))
2889            .map_err(CascadeError::Git)?;
2890
2891        for branch_result in branches {
2892            let (branch, _) = branch_result.map_err(CascadeError::Git)?;
2893
2894            if let Some(branch_name) = branch.name().map_err(CascadeError::Git)? {
2895                // Check if this branch contains the commit
2896                if let Ok(branch_head) = branch.get().peel_to_commit() {
2897                    // Walk the commit history from this branch's HEAD
2898                    let mut revwalk = self.repo.revwalk().map_err(CascadeError::Git)?;
2899                    revwalk.push(branch_head.id()).map_err(CascadeError::Git)?;
2900
2901                    for commit_oid in revwalk {
2902                        let commit_oid = commit_oid.map_err(CascadeError::Git)?;
2903                        if commit_oid == oid {
2904                            return Ok(branch_name.to_string());
2905                        }
2906                    }
2907                }
2908            }
2909        }
2910
2911        // If not found in any branch, might be on current HEAD
2912        Err(CascadeError::branch(format!(
2913            "Commit {commit_hash} not found in any local branch"
2914        )))
2915    }
2916
2917    // Async wrappers for potentially blocking operations
2918
2919    /// Fetch from remote origin (async)
2920    pub async fn fetch_async(&self) -> Result<()> {
2921        let repo_path = self.path.clone();
2922        crate::utils::async_ops::run_git_operation(move || {
2923            let repo = GitRepository::open(&repo_path)?;
2924            repo.fetch()
2925        })
2926        .await
2927    }
2928
2929    /// Pull changes from remote (async)
2930    pub async fn pull_async(&self, branch: &str) -> Result<()> {
2931        let repo_path = self.path.clone();
2932        let branch_name = branch.to_string();
2933        crate::utils::async_ops::run_git_operation(move || {
2934            let repo = GitRepository::open(&repo_path)?;
2935            repo.pull(&branch_name)
2936        })
2937        .await
2938    }
2939
2940    /// Push branch to remote (async)
2941    pub async fn push_branch_async(&self, branch_name: &str) -> Result<()> {
2942        let repo_path = self.path.clone();
2943        let branch = branch_name.to_string();
2944        crate::utils::async_ops::run_git_operation(move || {
2945            let repo = GitRepository::open(&repo_path)?;
2946            repo.push(&branch)
2947        })
2948        .await
2949    }
2950
2951    /// Cherry-pick commit (async)
2952    pub async fn cherry_pick_commit_async(&self, commit_hash: &str) -> Result<String> {
2953        let repo_path = self.path.clone();
2954        let hash = commit_hash.to_string();
2955        crate::utils::async_ops::run_git_operation(move || {
2956            let repo = GitRepository::open(&repo_path)?;
2957            repo.cherry_pick(&hash)
2958        })
2959        .await
2960    }
2961
2962    /// Get commit hashes between two refs (async)
2963    pub async fn get_commit_hashes_between_async(
2964        &self,
2965        from: &str,
2966        to: &str,
2967    ) -> Result<Vec<String>> {
2968        let repo_path = self.path.clone();
2969        let from_str = from.to_string();
2970        let to_str = to.to_string();
2971        crate::utils::async_ops::run_git_operation(move || {
2972            let repo = GitRepository::open(&repo_path)?;
2973            let commits = repo.get_commits_between(&from_str, &to_str)?;
2974            Ok(commits.into_iter().map(|c| c.id().to_string()).collect())
2975        })
2976        .await
2977    }
2978
2979    /// Reset a branch to point to a specific commit
2980    pub fn reset_branch_to_commit(&self, branch_name: &str, commit_hash: &str) -> Result<()> {
2981        info!(
2982            "Resetting branch '{}' to commit {}",
2983            branch_name,
2984            &commit_hash[..8]
2985        );
2986
2987        // Find the target commit
2988        let target_oid = git2::Oid::from_str(commit_hash).map_err(|e| {
2989            CascadeError::branch(format!("Invalid commit hash '{commit_hash}': {e}"))
2990        })?;
2991
2992        let _target_commit = self.repo.find_commit(target_oid).map_err(|e| {
2993            CascadeError::branch(format!("Could not find commit '{commit_hash}': {e}"))
2994        })?;
2995
2996        // Find the branch
2997        let _branch = self
2998            .repo
2999            .find_branch(branch_name, git2::BranchType::Local)
3000            .map_err(|e| {
3001                CascadeError::branch(format!("Could not find branch '{branch_name}': {e}"))
3002            })?;
3003
3004        // Update the branch reference to point to the target commit
3005        let branch_ref_name = format!("refs/heads/{branch_name}");
3006        self.repo
3007            .reference(
3008                &branch_ref_name,
3009                target_oid,
3010                true,
3011                &format!("Reset {branch_name} to {commit_hash}"),
3012            )
3013            .map_err(|e| {
3014                CascadeError::branch(format!(
3015                    "Could not reset branch '{branch_name}' to commit '{commit_hash}': {e}"
3016                ))
3017            })?;
3018
3019        tracing::info!(
3020            "Successfully reset branch '{}' to commit {}",
3021            branch_name,
3022            &commit_hash[..8]
3023        );
3024        Ok(())
3025    }
3026
3027    /// Detect the parent branch of the current branch using multiple strategies
3028    pub fn detect_parent_branch(&self) -> Result<Option<String>> {
3029        let current_branch = self.get_current_branch()?;
3030
3031        // Strategy 1: Check if current branch has an upstream tracking branch
3032        if let Ok(Some(upstream)) = self.get_upstream_branch(&current_branch) {
3033            // Extract the branch name from "origin/branch-name" format
3034            if let Some(branch_name) = upstream.split('/').nth(1) {
3035                if self.branch_exists(branch_name) {
3036                    tracing::debug!(
3037                        "Detected parent branch '{}' from upstream tracking",
3038                        branch_name
3039                    );
3040                    return Ok(Some(branch_name.to_string()));
3041                }
3042            }
3043        }
3044
3045        // Strategy 2: Use git's default branch detection
3046        if let Ok(default_branch) = self.detect_main_branch() {
3047            // Don't suggest the current branch as its own parent
3048            if current_branch != default_branch {
3049                tracing::debug!(
3050                    "Detected parent branch '{}' as repository default",
3051                    default_branch
3052                );
3053                return Ok(Some(default_branch));
3054            }
3055        }
3056
3057        // Strategy 3: Find the branch with the most recent common ancestor
3058        // Get all local branches and find the one with the shortest commit distance
3059        if let Ok(branches) = self.list_branches() {
3060            let current_commit = self.get_head_commit()?;
3061            let current_commit_hash = current_commit.id().to_string();
3062            let current_oid = current_commit.id();
3063
3064            let mut best_candidate = None;
3065            let mut best_distance = usize::MAX;
3066
3067            for branch in branches {
3068                // Skip the current branch and any branches that look like version branches
3069                if branch == current_branch
3070                    || branch.contains("-v")
3071                    || branch.ends_with("-v2")
3072                    || branch.ends_with("-v3")
3073                {
3074                    continue;
3075                }
3076
3077                if let Ok(base_commit_hash) = self.get_branch_commit_hash(&branch) {
3078                    if let Ok(base_oid) = git2::Oid::from_str(&base_commit_hash) {
3079                        // Find merge base between current branch and this branch
3080                        if let Ok(merge_base_oid) = self.repo.merge_base(current_oid, base_oid) {
3081                            // Count commits from merge base to current head
3082                            if let Ok(distance) = self.count_commits_between(
3083                                &merge_base_oid.to_string(),
3084                                &current_commit_hash,
3085                            ) {
3086                                // Prefer branches with shorter distances (more recent common ancestor)
3087                                // Also prefer branches that look like base branches
3088                                let is_likely_base = self.is_likely_base_branch(&branch);
3089                                let adjusted_distance = if is_likely_base {
3090                                    distance
3091                                } else {
3092                                    distance + 1000
3093                                };
3094
3095                                if adjusted_distance < best_distance {
3096                                    best_distance = adjusted_distance;
3097                                    best_candidate = Some(branch.clone());
3098                                }
3099                            }
3100                        }
3101                    }
3102                }
3103            }
3104
3105            if let Some(ref candidate) = best_candidate {
3106                tracing::debug!(
3107                    "Detected parent branch '{}' with distance {}",
3108                    candidate,
3109                    best_distance
3110                );
3111            }
3112
3113            return Ok(best_candidate);
3114        }
3115
3116        tracing::debug!("Could not detect parent branch for '{}'", current_branch);
3117        Ok(None)
3118    }
3119
3120    /// Check if a branch name looks like a typical base branch
3121    fn is_likely_base_branch(&self, branch_name: &str) -> bool {
3122        let base_patterns = [
3123            "main",
3124            "master",
3125            "develop",
3126            "dev",
3127            "development",
3128            "staging",
3129            "stage",
3130            "release",
3131            "production",
3132            "prod",
3133        ];
3134
3135        base_patterns.contains(&branch_name)
3136    }
3137}
3138
3139#[cfg(test)]
3140mod tests {
3141    use super::*;
3142    use std::process::Command;
3143    use tempfile::TempDir;
3144
3145    fn create_test_repo() -> (TempDir, PathBuf) {
3146        let temp_dir = TempDir::new().unwrap();
3147        let repo_path = temp_dir.path().to_path_buf();
3148
3149        // Initialize git repository
3150        Command::new("git")
3151            .args(["init"])
3152            .current_dir(&repo_path)
3153            .output()
3154            .unwrap();
3155        Command::new("git")
3156            .args(["config", "user.name", "Test"])
3157            .current_dir(&repo_path)
3158            .output()
3159            .unwrap();
3160        Command::new("git")
3161            .args(["config", "user.email", "test@test.com"])
3162            .current_dir(&repo_path)
3163            .output()
3164            .unwrap();
3165
3166        // Create initial commit
3167        std::fs::write(repo_path.join("README.md"), "# Test").unwrap();
3168        Command::new("git")
3169            .args(["add", "."])
3170            .current_dir(&repo_path)
3171            .output()
3172            .unwrap();
3173        Command::new("git")
3174            .args(["commit", "-m", "Initial commit"])
3175            .current_dir(&repo_path)
3176            .output()
3177            .unwrap();
3178
3179        (temp_dir, repo_path)
3180    }
3181
3182    fn create_commit(repo_path: &PathBuf, message: &str, filename: &str) {
3183        let file_path = repo_path.join(filename);
3184        std::fs::write(&file_path, format!("Content for {filename}\n")).unwrap();
3185
3186        Command::new("git")
3187            .args(["add", filename])
3188            .current_dir(repo_path)
3189            .output()
3190            .unwrap();
3191        Command::new("git")
3192            .args(["commit", "-m", message])
3193            .current_dir(repo_path)
3194            .output()
3195            .unwrap();
3196    }
3197
3198    #[test]
3199    fn test_repository_info() {
3200        let (_temp_dir, repo_path) = create_test_repo();
3201        let repo = GitRepository::open(&repo_path).unwrap();
3202
3203        let info = repo.get_info().unwrap();
3204        assert!(!info.is_dirty); // Should be clean after commit
3205        assert!(
3206            info.head_branch == Some("master".to_string())
3207                || info.head_branch == Some("main".to_string()),
3208            "Expected default branch to be 'master' or 'main', got {:?}",
3209            info.head_branch
3210        );
3211        assert!(info.head_commit.is_some()); // Just check it exists
3212        assert!(info.untracked_files.is_empty()); // Should be empty after commit
3213    }
3214
3215    #[test]
3216    fn test_force_push_branch_basic() {
3217        let (_temp_dir, repo_path) = create_test_repo();
3218        let repo = GitRepository::open(&repo_path).unwrap();
3219
3220        // Get the actual default branch name
3221        let default_branch = repo.get_current_branch().unwrap();
3222
3223        // Create source branch with commits
3224        create_commit(&repo_path, "Feature commit 1", "feature1.rs");
3225        Command::new("git")
3226            .args(["checkout", "-b", "source-branch"])
3227            .current_dir(&repo_path)
3228            .output()
3229            .unwrap();
3230        create_commit(&repo_path, "Feature commit 2", "feature2.rs");
3231
3232        // Create target branch
3233        Command::new("git")
3234            .args(["checkout", &default_branch])
3235            .current_dir(&repo_path)
3236            .output()
3237            .unwrap();
3238        Command::new("git")
3239            .args(["checkout", "-b", "target-branch"])
3240            .current_dir(&repo_path)
3241            .output()
3242            .unwrap();
3243        create_commit(&repo_path, "Target commit", "target.rs");
3244
3245        // Test force push from source to target
3246        let result = repo.force_push_branch("target-branch", "source-branch");
3247
3248        // Should succeed in test environment (even though it doesn't actually push to remote)
3249        // The important thing is that the function doesn't panic and handles the git2 operations
3250        assert!(result.is_ok() || result.is_err()); // Either is acceptable for unit test
3251    }
3252
3253    #[test]
3254    fn test_force_push_branch_nonexistent_branches() {
3255        let (_temp_dir, repo_path) = create_test_repo();
3256        let repo = GitRepository::open(&repo_path).unwrap();
3257
3258        // Get the actual default branch name
3259        let default_branch = repo.get_current_branch().unwrap();
3260
3261        // Test force push with nonexistent source branch
3262        let result = repo.force_push_branch("target", "nonexistent-source");
3263        assert!(result.is_err());
3264
3265        // Test force push with nonexistent target branch
3266        let result = repo.force_push_branch("nonexistent-target", &default_branch);
3267        assert!(result.is_err());
3268    }
3269
3270    #[test]
3271    fn test_force_push_workflow_simulation() {
3272        let (_temp_dir, repo_path) = create_test_repo();
3273        let repo = GitRepository::open(&repo_path).unwrap();
3274
3275        // Simulate the smart force push workflow:
3276        // 1. Original branch exists with PR
3277        Command::new("git")
3278            .args(["checkout", "-b", "feature-auth"])
3279            .current_dir(&repo_path)
3280            .output()
3281            .unwrap();
3282        create_commit(&repo_path, "Add authentication", "auth.rs");
3283
3284        // 2. Rebase creates versioned branch
3285        Command::new("git")
3286            .args(["checkout", "-b", "feature-auth-v2"])
3287            .current_dir(&repo_path)
3288            .output()
3289            .unwrap();
3290        create_commit(&repo_path, "Fix auth validation", "auth.rs");
3291
3292        // 3. Smart force push: update original branch from versioned branch
3293        let result = repo.force_push_branch("feature-auth", "feature-auth-v2");
3294
3295        // Verify the operation is handled properly (success or expected error)
3296        match result {
3297            Ok(_) => {
3298                // Force push succeeded - verify branch state if possible
3299                Command::new("git")
3300                    .args(["checkout", "feature-auth"])
3301                    .current_dir(&repo_path)
3302                    .output()
3303                    .unwrap();
3304                let log_output = Command::new("git")
3305                    .args(["log", "--oneline", "-2"])
3306                    .current_dir(&repo_path)
3307                    .output()
3308                    .unwrap();
3309                let log_str = String::from_utf8_lossy(&log_output.stdout);
3310                assert!(
3311                    log_str.contains("Fix auth validation")
3312                        || log_str.contains("Add authentication")
3313                );
3314            }
3315            Err(_) => {
3316                // Expected in test environment without remote - that's fine
3317                // The important thing is we tested the code path without panicking
3318            }
3319        }
3320    }
3321
3322    #[test]
3323    fn test_branch_operations() {
3324        let (_temp_dir, repo_path) = create_test_repo();
3325        let repo = GitRepository::open(&repo_path).unwrap();
3326
3327        // Test get current branch - accept either main or master
3328        let current = repo.get_current_branch().unwrap();
3329        assert!(
3330            current == "master" || current == "main",
3331            "Expected default branch to be 'master' or 'main', got '{current}'"
3332        );
3333
3334        // Test create branch
3335        Command::new("git")
3336            .args(["checkout", "-b", "test-branch"])
3337            .current_dir(&repo_path)
3338            .output()
3339            .unwrap();
3340        let current = repo.get_current_branch().unwrap();
3341        assert_eq!(current, "test-branch");
3342    }
3343
3344    #[test]
3345    fn test_commit_operations() {
3346        let (_temp_dir, repo_path) = create_test_repo();
3347        let repo = GitRepository::open(&repo_path).unwrap();
3348
3349        // Test get head commit
3350        let head = repo.get_head_commit().unwrap();
3351        assert_eq!(head.message().unwrap().trim(), "Initial commit");
3352
3353        // Test get commit by hash
3354        let hash = head.id().to_string();
3355        let same_commit = repo.get_commit(&hash).unwrap();
3356        assert_eq!(head.id(), same_commit.id());
3357    }
3358
3359    #[test]
3360    fn test_checkout_safety_clean_repo() {
3361        let (_temp_dir, repo_path) = create_test_repo();
3362        let repo = GitRepository::open(&repo_path).unwrap();
3363
3364        // Create a test branch
3365        create_commit(&repo_path, "Second commit", "test.txt");
3366        Command::new("git")
3367            .args(["checkout", "-b", "test-branch"])
3368            .current_dir(&repo_path)
3369            .output()
3370            .unwrap();
3371
3372        // Test checkout safety with clean repo
3373        let safety_result = repo.check_checkout_safety("main");
3374        assert!(safety_result.is_ok());
3375        assert!(safety_result.unwrap().is_none()); // Clean repo should return None
3376    }
3377
3378    #[test]
3379    fn test_checkout_safety_with_modified_files() {
3380        let (_temp_dir, repo_path) = create_test_repo();
3381        let repo = GitRepository::open(&repo_path).unwrap();
3382
3383        // Create a test branch
3384        Command::new("git")
3385            .args(["checkout", "-b", "test-branch"])
3386            .current_dir(&repo_path)
3387            .output()
3388            .unwrap();
3389
3390        // Modify a file to create uncommitted changes
3391        std::fs::write(repo_path.join("README.md"), "Modified content").unwrap();
3392
3393        // Test checkout safety with modified files
3394        let safety_result = repo.check_checkout_safety("main");
3395        assert!(safety_result.is_ok());
3396        let safety_info = safety_result.unwrap();
3397        assert!(safety_info.is_some());
3398
3399        let info = safety_info.unwrap();
3400        assert!(!info.modified_files.is_empty());
3401        assert!(info.modified_files.contains(&"README.md".to_string()));
3402    }
3403
3404    #[test]
3405    fn test_unsafe_checkout_methods() {
3406        let (_temp_dir, repo_path) = create_test_repo();
3407        let repo = GitRepository::open(&repo_path).unwrap();
3408
3409        // Create a test branch
3410        create_commit(&repo_path, "Second commit", "test.txt");
3411        Command::new("git")
3412            .args(["checkout", "-b", "test-branch"])
3413            .current_dir(&repo_path)
3414            .output()
3415            .unwrap();
3416
3417        // Modify a file to create uncommitted changes
3418        std::fs::write(repo_path.join("README.md"), "Modified content").unwrap();
3419
3420        // Test unsafe checkout methods bypass safety checks
3421        let _result = repo.checkout_branch_unsafe("main");
3422        // Note: This might still fail due to git2 restrictions, but shouldn't hit our safety code
3423        // The important thing is that it doesn't trigger our safety confirmation
3424
3425        // Test unsafe commit checkout
3426        let head_commit = repo.get_head_commit().unwrap();
3427        let commit_hash = head_commit.id().to_string();
3428        let _result = repo.checkout_commit_unsafe(&commit_hash);
3429        // Similar to above - testing that safety is bypassed
3430    }
3431
3432    #[test]
3433    fn test_get_modified_files() {
3434        let (_temp_dir, repo_path) = create_test_repo();
3435        let repo = GitRepository::open(&repo_path).unwrap();
3436
3437        // Initially should have no modified files
3438        let modified = repo.get_modified_files().unwrap();
3439        assert!(modified.is_empty());
3440
3441        // Modify a file
3442        std::fs::write(repo_path.join("README.md"), "Modified content").unwrap();
3443
3444        // Should now detect the modified file
3445        let modified = repo.get_modified_files().unwrap();
3446        assert_eq!(modified.len(), 1);
3447        assert!(modified.contains(&"README.md".to_string()));
3448    }
3449
3450    #[test]
3451    fn test_get_staged_files() {
3452        let (_temp_dir, repo_path) = create_test_repo();
3453        let repo = GitRepository::open(&repo_path).unwrap();
3454
3455        // Initially should have no staged files
3456        let staged = repo.get_staged_files().unwrap();
3457        assert!(staged.is_empty());
3458
3459        // Create and stage a new file
3460        std::fs::write(repo_path.join("staged.txt"), "Staged content").unwrap();
3461        Command::new("git")
3462            .args(["add", "staged.txt"])
3463            .current_dir(&repo_path)
3464            .output()
3465            .unwrap();
3466
3467        // Should now detect the staged file
3468        let staged = repo.get_staged_files().unwrap();
3469        assert_eq!(staged.len(), 1);
3470        assert!(staged.contains(&"staged.txt".to_string()));
3471    }
3472
3473    #[test]
3474    fn test_create_stash_fallback() {
3475        let (_temp_dir, repo_path) = create_test_repo();
3476        let repo = GitRepository::open(&repo_path).unwrap();
3477
3478        // Test stash creation - newer git versions allow empty stashes
3479        let result = repo.create_stash("test stash");
3480
3481        // Either succeeds (newer git with empty stash) or fails with helpful message
3482        match result {
3483            Ok(stash_id) => {
3484                // Modern git allows empty stashes, verify we got a stash ID
3485                assert!(!stash_id.is_empty());
3486                assert!(stash_id.contains("stash") || stash_id.len() >= 7); // SHA or stash@{n}
3487            }
3488            Err(error) => {
3489                // Older git should fail with helpful message
3490                let error_msg = error.to_string();
3491                assert!(
3492                    error_msg.contains("No local changes to save")
3493                        || error_msg.contains("git stash push")
3494                );
3495            }
3496        }
3497    }
3498
3499    #[test]
3500    fn test_delete_branch_unsafe() {
3501        let (_temp_dir, repo_path) = create_test_repo();
3502        let repo = GitRepository::open(&repo_path).unwrap();
3503
3504        // Create a test branch
3505        create_commit(&repo_path, "Second commit", "test.txt");
3506        Command::new("git")
3507            .args(["checkout", "-b", "test-branch"])
3508            .current_dir(&repo_path)
3509            .output()
3510            .unwrap();
3511
3512        // Add another commit to the test branch to make it different from main
3513        create_commit(&repo_path, "Branch-specific commit", "branch.txt");
3514
3515        // Go back to main
3516        Command::new("git")
3517            .args(["checkout", "main"])
3518            .current_dir(&repo_path)
3519            .output()
3520            .unwrap();
3521
3522        // Test unsafe delete bypasses safety checks
3523        // Note: This may still fail if the branch has unpushed commits, but it should bypass our safety confirmation
3524        let result = repo.delete_branch_unsafe("test-branch");
3525        // Even if it fails, the key is that it didn't prompt for user confirmation
3526        // So we just check that it attempted the operation without interactive prompts
3527        let _ = result; // Don't assert success since delete may fail for git reasons
3528    }
3529
3530    #[test]
3531    fn test_force_push_unsafe() {
3532        let (_temp_dir, repo_path) = create_test_repo();
3533        let repo = GitRepository::open(&repo_path).unwrap();
3534
3535        // Create a test branch
3536        create_commit(&repo_path, "Second commit", "test.txt");
3537        Command::new("git")
3538            .args(["checkout", "-b", "test-branch"])
3539            .current_dir(&repo_path)
3540            .output()
3541            .unwrap();
3542
3543        // Test unsafe force push bypasses safety checks
3544        // Note: This will likely fail due to no remote, but it tests the safety bypass
3545        let _result = repo.force_push_branch_unsafe("test-branch", "test-branch");
3546        // The key is that it doesn't trigger safety confirmation dialogs
3547    }
3548
3549    #[test]
3550    fn test_cherry_pick_basic() {
3551        let (_temp_dir, repo_path) = create_test_repo();
3552        let repo = GitRepository::open(&repo_path).unwrap();
3553
3554        // Create a branch with a commit to cherry-pick
3555        repo.create_branch("source", None).unwrap();
3556        repo.checkout_branch("source").unwrap();
3557
3558        std::fs::write(repo_path.join("cherry.txt"), "Cherry content").unwrap();
3559        Command::new("git")
3560            .args(["add", "."])
3561            .current_dir(&repo_path)
3562            .output()
3563            .unwrap();
3564
3565        Command::new("git")
3566            .args(["commit", "-m", "Cherry commit"])
3567            .current_dir(&repo_path)
3568            .output()
3569            .unwrap();
3570
3571        let cherry_commit = repo.get_head_commit_hash().unwrap();
3572
3573        // Switch back to previous branch (where source was created from)
3574        // Using `git checkout -` is environment-agnostic
3575        Command::new("git")
3576            .args(["checkout", "-"])
3577            .current_dir(&repo_path)
3578            .output()
3579            .unwrap();
3580
3581        repo.create_branch("target", None).unwrap();
3582        repo.checkout_branch("target").unwrap();
3583
3584        // Cherry-pick the commit
3585        let new_commit = repo.cherry_pick(&cherry_commit).unwrap();
3586
3587        // Verify cherry-pick succeeded (commit exists)
3588        repo.repo
3589            .find_commit(git2::Oid::from_str(&new_commit).unwrap())
3590            .unwrap();
3591
3592        // Verify file exists on target branch
3593        assert!(
3594            repo_path.join("cherry.txt").exists(),
3595            "Cherry-picked file should exist"
3596        );
3597
3598        // Verify source branch is unchanged
3599        repo.checkout_branch("source").unwrap();
3600        let source_head = repo.get_head_commit_hash().unwrap();
3601        assert_eq!(
3602            source_head, cherry_commit,
3603            "Source branch should be unchanged"
3604        );
3605    }
3606
3607    #[test]
3608    fn test_cherry_pick_preserves_commit_message() {
3609        let (_temp_dir, repo_path) = create_test_repo();
3610        let repo = GitRepository::open(&repo_path).unwrap();
3611
3612        // Create commit with specific message
3613        repo.create_branch("msg-test", None).unwrap();
3614        repo.checkout_branch("msg-test").unwrap();
3615
3616        std::fs::write(repo_path.join("msg.txt"), "Content").unwrap();
3617        Command::new("git")
3618            .args(["add", "."])
3619            .current_dir(&repo_path)
3620            .output()
3621            .unwrap();
3622
3623        let commit_msg = "Test: Special commit message\n\nWith body";
3624        Command::new("git")
3625            .args(["commit", "-m", commit_msg])
3626            .current_dir(&repo_path)
3627            .output()
3628            .unwrap();
3629
3630        let original_commit = repo.get_head_commit_hash().unwrap();
3631
3632        // Cherry-pick to another branch (use previous branch via git checkout -)
3633        Command::new("git")
3634            .args(["checkout", "-"])
3635            .current_dir(&repo_path)
3636            .output()
3637            .unwrap();
3638        let new_commit = repo.cherry_pick(&original_commit).unwrap();
3639
3640        // Get commit message of new commit
3641        let output = Command::new("git")
3642            .args(["log", "-1", "--format=%B", &new_commit])
3643            .current_dir(&repo_path)
3644            .output()
3645            .unwrap();
3646
3647        let new_msg = String::from_utf8_lossy(&output.stdout);
3648        assert!(
3649            new_msg.contains("Special commit message"),
3650            "Should preserve commit message"
3651        );
3652    }
3653
3654    #[test]
3655    fn test_cherry_pick_handles_conflicts() {
3656        let (_temp_dir, repo_path) = create_test_repo();
3657        let repo = GitRepository::open(&repo_path).unwrap();
3658
3659        // Create conflicting content
3660        std::fs::write(repo_path.join("conflict.txt"), "Original").unwrap();
3661        Command::new("git")
3662            .args(["add", "."])
3663            .current_dir(&repo_path)
3664            .output()
3665            .unwrap();
3666
3667        Command::new("git")
3668            .args(["commit", "-m", "Add conflict file"])
3669            .current_dir(&repo_path)
3670            .output()
3671            .unwrap();
3672
3673        // Create branch with different content
3674        repo.create_branch("conflict-branch", None).unwrap();
3675        repo.checkout_branch("conflict-branch").unwrap();
3676
3677        std::fs::write(repo_path.join("conflict.txt"), "Modified").unwrap();
3678        Command::new("git")
3679            .args(["add", "."])
3680            .current_dir(&repo_path)
3681            .output()
3682            .unwrap();
3683
3684        Command::new("git")
3685            .args(["commit", "-m", "Modify conflict file"])
3686            .current_dir(&repo_path)
3687            .output()
3688            .unwrap();
3689
3690        let conflict_commit = repo.get_head_commit_hash().unwrap();
3691
3692        // Try to cherry-pick (should fail due to conflict)
3693        // Go back to previous branch
3694        Command::new("git")
3695            .args(["checkout", "-"])
3696            .current_dir(&repo_path)
3697            .output()
3698            .unwrap();
3699        std::fs::write(repo_path.join("conflict.txt"), "Different").unwrap();
3700        Command::new("git")
3701            .args(["add", "."])
3702            .current_dir(&repo_path)
3703            .output()
3704            .unwrap();
3705
3706        Command::new("git")
3707            .args(["commit", "-m", "Different change"])
3708            .current_dir(&repo_path)
3709            .output()
3710            .unwrap();
3711
3712        // Cherry-pick should fail with conflict
3713        let result = repo.cherry_pick(&conflict_commit);
3714        assert!(result.is_err(), "Cherry-pick with conflict should fail");
3715    }
3716
3717    #[test]
3718    fn test_reset_to_head_clears_staged_files() {
3719        let (_temp_dir, repo_path) = create_test_repo();
3720        let repo = GitRepository::open(&repo_path).unwrap();
3721
3722        // Create and stage some files
3723        std::fs::write(repo_path.join("staged1.txt"), "Content 1").unwrap();
3724        std::fs::write(repo_path.join("staged2.txt"), "Content 2").unwrap();
3725
3726        Command::new("git")
3727            .args(["add", "staged1.txt", "staged2.txt"])
3728            .current_dir(&repo_path)
3729            .output()
3730            .unwrap();
3731
3732        // Verify files are staged
3733        let staged_before = repo.get_staged_files().unwrap();
3734        assert_eq!(staged_before.len(), 2, "Should have 2 staged files");
3735
3736        // Reset to HEAD
3737        repo.reset_to_head().unwrap();
3738
3739        // Verify no files are staged after reset
3740        let staged_after = repo.get_staged_files().unwrap();
3741        assert_eq!(
3742            staged_after.len(),
3743            0,
3744            "Should have no staged files after reset"
3745        );
3746    }
3747
3748    #[test]
3749    fn test_reset_to_head_clears_modified_files() {
3750        let (_temp_dir, repo_path) = create_test_repo();
3751        let repo = GitRepository::open(&repo_path).unwrap();
3752
3753        // Modify an existing file
3754        std::fs::write(repo_path.join("README.md"), "# Modified content").unwrap();
3755
3756        // Stage the modification
3757        Command::new("git")
3758            .args(["add", "README.md"])
3759            .current_dir(&repo_path)
3760            .output()
3761            .unwrap();
3762
3763        // Verify file is modified and staged
3764        assert!(repo.is_dirty().unwrap(), "Repo should be dirty");
3765
3766        // Reset to HEAD
3767        repo.reset_to_head().unwrap();
3768
3769        // Verify repo is clean
3770        assert!(
3771            !repo.is_dirty().unwrap(),
3772            "Repo should be clean after reset"
3773        );
3774
3775        // Verify file content is restored
3776        let content = std::fs::read_to_string(repo_path.join("README.md")).unwrap();
3777        assert_eq!(
3778            content, "# Test",
3779            "File should be restored to original content"
3780        );
3781    }
3782
3783    #[test]
3784    fn test_reset_to_head_preserves_untracked_files() {
3785        let (_temp_dir, repo_path) = create_test_repo();
3786        let repo = GitRepository::open(&repo_path).unwrap();
3787
3788        // Create untracked file
3789        std::fs::write(repo_path.join("untracked.txt"), "Untracked content").unwrap();
3790
3791        // Stage some other file
3792        std::fs::write(repo_path.join("staged.txt"), "Staged content").unwrap();
3793        Command::new("git")
3794            .args(["add", "staged.txt"])
3795            .current_dir(&repo_path)
3796            .output()
3797            .unwrap();
3798
3799        // Reset to HEAD
3800        repo.reset_to_head().unwrap();
3801
3802        // Verify untracked file still exists
3803        assert!(
3804            repo_path.join("untracked.txt").exists(),
3805            "Untracked file should be preserved"
3806        );
3807
3808        // Verify staged file was removed (since it was never committed)
3809        assert!(
3810            !repo_path.join("staged.txt").exists(),
3811            "Staged but uncommitted file should be removed"
3812        );
3813    }
3814
3815    #[test]
3816    fn test_cherry_pick_does_not_modify_source() {
3817        let (_temp_dir, repo_path) = create_test_repo();
3818        let repo = GitRepository::open(&repo_path).unwrap();
3819
3820        // Create source branch with multiple commits
3821        repo.create_branch("feature", None).unwrap();
3822        repo.checkout_branch("feature").unwrap();
3823
3824        // Add multiple commits
3825        for i in 1..=3 {
3826            std::fs::write(
3827                repo_path.join(format!("file{i}.txt")),
3828                format!("Content {i}"),
3829            )
3830            .unwrap();
3831            Command::new("git")
3832                .args(["add", "."])
3833                .current_dir(&repo_path)
3834                .output()
3835                .unwrap();
3836
3837            Command::new("git")
3838                .args(["commit", "-m", &format!("Commit {i}")])
3839                .current_dir(&repo_path)
3840                .output()
3841                .unwrap();
3842        }
3843
3844        // Get source branch state
3845        let source_commits = Command::new("git")
3846            .args(["log", "--format=%H", "feature"])
3847            .current_dir(&repo_path)
3848            .output()
3849            .unwrap();
3850        let source_state = String::from_utf8_lossy(&source_commits.stdout).to_string();
3851
3852        // Cherry-pick middle commit to another branch
3853        let commits: Vec<&str> = source_state.lines().collect();
3854        let middle_commit = commits[1];
3855
3856        // Go back to previous branch
3857        Command::new("git")
3858            .args(["checkout", "-"])
3859            .current_dir(&repo_path)
3860            .output()
3861            .unwrap();
3862        repo.create_branch("target", None).unwrap();
3863        repo.checkout_branch("target").unwrap();
3864
3865        repo.cherry_pick(middle_commit).unwrap();
3866
3867        // Verify source branch is completely unchanged
3868        let after_commits = Command::new("git")
3869            .args(["log", "--format=%H", "feature"])
3870            .current_dir(&repo_path)
3871            .output()
3872            .unwrap();
3873        let after_state = String::from_utf8_lossy(&after_commits.stdout).to_string();
3874
3875        assert_eq!(
3876            source_state, after_state,
3877            "Source branch should be completely unchanged after cherry-pick"
3878        );
3879    }
3880
3881    #[test]
3882    fn test_detect_parent_branch() {
3883        let (_temp_dir, repo_path) = create_test_repo();
3884        let repo = GitRepository::open(&repo_path).unwrap();
3885
3886        // Create a custom base branch (not just main/master)
3887        repo.create_branch("dev123", None).unwrap();
3888        repo.checkout_branch("dev123").unwrap();
3889        create_commit(&repo_path, "Base commit on dev123", "base.txt");
3890
3891        // Create feature branch from dev123
3892        repo.create_branch("feature-branch", None).unwrap();
3893        repo.checkout_branch("feature-branch").unwrap();
3894        create_commit(&repo_path, "Feature commit", "feature.txt");
3895
3896        // Should detect dev123 as parent since it's the most recent common ancestor
3897        let detected_parent = repo.detect_parent_branch().unwrap();
3898
3899        // The algorithm should find dev123 through either Strategy 2 (default branch)
3900        // or Strategy 3 (common ancestor analysis)
3901        assert!(detected_parent.is_some(), "Should detect a parent branch");
3902
3903        // Since we can't guarantee which strategy will work in the test environment,
3904        // just verify it returns something reasonable
3905        let parent = detected_parent.unwrap();
3906        assert!(
3907            parent == "dev123" || parent == "main" || parent == "master",
3908            "Parent should be dev123, main, or master, got: {parent}"
3909        );
3910    }
3911}