import requests


def get_all_topk_articles(day_range):
    """
    Accepts a list of dicts with year, month, and day values
    Returns a dictionary (article titles as keys)
        with all articles that were in the topk list during those dates
        and the pageview counts for each of the dates the article appeared in the topk

    Example query: https://wikimedia.org/api/rest_v1/metrics/pageviews/top/en.wikipedia.org/all-access/2020/03/31
    """

    q_template= "https://wikimedia.org/api/rest_v1/metrics/pageviews/top/en.wikipedia.org/all-access/{year}/{month}/{day}"

    all_articles = {}

    for day_val in day_range:
        q_string = q_template.format(**day_val)
        r = requests.get(
            url = q_string,
            headers = {'User-Agent': "hostbot (https://wikitech.wikimedia.org/wiki/Tool:HostBot, jonnymorgan.esq@gmail.com)"},
                )
    #     print(r.headers)
    #     print(r.text)
    #     print(r.url)
        response = r.json()
    #     print(response)

#         response = requests.get(q_string).json()
        top_articles_list = response['items'][0]['articles']

        for ar in top_articles_list:
            if ar['article'] in all_articles.keys():
                all_articles[ar['article']].update({day_val['api_date'] : ar['views']})

            else:
                all_articles.update({ar['article'] : {day_val['api_date'] : ar['views']}})

    return all_articles