import os
import sys
import ctypes
from ctypes.util import find_library
from pathlib import Path

class DLLLoaderError(Exception):
    """自定义DLL加载异常"""
    pass

def setup_dependencies(dll_paths=None):
    """配置DLL搜索路径"""
    if dll_paths is None:
        dll_paths = [
            Path(__file__).parent / 'libs',
            Path(os.getenv('LOCALAPPDATA')) / 'MSYS2' / 'mingw64' / 'bin'
        ]
    
    os.environ['PATH'] = os.pathsep.join([
        str(p.resolve()) for p in dll_paths if p.exists()
    ]) + os.pathsep + os.environ.get('PATH', '')

def load_dll(dll_name, mode=ctypes.DEFAULT_MODE, handle_errors=True):
    """增强版DLL加载函数"""
    try:
        # 尝试标准加载方式
        dll = ctypes.CDLL(dll_name, mode=mode)
        print(f"✅ 成功加载 {dll_name}")
        return dll
    except OSError as e:
        if handle_errors:
            # 尝试通过PATH查找
            lib_path = find_library(dll_name)
            if lib_path:
                return ctypes.CDLL(lib_path, mode=mode)
            
            # 尝试MSYS2路径
            msys_path = Path(os.getenv('LOCALAPPDATA')) / 'MSYS2' / 'mingw64' / 'bin' / dll_name
            if msys_path.exists():
                return ctypes.CDLL(str(msys_path), mode=mode)
            
            # 生成详细错误报告
            path_list = os.environ.get('PATH', '').split(os.pathsep)
            raise DLLLoaderError(
                f"无法加载 {dll_name}\n"
                f"错误详情: {str(e)}\n"
                f"搜索路径:\n• " + "\n• ".join(path_list)
            )
        else:
            raise

# 自动配置默认路径
try:
    setup_dependencies()
except Exception as e:
    print(f"⚠️ 初始化依赖失败: {e}")

if __name__ == '__main__':
    # 自测试代码
    try:
        test_dll = load_dll('gtk-3-0.dll')
        print(f"测试DLL句柄: {test_dll._handle}")
    except DLLLoaderError as e:
        print(f"❌ 自测试失败: {e}")
