import requests
import yaml


def refresh_token(url, client_id, refresh_token, scope=None):
    """Refresh the access token and id token.

    See https://auth0.com/docs/tokens/refresh-tokens/use-refresh-tokens

    :param url: Authentication URL
    :param client_id: Client ID of this CLI tool
    :param refresh_token: Refresh token to use
    :param scope: Space-delimited list of requested scope permissions
    :return dict: Refresh response
    """
    token_url = url + '/oauth/token'
    payload = {
        'grant_type': 'refresh_token',
        'client_id': client_id,
        'refresh_token': refresh_token,
    }
    if scope:
        payload['scope'] = scope
    headers = {'content-type': 'application/x-www-form-urlencoded'}
    response = requests.post(url=token_url, data=payload, headers=headers)
    res = yaml.safe_load(response.text)
    return res