import requests


def handle_429(response, default_delay=70):
    """ Handle 429: output warning and suuggested next steps

    The user has exceeded their rate limit. This method will return the
    number of seconds the caller should wait based on the dictated
    rate-limiting logic specified by the API.

    Parameters
    ----------
    response: requests.Response
        The response from the HTTP request

    default_delay: int
        Default number of seconds to wait between requests. This
        integer should be non-negative.

    Returns
    -------
    delay: int
        The number of seconds the caller should wait until the
        next PerSecData API call. This number will be non-negative.
    """
    assert isinstance(response, requests.Response)
    assert response.status_code == 429
    assert default_delay >= 0

    url = response.request.url
    delay = default_delay
    response_retry_delay = response.headers.get('retry-after')

    print('HTTP 429 API throttled')
    if response_retry_delay:
        print(f'Will retry after: {response_retry_delay} seconds...')
        delay = int(response_retry_delay)
    else:
        print(f'Do not know wait time to retry for request: {url}')
        print(f'Continuing with next request after {default_delay} sec throttle window time...')
        delay = default_delay

    assert delay >= 0

    return delay