import requests
from apollo.exceptions import RecaptchaVerificationException
import logging

logger = logging.getLogger(__name__)


def verify_token(token, recaptcha_secret_key=None):
    """ takes a token as generated by a frontend verification request (see https://developers.google.com/recaptcha/docs/v3
    for reference) and verifies the token against Googles' services
    :param token: `str` token as given by the frontend
    :param recaptcha_secret_key: `str` secret key for the recaptcha service
    :return: `bool` True if the verification succeeded, False otherwise
    :raises: `apollo.exceptions.RecaptchaVerificationException` if verification returns an error code
    """
    url = 'https://www.google.com/recaptcha/api/siteverify'
    data = {
        'secret': recaptcha_secret_key,
        'response': token
    }

    resp = requests.post(url, data=data)

    if not resp.ok:
        logger.error('got bad response from recaptcha API: %s' % resp.content)
        raise RecaptchaVerificationException('got error response from recaptcha verification (status = %s)' % resp.status_code)

    resp_json = resp.json()
    logger.debug('got response from recaptcha verification: JSON = %s' % resp_json)

    if resp_json.get('error-codes'):
        raise RecaptchaVerificationException('error codes in recaptcha verification: %s' % resp_json.get('error-codes'))

    return resp_json.get('success')