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 = 'Depression_Decoder'
    TARGET_DIR = os.path.join(DIST_DIR, APP_NAME)
    
    MODEL_SRC = os.path.join(BASE_DIR, 'model')
    RAW_DATA_SRC = os.path.join(BASE_DIR, 'raw_data')
    
    MODEL_DST = os.path.join(TARGET_DIR, 'model')
    RAW_DATA_DST = os.path.join(TARGET_DIR, 'raw_data')

    # 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] Copying external resources...")
    
    # 复制 model 文件夹
    if os.path.exists(MODEL_SRC):
        if os.path.exists(MODEL_DST):
            shutil.rmtree(MODEL_DST)
        shutil.copytree(MODEL_SRC, MODEL_DST)
        print(f"      Copied: model -> {MODEL_DST}")
    else:
        print(f"      Warning: Source model dir not found at {MODEL_SRC}")

    # 复制 raw_data 文件夹
    if os.path.exists(RAW_DATA_SRC):
        if os.path.exists(RAW_DATA_DST):
            shutil.rmtree(RAW_DATA_DST)
        shutil.copytree(RAW_DATA_SRC, RAW_DATA_DST)
        print(f"      Copied: raw_data -> {RAW_DATA_DST}")
    else:
        print(f"      Warning: Source raw_data dir not found at {RAW_DATA_SRC}")

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

if __name__ == "__main__":
    main()
