"""SHA256 checksum utilities for skill content."""

import hashlib
from pathlib import Path

# Files/dirs generated by neoskills or build tools — not intrinsic skill content
_SKIP_NAMES = {
    "metadata.yaml",
    "provenance.yaml",
    ".gitkeep",
    ".DS_Store",
    "__pycache__",
}
_SKIP_SUFFIXES = {".pyc", ".pyo"}


def _is_intrinsic(path: Path) -> bool:
    """Return True if this file is intrinsic skill content (not generated metadata)."""
    if path.name in _SKIP_NAMES:
        return False
    if path.suffix in _SKIP_SUFFIXES:
        return False
    # Skip anything inside __pycache__ or .git directories
    for part in path.parts:
        if part in ("__pycache__", ".git"):
            return False
    return True


def checksum_string(content: str) -> str:
    """SHA256 hash of a string."""
    return hashlib.sha256(content.encode("utf-8")).hexdigest()


def checksum_file(filepath: Path) -> str:
    """SHA256 hash of a file's contents."""
    return checksum_string(filepath.read_text(encoding="utf-8"))


def checksum_directory(dirpath: Path) -> str:
    """SHA256 hash of intrinsic skill files in a directory.

    Skips neoskills-generated metadata (metadata.yaml, provenance.yaml),
    build artifacts (__pycache__), and VCS files (.git, .gitkeep).
    Each file contributes its relative path + content to the digest.
    """
    h = hashlib.sha256()
    for f in sorted(dirpath.rglob("*")):
        if f.is_file() and _is_intrinsic(f.relative_to(dirpath)):
            rel = f.relative_to(dirpath)
            h.update(str(rel).encode("utf-8"))
            h.update(f.read_bytes())
    return h.hexdigest()
