cascade_cli/git/
repository.rs

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