"""Utility to diff nix derivations."""

import logging
import shutil

from flupdt.common import bash_wrapper

logger = logging.getLogger(__name__)


def compare_derivations(
    path_to_flake: str, path_to_pre_drv: str, path_to_post_drv: str, *, soft_failure: bool = True
) -> str:
    """Gets all derivations present in a flake.

    :param path_to_flake: path to flake to be checked
    :returns a list of all valid derivations in the flake
    :raises RuntimeError: fails if nix is not present in the PATH
    """
    nvd_path = shutil.which("nvd")
    if nvd_path is None:
        status_msg = "nvd is not available in the PATH, please verify that it is installed"
        raise RuntimeError(status_msg)
    stdout, stderr, returncode = bash_wrapper(
        f"{nvd_path} diff {path_to_pre_drv} {path_to_post_drv}", path=path_to_flake
    )

    if returncode != 0:
        log_func = logger.error
        if soft_failure:
            log_func = logger.warning
        logger.warning(f"diff failed for {path_to_pre_drv} and {path_to_post_drv}")
        log_func(stderr)

    return stdout