import logging


def filter_terms(date, terms):
    """
    Filter the terms a legislator to a date
    Args:
        date (string in YYYY-MM-DD format):
            Date by which to select the term
        terms (list):
            List of dicts, each with a "start" and "end" key in the same format
    Returns:
        First element of `term` that intersects with `date`
    """
    for term in reversed(terms):
        if term["start"] <= date <= term["end"]: 
            return term

    last_term = terms[-1]
    logging.warning(
        f"Legislator's terms do not overlap with {date} "
        f" using most recent term, ending {last_term['end']}"
    )
    return last_term