"""Save the isolated PTP1B_Lab scene as .blend and export it as GLB.

Run inside Blender after build_lab.py (OUT_DIR must be defined by the caller).
Only the PTP1B_Lab scene and its dependencies are written; the session's own file
is never saved or overwritten.
"""
import bpy, os, json, hashlib

OUT = globals()["OUT_DIR"]
lab = bpy.data.scenes["PTP1B_Lab"]
blend = os.path.join(OUT, "ptp1b_research_lab.blend")
glb = os.path.join(OUT, "ptp1b_laboratory.glb")

# render-preview lighting for the .blend only (not exported)
for ob in lab.collection.all_objects:
    if ob.type == "LIGHT":
        ob.data.energy = 75
try:
    lab.world.node_tree.nodes["Background"].inputs[0].default_value = (0.55, 0.57, 0.60, 1)
    lab.world.node_tree.nodes["Background"].inputs[1].default_value = 0.35
except Exception as e:
    print("world tweak skipped", e)

bpy.data.libraries.write(blend, {lab}, compress=True)

win = bpy.context.window
prev = win.scene
win.scene = lab
for ob in bpy.context.view_layer.objects:
    ob.select_set(False)
kw = dict(filepath=glb, export_format="GLB", use_active_scene=True, export_apply=True, export_yup=True, export_extras=True,
          export_cameras=False, export_lights=False, export_materials="EXPORT", export_texcoords=True, export_normals=True)
try:
    res = bpy.ops.export_scene.gltf(**kw)
except TypeError as e:
    print("retrying export with reduced options:", e)
    res = bpy.ops.export_scene.gltf(filepath=glb, export_format="GLB", use_active_scene=True, export_apply=True)
print("export", res)
info = {}
for p in (blend, glb):
    data = open(p, "rb").read()
    info[os.path.basename(p)] = dict(bytes=len(data), sha256=hashlib.sha256(data).hexdigest())
info["blender_version"] = bpy.app.version_string
info["scene"] = lab.name
info["objects"] = len(lab.collection.all_objects)
with open(os.path.join(OUT, "blender_export_record.json"), "w") as fh:
    json.dump(info, fh, indent=1)
print("EXPORT_OK", json.dumps(info))
