use anyhow::{bail, Result};
use std::process::Command;

use crate::git::cli::GitCli;

impl GitCli {
    pub fn ahead_behind(&self, repo_path: &str) -> Result<(i32, i32)> {
        let output = Command::new("git")
            .args(["-C", repo_path, "rev-list", "--left-right", "--count", "HEAD...@{upstream}"])
            .output()?;
        if !output.status.success() {
            bail!(
                "git rev-list failed (exit {}): {}",
                output.status,
                String::from_utf8_lossy(&output.stderr)
            );
        }
        let txt = String::from_utf8_lossy(&output.stdout);
        let mut ahead = 0;
        let mut behind = 0;
        if let Some(line) = txt.lines().next() {
            let parts: Vec<&str> = line.split_whitespace().collect();
            if parts.len() == 2 {
                ahead = parts[0].parse::<i32>().unwrap_or(0);
                behind = parts[1].parse::<i32>().unwrap_or(0);
            }
        }
        Ok((ahead, behind))
    }

}
