import os
import json
import shutil

current_dir = os.path.dirname(os.path.abspath(__file__))
weshop_native_dir = os.path.dirname(current_dir)
wehsop_init_dir = os.path.join(os.path.dirname(weshop_native_dir), 'init_files')
packages_dir = os.path.join(weshop_native_dir, 'packages')
bin_dir = os.path.join(weshop_native_dir, "bin")
log_dir = os.path.join(weshop_native_dir, "logs")
userData_dir = os.path.join(weshop_native_dir, "userData")
pid_json = os.path.join(bin_dir, "pid.json")

if __name__ == '__main__':
    # 移除userData/Data/文件夹下数据
    for root, dirs, files in os.walk(os.path.join(userData_dir, "Data")):
        for file in files:
            file_path = os.path.join(root, file)
            os.remove(file_path)
    # 移除userData/User/mongo_replica文件夹
    try:
        shutil.rmtree(os.path.join(userData_dir, "User", "mongo_replica"))
    except FileNotFoundError:
        print('no mongo_replica')
    # 移除logs文件夹
    try:
        shutil.rmtree(os.path.join(weshop_native_dir, "logs"))
    except FileNotFoundError:
        print('no logs')
    # 移除packages/stable-diffusion-webui/cache.json文件
    try:
        os.remove(os.path.join(packages_dir, "stable-diffusion-webui", "cache.json"))
    except FileNotFoundError:
        print('no cache.json')
    # 清除json
    with open(pid_json, "w") as file:
        json.dump({"pid":[]},file)

    # 移除resources/.logInfo.json文件
    try:
        os.remove(os.path.join(weshop_native_dir, "resources", ".logInfo.json"))
    except FileNotFoundError:
        print('no .logInfo.json')
        
    shutil.copytree(os.path.join(wehsop_init_dir, "mongo_replica"), os.path.join(userData_dir, "User", "mongo_replica"))
    shutil.copytree(os.path.join(wehsop_init_dir, "logs"), os.path.join(weshop_native_dir, "logs"))
    shutil.copy2(os.path.join(wehsop_init_dir, "stable-diffusion-webui", "cache.json"), os.path.join(packages_dir, "stable-diffusion-webui"))