import functools


def matches_segment(segment_name, conditions=None):
    """
    Decorator used to match a x12 processing rule to a x12 segment.
    Matches are made by segment type with optional matching conditions.
    Matching conditions are limited to equality checks.
    The wrapped function is updated to include a segment_grouping attribute equal to the segment_name.
    :param segment_name: The X12 segment name
    :param conditions: Dictionary of conditions. Key = x12 segment field index (zero based), Value = field value.
    :return: the decorated function
    """
    if conditions is None:
        conditions = {}

    def decorator(func):
        func.segment_grouping = segment_name.upper()

        @functools.wraps(func)
        def wrapped(segment_data, data_context, data_cache):
            if segment_name.upper() == segment_data[0].upper():
                unmatched = {k: v for k, v in conditions.items() if segment_data[k].upper() != v.upper()}
                if len(unmatched) == 0:
                    func(segment_data, data_context, data_cache)
        return wrapped

    return decorator