"""
Hashing utility functions for large files.

Provides a memory-efficient way to compute MD5 checksums by leveraging
operating system utilities (md5sum, md5, CertUtil). Useful for very
large files that cannot fit into RAM.
"""

# Safe usage: list args, no shell, validated file paths
import subprocess  # nosec: B404
import sys
from pathlib import Path


def compute_md5(file_path: Path) -> str:
    """
    Calculate the MD5 checksum of a file in a memory-efficient way.

    This function computes the MD5 hash without reading the entire file into
    memory at once. Instead, it leverages operating system utilities
    (`md5sum` on Linux, `md5` on macOS, `CertUtil` on Windows). This allows
    processing very large files without running into memory constraints.

    Parameters
    ----------
    file_path : Path
        Path to the file for which the MD5 checksum should be calculated.

    Returns
    -------
    str
        The MD5 checksum of the file as a hexadecimal string.

    Raises
    ------
    RuntimeError
        If the operating system is unsupported.

    Notes
    -----
    This function uses a memory-efficient approach to calculate the MD5 checksum:
        - On Linux, it uses the `md5sum` command.
        - On macOS, it uses the `md5` command.
        - On Windows, it uses `CertUtil -hashfile`.
        - This approach avoids loading the entire file into memory.

    """
    # Linux: use md5sum, macOS: use md5 -q, Windows: use CertUtil
    if sys.platform.startswith("linux"):
        cmd = ["md5sum", str(file_path)]
    elif sys.platform.startswith("darwin"):
        cmd = ["md5", "-q", str(file_path)]
    elif sys.platform.startswith("win"):
        cmd = ["CertUtil", "-hashfile", str(file_path), "MD5"]
    else:
        raise RuntimeError(f"Unsupported OS: {sys.platform}")

    # Run the checksum command
    # Safe: list args, no shell, validated file paths
    result = subprocess.run(cmd, capture_output=True, text=True, check=True)  # noqa: S603 # nosec: B603

    # Windows output is different, parse accordingly
    if sys.platform.startswith("win"):
        lines = [line.strip() for line in result.stdout.splitlines() if line.strip()]
        return lines[1].replace(" ", "").lower()  # Remove spaces and lowercase
    return result.stdout.strip().split()[0].lower()  # Linux/macOS output
