from math import ceil


def paginate(query, page, page_size):
    page = max(int(page), 1)
    page_size = max(int(page_size), 1)
    total = query.count()
    items = query.offset((page - 1) * page_size).limit(page_size).all()
    return {
        "items": items,
        "page": page,
        "page_size": page_size,
        "total": total,
        "pages": ceil(total / page_size) if page_size else 0,
    }
