import click


def get_checkpoint(db, id_or_alias):
    """Returns checkpoint entry in `db` indicated by `id_or_alias`.

    First tries to match an ID, then an alias. For the case of repeated
    aliases, will first match local checkpoints and then remotes. In both
    cases, matching will be newest first.
    """
    # Go through the checkpoints ordered by creation date. There shouldn't be
    # repeated aliases, but if there are, prioritize the newest one.
    local_checkpoints = sorted(
        [c for c in db['checkpoints'] if c['source'] == 'local'],
        key=lambda c: c['created_at'], reverse=True
    )
    remote_checkpoints = sorted(
        [c for c in db['checkpoints'] if c['source'] == 'remote'],
        key=lambda c: c['created_at'], reverse=True
    )

    selected = []
    for cp in local_checkpoints:
        if cp['id'] == id_or_alias or cp['alias'] == id_or_alias:
            selected.append(cp)

    for cp in remote_checkpoints:
        if cp['id'] == id_or_alias or cp['alias'] == id_or_alias:
            selected.append(cp)

    if len(selected) < 1:
        return None

    if len(selected) > 1:
        click.echo(
            "Multiple checkpoints found for '{}' ({}). Returning '{}'.".format(
                id_or_alias, len(selected), selected[0]['id']
            )
        )

    return selected[0]