#!/usr/bin/env python3
"""
运行增强版光路可视化脚本
使用Blender生成光学系统高级光路模型

功能特点:
- 发光光路效果
- 光路起点和终点标记
- 光路密度可视化
- 高质量渲染

使用方法:
1. 确保已安装Blender
2. 运行此脚本: python run_light_path_advanced.py

输出文件:
- light_path_advanced.blend - Blender工程文件
- light_path_advanced.glb - Web友好格式
- light_path_render.png - 渲染图像
"""

import subprocess
import sys
import os
import platform

def find_blender():
    """查找Blender可执行文件"""
    system = platform.system()
    
    common_paths = []
    if system == "Windows":
        common_paths = [
            r"C:\Program Files\Blender Foundation\Blender 3.6\blender.exe",
            r"C:\Program Files\Blender Foundation\Blender 4.0\blender.exe",
            r"C:\Program Files\Blender Foundation\Blender 4.1\blender.exe",
            r"C:\Program Files (x86)\Blender Foundation\Blender 3.6\blender.exe",
        ]
    elif system == "Darwin":  # macOS
        common_paths = [
            "/Applications/Blender.app/Contents/MacOS/Blender",
            "/usr/local/bin/blender",
        ]
    elif system == "Linux":
        common_paths = [
            "/usr/bin/blender",
            "/usr/local/bin/blender",
            "/snap/bin/blender",
        ]
    
    # 首先尝试从PATH中找到blender
    try:
        result = subprocess.run(["which", "blender"], capture_output=True, text=True)
        if result.returncode == 0:
            return result.stdout.strip()
    except:
        pass
    
    # 尝试常见路径
    for path in common_paths:
        if os.path.exists(path):
            return path
    
    return None

def run_advanced_light_path_script():
    """运行增强版光路可视化Blender脚本"""
    blender_path = find_blender()
    
    if not blender_path:
        print("❌ 错误：未找到Blender安装")
        print("\n请确保已安装Blender并且可以从命令行访问")
        print("下载地址: https://www.blender.org/download/")
        return False
    
    print(f"✅ 找到Blender: {blender_path}")
    
    # 检查必要文件
    script_path = os.path.abspath("light_path_advanced.py")
    if not os.path.exists(script_path):
        print(f"❌ 错误：未找到脚本文件 {script_path}")
        return False
    
    json_path = os.path.abspath("miao_light_path_tsingtao.json")
    if not os.path.exists(json_path):
        print(f"❌ 错误：未找到光路数据文件 {json_path}")
        return False
    
    print("🚀 开始运行增强版光路可视化脚本...")
    print("这可能需要较长时间，请耐心等待...")
    print("增强版功能包括:")
    print("- 发光光路效果")
    print("- 起点和终点标记")
    print("- 光路密度可视化")
    print("- 高质量渲染")
    
    try:
        # 运行Blender脚本
        cmd = [
            blender_path,
            "--background",  # 后台运行
            "--python", script_path
        ]
        
        result = subprocess.run(cmd, capture_output=True, text=True, timeout=900)  # 15分钟超时
        
        if result.returncode == 0:
            print("✅ 增强版光路可视化脚本执行成功！")
            print("\n输出信息:")
            print(result.stdout)
            
            # 检查生成的文件
            expected_files = [
                "light_path_advanced.blend",
                "light_path_advanced.glb", 
                "light_path_render.png"
            ]
            
            print("\n📁 生成的文件:")
            for filename in expected_files:
                if os.path.exists(filename):
                    size = os.path.getsize(filename)
                    print(f"✅ {filename} ({size:,} bytes)")
                else:
                    print(f"❌ {filename} (未找到)")
            
            return True
        else:
            print("❌ 增强版光路可视化脚本执行失败")
            print("错误输出:")
            print(result.stderr)
            if result.stdout:
                print("标准输出:")
                print(result.stdout)
            return False
            
    except subprocess.TimeoutExpired:
        print("❌ 脚本执行超时（超过15分钟）")
        return False
    except Exception as e:
        print(f"❌ 执行时出错: {e}")
        return False

def main():
    print("🎨 光学系统光路可视化 - 增强版")
    print("=" * 50)
    print("使用Blender生成高级3D光路模型")
    print()
    
    if run_advanced_light_path_script():
        print("\n🎉 任务完成！")
        print("\n您可以:")
        print("1. 使用Blender打开 light_path_advanced.blend 文件进行编辑")
        print("2. 在Web浏览器中查看 light_path_advanced.glb 文件")
        print("3. 查看高质量渲染图像 light_path_render.png")
        print("\n增强版光路模型特点:")
        print("- 每条光路使用不同颜色和发光强度")
        print("- 绿色球体标记光路起点")
        print("- 红色球体标记光路终点")
        print("- 光路密度体积可视化")
        print("- 高质量Cycles渲染引擎")
        print("- 自动优化相机角度和光照")
        print("- 支持交互式3D查看")
    else:
        print("\n❌ 任务失败，请检查错误信息")
        sys.exit(1)

if __name__ == "__main__":
    main()
