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'
    
    MODEL_SRC = os.path.join(BASE_DIR, 'model')
    RAW_DATA_SRC = os.path.join(BASE_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...")
    cmd = [
        "pyinstaller",
        "build_algorithm.spec",
        "--clean",
        "--noconfirm"
    ]
    
    try:
        subprocess.check_call(cmd, shell=True)
    except subprocess.CalledProcessError:
        print("Error: PyInstaller failed.")
        sys.exit(1)

    # 4. 复制外部资源 (如果存在)
    print("[3/3] Copying external resources...")
    
    # 确保 dist 目录存在 (pyinstaller 应该已经创建了)
    if not os.path.exists(DIST_DIR):
        os.makedirs(DIST_DIR)

    for src_path, folder_name in [(MODEL_SRC, 'model'), (RAW_DATA_SRC, 'raw_data')]:
        dst_path = os.path.join(DIST_DIR, folder_name)
        if os.path.exists(src_path):
            try:
                if os.path.exists(dst_path):
                    shutil.rmtree(dst_path)
                shutil.copytree(src_path, dst_path)
                print(f"      Copied {folder_name} to dist/")
            except Exception as e:
                print(f"      Error copying {folder_name}: {e}")
        else:
            print(f"      Note: {folder_name} source not found at {src_path}, skipping.")

    print("\n" + "="*50)
    print(f"SUCCESS! Executable is in: {DIST_DIR}")
    print("="*50)

if __name__ == "__main__":
    main()
