import pathlib
from datetime import datetime


def dedup_prefix(files_to_merge):
    """
    Deduplicate a list of files based on their prefix (before the dash).

    For example, given these files:
    - Prefix-11122020.blk
    - Prefix-12122020.blk
    - Other-11122020.blk

    This would return Prefix-12122020.blk and Other-11122020.blk files. These
    are the most recent files (by DDMMYYYY) for the given prefix.
    """
    most_recent_date = {}
    most_recent = {}
    for (index, filename) in enumerate(files_to_merge):
        path = pathlib.Path(filename)
        try:
            (prefix, date_str) = path.stem.rsplit("-", maxsplit=1)
        except ValueError:
            # no date suffix, ensure we include the file
            most_recent[filename] = (index, filename)
            continue
        date = datetime.strptime(date_str, "%d%m%Y").date()
        key = (prefix, path.suffix.lower())
        if key not in most_recent_date or most_recent_date[key] < date:
            most_recent_date[key] = date
            most_recent[key] = (index, filename)

    return [filename for (_, filename) in sorted(most_recent.values())]