from typing import Dict
from typing import List
import re


def _add_affiliation(author_line: str,
                     enumaffils: Dict,
                     author_entry: List[str],
                     name: str) -> List:
    """
    Add author affiliation to author_entry if one is found in author_line.

    This should deal with these cases
    Smith B(labX) Smith B(1) Smith B(1, 2) Smith B(1 & 2) Smith B(1 and 2)
    """
    en = re.escape(name)
    namerex = r'{}\s*\(([^\(\)]+)'.format(en.replace(' ', 's*'))
    m = re.search(namerex, author_line, flags=re.IGNORECASE)
    if not m:
        return author_entry

    # Now see if we have enumerated references (just commas, digits, &, and)
    affils = m.group(1).rstrip().lstrip()
    affils = re.sub(r'(&|and)/,', ',', affils, flags=re.IGNORECASE)

    if re.match(r'^[\d,\s]+$', affils):
        for affil in affils.split(','):
            if affil in enumaffils:
                author_entry.append(enumaffils[affil])
    else:
        author_entry.append(affils)

    return author_entry