from typing import Counter


def _get_common_hdr_value(base, extns, key):
    """
    Helper function to get a common header value from a list of extensions.

    Parameters
    ----------
    base : :any:`astrodata.AstroData`
        Original AstroData instance that may contain useful headers
    extns : iterable of :any:`astrodata.Astrodata`
        AstroData extensions to be examined
    key : str
        The FITS header key to find in each extension 

    Raises
    ------
    KeyError
        If the ``key`` parameter has multiple values across the extensions
    """

    # Get the keyword from every extension
    vals = [x.hdr.get(key) for x in extns]
    c = Counter(vals)
    # Not all extensions may not contain the keyword, but we don't care about blanks
    del c[None]
    # If the keyword doesn't exist at all in the extensions,
    # then use the base value instead
    if len(c) == 0:
        return base.phu.get(key)
    # Check that every extension has the same value for the keyword
    most_common = c.most_common()
    base = most_common[0]
    if len(most_common) != 1:
        # Ignore single errors in this header, as long as the most common
        # value is more than half
        if base[1] < len(vals) // 2:
          raise KeyError('multiple values for ' + key + " " + str(vals))

        for val in most_common[1:]:
          if val[1] == 1:
            print('Ignoring single error in', key, 'header')
          else:
            raise KeyError('multiple values for ' + key + " " + str(vals))

    return base[0]