import re
from datetime import datetime
import logging


def sort_by_closest(metas, closest_datetime):
    """Given a list of index snapshot metadata, and a datetime reference, sorts metadata in-place by temporally closest to reference time"""
    
    closest_datetime = closest_datetime.replace(tzinfo=None)
    def delta_to_approx_crawl_date(meta):
        m = re.search(r"CC-MAIN-(\d\d\d\d)(\d\d)(\d\d)", meta['filename']) # use filename as proxy for crawl time
        if m:
            year, month, day = m.group(1), m.group(2), m.group(3)
            crawl_time = datetime(int(year), int(month), int(day), tzinfo=None)
            delta = abs(closest_datetime - crawl_time)
            return delta
    try:
        metas.sort(key=delta_to_approx_crawl_date)
        return True
    except Exception as e:
        logging.error("Could not sort CommonCrawl snapshots by closest reference time: " + str(e))
        return False