import json
import os
import re
import ipdb

def load_json(path):
    """ load_json(path:str)->jsObject
    从指定文件读取内容，解析为 json 返回
    @param path: 文件路径
    @return: 解析后的 json
    """
    with open(path) as f:
        data = f.read()
        return json.loads(data)


def dump_json(path, data):
    """ dump_json(path:str, data:obj)->None
    从指定文件读取内容，解析为 json 返回
    @param path: 文件路径
    @param data: json 对象
    @return: None
    """
    with open(path, "w+") as df:
        df.write(json.dumps(data, indent=2, ensure_ascii=False))


def add_number():
    data_root_dir = "./data"
    data_level_dir_list = [
        os.path.join(data_root_dir, _dir) for _dir in os.listdir(data_root_dir)]
    for data_level_dir in data_level_dir_list:
        if os.path.isfile(data_level_dir) is True:
            continue
        _1st_layer_dir_list = [
            os.path.join(data_level_dir, _dir) for _dir in os.listdir(data_level_dir)]
        for _1st_layer_dir in _1st_layer_dir_list:
            if _1st_layer_dir.find("leetcode") == -1:
                continue
            _2nd_layer_dir_list = [
                os.path.join(_1st_layer_dir, _dir) for _dir in os.listdir(_1st_layer_dir)]
            for _2nd_layer_dir in _2nd_layer_dir_list:
                if os.path.isfile(_2nd_layer_dir) is True:
                    continue
                _basename = os.path.basename(_2nd_layer_dir)
                _basename = re.sub(r"^[0-9]{1,3}?\.", "", _basename)
                number = str(_basename.split("-")[0])
                config_file_name = os.path.join(_2nd_layer_dir, "config.json")
                config = load_json(config_file_name)
                for index, item in enumerate(config["keywords_must"]):
                    if isinstance(item, list):
                        if number in item:
                            continue
                        item.append(number)
                        config["keywords_must"][index] = item
                dump_json(config_file_name, config)


def main():
    add_number()


if __name__=="__main__":
    main()