# -*- coding: utf-8 -*-
"""
PyInstaller 打包验证脚本
用于在没有 EEG 设备的情况下验证打包是否成功
"""

import os
import sys
import subprocess
import shutil

def check_pyinstaller_installed():
    """检查 PyInstaller 是否安装"""
    try:
        result = subprocess.run(['pyinstaller', '--version'],
                               capture_output=True, text=True)
        print(f"✓ PyInstaller 版本: {result.stdout.strip()}")
        return True
    except FileNotFoundError:
        print("✗ PyInstaller 未安装")
        return False

def check_dist_folder():
    """检查 dist 文件夹是否存在"""
    base_dir = os.path.dirname(os.path.abspath(__file__))
    dist_dir = os.path.join(base_dir, 'dist', 'start_parse')

    if os.path.exists(dist_dir):
        print(f"✓ dist 文件夹存在: {dist_dir}")

        # 检查 exe 文件
        exe_path = os.path.join(dist_dir, 'start_parse.exe')
        if os.path.exists(exe_path):
            size_mb = os.path.getsize(exe_path) / (1024 * 1024)
            print(f"✓ 可执行文件存在: start_parse.exe ({size_mb:.1f} MB)")
        else:
            print("✗ 可执行文件不存在")
            return False

        # 检查资源文件
        xlsx_path = os.path.join(dist_dir, 'xy_64.xlsx')
        if os.path.exists(xlsx_path):
            print(f"✓ 资源文件存在: xy_64.xlsx")
        else:
            print("✗ 资源文件 xy_64.xlsx 不存在")

        return True
    else:
        print(f"✗ dist 文件夹不存在，请先运行打包")
        return False

def check_dependencies():
    """检查关键依赖是否在打包中"""
    base_dir = os.path.dirname(os.path.abspath(__file__))
    dist_dir = os.path.join(base_dir, 'dist', 'start_parse')

    if not os.path.exists(dist_dir):
        return False

    # 检查关键 DLL 文件
    critical_dlls = [
        # zmq 依赖
        'libzmq.pyd',
        # numpy 依赖
        'numpy.core._multiarray_umath.cp310-win_amd64.pyd',
        # scipy 依赖
        'scipy.special._ufuncs.cp310-win_amd64.pyd',
    ]

    print("\n检查关键依赖文件:")
    found_count = 0
    for dll in critical_dlls:
        found = False
        for root, dirs, files in os.walk(dist_dir):
            if dll in files:
                found = True
                break
        status = "✓" if found else "✗"
        print(f"  {status} {dll}")
        if found:
            found_count += 1

    return found_count >= len(critical_dlls) // 2

def test_imports():
    """测试关键模块是否可以导入"""
    print("\n测试模块导入:")

    modules = ['zmq', 'serial', 'numpy', 'pandas', 'scipy']
    success = True

    for mod in modules:
        try:
            __import__(mod)
            print(f"  ✓ {mod}")
        except ImportError as e:
            print(f"  ✗ {mod}: {e}")
            success = False

    return success

def main():
    print("=" * 60)
    print("PyInstaller 打包验证")
    print("=" * 60)

    checks = [
        ("1. 检查 PyInstaller 安装", check_pyinstaller_installed),
        ("2. 检查 dist 文件夹", check_dist_folder),
        ("3. 检查依赖文件", check_dependencies),
        ("4. 测试模块导入", test_imports),
    ]

    results = []
    for name, check_func in checks:
        print(f"\n{name}")
        print("-" * 40)
        results.append(check_func())

    print("\n" + "=" * 60)
    print("验证结果汇总:")
    print("=" * 60)

    all_passed = all(results)
    if all_passed:
        print("✓ 所有检查通过！打包成功。")
        print("\n下一步:")
        print("  1. 将 dist/start_parse 文件夹复制到目标电脑")
        print("  2. 连接 EEG 设备并运行 start_parse.exe")
        print("  3. 观察控制台输出是否正常")
    else:
        print("✗ 部分检查未通过，请查看上述详细信息")

    return all_passed

if __name__ == "__main__":
    main()
