# -*- coding: utf-8 -*-
"""
打包脚本 - datacollect
用于将 EEG 数据采集程序打包为独立的 exe 文件
"""

import os
import sys
import shutil
import subprocess

def main():
    # 1. 定义路径
    BASE_DIR = os.path.dirname(os.path.abspath(__file__))
    DIST_DIR = os.path.join(BASE_DIR, 'dist')
    BUILD_DIR = os.path.join(BASE_DIR, 'build')
    APP_NAME = 'start_parse'

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

    # 3. 检查必要文件
    print("\n[2/3] Checking required files...")
    required_files = ['start_parse.py', 'eegParser.py', 'build_algorithm.spec', 'xy_64.xlsx']
    for f in required_files:
        path = os.path.join(BASE_DIR, f)
        if os.path.exists(path):
            print(f"      ✓ {f}")
        else:
            print(f"      ✗ {f} NOT FOUND!")
            sys.exit(1)

    # 4. 运行 PyInstaller
    print("\n[3/3] Running PyInstaller...")
    spec_file = os.path.join(BASE_DIR, 'build_algorithm.spec')

    cmd = [
        sys.executable,
        "-m", "PyInstaller",
        spec_file,
        "--clean",
        "--noconfirm"
    ]

    try:
        subprocess.check_call(cmd, cwd=BASE_DIR)
    except subprocess.CalledProcessError as e:
        print(f"\n✗ PyInstaller failed with error code: {e.returncode}")
        sys.exit(1)

    # 5. 验证结果
    exe_path = os.path.join(DIST_DIR, APP_NAME, f'{APP_NAME}.exe')
    if os.path.exists(exe_path):
        size_mb = os.path.getsize(exe_path) / (1024 * 1024)
        print(f"\n{'='*50}")
        print(f"✓ SUCCESS! Executable created:")
        print(f"  {exe_path}")
        print(f"  Size: {size_mb:.1f} MB")
        print(f"{'='*50}")
        print(f"\n部署说明:")
        print(f"  1. 复制 dist/start_parse 文件夹到目标电脑")
        print(f"  2. 确保目标电脑已安装 EEG 设备的 USB 驱动")
        print(f"  3. 运行 start_parse.exe")
    else:
        print("\n✗ Build failed - executable not found")
        sys.exit(1)

if __name__ == "__main__":
    main()
