import bpy, sys, math, mathutils

argv = sys.argv[sys.argv.index("--")+1:]
GLB, OUTDIR = argv[0], argv[1]

# Escena limpia
bpy.ops.wm.read_factory_settings(use_empty=True)
bpy.ops.import_scene.gltf(filepath=GLB)
meshes = [o for o in bpy.context.scene.objects if o.type == 'MESH']

# Bounding box combinado
coords = []
for o in meshes:
    for v in o.bound_box:
        coords.append(o.matrix_world @ mathutils.Vector(v))
minc = mathutils.Vector(tuple(min(c[i] for c in coords) for i in range(3)))
maxc = mathutils.Vector(tuple(max(c[i] for c in coords) for i in range(3)))
center = (minc + maxc) / 2
size = (maxc - minc)
radius = size.length / 2
print(f"BOUNDS size={tuple(round(x,3) for x in size)} center={tuple(round(x,3) for x in center)}")

# Workbench: arcilla + cavidad (resalta detalle de geometría)
scene = bpy.context.scene
scene.render.engine = 'BLENDER_WORKBENCH'
sh = scene.display.shading
sh.light = 'STUDIO'
sh.show_cavity = True
sh.cavity_type = 'BOTH'
sh.curvature_ridge_factor = 1.0
sh.curvature_valley_factor = 1.0
sh.color_type = 'SINGLE'
sh.single_color = (0.62, 0.57, 0.52)
scene.render.resolution_x = 900
scene.render.resolution_y = 900
scene.render.film_transparent = False
scene.view_settings.view_transform = 'Standard'

# Cámara ortográfica (encuadre garantizado)
cam_data = bpy.data.cameras.new('Cam')
cam_data.type = 'ORTHO'
cam_data.ortho_scale = max(size.x, size.y, size.z) * 1.15
cam = bpy.data.objects.new('Cam', cam_data)
scene.collection.objects.link(cam)
scene.camera = cam

def look_at(obj, target):
    d = (target - obj.location)
    obj.rotation_euler = d.to_track_quat('-Z', 'Y').to_euler()

views = {"00_front": 0, "45": 45, "90_side": 90, "135": 135, "180_back": 180}
for name, deg in views.items():
    a = math.radians(deg)
    direction = mathutils.Vector((math.sin(a), -math.cos(a), 0.25)).normalized()
    cam.location = center + direction * radius * 4
    look_at(cam, center)
    scene.render.filepath = f"{OUTDIR}/preview_{name}.png"
    bpy.ops.render.render(write_still=True)
    print(f"RENDER_OK {name}")
print("DONE")
