import os
import json

categories = [
    "CZSK",
    "US",
]


def genList(cwd):
    channels_dir = os.path.join(cwd, "resources", "channels")

    def get_channels():
        files = os.listdir(os.path.join(channels_dir, "_Channels"))
        sorted_items = sorted(files, key=lambda x: int(x.split('.')[0]))
        originals = [json.loads(open(os.path.join(channels_dir, "_Channels", file), "r", encoding="utf-8").read()) \
                        for file in sorted_items]
        result = {}
        for l in originals:
            for k, v in l.items():
                result[k] = v

        return result

    main: dict = get_channels()

    for category in categories:
        for file in os.listdir(os.path.join(channels_dir, category)):
            
            loaded = json.load(open(os.path.join(channels_dir, category, file), "r", encoding="utf-8"))
            
            for item in loaded:
                if item['channel_id'] not in main:

                    raise Exception(f"Channel '{item['channel_id']}' not in main list...")

                if 'sources' not in main[item['channel_id']]:
                    main[item['channel_id']]['sources'] = []

                main[item['channel_id']]['sources'].append(item)
            
    return main

