from glob import glob
import os
import json 
import random

train_cnt = 0
test_cnt = 0
val_cnt = 0
combined_cnt = 0

train_final = {}
test_final = {}
val_final = {}
combined_final = {}
for fn in glob("data/tasks/*/*"):
    print(fn)
    app_name = fn.split('/')[3]
    app_type = fn.split('/')[2]
    for i in range(1,10):
        image = f"data/data/{app_type}/{app_name}/screen_{i}.png"
        if os.path.exists(image) == False:
            if i == 1:
                print(image)
            continue
        ocr = f"ocr/{app_type}/{app_name}/screen_{i}.json"
        assert os.path.exists(ocr), ocr
        color = f"detact_color/{app_type}/{app_name}/screen_{i}.json"
        assert os.path.exists(color), color
        icon = f"detact_icon/{app_type}/{app_name}/screen_{i}.json"
        assert os.path.exists(icon), icon
        box = f"data/metadata/{app_type}/boxes/{app_name}/screen_{i}.json"
        assert os.path.exists(box), box
        script_to_task_fn = {}
        cnt = 0
        for task_fn in glob(f"{fn}/task_{i}.*.txt"):
            txt =  '\n'.join(open(task_fn).read().strip().split('\n')[1:])
            if txt not in script_to_task_fn:
                script_to_task_fn[txt] = []
            script_to_task_fn[txt].append(task_fn)
            cnt += 1
        
            
        for k in script_to_task_fn:
            c_tasks = script_to_task_fn[k]
            rand = random.randint(1,10)
            if rand <= 7:
                for c in c_tasks:
                    train_final[train_cnt] = {"task": c, "image": image, "ocr": ocr, "color": color, "icon": icon, "box": box}
                    train_cnt += 1
                    combined_final[combined_cnt] = {"task": c, "image": image, "ocr": ocr, "color": color, "icon": icon, "box": box}
                    combined_cnt += 1
            elif rand == 8:
                for c in c_tasks:
                    val_final[val_cnt] = {"task": c, "image": image, "ocr": ocr, "color": color, "icon": icon, "box": box}
                    val_cnt += 1
                    combined_final[combined_cnt] = {"task": c, "image": image, "ocr": ocr, "color": color, "icon": icon, "box": box}
                    combined_cnt += 1
            elif rand > 8:
                for c in c_tasks:
                    test_final[test_cnt] = {"task": c, "image": image, "ocr": ocr, "color": color, "icon": icon, "box": box}
                    test_cnt += 1
                    combined_final[combined_cnt] = {"task": c, "image": image, "ocr": ocr, "color": color, "icon": icon, "box": box}
                    combined_cnt += 1
                    
            
            
print(train_cnt)
print(val_cnt)
print(test_cnt)
print(combined_cnt)

json.dump(train_final, open('train.json', "w"), indent=4)
json.dump(val_final, open("val.json","w"), indent=4)
json.dump(test_final, open("test.json","w"), indent=4)
json.dump(combined_final, open('combined.json','w'), indent=4)