from urllib.parse import parse_qs, urlencode
WINDOW = 1


def table_page_range(page) -> list[list[int]]:
    """
    Calculate windowed pagination ranges for rendering table footers (e.g., [1, 2, 3, 4] or [[1], [4,5,6], [10]]).
    
    Args:
        page: A Django pagination `Page` object.

    Returns:
        list[list[int]]: A list of page number blocks used to render pagination gaps.
    """
    num_pages = page.paginator.num_pages
    if num_pages == 0:
        return []

    current = page.number
    low = max(1, current - WINDOW)
    high = min(num_pages, current + WINDOW)

    main_start = 1 if low <= 2 else low
    main_end = num_pages if high >= num_pages - 1 else high

    out = []

    if main_start > 1:
        out.append([1])

    out.append(list(range(main_start, main_end + 1)))

    if main_end < num_pages:
        out.append([num_pages])

    return out


def update_url(url: str, **kwargs) -> str:
    """
    Update or append URL query parameters safely.

    Args:
        url (str): The original URL.
        **kwargs: The query string parameters to add or override.

    Returns:
        str: The updated URL.
    """
    url_parts = url.split("?")
    path = url_parts[0]
    query_str = url_parts[1] if len(url_parts) > 1 else ""
    query_params = parse_qs(query_str)
    query_params.update(kwargs)
    return path + "?" + urlencode(query_params, doseq=True)


