import os
import shutil
import subprocess
import sys

def main():
    # 1. 定义路径
    BASE_DIR = os.path.dirname(os.path.abspath(__file__))
    DIST_DIR = os.path.join(BASE_DIR, 'dist')
    APP_NAME = 'runDecoder'
    TARGET_DIR = os.path.join(DIST_DIR, APP_NAME)
    
    # 定义需要复制的资源 {源路径: 目标子路径}
    # 目标子路径相对于 TARGET_DIR
    RESOURCES = {
        'config.ini': 'config.ini',
        'online_Models': 'online_Models',
        'Tools': 'Tools',
    }

    # 2. 清理旧构建
    print("[1/3] Cleaning up old builds...")
    if os.path.exists(DIST_DIR):
        try:
            shutil.rmtree(DIST_DIR)
            print("      Cleaned dist/")
        except Exception as e:
            print(f"      Warning: Could not clean dist/: {e}")
    
    BUILD_DIR = os.path.join(BASE_DIR, 'build')
    if os.path.exists(BUILD_DIR):
        try:
            shutil.rmtree(BUILD_DIR)
            print("      Cleaned build/")
        except Exception as e:
            print(f"      Warning: Could not clean build/: {e}")

    # 3. 运行 PyInstaller
    print("[2/3] Running PyInstaller...")
    # 注意：我们这里不传 --noupx，因为已经在 spec 文件里把 upx=False 写死了
    cmd = [
        "pyinstaller",
        "build_algorithm.spec",
        "--clean"
    ]
    
    try:
        subprocess.check_call(cmd, shell=True)
    except subprocess.CalledProcessError:
        print("Error: PyInstaller failed.")
        sys.exit(1)

    # 4. 复制外部资源文件夹
    print("[3/3] Verifying and Copying external resources...")
    
    for src_name, dst_name in RESOURCES.items():
        src_path = os.path.join(BASE_DIR, src_name)
        dst_path = os.path.join(TARGET_DIR, dst_name)
        
        if os.path.exists(src_path):
            if os.path.isfile(src_path):
                # 如果是文件
                try:
                    shutil.copy2(src_path, dst_path)
                    print(f"      Copied file: {src_name} -> {dst_name}")
                except Exception as e:
                    print(f"      Error copying file {src_name}: {e}")
            else:
                # 如果是文件夹
                if os.path.exists(dst_path):
                    try:
                        shutil.rmtree(dst_path) # 先删除 spec 生成的旧文件夹 (如果有)
                    except Exception as e:
                        print(f"      Warning: Could not remove existing dir {dst_path}: {e}")
                try:
                    shutil.copytree(src_path, dst_path, ignore=shutil.ignore_patterns('*.pyc', '__pycache__'))
                    print(f"      Copied dir: {src_name} -> {dst_name}")
                except Exception as e:
                    print(f"      Error copying dir {src_name}: {e}")
        else:
            print(f"      Warning: Source resource not found at {src_path}")

    print("\n" + "="*50)
    print(f"SUCCESS! Build artifacts are in: {TARGET_DIR}")
    print("="*50)

if __name__ == "__main__":
    main()
