"""Provides components to evaluate nix components and process the result."""

from __future__ import annotations

import logging
import re

from flupdt.common import bash_wrapper

drv_re = re.compile(r".*(/nix/store/.*\.drv).*")

logger = logging.getLogger(__name__)


def evaluate_output(path: str, output: str) -> str | None:
    """Evaluates a given output in a flake.

    :param path: path to flake
    :param output: flake output to be evaluated
    :returns the .drv path on success or None on failure
    :raises RuntimeError: evaluation succeeds but no derivation is found
    """
    logger.info(f"evaluating {output}")
    out = bash_wrapper(f"nix eval {path}#{output} --accept-flake-config")
    logger.debug(out[0])
    logger.debug(out[1])
    logger.debug(out[2])
    if out[2] != 0:
        logger.warning(f"output {output} did not evaluate correctly")
        return None
    drv_match = drv_re.match(out[0])
    if drv_match is None:
        out_msg = "derivation succeeded but output derivation does not contain a derivation"
        raise RuntimeError(out_msg)
    drv = drv_match.group(1)
    logger.debug(f"derivation evaluated to {drv}")

    return drv