"""Run inside Blender, directly or with local Blender MCP.
Set EXPORT_PATH to an absolute .glb path. Does not upload or store credentials.
The AI client uploads the resulting file to build0 and connects its new asset ID.
"""
import bpy
import json
import os
from mathutils import Vector

EXPORT_PATH = globals().get("EXPORT_PATH", "")
if not EXPORT_PATH or not os.path.isabs(EXPORT_PATH) or not EXPORT_PATH.lower().endswith(".glb"):
    raise ValueError("Set EXPORT_PATH to an absolute .glb file path before running.")
if os.path.exists(EXPORT_PATH) and not globals().get("ALLOW_OVERWRITE", False):
    raise ValueError("File exists. Choose a new path or set ALLOW_OVERWRITE=True.")
selected = list(bpy.context.selected_objects)
if not selected:
    raise ValueError("Select the intended collection's objects first.")
warnings = []
errors = []
depsgraph = bpy.context.evaluated_depsgraph_get()
points = []
triangles = 0
for obj in selected:
    if any(abs(v - 1) > 0.001 for v in obj.scale):
        warnings.append(obj.name + ": non-unit scale; apply transforms deliberately before export.")
    if obj.type == 'MESH':
        evaluated = obj.evaluated_get(depsgraph)
        mesh = evaluated.to_mesh()
        try:
            mesh.calc_loop_triangles()
            triangles += len(mesh.loop_triangles)
            points.extend(evaluated.matrix_world @ Vector(corner) for corner in evaluated.bound_box)
        finally:
            evaluated.to_mesh_clear()
materials = {m for obj in selected for m in getattr(obj.data, 'materials', []) if m}
images = set()
for material in materials:
    if not material.use_nodes:
        warnings.append(material.name + ": use Principled BSDF for glTF-compatible PBR materials.")
    if material.node_tree:
        for node in material.node_tree.nodes:
            if node.type == 'TEX_IMAGE':
                if not node.image:
                    errors.append(material.name + ": image node has no texture.")
                else:
                    images.add(node.image)
                    if node.image.size[0] == 0 or node.image.size[1] == 0:
                        errors.append(node.image.name + ": missing or unloaded image.")
                    if max(node.image.size) > 4096:
                        errors.append(node.image.name + ": texture exceeds 4096 pixels.")
if triangles > 100000: errors.append("More than 100,000 evaluated triangles; simplify the selected model.")
if len(materials) > 24: errors.append("More than 24 materials; consolidate materials.")
if len(images) > 16: errors.append("More than 16 textures; use texture atlases.")
if bpy.context.scene.unit_settings.scale_length != 1:
    warnings.append("Scene unit scale is not one metre; check exported dimensions carefully.")
actions = sorted({obj.animation_data.action.name for obj in selected if obj.animation_data and obj.animation_data.action})
report = {"selected": len(selected), "triangles": triangles, "materials": len(materials), "textures": len(images), "actions": actions, "warnings": warnings, "errors": errors}
if points:
    report["bounds_blender_z_up"] = {"min": [min(p[i] for p in points) for i in range(3)], "max": [max(p[i] for p in points) for i in range(3)]}
print(json.dumps(report, indent=2))
if errors:
    raise ValueError("Fix the export report errors before exporting.")
if bpy.context.object and bpy.context.object.mode != 'OBJECT':
    bpy.ops.object.mode_set(mode='OBJECT')
os.makedirs(os.path.dirname(EXPORT_PATH), exist_ok=True)
result = bpy.ops.export_scene.gltf(filepath=EXPORT_PATH, export_format='GLB', use_selection=True, export_yup=True, export_apply=True, export_animations=True, export_materials='EXPORT')
if 'FINISHED' not in result:
    raise RuntimeError("Blender did not complete the GLB export.")
size = os.path.getsize(EXPORT_PATH)
print(json.dumps({"exported": EXPORT_PATH, "bytes": size, "within_upload_budget": size <= 10 * 1024 * 1024, "next": "Upload this GLB via build0 upload_model; inspect and privately test before publication."}))
if size > 10 * 1024 * 1024:
    raise ValueError("GLB exceeds 10 MB. Resize textures or split the asset before uploading.")
