#!/usr/bin/env python
# -*- coding: utf-8 -*-

"""
PyQt5安装诊断和修复工具
"""

import os
import sys
import subprocess
import platform

def check_pyqt_installation():
    """检查PyQt5安装情况"""
    print("正在检查PyQt5安装...")
    
    try:
        import PyQt5
        print(f"已安装PyQt5")
        
        # 检查核心组件
        try:
            from PyQt5 import QtCore
            print("✓ QtCore 正常")
        except ImportError as e:
            print(f"✗ QtCore 导入失败: {e}")
            
        try:
            from PyQt5 import QtWidgets
            print("✓ QtWidgets 正常")
        except ImportError as e:
            print(f"✗ QtWidgets 导入失败: {e}")
            
        try:
            from PyQt5 import QtGui
            print("✓ QtGui 正常")
        except ImportError as e:
            print(f"✗ QtGui 导入失败: {e}")
        
        # 检查平台插件
        try:
            from PyQt5.QtWidgets import QApplication
            app = QApplication([])
            print("✓ QApplication 实例化成功")
        except Exception as e:
            print(f"✗ QApplication 实例化失败: {e}")
            
        # 检查插件路径
        plugin_path = os.path.join(os.path.dirname(PyQt5.__file__), "Qt5", "plugins")
        platform_path = os.path.join(plugin_path, "platforms")
        
        print(f"\n检查插件目录:")
        print(f"插件基础路径: {plugin_path}")
        print(f"平台插件路径: {platform_path}")
        
        if os.path.exists(platform_path):
            print(f"✓ 平台插件目录存在")
            plugins = os.listdir(platform_path)
            print(f"平台插件文件: {', '.join(plugins)}")
            
            if "qwindows.dll" in plugins:
                print("✓ Windows平台插件已存在")
            else:
                print("✗ 缺少Windows平台插件 (qwindows.dll)")
        else:
            print(f"✗ 平台插件目录不存在")
            
        return True
    except ImportError as e:
        print(f"PyQt5导入失败: {e}")
        return False

def reinstall_pyqt():
    """重新安装PyQt5"""
    print("\n尝试修复PyQt5安装...")
    
    # 卸载现有安装
    print("1. 卸载现有PyQt5...")
    subprocess.run([sys.executable, "-m", "pip", "uninstall", "-y", "PyQt5", "PyQt5-Qt5", "PyQt5-sip"], 
                   capture_output=True)
    
    # 安装PyQt5
    print("2. 重新安装PyQt5...")
    result = subprocess.run([sys.executable, "-m", "pip", "install", "-i", 
                            "https://pypi.tuna.tsinghua.edu.cn/simple", "PyQt5"],
                           capture_output=True, text=True)
    
    if result.returncode == 0:
        print("PyQt5安装成功")
    else:
        print(f"PyQt5安装失败: {result.stderr}")
    
    # 设置环境变量
    print("3. 设置QT_PLUGIN_PATH环境变量...")
    try:
        import PyQt5
        plugin_path = os.path.join(os.path.dirname(PyQt5.__file__), "Qt5", "plugins")
        os.environ["QT_PLUGIN_PATH"] = plugin_path
        print(f"环境变量已设置: QT_PLUGIN_PATH={plugin_path}")
    except ImportError:
        print("无法设置QT_PLUGIN_PATH，PyQt5导入失败")
    
    return check_pyqt_installation()

def create_test_app():
    """创建一个测试应用程序"""
    print("\n创建测试应用程序...")
    
    try:
        from PyQt5.QtWidgets import QApplication, QWidget, QLabel, QVBoxLayout
        from PyQt5.QtCore import Qt
        
        app = QApplication([])
        window = QWidget()
        window.setWindowTitle("PyQt5测试")
        window.setGeometry(100, 100, 300, 200)
        
        layout = QVBoxLayout()
        label = QLabel("PyQt5测试成功！")
        label.setAlignment(Qt.AlignCenter)
        layout.addWidget(label)
        window.setLayout(layout)
        
        print("测试应用程序创建成功！")
        
        # 只显示3秒
        timer = app.startTimer(3000)
        app.timerEvent = lambda ev: app.quit() if ev.timerId() == timer else None
        
        window.show()
        app.exec_()
        return True
    except Exception as e:
        print(f"测试应用程序创建失败: {e}")
        return False

def create_fix_script():
    """创建启动修复脚本"""
    script_content = """@echo off
chcp 65001
echo 修复PyQt5环境变量
echo ==================

REM 获取PyQt5的插件路径
for /f "tokens=*" %%a in ('python -c "import PyQt5, os; print(os.path.join(os.path.dirname(PyQt5.__file__), 'Qt5', 'plugins'))"') do set QT_PLUGIN_PATH=%%a

echo 设置环境变量: QT_PLUGIN_PATH=%QT_PLUGIN_PATH%
setx QT_PLUGIN_PATH "%QT_PLUGIN_PATH%"

echo 完成! 现在尝试运行 python main.py
pause
"""
    with open("fix_qt_env.bat", "w", encoding="utf-8") as f:
        f.write(script_content)
    print("\n已创建修复脚本: fix_qt_env.bat")

def create_launch_script():
    """创建新的启动脚本"""
    script_content = """#!/usr/bin/env python
# -*- coding: utf-8 -*-

import os
import sys
import PyQt5

# 设置PyQt5插件路径
os.environ["QT_PLUGIN_PATH"] = os.path.join(os.path.dirname(PyQt5.__file__), "Qt5", "plugins")

# 导入并运行主程序
import main
main.main()
"""
    with open("run_app.py", "w", encoding="utf-8") as f:
        f.write(script_content)
    print("已创建启动脚本: run_app.py")
    
    bat_content = """@echo off
chcp 65001
echo 启动智能音频处理助手(修复版)
echo =======================

python run_app.py
pause
"""
    with open("run_fixed.bat", "w", encoding="utf-8") as f:
        f.write(bat_content)
    print("已创建启动批处理文件: run_fixed.bat")

if __name__ == "__main__":
    print("=" * 50)
    print("PyQt5安装诊断和修复工具")
    print("=" * 50)
    
    if check_pyqt_installation():
        print("\nPyQt5基本安装正常，但可能存在平台插件问题")
    else:
        reinstall_pyqt()
    
    # 创建修复脚本
    create_fix_script()
    create_launch_script()
    
    print("\n推荐的修复步骤:")
    print("1. 运行 fix_qt_env.bat 设置环境变量")
    print("2. 使用 run_fixed.bat 或 python run_app.py 启动程序")
    print("\n如果仍然无法解决，请尝试使用命令行版本:")
    print("python cmd_audio_processor.py --help")
    print("=" * 50) 