#!/usr/bin/env python3
"""
运行融合光学系统脚本的辅助脚本
"""

import subprocess
import sys
import os

def run_fused_optical_system():
    """运行融合光学系统脚本"""
    
    # 检查Blender是否可用
    blender_cmd = None
    
    # 常见的Blender安装路径
    possible_paths = [
        "blender",  # 如果在PATH中
        "/Applications/Blender.app/Contents/MacOS/Blender",  # macOS
        "/usr/bin/blender",  # Linux
        "C:\\Program Files\\Blender Foundation\\Blender\\blender.exe",  # Windows
    ]
    
    for path in possible_paths:
        try:
            result = subprocess.run([path, "--version"], 
                                  capture_output=True, text=True, timeout=10)
            if result.returncode == 0:
                blender_cmd = path
                print(f"✅ 找到Blender: {path}")
                break
        except (subprocess.TimeoutExpired, FileNotFoundError, subprocess.SubprocessError):
            continue
    
    if not blender_cmd:
        print("❌ 错误：找不到Blender安装")
        print("请确保Blender已安装并在PATH中，或者手动指定Blender路径")
        return False
    
    # 检查必要的JSON文件
    optical_json = "./e8caffb4622e03b1495bbc1ed13fce13.json"
    light_path_json = "./miao_light_path_tsingtao.json"
    
    missing_files = []
    if not os.path.exists(optical_json):
        missing_files.append(optical_json)
    if not os.path.exists(light_path_json):
        missing_files.append(light_path_json)
    
    if missing_files:
        print(f"❌ 错误：缺少必要的JSON文件：{missing_files}")
        print("请确保以下文件存在：")
        print(f"  - {optical_json}")
        print(f"  - {light_path_json}")
        return False
    
    # 检查融合脚本
    fused_script = "./fused_optical_system.py"
    if not os.path.exists(fused_script):
        print(f"❌ 错误：找不到融合脚本：{fused_script}")
        return False
    
    print("🚀 开始运行融合光学系统脚本...")
    print(f"光学系统数据：{optical_json}")
    print(f"光路数据：{light_path_json}")
    print(f"Blender命令：{blender_cmd}")
    
    try:
        # 运行Blender命令
        cmd = [
            blender_cmd,
            "--background",  # 后台运行
            "--python", fused_script,
            "--",  # 分隔符
            optical_json,
            light_path_json
        ]
        
        print(f"执行命令：{' '.join(cmd)}")
        
        result = subprocess.run(cmd, 
                              capture_output=True, 
                              text=True, 
                              timeout=300)  # 5分钟超时
        
        if result.returncode == 0:
            print("✅ 融合光学系统脚本执行成功！")
            print("\n输出文件：")
            print("- fused_optical_system.blend")
            print("- fused_optical_system.glb") 
            print("- fused_optical_system.obj")
            print("- fused_optical_system_render.png")
            
            # 显示脚本输出
            if result.stdout:
                print("\n脚本输出：")
                print(result.stdout)
            
            return True
        else:
            print(f"❌ 融合光学系统脚本执行失败，返回码：{result.returncode}")
            if result.stderr:
                print("错误输出：")
                print(result.stderr)
            if result.stdout:
                print("标准输出：")
                print(result.stdout)
            return False
            
    except subprocess.TimeoutExpired:
        print("❌ 脚本执行超时（超过5分钟）")
        return False
    except Exception as e:
        print(f"❌ 执行过程中出错：{e}")
        return False

def main():
    """主函数"""
    print("🎨 融合光学系统脚本运行器")
    print("=" * 40)
    
    success = run_fused_optical_system()
    
    if success:
        print("\n🎉 任务完成！")
        sys.exit(0)
    else:
        print("\n❌ 任务失败！")
        sys.exit(1)

if __name__ == "__main__":
    main()
