#!/usr/bin/env python3
"""
运行脚本 - 使用Blender生成3D光学系统模型

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

输出文件:
- optical_system.obj - 3D模型文件
- optical_system.glb - Web友好格式
- optical_system.blend - Blender工程文件 
- optical_system_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 (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_blender_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("toModel.py")
    if not os.path.exists(script_path):
        print(f"❌ 错误：未找到脚本文件 {script_path}")
        return False
    
    json_path = os.path.abspath("e8caffb4622e03b1495bbc1ed13fce13.json")
    if not os.path.exists(json_path):
        print(f"❌ 错误：未找到JSON数据文件 {json_path}")
        return False
    
    print("🚀 开始运行Blender脚本...")
    print("这可能需要几分钟时间，请耐心等待...")
    
    try:
        # 运行Blender脚本
        cmd = [
            blender_path,
            "--background",  # 后台运行
            "--python", script_path
        ]
        
        result = subprocess.run(cmd, capture_output=True, text=True, timeout=300)
        
        if result.returncode == 0:
            print("✅ Blender脚本执行成功！")
            print("\n输出信息:")
            print(result.stdout)
            
            # 检查生成的文件
            expected_files = [
                "optical_system.obj",
                "optical_system.glb", 
                "optical_system.blend",
                "optical_system_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("❌ Blender脚本执行失败")
            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("🎨 Blender 3D光学系统建模脚本")
    print("=" * 40)
    
    if run_blender_script():
        print("\n🎉 任务完成！")
        print("\n您可以:")
        print("1. 使用Blender打开 optical_system.blend 文件进行编辑")
        print("2. 在3D软件中导入 optical_system.obj 文件")
        print("3. 在Web浏览器中查看 optical_system.glb 文件")
        print("4. 查看渲染图像 optical_system_render.png")
    else:
        print("\n❌ 任务失败，请检查错误信息")
        sys.exit(1)

if __name__ == "__main__":
    main() 