import bpy, sys, math, os

glb_path = sys.argv[sys.argv.index("--") + 1]
out_dir = sys.argv[sys.argv.index("--") + 2]

bpy.ops.wm.read_factory_settings(use_empty=True)
bpy.ops.import_scene.gltf(filepath=glb_path)

# Frame all objects
bpy.ops.object.select_all(action='SELECT')
objs = [o for o in bpy.context.selected_objects if o.type == 'MESH']

# Compute bounding box center/size
import mathutils
min_co = mathutils.Vector((1e9,1e9,1e9))
max_co = mathutils.Vector((-1e9,-1e9,-1e9))
for o in objs:
    for v in o.bound_box:
        world_v = o.matrix_world @ mathutils.Vector(v)
        min_co.x = min(min_co.x, world_v.x); max_co.x = max(max_co.x, world_v.x)
        min_co.y = min(min_co.y, world_v.y); max_co.y = max(max_co.y, world_v.y)
        min_co.z = min(min_co.z, world_v.z); max_co.z = max(max_co.z, world_v.z)
center = (min_co + max_co) / 2
size = max_co - min_co
radius = max(size.x, size.y, size.z) * 1.6

# Light
light_data = bpy.data.lights.new(name="sun", type='SUN')
light_data.energy = 3
light_obj = bpy.data.objects.new(name="sun", object_data=light_data)
bpy.context.collection.objects.link(light_obj)
light_obj.rotation_euler = (math.radians(50), 0, math.radians(30))

# Camera
cam_data = bpy.data.cameras.new("cam")
cam_obj = bpy.data.objects.new("cam", cam_data)
bpy.context.collection.objects.link(cam_obj)
bpy.context.scene.camera = cam_obj

scene = bpy.context.scene
scene.render.engine = 'BLENDER_EEVEE'
scene.render.resolution_x = 800
scene.render.resolution_y = 800
scene.world = bpy.data.worlds.new("World")
scene.world.use_nodes = True
scene.world.node_tree.nodes["Background"].inputs[1].default_value = 1.0

angles = [0, 90, 180, 270]
for i, az in enumerate(angles):
    az_r = math.radians(az)
    el_r = math.radians(35)
    x = center.x + radius * math.cos(el_r) * math.cos(az_r)
    y = center.y + radius * math.cos(el_r) * math.sin(az_r)
    z = center.z + radius * math.sin(el_r)
    cam_obj.location = (x, y, z)
    direction = center - mathutils.Vector((x, y, z))
    rot_quat = direction.to_track_quat('-Z', 'Y')
    cam_obj.rotation_euler = rot_quat.to_euler()
    scene.render.filepath = os.path.join(out_dir, f"view_{i}_{az}deg.png")
    bpy.ops.render.render(write_still=True)

print("DONE_RENDER")
