#! /usr/bin/python

import re
import requests
import sys
import tweepy
import urllib.request

_rt = re.compile(r'^(?P<rt>RT\s.+?: ?)')

api_key = ""
api_secrets = ""
access_token = ""
access_secret = ""
bearer_token = ""

client = tweepy.Client(bearer_token=bearer_token, 
    consumer_key=api_key, 
    consumer_secret=api_secrets, 
    access_token=access_token, 
    access_token_secret=access_secret, 
    return_type = tweepy.Response,
    wait_on_rate_limit=True)

def query(username, maxnum=10):
  tweets = client.search_recent_tweets(query="from:" + username, 
      tweet_fields=['author_id', 'created_at'],
      expansions='referenced_tweets.id',
      max_results=maxnum)

  if tweets.data is None:
    print("User " + username + " made no tweets during the last 7 days.")
    return None

  for elem in reversed(tweets.data):
    if elem.referenced_tweets is not None and elem.referenced_tweets[0].type == "retweeted":
      initial_text = elem.text
      match = re.search(_rt, initial_text)
      rt = None
      if match is not None:
        rt = match.group("rt")

      id = elem.referenced_tweets[0].id
      t = client.get_tweet(id)
      print(rt + t.data.text + "\n" + "[By @" + username + " at " + str(elem.created_at) + "]")
    else:
      print(elem.text + "\n" + "[By @" + username + " at " + str(elem.created_at) + "]")

    print("---------------------------------")

def main():
  if len(sys.argv) == 2 or len(sys.argv) == 3:
    if len(sys.argv) == 3:
      query(sys.argv[1], sys.argv[2])
    else:
      query(sys.argv[1])
  else:
    print("Usage: './twfetch.py USERNAME [NUM_ENTRIES]'")

if __name__ == '__main__':
  main()