from typing import Counter
from typing import Dict


def sort_counter(counter: Counter, alphabetical: bool) -> Dict[str, int]:
    """Sort counter according to custom logic.

    Args:
        counter: Imported packages and their corresponding count
        alphabetical: Whether to sort counter alphabetically

    Returns:
        Sorted counter
    """
    def custom_order(tup):
        # Sort first by count (descending), and then by name
        return -tup[1], tup[0]

    sort_key = None if alphabetical else custom_order
    return dict(sorted(counter.items(), key=sort_key))