from operator import itemgetter
import requests

# Make an API call and store the response.
url = 'https://hacker-news.firebaseio.com/v0/topstories.json'
r = requests.get(url)
print(f"Status code: {r.status_code}")

# Process information about each submission.
submission_ids = r.json()
submission_dicts = []
for submission_id in submission_ids[:15]:
    url = f"https://hacker-news.firebaseio.com/v0/item/{submission_id}.json"
    r = requests.get(url)
    print(f"id: {submission_id}\tstatus: {r.status_code}")
    response_dict = r.json()

    try:
        title = response_dict['title']
        hn_link = f"http://news.ycombinator.com/item?id={submission_id}"
        if 'descendants' not in response_dict:
            raise NameError
            comments = 0
        else:
            comments = response_dict['descendants']

    except NameError:
        print("No comments in this link.")
    # Build a dictironary for each article.
    else:
        submission_dict = {
            'title': title,
            'hn_link': hn_link,
            'comments': comments,
        }
        submission_dicts.append(submission_dict)
submission_dicts = sorted(submission_dicts, key=itemgetter('comments'), reverse=True)

for submission_dict in submission_dicts:
    print(f"\nTitle: {submission_dict['title']}")
    print(f"Discussion link: {submission_dict['hn_link']}")
    print(f"Comments: {submission_dict['comments']}")