from typing import List
from typing import Tuple


def get_range_directives_gatecharacterization(
    fit_range_update_directives: List[str],
    current_valid_ranges: List[Tuple[float, float]],
    safety_voltage_ranges: List[Tuple[float, float]],
    dV_stop: float = 0.1,
) -> Tuple[List[str], List[str]]:
    """Determines voltage range directives to update ranges for a subsequent
    tuning stage iteration. It checks if the voltage range update directives
    determined previously, e.g by a fit class, can be carried out based on the
    supplied safety ranges.

    Args:
        fit_range_update_directives: Directives determined previously, such as
            during fitting.
        current_valid_ranges: Voltage range swept at previous iteration.
        safety_voltage_ranges: Safety range of gate/voltage parameter swept.
        dV_stop: Mininmal voltage difference between current and safety ranges
            for current ranges to be changed. Default is 100mV.

    Returns:
        list: Range update directives, e.g. 'x more negative'.
        list: Issues encountered, e.g. 'positive safety voltage reached'.
    """

    safety_v_range = safety_voltage_ranges[0]
    current_v_range = current_valid_ranges[0]

    neg_range_avail = abs(current_v_range[0] - safety_v_range[0])
    pos_range_avail = abs(current_v_range[1] - safety_v_range[1])

    range_update_directives = []
    issues = []

    for update_directive in fit_range_update_directives:
        if update_directive == "x more negative":
            if neg_range_avail >= dV_stop:
                range_update_directives.append("x more negative")
            else:
                issues.append("negative safety voltage reached")
        elif update_directive == "x more positive":
            if pos_range_avail >= dV_stop:
                range_update_directives.append("x more positive")
            else:
                issues.append("positive safety voltage reached")
        else:
            raise KeyError("Unknown voltage range update directive.")

    return range_update_directives, issues