"""
Shared test fixtures and utilities.

This module contains fixtures and helper functions that are shared across
both unit tests and integration tests.
"""

import subprocess
from pathlib import Path

import pytest

from persuade.constants import GIT_CHECK_IGNORE_TIMEOUT

# =============================================================================
# Git Test Utilities
# =============================================================================


def check_git_available() -> bool:
    """Check if git is available on the system.

    Returns:
        bool: True if git is available, False otherwise
    """
    try:
        result = subprocess.run(
            ["git", "--version"],
            capture_output=True,
            timeout=GIT_CHECK_IGNORE_TIMEOUT,
            check=False,
        )
        return result.returncode == 0
    except (FileNotFoundError, subprocess.TimeoutExpired):
        return False


def init_git_repo(target_path: Path) -> None:
    """Initialize a git repository with test configuration.

    Creates a new git repository and configures test user credentials.

    Args:
        target_path: Directory where the git repository should be initialized

    Raises:
        RuntimeError: If git initialization or configuration fails
    """
    try:
        subprocess.run(["git", "init"], cwd=target_path, capture_output=True, check=True)
        subprocess.run(
            ["git", "config", "user.email", "test@example.com"],
            cwd=target_path,
            capture_output=True,
            check=True,
        )
        subprocess.run(
            ["git", "config", "user.name", "Test User"],
            cwd=target_path,
            capture_output=True,
            check=True,
        )
    except subprocess.CalledProcessError as e:
        raise RuntimeError(f"Failed to initialize git repo at {target_path}: {e}") from e


# =============================================================================
# Shared Git Fixtures
# =============================================================================


@pytest.fixture
def git_repo(tmp_path: Path) -> Path:
    """Create a temporary git repository for testing.

    Skips the test if git is not available on the system.

    Args:
        tmp_path: Pytest's temporary directory fixture

    Returns:
        Path to the initialized git repository
    """
    if not check_git_available():
        pytest.skip("Git not available")
    init_git_repo(tmp_path)
    return tmp_path
