from tubeup.TubeUp import TubeUp
from yt_dlp.utils import sanitize_filename
import glob
import json
import os
import internetarchive

seen_ids = []

tu = TubeUp()

for basename in glob.glob('*.info.json'):
    print(basename + " " + str(os.path.getsize(basename)))
    if os.path.getsize(basename) != 0:
        if not any(x in os.listdir(".") for x in [sanitize_filename(basename[:-10] + ".mp4", restricted=True),
                                                sanitize_filename(basename[:-10] + ".mkv", restricted=True),
                                                sanitize_filename(basename[:-10] + ".webm", restricted=True)]):
            print("no video downloaded")
            continue
        with open(basename, "r", encoding="utf-8") as jf:
            jsons = json.load(jf)
        jsons["extractor"] = "youtube" if "extractor" not in jsons else jsons["extractor"]
        jsons["display_id"] = basename[:-10].split("-")[:-11] if "extractor" not in jsons else jsons["id"]
        jsons["title"] = jsons["fulltitle"] if "extractor" not in jsons else jsons["title"]
        jsons["webpage_url"] = "https://youtube.com/watch?v=%s" % (jsons["display_id"])
        jsons["extractor_key"] = "Youtube"
        with open(basename, "w", encoding="utf-8") as jf:
            jf.write(json.dumps(jsons))
        if not internetarchive.get_item("%s-%s" % (jsons["extractor"], jsons["display_id"])).exists:
            identifier, meta = tu.upload_ia(sanitize_filename(basename[:-10]))
            print("%s, %s" % (identifier, meta))
            print("uploaded %s" % basename)
        else:
            print("skipped %s, item already exists" % basename)
