"""Git repository information extraction."""

import subprocess
from pathlib import Path

from apiposture_pro.features.historical_tracking.models import GitInfo


def get_git_info(project_path: Path) -> GitInfo:
    """
    Extract Git repository information.

    Args:
        project_path: Path to project directory

    Returns:
        GitInfo with repository metadata
    """
    git_info = GitInfo()

    try:
        # Check if it's a git repository
        result = subprocess.run(
            ["git", "rev-parse", "--git-dir"],
            cwd=project_path,
            capture_output=True,
            text=True,
            timeout=5,
        )

        if result.returncode != 0:
            return git_info  # Not a git repository

        # Get current commit SHA
        result = subprocess.run(
            ["git", "rev-parse", "HEAD"],
            cwd=project_path,
            capture_output=True,
            text=True,
            timeout=5,
        )
        if result.returncode == 0:
            git_info.commit_sha = result.stdout.strip()

        # Get current branch
        result = subprocess.run(
            ["git", "rev-parse", "--abbrev-ref", "HEAD"],
            cwd=project_path,
            capture_output=True,
            text=True,
            timeout=5,
        )
        if result.returncode == 0:
            git_info.branch = result.stdout.strip()

        # Check if working directory is dirty
        result = subprocess.run(
            ["git", "status", "--porcelain"],
            cwd=project_path,
            capture_output=True,
            text=True,
            timeout=5,
        )
        if result.returncode == 0:
            git_info.is_dirty = bool(result.stdout.strip())

        # Get remote URL
        result = subprocess.run(
            ["git", "config", "--get", "remote.origin.url"],
            cwd=project_path,
            capture_output=True,
            text=True,
            timeout=5,
        )
        if result.returncode == 0:
            git_info.remote_url = result.stdout.strip()

    except (subprocess.TimeoutExpired, FileNotFoundError, OSError):
        # Git not available or timeout
        pass

    return git_info
