import csv
import re


def lookup_county(county_code, office_code):
    """ Maps county numbers from a docket number (41, 20, etc.) to county
    names.


    The MDJ Docket search requires a user to select the name of the county
    to search. We can get the name of the county from a Docket Number, but it
    is not straightforward.

    MDJ Docket numbers start with "MDJ-012345". The five digits are a
    county code and an office code. Some counties share the same code, so the
    name of a county depends on all five of these digits.

    This method uses a reference table to match the county and office codes
    to the correct county's name.

    Args:
        county_code (str): Two-digit code that (usually) identifies a county.
        office_code (str): Three more digits that are sometimes necessary to
        identify a county, when two counties share the same county code.

    Returns:
        The name of a county, or None, if no match was found. Raise an
        AssertionError if multiple matches were found, because then something
        is wrong with the reference table.

    """
    full_five_digits = "{}{}".format(county_code, office_code)
    with open("references/county_lookup.csv", "r") as f:
        reader = csv.DictReader(f)
        matches = []
        for row in reader:
            if re.match(row["regex"], full_five_digits):
                matches.append(row["County"])
    assert len(matches) <= 1, "Error: Found multiple matches for {}".format(
        full_five_digits)
    if len(matches) == 0:
        return None
    return matches[0]