import csv
import json
import os


def discover_sets():
    # find all set directories
    sets = []
    for root, dirs, files in os.walk("sets"):
        for dir in dirs:
            sets.append(dir)

    return sets


def find_card(all_card_data, name):
    for card in all_card_data:
        if card["name"] == name:
            return card

    return None


def find_card_with_dual_faces(all_card_data, name):
    for card in all_card_data:
        parts = [p.strip() for p in card["name"].split("//")]

        if name in parts:
            return card

    return None


def main():
    with open("oracle-cards-20240421210231.json") as f:
        all_card_data = json.load(f)

    for set in discover_sets():
        ratings_csv = os.path.join("sets", set, "card-ratings-all.csv")
        ratings_json = os.path.join("sets", set, "card-ratings-all.json")

        card_data_json = os.path.join("sets", set, "card-data.json")

        with (open(ratings_csv) as f):
            lines = []
            cards = []
            for line in csv.DictReader(f):
                name = line["\ufeff\"Name\""]
                line["Name"] = name
                del line["\ufeff\"Name\""]
                lines.append(line)

                card_data = find_card(all_card_data, name)
                if card_data is None:
                    card_data = find_card_with_dual_faces(all_card_data, name)

                if card_data is None:
                    print(f"Could not find card data for {name}")
                    continue

                cards.append(card_data)

        with open(ratings_json, "w") as f:
            json.dump(lines, f, indent=4)

        with open(card_data_json, "w") as f:
            json.dump(cards, f, indent=4)


if __name__ == '__main__':
    main()
