import json

from webarenasafe.data_generator_assign_policies_suitecrm import load_json_file, save_json_file


def split_evals(data):
    total = 0
    for task in data:
        if "program_html" in task["eval"]["eval_types"] and "suitecrm" in task["sites"]:
            eval_before = len(task["eval"]["program_html"])
            for item in task["eval"]["program_html"]:
                must_include_exists = "required_contents" in item and "must_include" in item["required_contents"]
                must_include = item["required_contents"]["must_include"] if must_include_exists else None
                if must_include_exists and len(must_include) >= 2:
                    # Split the must_include array into individual objects
                    new_program_html = []
                    new_item_copy = item.copy()
                    task["eval"]["program_html"].remove(item)
                    for value in must_include:
                        new_item = new_item_copy.copy()
                        new_item["required_contents"] = {"must_include": [value]}
                        task["eval"]["program_html"].append(new_item)
                    print("Updating {}".format(task['task_id']))
                    # Keep the item as is if required_contents or must_include is missing

                    # task["eval"]["program_html"] = new_program_html
            if len(task["eval"]["program_html"]) - eval_before != 0 :
                total+=1
                print("Evals Changed: {} --> {}".format(len(task["eval"]["program_html"]),eval_before))
                print("-----")
                print(json.dumps(task["eval"]["program_html"],indent=4))
                print("-----")

    print("\n")
    print("Totally updated {} tasks".format(total))
    save_json_file(data, "./test.raw.seperated.json")
