# Simple helpers copied out of views.py logic.

def filter_items(items, q, status_filter):
    """
    items: a Django QuerySet or list of Item objects
    q: search string
    status_filter: one of 'all', 'expired', 'out', 'low', 'ok'
    Returns a list.
    """
    # If items is a QuerySet we can still iterate; then convert to list at end.
    if q:
        # If items is a QuerySet we can use icontains filters,
        # otherwise (if already a list) we do Python filtering.
        try:
            items = items.filter(name__icontains=q) | items.filter(product_id__icontains=q)
        except Exception:
            items = [i for i in items if (q.lower() in i.name.lower()) or (q.lower() in i.product_id.lower())]

    # Status filtering must happen in Python because status is computed.
    if status_filter != "all":
        items = [i for i in items if i.status == status_filter]
    else:
        items = list(items)

    return items


def sort_items(items, sort):
    """
    items: list of Item objects
    sort: one of 'name_asc', 'status_severity', 'days_left_asc', 'created_desc'
    Returns the same list sorted (in-place behavior but also returns it).
    """
    if sort == "name_asc":
        items.sort(key=lambda x: x.name.lower())
    elif sort == "status_severity":
        rank = {"expired": 3, "out": 2, "low": 1, "ok": 0}
        items.sort(key=lambda x: (-rank.get(x.status, 0), x.name.lower()))
    elif sort == "days_left_asc":
        def dl(i):
            # Large number pushes None days_left to end.
            return 999999 if i.days_left is None else i.days_left
        items.sort(key=lambda x: dl(x))
    else:  # created_desc
        items.sort(key=lambda x: x.created_at, reverse=True)
    return items


def summarize_counts(items):
    """
    Count basic status categories.
    """
    return {
        "total": len(items),
        "low": sum(1 for i in items if i.status == "low"),
        "out": sum(1 for i in items if i.status == "out"),
        "expired": sum(1 for i in items if i.status == "expired"),
    }