import json

with open(f"./scripts/grouvee.json", "r", encoding="utf-8") as log_file:
    orig_log_items = json.load(log_file)

for log in ["log", "current", "wishlist"]:
    print(f"Processing {log}…")

    with open(f"./data/games/{log}.json", "r", encoding="utf-8") as log_file:
        log_items = json.load(log_file)

    for i, item in enumerate(log_items):
        print(f"Processing {item['Title']}...")

        if "GiantBomb ID" in item:
            orig_item = [""]
            if "" != item["GiantBomb ID"]:
                orig_item = [
                    orig_item
                    for orig_item in orig_log_items
                    if orig_item["giantbomb_id"] == int(item["GiantBomb ID"])
                ]

            elif "" == item["GiantBomb ID"]:
                orig_item = [
                    orig_item
                    for orig_item in orig_log_items
                    if orig_item["name"] == item["Title"]
                ]

            if [] == orig_item:
                print(f"No item {item['Title']} found in original log!")
                log_items[i] = item
                break

            elif 1 < len(orig_item):
                raise Exception(f"Multiple items returned for {item['Title']}!")

            else:
                orig_item = orig_item[0]

            if "Wish List" in orig_item["shelves"]:
                item["date_added"] = orig_item["shelves"]["Wish List"]["date_added"]

            elif "Backlog" in orig_item["shelves"]:
                item["date_added"] = orig_item["shelves"]["Backlog"]["date_added"]

            elif "Played" in orig_item["shelves"] and "log" == log:
                item["date_added"] = orig_item["shelves"]["Played"]["date_added"]

            else:
                print(f"No date_added for {item['Title']}!")

        log_items[i] = item

        print(f"Finished processing {item['Title']}.")

    with open(f"./data/games/{log}.json", "w", encoding="utf-8") as log_file:
        json.dump(log_items, log_file, indent=4)

    print(f"Finished processing {log}.")
