"""List and sequence snippets."""
from collections import Counter
from itertools import islice, zip_longest


def chunk(items, size):
    """Split a list into consecutive pieces of at most ``size`` items.

    >>> chunk([1, 2, 3, 4, 5], 2)
    [[1, 2], [3, 4], [5]]
    """
    if size < 1:
        raise ValueError("size must be >= 1")
    return [items[i:i + size] for i in range(0, len(items), size)]


def flatten(nested):
    """Flatten one level of nesting.

    >>> flatten([[1, 2], [3], [], [4, 5]])
    [1, 2, 3, 4, 5]
    """
    return [x for sub in nested for x in sub]


def deep_flatten(nested):
    """Flatten lists and tuples nested to any depth (strings stay whole).

    >>> deep_flatten([1, [2, [3, (4, 5)]], "ab"])
    [1, 2, 3, 4, 5, 'ab']
    """
    out = []
    for x in nested:
        if isinstance(x, (list, tuple)):
            out.extend(deep_flatten(x))
        else:
            out.append(x)
    return out


def unique(items):
    """Remove duplicates while keeping the first-seen order.

    >>> unique([3, 1, 3, 2, 1])
    [3, 1, 2]
    """
    return list(dict.fromkeys(items))


def unique_by(items, key):
    """Remove duplicates by a key function, keeping the first item per key.

    >>> unique_by(["apple", "Avocado", "banana"], key=lambda s: s[0].lower())
    ['apple', 'banana']
    """
    seen = set()
    out = []
    for x in items:
        k = key(x)
        if k not in seen:
            seen.add(k)
            out.append(x)
    return out


def duplicates(items):
    """Return the values that appear more than once, in first-seen order.

    >>> duplicates([1, 2, 2, 3, 3, 3, 4])
    [2, 3]
    """
    return [x for x, n in Counter(items).items() if n > 1]


def compact(items):
    """Drop falsy values (0, '', None, False, empty containers).

    >>> compact([0, 1, '', 'a', None, [], [2], False])
    [1, 'a', [2]]
    """
    return [x for x in items if x]


def group_by(items, key):
    """Group items into a dict of lists by a key function.

    >>> group_by(["one", "two", "three"], len)
    {3: ['one', 'two'], 5: ['three']}
    """
    groups = {}
    for x in items:
        groups.setdefault(key(x), []).append(x)
    return groups


def partition(items, predicate):
    """Split into (matching, not_matching) in a single pass.

    >>> partition(range(6), lambda n: n % 2 == 0)
    ([0, 2, 4], [1, 3, 5])
    """
    yes, no = [], []
    for x in items:
        (yes if predicate(x) else no).append(x)
    return yes, no


def most_frequent(items):
    """Return the most common value (the first one seen wins a tie).

    >>> most_frequent(['a', 'b', 'a', 'c', 'b', 'a'])
    'a'
    """
    return Counter(items).most_common(1)[0][0]


def transpose(rows):
    """Swap rows and columns of a rectangular 2D list.

    >>> transpose([[1, 2, 3], [4, 5, 6]])
    [[1, 4], [2, 5], [3, 6]]
    """
    return [list(col) for col in zip(*rows)]


def zip_fill(*seqs, fill=None):
    """Zip sequences of different lengths, padding the short ones.

    >>> zip_fill([1, 2, 3], ['a'], fill='-')
    [(1, 'a'), (2, '-'), (3, '-')]
    """
    return list(zip_longest(*seqs, fillvalue=fill))


def rotate(items, n):
    """Rotate a list ``n`` places to the left (negative ``n`` rotates right).

    >>> rotate([1, 2, 3, 4, 5], 2)
    [3, 4, 5, 1, 2]
    >>> rotate([1, 2, 3, 4, 5], -1)
    [5, 1, 2, 3, 4]
    """
    if not items:
        return []
    n %= len(items)
    return items[n:] + items[:n]


def sliding_window(items, size):
    """Yield overlapping windows of ``size`` consecutive items.

    >>> list(sliding_window([1, 2, 3, 4], 3))
    [(1, 2, 3), (2, 3, 4)]
    """
    it = iter(items)
    window = tuple(islice(it, size))
    if len(window) == size:
        yield window
    for x in it:
        window = window[1:] + (x,)
        yield window


def difference(a, b):
    """Items of ``a`` not in ``b``, keeping order and duplicates of ``a``.

    >>> difference([1, 2, 3, 2, 4], [2, 4])
    [1, 3]
    """
    exclude = set(b)
    return [x for x in a if x not in exclude]


def intersection(a, b):
    """Items of ``a`` that are also in ``b``, keeping the order of ``a``.

    >>> intersection([5, 1, 3, 1], [1, 5])
    [5, 1, 1]
    """
    keep = set(b)
    return [x for x in a if x in keep]


def all_equal(items):
    """True if every element is equal (also True for an empty list).

    >>> all_equal([2, 2, 2]), all_equal([2, 3]), all_equal([])
    (True, False, True)
    """
    return len(set(items)) <= 1 if all(_hashable(x) for x in items) else all(x == items[0] for x in items)


def _hashable(x):
    try:
        hash(x)
    except TypeError:
        return False
    return True


def index_all(items, value):
    """Every index where ``value`` occurs.

    >>> index_all(['a', 'b', 'a', 'c', 'a'], 'a')
    [0, 2, 4]
    """
    return [i for i, x in enumerate(items) if x == value]


def sort_by_keys(items, *keys):
    """Sort dicts by several keys; prefix a key with '-' for descending.

    >>> people = [{'n': 'b', 'age': 30}, {'n': 'a', 'age': 30}, {'n': 'c', 'age': 25}]
    >>> [p['n'] for p in sort_by_keys(people, '-age', 'n')]
    ['a', 'b', 'c']
    """
    result = list(items)
    for key in reversed(keys):  # stable sort: apply the least important key first
        desc = key.startswith('-')
        name = key.lstrip('-')
        result.sort(key=lambda d: d[name], reverse=desc)
    return result


def first(items, predicate=None, default=None):
    """First item (optionally the first that matches ``predicate``), else ``default``.

    >>> first([1, 4, 6], lambda n: n > 3)
    4
    >>> first([], default='none')
    'none'
    """
    return next((x for x in items if predicate is None or predicate(x)), default)
