"""Git and GitHub CLI helpers.

Used for prerequisite validation (is gh/git installed, is GitHub
accessible) and later for cloning repos and running diffs.
"""

import logging
import shutil
import subprocess
from typing import Any

logger = logging.getLogger(__name__)


def check_git_installed() -> dict[str, Any]:
    """Check if git is installed and return version info."""
    git_path = shutil.which("git")
    if not git_path:
        return {"installed": False, "version": None, "path": None}

    try:
        result = subprocess.run(
            ["git", "--version"],
            capture_output=True,
            text=True,
            timeout=10,
        )
        version = result.stdout.strip() if result.returncode == 0 else "unknown"
        return {"installed": True, "version": version, "path": git_path}
    except (subprocess.TimeoutExpired, FileNotFoundError):
        return {"installed": True, "version": "unknown", "path": git_path}


def check_github_access() -> dict[str, Any]:
    """Check if GitHub is accessible via gh CLI or SSH.

    Returns dict with 'method' ('gh_cli', 'ssh', or None),
    'authenticated' (bool), 'username' (str or None),
    and 'message' (str).
    """
    gh_path = shutil.which("gh")
    if gh_path:
        try:
            result = subprocess.run(
                ["gh", "auth", "status"],
                capture_output=True,
                text=True,
                timeout=15,
            )
            if result.returncode == 0:
                output = result.stdout + result.stderr
                username = None
                for line in output.splitlines():
                    if "account" in line.lower():
                        parts = line.strip().split()
                        for i, part in enumerate(parts):
                            if part.lower() == "account":
                                if i + 1 < len(parts):
                                    username = parts[i + 1]
                                break
                return {
                    "method": "gh_cli",
                    "authenticated": True,
                    "username": username,
                    "message": "GitHub CLI authenticated",
                }
            else:
                return {
                    "method": "gh_cli",
                    "authenticated": False,
                    "username": None,
                    "message": (
                        "GitHub CLI found but not authenticated. "
                        "Run: gh auth login"
                    ),
                }
        except (subprocess.TimeoutExpired, FileNotFoundError):
            pass

    try:
        result = subprocess.run(
            ["ssh", "-T", "git@github.com"],
            capture_output=True,
            text=True,
            timeout=10,
        )
        output = result.stdout + result.stderr
        if "successfully authenticated" in output.lower():
            return {
                "method": "ssh",
                "authenticated": True,
                "username": None,
                "message": "SSH access to GitHub authenticated",
            }
    except (subprocess.TimeoutExpired, FileNotFoundError):
        pass

    return {
        "method": None,
        "authenticated": False,
        "username": None,
        "message": (
            "No GitHub access found. Install GitHub CLI (gh) and run 'gh auth login', "
            "or configure SSH keys for git@github.com. "
            "GitHub access is required to clone CloudSense package repositories."
        ),
    }
