import logging


def _infill_variable(cruncher_i, req_variable, leader_i, to_fill_i, **kwargs):
    """
    A function used to iterate the actual crunching if the data doesn't already
    exist.
    Parameters
    ----------
    cruncher_i : :obj: silicone cruncher
        the initiated silicone cruncher to use for the infilling

    req_variable : str
        The follower variable to infill.

    leader_i : list[str]
        The leader variable to guide the infilling.

    to_fill_i : IamDataFrame
        The dataframe to infill.

    kwargs : Dict
        Any key word arguments to include in the cruncher calculation

    Returns
    -------
    :obj:IamDataFrame
        The infilled component of the dataframe (or None if no infilling done)
    """
    filler = cruncher_i.derive_relationship(req_variable, leader_i, **kwargs)
    # only fill for scenarios who don't have that variable
    # quieten logging about empty data frame as it doesn't matter here
    logging.getLogger("pyam.core").setLevel(logging.CRITICAL)
    not_to_fill = to_fill_i.filter(variable=req_variable)

    to_fill_var = to_fill_i.copy()
    if not not_to_fill.data.empty:
        for (model, scenario), _ in not_to_fill.data.groupby(["model", "scenario"]):
            to_fill_var = to_fill_var.filter(model=model, scenario=scenario, keep=False)
    if not to_fill_var.data.empty:
        interpolated = filler(to_fill_var)
        return interpolated
    logging.getLogger("pyam.core").setLevel(logging.WARNING)
    return None