import json
import re


def uri_reddit(bot, response, matches):
    """ Extract Reddit thread information. """
    post, comments = json.loads(response.text)
    subreddit = matches.group(2)

    # Do we want the OP or a specific reply?
    if matches.group(4):
        data = comments['data']['children'][0]['data']
        title = data['body']
    else:
        data = post['data']['children'][0]['data']
        title = data['title']

    # Un-markdownify a bit.
    title = re.sub(r'\!?\[(.*)\]\((.+)\)', r'\1: \2', title)
    # Clean up.
    title = title.replace('\n', ' ')
    title = re.sub(r'\s+', ' ', title).strip()
    title = title[:300] + '...' * (len(title) > 300)

    # Get metadata.
    meta = None
    if not data.get('score_hidden'):
        meta = '↑↓{}'.format(data['score'])

    return 'Reddit: /r/{}'.format(subreddit), title, meta