import sys
import os
import platform
from core.logger import get_logger

logger = get_logger('bgxiong_resolve_api')

def GetResolve():
    """
    针对 Electron 环境优化的 DaVinci Resolve 对象获取函数
    """
    try:
        # 1. 检查 Python 版本 (重要：3.12+ 几乎必崩)
        major, minor = sys.version_info[:2]
        if major != 3 or minor > 11:
            logger.error(f"当前 Python 版本 {major}.{minor} 可能不兼容，建议使用 3.10 或 3.11")

        # 2. 预设安装路径 (Windows 为例)
        resolve_path = r"C:\Program Files\Blackmagic Design\DaVinci Resolve"
        script_module_path = os.path.join(os.environ.get('PROGRAMDATA', ''), 
                                          "Blackmagic Design", "DaVinci Resolve", 
                                          "Support", "Developer", "Scripting", "Modules")

        # 3. 核心修复：将达芬奇根目录加入 DLL 搜索路径
        # 这是解决 "initialization of fusionscript failed" 的救命药
        if sys.platform.startswith("win"):
            if os.path.exists(resolve_path):
                # 针对 Python 3.8+ 的新 DLL 加载机制
                if hasattr(os, 'add_dll_directory'):
                    os.add_dll_directory(resolve_path)
                # 兼容旧机制及子进程环境
                os.environ['PATH'] = resolve_path + os.pathsep + os.environ.get('PATH', '')
            
        # 4. 将脚本模块路径加入 sys.path
        if script_module_path not in sys.path and os.path.exists(script_module_path):
            sys.path.append(script_module_path)

        # 5. 尝试导入
        try:
            import DaVinciResolveScript as bmd
        except ImportError as e:
            logger.error(f"无法导入 DaVinciResolveScript: {e}")
            return None

        # 6. 连接 Resolve
        # 注意：Electron 唤起时，达芬奇可能需要一点时间响应 IPC
        resolve = bmd.scriptapp("Resolve")
        
        if not resolve:
            # 这里的失败通常意味着：1. 没开 Studio 版；2. 达芬奇正在忙碌
            logger.error("bmd.scriptapp('Resolve') 返回了 None。请检查是否为 Studio 版本。")
            return None
            
        return resolve

    except Exception as e:
        logger.error(f"获取 Resolve 对象时发生异常: {str(e)}")
        import traceback
        logger.error(traceback.format_exc())
        return None

def get_resolve():
    return GetResolve()