"""Gitignore loading utilities.

Provides functions to load .gitignore patterns using the pathspec library.
"""

from __future__ import annotations

import logging
from pathlib import Path  # noqa: TC003 - used at runtime for path operations

from pathspec.gitignore import GitIgnoreSpec

logger = logging.getLogger(__name__)


def load_gitignore_spec(repo_path: Path) -> GitIgnoreSpec | None:
    """Load .gitignore patterns from a repository.

    Args:
        repo_path: Path to repository root.

    Returns:
        GitIgnoreSpec if .gitignore exists and is valid, None otherwise.

    Does nothing if .gitignore doesn't exist or cannot be read.
    """
    gitignore_path = repo_path / ".gitignore"

    if not gitignore_path.is_file():
        logger.debug("No .gitignore found at %s", gitignore_path)
        return None

    try:
        content = gitignore_path.read_text(encoding="utf-8")
    except OSError as e:
        logger.warning("Could not read .gitignore: %s", e)
        return None
    except UnicodeDecodeError as e:
        logger.warning("Could not decode .gitignore as UTF-8: %s", e)
        return None

    if not content.strip():
        logger.debug(".gitignore is empty")
        return None

    try:
        lines = content.splitlines()
        spec = GitIgnoreSpec.from_lines(lines)
        logger.debug("Loaded %d patterns from .gitignore", len(lines))
        return spec
    except (OSError, ValueError) as exc:
        logger.debug("Could not load .gitignore: %s", exc)
