# -*- coding: utf-8 -*-
import requests
import urlparse

from distribution import app


def get_amp_cache_url(article_amp_url, url_pattern='{}{}'):
    item_url = urlparse.urlparse(article_amp_url)
    amp_path = '/public/amp{}'.format(item_url.path)
    amp_url = urlparse.urlunparse([
        item_url.scheme, app.config['AMP_PUBLIC_HOST'], amp_path, '', '', ''])

    app.logger.debug("Public AMP URL {}".format(amp_url))
    parse_result = urlparse.urlparse(amp_url)
    return url_pattern.format(
        app.config['AMP_CACHE_URL'],
        'c/{}{}{}'.format('s/' if parse_result.scheme == 'https' else '',
                          parse_result.netloc, parse_result.path))


def update_cache(article_amp_url):
    """
    Update the page cached version in the AMP CDN if it's exists.
    More info here: https://developers.google.com/amp/cache/update-ping
    """
    try:
        if requests.head(get_amp_cache_url(article_amp_url), verify=False).status_code == 200:
            response = requests.get(get_amp_cache_url(article_amp_url, '{}update-ping/{}'), verify=False)

            if response.status_code != 204:
                app.logger.error(
                    "AMP cache failed with status code {}. Response content: {}".format(
                        response.status_code, response.text))
    except Exception as e:
        app.logger.exception(e)
