import argparse
import os

parser = argparse.ArgumentParser()


current_dir = os.path.dirname(os.path.abspath(__file__))
weshop_native_dir = os.path.dirname(current_dir)
resources_dir = os.path.join(weshop_native_dir, "resources")
package_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")
err_dir = os.path.join(resources_dir, "err")
python_exe = os.path.join(bin_dir, "python","python.exe")
userData_dir = os.path.join(weshop_native_dir, "userData")
gpu_pid_file = os.path.join(weshop_native_dir, "bin", "gpu_service.txt")
electron_status_file = os.path.join(weshop_native_dir, "logs", "status.log")
models_dir = os.path.join(weshop_native_dir, "models")


parser.add_argument('--path', type=str, help='path to compressed upgrade file', default="")
args = parser.parse_args()

zip_path = args.path

import zipfile
from tqdm import tqdm

start_log = os.path.join(log_dir, "start.log")

def extract_zip_with_progress(zip_path, extract_path):
    with zipfile.ZipFile(zip_path, 'r') as zip_ref, open(start_log, "a") as log_file:
        total_files = len(zip_ref.infolist())
        extracted_files = 0

        progress = 0
        previous_progress = progress

        for member in tqdm(zip_ref.infolist(), desc='Extracting', unit='files', ncols=80):
            zip_ref.extract(member, extract_path)
            extracted_files += 1
            progress = round(extracted_files/total_files, 2) 
            # print(f'current Progress: {progress} %', end='\r', file=log_file, flush=True)
            # print(f'previous Progress: {previous_progress} %', end='\r', file=log_file, flush=True)
            # Update progress bar
            if progress == 1.0 or progress >= (previous_progress + 0.1):
                previous_progress = progress
                # print(f'更新进度: {progress * 100} %', end='\r', file=log_file)


if __name__ == '__main__':
    dest_dir = os.path.join(weshop_native_dir, "..")
    if zip_path == "":
        print("file not found")
    extract_zip_with_progress(zip_path, dest_dir)                                                                                         