import os
import tweepy
import json
import glob
import subprocess
import random
API_KEY = "API_KEY"
API_KEY_SECRET = "API_KEY_SECRET"
access_tokens = []
if os.path.exists("./credentials.json"):
    with open("credentials.json", "r") as f:
        access_tokens = json.load(f)

oauth1_user_handler = None
try:
    oauth1_user_handler = tweepy.OAuth1UserHandler(
        API_KEY, API_KEY_SECRET,
        access_tokens[0], access_tokens[1],
        callback="oob"
    )
except IndexError:
    oauth1_user_handler = tweepy.OAuth1UserHandler(
        API_KEY, API_KEY_SECRET,
        callback="oob"
    )

if not access_tokens:
    print(oauth1_user_handler.get_authorization_url())
    pin = input("Input PIN: ")
    access_tokens.extend(oauth1_user_handler.get_access_token(pin))
    with open("credentials.json", "w") as f:
        json.dump(access_tokens, f)

episode = random.choice(list(glob.glob("D:\\Movies\\Anime\\Kill Me Baby\\*.mkv")))
result = subprocess.run(["ffprobe.exe", "-v", "quiet", "-of", "csv=p=0",
                  "-show_entries", "format=duration", episode],
                 capture_output=True, text=True)
test = random.randint(0, round(float(result.stdout.strip())))
result = subprocess.run(["ffmpeg.exe", "-hide_banner", "-loglevel",
                  "warning", "-i", episode, "-y", "-frames:v", "1",
                  "-ss", str(test), "screencap.jpg"])

api = tweepy.API(oauth1_user_handler)
with open("screencap.jpg", "rb") as f:
    media = api.media_upload(None, file=f)
api.update_status("", media_ids=[media.media_id_string])
