"""Git utilities for CadeCoder."""

import logging
import subprocess

log = logging.getLogger(__name__)


def get_current_branch_name() -> tuple[str, str | None]:
    """Get the current active Git branch name.

    Returns:
        Tuple of (branch_name, error_message). error_message is None on success.
    """
    command = ["git", "rev-parse", "--abbrev-ref", "HEAD"]
    try:
        log.debug(f"Running git command: {' '.join(command)}")
        result = subprocess.run(
            command,
            capture_output=True,
            text=True,
            check=False,
        )
        stdout_val = result.stdout.strip()
        if result.returncode != 0:
            err_msg = (
                result.stderr.strip()
                if result.stderr
                else f"Command failed: exit code {result.returncode}"
            )
            return stdout_val, err_msg
        return stdout_val, None
    except Exception as e:
        log.error(f"Unexpected error running git command: {e}")
        return "", f"Error running git command: {str(e)}"


def get_status() -> tuple[str, str | None]:
    """Get repository status using 'git status --short'.

    Returns:
        Tuple of (status_output, error_message). error_message is None on success.
    """
    command = ["git", "status", "--short"]
    try:
        log.debug(f"Running git command: {' '.join(command)}")
        result = subprocess.run(
            command,
            capture_output=True,
            text=True,
            check=False,
        )
        stdout_val = result.stdout.strip()
        if result.returncode != 0:
            err_msg = (
                result.stderr.strip()
                if result.stderr
                else f"Command failed: exit code {result.returncode}"
            )
            return stdout_val, err_msg
        return stdout_val, None
    except Exception as e:
        log.error(f"Unexpected error running git command: {e}")
        return "", f"Error running git command: {str(e)}"
